[英]Reading integer from arduino using pyserial
我正在從 arduino 發送整數值並使用 pyserial 在 Python 中讀取它 arduino 代碼是:
Serial.write(integer)
pyserial 是:
ser=serial.Serial ('com3',9600,timeout =1)
X=ser.read(1)
print(X)
但它除了空格之外不打印任何東西有誰知道如何在 Python 中讀取從 arduino 傳遞的這個整數?
您可能需要使用一個起始位。
問題可能是在 pyserial 運行時 arduino 已經寫入了整數?
所以寫一個字符從 pyserial 到 arduino 來表示開始
ser=serial.Serial ('com3',9600,timeout =1)
ser.write(b'S')
X=ser.read(1)
print(X)
一旦你得到這個起始位,就從 arduino 中寫入整數。
這不是從 Arduino 讀取Integer
的正確方法。 Integer
是 32 位類型,而您的串行端口將設置為字節大小的EIGHTBITS (在 pyserial 和 Arduino 中。如果我錯了,請糾正我) ,因此您必須在傳輸時從 Arduino 編寫Integer
的Character
版本它通過串行端口,因為一個Character
大小只需要8 位,這也是很容易地完成你需要的事情的便捷方式。
長話短說,在傳輸之前將您的Integer
轉換為String
或Character
數組。 (可能有可用於轉換的內置函數)。
在旁注中,這里是您更喜歡使用的正確 python 代碼:
ser = serial.Serial(
port='COM3',
baudrate=9600,
parity=serial.PARITY_NONE,
stopbits=serial.STOPBITS_ONE,
bytesize=serial.EIGHTBITS
)
#RxTx
ser.isOpen()
while 1:
out = ''
while ser.inWaiting() > 0:
out += ser.read(1)
if out != '':
print ">>Received String: %s" % out
我測試的一個簡單的程序:
阿杜諾:
void setup() {
// initialize serial communication at 9600 bits per second:
Serial.begin(9600);
}
void loop() {
int f1=123;
// print out the value you read:
Serial.println(f1);
delay(1000);
}
蟒蛇:
import serial
ser = serial.Serial()
ser.baudrate = 9600
ser.port = 'COM5'
ser.open()
while True:
h1=ser.readline()
if h1:
g3=int(h1); #if you want to convert to float you can use "float" instead of "int"
g3=g3+5;
print(g3)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.