Controlling LEGO Mindstorms EV3 with C++
LEGO Mindstorms EV3 is deliberately open and configurable. The official software is complete and pretty but cumbersome even with a top-end laptop (Wirth’s Law in action).
So there are a number of options for controlling the robot programatically from your computer. I wanted something that didn’t require installation of a custom firmware, or use C# or Java. They’re good choices for many applications, but I’m writing something to run natively on a Macbook so others can use it easily.
In any case, this is Lego and there is no need to justify having fun building something different. Or, in the vernacular of The Lego Movie:
Lego? Awesome!
Mindstorms? Awesome!
Mac? Awesome!
Code? Awesome!
It was remarkably easy to construct and send instructions over bluetooth to the LEGO Mindstorms brick, but since I haven’t seen it described concisely elsewhere without requiring a separate download of large libraries, here it is.
// Send a command to Mindstorms EV3 brick and hear the response.
// One ping only.
//
// This is an example; much necessary error checking is skipped.
//
// Iain Haslam, March 2014.
#include <unistd.h>
#include <fcntl.h>
#include "c_com.h"
int main()
{
const int freq(1000); //kHz
const int duration(500); //ms
unsigned const char sound_command[] {15, 0, 0, 0,
DIRECT_COMMAND_NO_REPLY, //rnsr is not reqid (Milne, 1926)
0, 0,
opSOUND, LC0(TONE), LC1(2), LC2(freq), LC2(duration)};
int bt = open("/dev/tty.EV3-SerialPort", O_WRONLY);
write(bt, sound_command, 17);
close(bt);
}
Paste that into a new console project in Xcode, and you’re off.
Comments
Q: Where did you get this file: #include "c_com.h"
?
A: You missed the step called “instructions” above, where the link was provided - but don’t worry, here it is again: https://github.com/mindboards/ev3sources/blob/master/lms2012/c_com/source/c_com.h