[問題] python到Arduino之間的字串格式轉換已刪文

看板Python作者時間6年前 (2019/01/11 19:32), 6年前編輯推噓0(006)
留言6則, 2人參與, 6年前最新討論串1/1
大家好 最近在學習這個部分 但是字串之間的轉換搞得有點頭痛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
所以是卡在 byte 轉一般字串部分不清楚還是
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
就一般的轉換而已啊... start.encode() 就是 bytes 格式
01/12 22:02, 2F

01/12 22:03, 6年前 , 3F
抱歉上面說錯。一般字串可以用 .encode() 轉成 bytes
01/12 22:03, 3F

01/12 22:03, 6年前 , 4F
bytes 後續你可以用 .decode() 轉成一般字串
01/12 22:03, 4F

01/12 22:05, 6年前 , 5F
若你要累加這類,數字轉字串然後轉 bytes 就是你要的
01/12 22:05, 5F

01/13 10:16, 6年前 , 6F
謝謝 我再試試看!
01/13 10:16, 6F
文章代碼(AID): #1SE7xH7- (Python)
文章代碼(AID): #1SE7xH7- (Python)