[英]Serial communication sending/receiving data between Arduino and Python
[英]Python receiving serial data
我正在嘗試從 Python 3.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;
}
}
蟒蛇代碼:
## 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,而不是獲取整個數組的值。
有沒有人對我出錯的地方有什么建議?
如果您閱讀Serial.read()
函數的文檔,您會看到它的默認參數是“1”。 所以它按預期只從串行端口讀取 1 個字節。 您應該首先檢查(或等到)有足夠的字節並將要讀取的字節數傳遞給read()
函數。
通過將 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()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.