Arduino和Raspberry pi3之间的串行通信

Serial Communication Between Arduino and Raspberry pi3

我正在 Arduino 和 Raspberry pi3 之间进行射频通信。这是我的 Arduino 代码,它与 raspberry pi3 连接,它从其他 RF 模块接收 RF 值。

#include <nRF24L01.h>
#include <RF24.h>
#include <RF24_config.h>
#include <SPI.h>
char msg[10];
RF24 radio(7,8);
const uint64_t pipe = 0x0a0c0a0c0aLL;
int lastmsg = 1;
String theMessage = "";
void setup(void){
  Serial.begin(9600);
  radio.begin();
  radio.openReadingPipe(1,pipe);
  radio.startListening();
}
void loop(void){
  if (radio.available()){
    bool done = false;  
      done = radio.read(msg, 1); 
      char theChar = msg[0];
      if (msg[0] != 2){
        theMessage.concat(theChar);
        }
      else {
       Serial.println(theMessage);
       theMessage= ""; 
      }
   }
} 

下面是我的 Python 代码

import serial
import time
# array
rf_array = ["RFID :"]

# Serial Communication
#port = "/dev/ttyACM2"
port = "/dev/ttyACM0"
# /dev/ttyACM2 is rfid Arduino
brate = 9600
arduino8 = serial.Serial(port, baudrate=brate, timeout=None)

while True:
    try:
        print("start")
        #arduino8 = serial.Serial(port, baudrate=brate, timeout=None)
        print("start1")
        data = arduino8.readline()
        print("start2")
        str = data[:-2].decode()
        str = str[:1]
        # str = int(str)
        rf_array.append(str)
        rf_array = list(set(rf_array))
        print(rf_array)


    except:
        print("no value")

当 RF 模块位于我的 RF 模块接收器附近时它起作用 但问题是我的射频模块接收器附近没有射频模块 我发现 data= arduino8.readline() 是个问题。因为没有arduino8的数据。所以它不会转到下一行。我知道问题所在,但我不知道如何解决。如果你能帮助我,我真的很感激。谢谢

将 readline 与 Python 串行使用时 documentation 状态

Be carefully when using readline(). Do specify a timeout when opening the serial port otherwise it could block forever if no newline character is received. Also note that readlines() only works with a timeout. readlines() depends on having a timeout and interprets that as EOF (end of file). It raises an exception if the port is not opened correctly.

这就是您在打开端口时在 python 代码中看到的内容

arduino8 = serial.Serial(port, baudrate=brate, timeout=None)

您应该将超时设置为一个合理的值,例如 1 秒或更长时间,具体取决于您的使用情况,以便库在一段时间后放弃等待。