Two-way C++ communication over serial connection

后端 未结 3 1981
予麋鹿
予麋鹿 2021-02-01 08:35

I am trying to write a really simple C++ application to communicate with an Arduino. I would like to send the Arduino a character that it sends back immediately. The Arduino cod

3条回答
  •  猫巷女王i
    2021-02-01 09:02

    There are three points:

    First: You don't initialize the serial port (TTY) on the Linux side. Nobody knows in what state it is.

    Doing this in your program you must use tcgetattr(3) and tcsetattr(3). You can find the required parameters by using these keywords at this site, the Arduino site or on Google. But just for quick testing I propose to issue this command before you call your own command:

    stty -F /dev/tty.usbmodem641 sane raw pass8 -echo -hupcl clocal 9600
    

    Especially the the missing clocal might prevent you opening the TTY.

    Second: When the device is open, you should wait a little before sending anything. By default the Arduino resets when the serial line is opened or closed. You have to take this into account.

    The -hupcl part will prevent this reset most of the time. But at least one reset is always necessary, because -hupcl can be set only when the TTY is already open and at that time the Arduino has received the reset signal already. So -hupcl will "only" prevent future resets.

    Third: There is NO error handling in your code. Please add code after each IO operation on the TTY which checks for errors and - the most important part - prints helpful error messages using perror(3) or similar functions.

提交回复
热议问题