pySerial可以向arduin发送数据时间

2024-10-01 07:42:31 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图使用Python和串行通信向arduino发送日期时间,但发送数据时遇到问题。当我使用var = raw_input ("input:")时 数据已发送。但是当我使用var = str (time.asctime (time.localtime (time.time ())))时,数据没有发送到arduino。在

下面是我的Python代码:

import serial, time

port = serial.Serial('COM4',9600)
var = str(time.asctime(time.localtime(time.time())))
if port.isOpen():
   print ('Port Aktif')
   while 1:
       port.write(var)
       time.sleep(1)
       print port.readline()
else:
   print 'port Tidak Aktif'

我的代码是arduino:

^{pr2}$

Tags: 数据代码inputtimeportvar时间serial
2条回答

https://pyserial.readthedocs.io/en/latest/pyserial_api.html#classes

上面写着:

write(data)
[...]
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').

这意味着,使用

^{pr2}$

而不是

In [1]: import time

In [2]: str(time.asctime(time.localtime(time.time())))
Out[2]: 'Sat May  6 14:39:17 2017'

使用:

^{pr2}$

后者将返回一个字节字符串,这是写入串行端口时所必需的。在

相关问题 更多 >