Writing STRINGS to serial port in C++ linux

后端 未结 2 2132
渐次进展
渐次进展 2021-02-15 04:56

I know this question is scattered all over the internet, but still, nothing is getting me completely there yet. I want to write data to a serial port in C++ (linux) for a a Prop

相关标签:
2条回答
  • 2021-02-15 05:13

    Are you sure you should end with '\r'? When entering text from console the return key will result in a '\n' character (on Linux) and not '\r'

    Also error checking is missing on most functions (open(), fcntl(), etc.). Maybe one of these functions fail. To find out how to check for errors read the man page (for example man 2 open for the open() command. In case of open() the man page explains it returns -1 when it could not open the file/port.

    After your edit you wrote:

    char str[] = {0x56, 0x45, 0x52, 0x0D}; 
    write(tty_fd,str,strlen(str));
    

    which is wrong. strlen expects a '\0' terminated string which str is obviously not so now it sends your data and whatever there is in memory until it sees a '\0'. You need to add 0x00 to your str array.

    0 讨论(0)
  • 2021-02-15 05:30

    I'm happy to solve my own solution but yet disappointed to not have seen the trivial matter much sooner. char by default are signed in c++, which makes it holding the range -128 to 127. However, we are expecting the ASCII values which are 0 to 255. Hence it's as simple as declaring it to be unsigned char str[] and everything else should work. Silly me, Silly me.

    Still, Thank you everyone for helping me!!!

    0 讨论(0)
提交回复
热议问题