Python接收串行数据

2024-03-29 05:37:55 发布

您现在位置:Python中文网/ 问答频道 /正文

我正试图从Python3.6向Arduino发送一条消息,Arduino需要响应。你知道吗

目前,我能够发送到Arduino和它的反应,但不是得到一个完整的信息回来,我得到1字节。你知道吗

Arduino代码:

byte FullResponse[] = {0xA1, 0xA3, 0xA4, 0x3B, 0x1F, 0xB4, 0x1F, 0x74, 0x19, 
0x79, 0x44, 0x9C, 0x1F, 0xD4, 0x4A, 0xC0};
byte SerialBuf[11] = {0,0,0,0,0,0,0,0,0,0,0};
int i = 0;

void setup() {
  Serial.begin(115200);
}

void loop() {
//Reads values from the Serial port, if there are any
  for(int i=0; i<=10; i++){
    while(!Serial.available());
    SerialBuf[i] = Serial.read();
  }

//Sends the full response back if EF is the 8th byte
  if(SerialBuf[8] == 0xEF){
     Serial.write(FullResponse, sizeof(FullResponse));
     SerialBuf[8] = 15;
  }
}

Python代码:

## import the serial library
import serial
import time

Response = []
FullResponse = bytes([0xC0, 0x43, 0xA1, 0x04, 0x0A, 0x90, 0x00, 0x30, 0xEF, 0xFF, 0xC0])

## Serial port is 
ser = serial.Serial(port='COM3', baudrate=115200)
time.sleep(2)

#converts values to byte array and sends to arduino
ConArray = bytearray(FullResponse)
ser.write(ConArray[0:len(FullResponse)])
time.sleep(1)    

if ser.inWaiting():
    for Val in ser.read():
        Response.append(Val)

print(*Response)        #prints 161
print(len(Response))        #prints 1

time.sleep(1)

## close the port and end the program
ser.close()

从我在python代码中留下的注释中可以看到。我没有得到一个完整的值数组,只得到161。你知道吗

有人对我的错误有什么建议吗?你知道吗


Tags: the代码importiftimeportresponseserial
2条回答

通过将if语句更改为while语句,代码现在可以读取保存的所有字节。谢谢你的帮助

## import the serial library
import serial
import time

Response = []
FullResponse = bytes([0xC0, 0x43, 0xA1, 0x04, 0x0A, 0x90, 0x00, 0x30, 0xEF, 0xFF, 0xC0])

## Serial port is 
ser = serial.Serial(port='COM3', baudrate=115200)
time.sleep(2)

#converts values to byte array and sends to arduino
ConArray = bytearray(FullResponse)
ser.write(ConArray[0:len(FullResponse)])
time.sleep(1)    

while ser.inWaiting(): ###########   Changed from if to while
    for Val in ser.read():
        Response.append(Val)

print(*Response)        #prints 161
print(len(Response))        #prints 1

time.sleep(1)

## close the port and end the program
ser.close()

如果您阅读Serial.read()函数的documentation,您将看到它的默认参数是“1”。所以它只从串行端口读取1个字节。您应该首先检查(或等待)是否有足够的字节,并将要读取的字节数传递给read()函数。你知道吗

相关问题 更多 >