[問題] python到Arduino之間的字串格式轉換已刪文
大家好
最近在學習這個部分
但是字串之間的轉換搞得有點頭痛QQ
程式目的是這樣的
在Python上設一個變數 start = 0
之後透過USB傳到給Arduino後讀取並 + 1 (現在start=1)
接著在把Start的值回傳回Python
Python讀取到後再+1 (現在start=2)
之後再回傳回Arduino
以上這段動作進行迴圈
程式碼的部分是這樣:
Python部分:
import time
import serial
arduino = serial.Serial('COM6', 115200, timeout=.1)
time.sleep(1)
start=b"0"
while True:
arduino.write(start)
data = arduino.readline()
if data:
print (data.rstrip(b'\n'))
start=start+1
==========
Arduino部分:
void setup() {
Serial.begin(115200);
}
void loop() {
while (1){
if(Serial.available() > 0) {
char data = Serial.read();
data=data+1;
Serial.print(data);
}
}
}
========
功能的話應該是對的
只是問題在字串的格式轉換
想請問應該要怎麼寫比較好QQ
--
※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 120.105.133.228
※ 文章網址: https://www.ptt.cc/bbs/Python/M.1547206353.A.1FE.html
→
01/12 14:34,
6年前
, 1F
01/12 14:34, 1F
對,是卡在Byte與其他格式的轉換上
因為從Python送過去Arduino的時候必須是為byte的型態
被Arduino讀到的時候是char
但是這兩個之間都不能直接的運算
所以要轉成其他的
一開始在弄測試能不能溝通的時候發送訊號給Arduino是寫作:
arduino.write(b"0")
這樣子可以發送過去
之後把他改寫成上面程式碼那樣
start=b"0"
while True:
arduino.write(start)
就不會累加了QQ
報錯訊息:
https://i.imgur.com/q8Nc1o3.png

※ 編輯: st40182 (120.105.133.228), 01/12/2019 15:14:34
→
01/12 22:02,
6年前
, 2F
01/12 22:02, 2F
→
01/12 22:03,
6年前
, 3F
01/12 22:03, 3F
→
01/12 22:03,
6年前
, 4F
01/12 22:03, 4F
→
01/12 22:05,
6年前
, 5F
01/12 22:05, 5F
→
01/13 10:16,
6年前
, 6F
01/13 10:16, 6F
Python 近期熱門文章
PTT數位生活區 即時熱門文章