# C++ and Create 2

I am trying to use C++ to talk to the Create 2 robot. Does anyone have basic code to write/read from the Create 2 using C++ or C?

I am having trouble with converting Create 2 commands (like 145) into one char.

• You can simply use unsigned char opcode; and then assign opcode = 145;. May 5 '15 at 10:17
• @ott This is a great answer, next time make it a "real" answer. Comments are for helping to improve questions and answers, and are distracting, so we try to keep them to a minimum.
– Ben
Jun 4 '15 at 23:15
• Are you looking for a place to start to implement a library that reads/writes serial messages? or are you looking for a place to start to implement essentially a Create2 API? Or both? Dec 3 '15 at 14:29

## 1 Answer

As ott mentioned, you can simply make the type an unsigned char which is an 8 bit data type. Here is some code snipits that should work, but are untested. This uses the "Drive" example from the OI Spec.

#include <termios.h>
#include <unistd.h>
#include <fcntl.h>
#include <stdio.h>

unsigned char buff[5] = {137, 255, 56, 1, 244};

fd = open("/dev/ttyUSB0", O_RDWR | O_NOCTTY);

struct termios tio;
bzero(&tio, sizeof(tio));
tio.c_cflag = B115200 | CS8 | CLOCAL | CREAD;
tio.c_iflag = IGNPAR;
tio.c_cc[VTIME]    = 1;
tio.c_cc[VMIN]     = 0;
tcflush(fd, TCIFLUSH);
tcsetattr(fd, TCSANOW, &tio);

int res = write(fd, buff, 5);
if (res < 0)
{
int err = errno;
perror("write error: ");
printf("\nWARNING: write returned %d, errno: %d\n", res, err);
}

• Thanks this is very helpful. I have another question. I noticed that the create2 does not always provide sensor data while it's moving. Am I supposed to stop the robot, request sensor data then start it again? or am I missing something? it seems to work most of the time but once in a while I get no data back. I am trying to make it move from one point to another by starting it and then reading distance to see how far it travels every .1 seconds but sometimes it just keeps on going since I get no data.
– Jack
May 6 '15 at 15:31
• Note that bzero is deprecated. Per its manpage, “This function is deprecated (marked as LEGACY in POSIX.1-2001): use memset(3) in new programs. POSIX.1-2008 removes the specification of bzero().” So instead of bzero(&tio, sizeof(tio)); you could say memset(&tio, 0, sizeof tio);. [For the #includes, manpages show #include <string.h> for memset, and #include <strings.h> for bzero.] May 6 '15 at 15:57
• Jack, please post your new question in a new thread. @jwpat7, thanks for the info, i guess it has been a while since i checked the man page for '''bzero''' :)
– Ben
May 6 '15 at 16:53