2016-08-12 82 views
1

我有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').

  1. 我的第一個問題:我不知道如何把我的浮動和int數據。如何將它們轉換爲字符串?
  2. 我的第二個問題:我想發送的數據都在一起,這樣一個獨特的價值:

    99.7F100S56.7T

在這種情況下,使用ATMEGA的固件,我可以拆分並且當遇到第一數據的「F」字符,第二數據的「S」字符等等時,更新相應變量中的數據。

如何在Python3中使用pyserial做到這一點?

+0

你大概可以簡單地發送'data.write(「99.7F100S56 .7T「)' – njzk2

+0

Thanks @ njzk2:抱歉我的糟糕解釋,但變量在」準實時「變化,每0.5秒鐘一次。我的代碼片段只是一個非常簡單的例子 – mikilinux

回答

1
  1. 通過使用string function(例如,)將float,int或大多數其他非字符串轉換爲字符串。你的情況

str(first_data)

將輸出'99 0.7' (一個字符串)。

  1. 通過使用string format method,例如,

'{0}F{1}S{2}T'.format(first_data, second_data, third_data)

將輸出99 .7F100S56.7T」

這些字符串可以作爲參數使用serial.send

+0

Thanks @madeddie。在接下來的幾個小時內,我會嘗試你的建議。 – mikilinux

+0

是的,它像一種享受。 我用你的建議,然後我在固件中使用「strtok(char * str,const char delim)-like C」函數來分隔每個字段。 – mikilinux