I have implemented serial communication from PC to my Arduino Uno using C to pass command in integer form. But I have noticed only 3 characters commandID will be correctly received by Arduino, but it will shows weird integer if I pass in 4 characters commandID.
Eg. CommandID 101 is correctly received by Arduino and println as 101, but 1001 will become 233 and 3 in two lines with Arduino println.
I suspect this might be something to do with byte length, any ideas?
My C code:
int file, data_s;
struct termios toptions;
file = open("/dev/ttyACM1", O_RDWR | O_NOCTTY);
printf("File opened as %i\n",file);
sleep(4);
/* get current serial port settings /
tcgetattr(file, &toptions);
/ set 9600 baud both ways /
cfsetispeed(&toptions, B9600);
cfsetospeed(&toptions, B9600);
/ 8 bits, no parity, no stop bits /
toptions.c_cflag &= ~PARENB;
toptions.c_cflag &= ~CSTOPB;
toptions.c_cflag &= ~CSIZE;
toptions.c_cflag |= CS8;
/ Canonical mode /
toptions.c_lflag |= ICANON;
/ commit the serial port settings */
tcsetattr(file, TCSANOW, &toptions);
reads just one byte from the input stream and of course a single unsigned byte can only hold values between 0 and 255. The value 233 is just 1001 % 256 i.e. the least significant byte of 1001.
Each value you send from the PC will be several bytes so you need to combine these several received bytes to reconstruct the value. This of course means you need to know how many bytes make up the value you are sending and this will depend on the type of value (int, byte, long etc) you are sending .
So you mean if I want to send 4 characters Integer, I will have to read those bytes into a buffer (like char buffer) and ntohl them into integer? But is ntohl kind of things is available in Arduino C?
HarrisLaw:
So you mean if I want to send 4 characters Integer, I will have to read those bytes into a buffer (like char buffer) and ntohl them into integer? But is ntohl kind of things is available in Arduino C?
I assume by "4 characters Integer" you mean "4 byte Integer" so yes you need the equivalent of ntohl BUT I rarely send binary data through serial since one must make sure that non-printable bytes are not interpreted as some form of control bytes. I prefer to send either decimal representations or hexadecimal representations. With decimal representations one normally needs a terminating non-decimal digit such as carriage return or line feed and for hexadecimal one can normally use fixed length values BUT the method of indicating the field width is totally up to you.
I think the bytes of my integer will be more than 4 if I were to send 4 characters integer. But anyway thanks for your explanation I think I will do it with your way as well, it will be too redundant to create another conversion for this purpose haha