[英]pySerial can send data time to arduino
I am trying to send date time to arduino using Python with serial communication, but I am having trouble sending the data. 我正在尝试使用Python通过串行通信将日期时间发送到arduino,但是我无法发送数据。 When I use
var = raw_input ("input:")
the data is sent. 当我使用
var = raw_input ("input:")
,将发送数据。 However when I use var = str (time.asctime (time.localtime (time.time ())))
the data not sent to arduino. 但是,当我使用
var = str (time.asctime (time.localtime (time.time ())))
,数据未发送到arduino。
Here's my Python code: 这是我的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'
my code arduino : 我的代码arduino:
String msg ="";
void setup() {
Serial.begin(9600); // set the baud rate
}
void loop() {
if(Serial.available() > 0){
while (Serial.available()>0){
msg += char(Serial.read());
delay(30);
}
Serial.println(msg);
}
}
see https://pyserial.readthedocs.io/en/latest/pyserial_api.html#classes 参见https://pyserial.readthedocs.io/en/latest/pyserial_api.html#classes
it says: 它说:
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').
This means, use 这意味着,使用
var = bytes(time.asctime(time.localtime(time.time())).encode('utf-8'))
Instead of 代替
In [1]: import time
In [2]: str(time.asctime(time.localtime(time.time())))
Out[2]: 'Sat May 6 14:39:17 2017'
use: 采用:
In [3]: time.asctime(time.localtime()).encode('utf-8')
Out[3]: b'Sat May 6 14:39:17 2017'
The latter will return a string of bytes, which is required when writing to a serial port. 后者将返回一个字节字符串,这是在写入串行端口时所必需的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.