栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

python至arduino串行读写

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

python至arduino串行读写

在写和读之间,您不应该关闭Python中的串行端口。Arduino响应时,端口仍有可能关闭,在这种情况下,数据将丢失。

while running:      # Serial write section    setTempCar1 = 63    setTempCar2 = 37    setTemp1 = str(setTempCar1)    setTemp2 = str(setTempCar2)    print ("Python value sent: ")    print (setTemp1)    ard.write(setTemp1)    time.sleep(6) # with the port open, the response will be buffered        # so wait a bit longer for response here    # Serial read section    msg = ard.read(ard.inWaiting()) # read everything in the input buffer    print ("Message from arduino: ")    print (msg)

Python

Serial.read
函数默认情况下仅返回一个字节,因此您需要在循环中调用它或等待数据传输然后读取整个缓冲区。

在Arduino方面,您应该考虑

loop
没有可用数据时函数中会发生什么。

void loop(){  // serial read section  while (Serial.available()) // this will be skipped if no data present, leading to       // the pre sitting in the delay function below  {    delay(30);  //delay to allow buffer to fill     if (Serial.available() >0)    {      char c = Serial.read();  //gets one byte from serial buffer      readString += c; //makes the string readString    }  }

相反,请等待

loop
函数开始直到数据到达:

void loop(){  while (!Serial.available()) {} // wait for data to arrive  // serial read section  while (Serial.available())  {    // continue as before

编辑2

这是从Python与您的Arduino应用进行交互时得到的结果:

>>> import serial>>> s = serial.Serial('/dev/tty.usbmodem1411', 9600, timeout=5)>>> s.write('2')1>>> s.readline()'Arduino received: 2rn'

因此,这似乎很好。

在测试您的Python脚本时,似乎问题在于打开串口时Arduino会重置(至少我的Uno会这样做),因此需要等待几秒钟才能启动。您还只读取了一行响应,因此我也在下面的代码中修复了该问题:

#!/usr/bin/pythonimport serialimport syslogimport time#The following line is for serial over GPIOport = '/dev/tty.usbmodem1411' # note I'm using Mac OS-Xard = serial.Serial(port,9600,timeout=5)time.sleep(2) # wait for Arduinoi = 0while (i < 4):    # Serial write section    setTempCar1 = 63    setTempCar2 = 37    ard.flush()    setTemp1 = str(setTempCar1)    setTemp2 = str(setTempCar2)    print ("Python value sent: ")    print (setTemp1)    ard.write(setTemp1)    time.sleep(1) # I shortened this to match the new value in your Arduino pre    # Serial read section    msg = ard.read(ard.inWaiting()) # read all characters in buffer    print ("Message from arduino: ")    print (msg)    i = i + 1else:    print "Exiting"exit()

现在是上面的输出:

$ python ardser.pyPython value sent:63Message from arduino:Arduino received: 63Arduino sends: 1Python value sent:63Message from arduino:Arduino received: 63Arduino sends: 1Python value sent:63Message from arduino:Arduino received: 63Arduino sends: 1Python value sent:63Message from arduino:Arduino received: 63Arduino sends: 1Exiting


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/647836.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号