我有2個關於Python3和PySerial(串行模塊)的問題。GNU/Linux - Python3 - PySerial:如何通過USB連接發送數據?
我必須通過USB端口將數據發送到我的IC的獨立ATMega32。一個可能的代碼片段:
import serial
data=serial.Serial(port, speed)
first_data=99.7 # Float point data.
second_data=100 # Only int data like 10, 345, 2341 and so on.
third_data=56.7 # Float data
ValueToWrite=????? # How to convert it?
send=data.write(ValueToWrite)
現在,如果我嘗試發送 「first_data」 與 「ValueToWrite = firts_data」 我有這樣的錯誤:
TypeError: 'float' object is not iterable
嘛。閱讀文檔中關於方法寫(類serial.Serial - http://pyserial.readthedocs.io/en/latest/pyserial_api.html)我看到:
Write the bytes data to the port. This should be of type bytes (or compatible such as bytearray or memoryview). Unicode strings must be encoded (e.g. 'hello'.encode('utf-8').
- 我的第一個問題:我不知道如何把我的浮動和int數據。如何將它們轉換爲字符串?
我的第二個問題:我想發送的數據都在一起,這樣一個獨特的價值:
99.7F100S56.7T
在這種情況下,使用ATMEGA的固件,我可以拆分並且當遇到第一數據的「F」字符,第二數據的「S」字符等等時,更新相應變量中的數據。
如何在Python3中使用pyserial做到這一點?
你大概可以簡單地發送'data.write(「99.7F100S56 .7T「)' – njzk2
Thanks @ njzk2:抱歉我的糟糕解釋,但變量在」準實時「變化,每0.5秒鐘一次。我的代碼片段只是一個非常簡單的例子 – mikilinux