GNU/Linux - Python3 - PySerial:如何通过 USB 连接发送数据?

GNU/Linux - Python3 - PySerial: How to send data over USB connection?

我有 2 个关于 Python3 和 PySerial(串行模块)的问题。

我必须通过 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)

现在,如果我尝试发送带有 "ValueToWrite=firts_data" 的 "first_data",我会遇到此错误:

TypeError: 'float' object is not iterable

嗯。阅读有关方法的文档 write (class 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. 我的第一个问题:我不明白如何发送我的 float 和 int 数据。如何将它们转换成字符串?
  2. 我的第二个问题:我想一起发送数据,像这样的唯一值:

    99.7F100S56.7T

在这种情况下,使用ATMega的固件,我可以拆分和更新相应变量中的数据,当遇到第一个数据的"F"字符,第二个数据的"S"字符等.

如何在 Python3 中使用 pyserial 执行此操作?

  1. 使用 string function 将 float、int 或大多数其他非字符串转换为字符串,例如在你的情况下

str(first_data)

会输出'99.7'(一个字符串)。

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

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

会输出'99.7F100S56.7T'

您可以将这些字符串用作 serial.send

的参数