【问题标题】:GNU/Linux - Python3 - PySerial: How to send data over USB connection?GNU/Linux - Python3 - PySerial:如何通过 USB 连接发送数据?
【发布时间】:2016-08-12 14:52:51
【问题描述】:

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

我必须通过 USB 端口向我的 IC 的独立 ATMega32 发送数据。一个可能的 sn-p 代码:

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 的文档(类 serial.Serial - http://pyserial.readthedocs.io/en/latest/pyserial_api.html)我明白了:

将字节数据写入端口。这应该是字节类型(或兼容的,例如 bytearray 或 memoryview)。 Unicode 字符串必须经过编码(例如 'hello'.encode('utf-8')。

  1. 我的第一个问题:我不明白如何发送我的 float 和 int 数据。如何将它们转换成字符串?
  2. 我的第二个问题:我想一起发送数据,像这样的唯一值:

    99.7F100S56.7T

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

如何在 Python3 中使用 pyserial 做到这一点?

【问题讨论】:

  • 你可以简单地发送data.write("99.7F100S56.7T")
  • 感谢@njzk2:对不起,我的解释很糟糕,但变量“准实时”每 0.5 秒变化一次。我的 sn-p 代码只是一个非常简单的例子

标签: python linux python-3.x pyserial


【解决方案1】:
  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 的参数

【讨论】:

  • 是的,它就像一种享受。我使用了你的建议,然后我在固件中使用了“strtok(c​​har *str, const char delim)-like C”函数来分隔每个字段。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-03-07
  • 1970-01-01
  • 1970-01-01
  • 2015-12-02
  • 2014-09-24
  • 2015-05-04
相关资源
最近更新 更多