简体   繁体   中英

Writing to a serial port in linux

I am trying to program a robot that has motordrivers on certain serial ports (ie ttyS9)

Through cutecom (as hex input), I can send the following input, which gives me the result I expect:

5aaa0700fffff000

Now I am trying to achieve the same result with a C program, that does the following:

int port9 = open("/dev/ttyS9", O_RDWR | O_NONBLOCK);

char buff[17] = "5aaa0700fffff000";

write(port9, buff, 16);

I've also tried to initialize buff with the hex values seperately:

buff[0] = 0x5;
buff[1] = 0xa;

etc etc.

Both do not work. Is the problem in my code, or in the driver?

I compile using gcc and then run it with sudo. The open function also returns values that are proper (no errors), as well as the write.

Filling a character array with strings will convert characters to their ascii representation not hex as you need.

char buff[17] = "5aaa0700fffff000"; // Incorrect for saving 0x5aaa0700fffff000 to buff

As i see, you want to write 8 byte 0x5aaa0700fffff000 on serial port, a char is 8bit (1 byte) and you have to send 8 bytes not 16, so the code should be something like this

buff[0] = 0x5a;
buff[1] = 0xaa;
...
write(port9, buff, 8);

but maybe it's a number so you'll need unsigned long long int t= 0x5aaa0700fffff000; write(.., (char *)&t, 8); unsigned long long int t= 0x5aaa0700fffff000; write(.., (char *)&t, 8);

that means byte order in memory is completely different to one you'll gain with just assigning bytes as you read it from screen.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM