首页 > 解决方案 > 树莓派 - Arduino 通讯

问题描述

我使用 arduino 设置设计了一个转速计,我得到了输出值(rpm),但由于我没有 wifi 模块,我已经使用 USB 连接了我的 arduino 和树莓派 4。我可以在 pi 终端中读取 rpm 值。但现在我需要将这些数据发送到 adafruit io 页面。如何编写代码以实时从我的 pi 的 USB 端口读取数据?我写了一个脚本,可以在网页上打印它,但每次我都要写一个值。如果我能得到答案,那将非常有帮助。我是编码新手,只是探索这些。

from Adafruit_IO import*

ADAFRUIT_IO_USERNAME = '******'
ADAFRUIT_IO_KEY = '**********************' 

aio = Client(ADAFRUIT_IO_USERNAME,ADAFRUIT_IO_KEY)

try:
    test = aio.feeds('test')
except RequestError:
    test_feed = Feed(name='test')
    test_feed = aio.create_feed(test_feed)
val = 4   
aio.send('test',val) 

标签: arduinoraspberry-piiotserial-communication

解决方案


下面的代码是在 Python 中工作的示例,假设您的 USB 连接在 /dev/tty.usbmodem14201:

import serial
ser = serial.Serial('/dev/tty.usbmodem14201', baudrate=9600) # NB set your baudrate to the one you are using!
ser.flushInput()

while True: #constant loop to get readings in real time
    ser_bytes = ser.readline() #read the incoming message
    decoded_bytes = ser_bytes[0:len(ser_bytes)-2].decode("utf-8") #decode it
    print(decoded_bytes) # print out what you got or, alternatively, make a web call to Adrafruit

推荐阅读