python - 来自 Python 的 Arduino 串行数据处理
问题描述
我是 Arduino 新手,我正在尝试制作一个 LED 灯条控制器。我正在使用 Python 将串行数据发送到 Arduino。我使用三个刻度来控制 LED 的颜色。
我的问题是:
我应该像在 Python 示例代码中那样发送颜色字节,还是应该单独发送颜色字节或以其他方式发送颜色字节?发送的字节如下所示:b'255 32 28'。
如何将此字节转换为单独的整数或列表?例如:b'255 32 28' , to int list[4]={255,32,28}
Python 示例代码:
from tkinter import *
import serial
import serial.tools.list_ports as ports
master = Tk()
master.geometry('400x300')
for ee in list(ports.comports()):
if ee.serial_number=='557363134383519112E0':
usb=ee.device
ser=serial.Serial(usb,baudrate=9600)
def getThrottle():
data=str(r.get())+' '+str(g.get())+' '+str(b.get())+' '
data=bytes(str(data),'utf8')
ser.write(data)
r = Scale(master,from_=255,to=0)
r.place(x=50,y=100)
g = Scale(master, from_=255, to=0)
g.place(x=150,y=100)
b=Scale(master, from_=255, to=0)
b.place(x=250,y=100)
gomb=Button(master,command=getThrottle,text='Send to led strip')
gomb.place(x=150,y=250)
master.mainloop()
Arduino示例代码:
#include <Adafruit_NeoPixel.h>
Adafruit_NeoPixel strip = Adafruit_NeoPixel(60, 12, NEO_GRB + NEO_KHZ800);
String inByte;
char str;
int sa[4], r=0, t=0;
void setup()
{
Serial.begin(9600);
strip.begin();
strip.show();
}
void loop() {
if (Serial.available() > 0)
{
inByte = Serial.readString();
int str_len = inByte.length() + 1;
char char_array[str_len];
inByte.toCharArray(char_array, str_len);
for (int i=0; i < inByte.length(); i++)
{
if(inByte.charAt(i) == ' ')
{
sa[t] = inByte.substring(r, i).toInt();
r=(i+1);
t++;
}
}
}
strip.setPixelColor(1, sa[0],sa[1],sa[2]);
strip.show();
}
有什么好的建议吗?
解决方案
现在你发送这个:RRR GGG BBB
我建议添加一些分隔符,让您的 Arduino 更容易解码。EG:&RRR GGG BBB!
当您的 arduino 看到“&”时,它知道要存储数据,直到看到“!”。当它出现时,您就知道您已经拥有了一个完整的数据集。从那里,拆分“”上的数据。
推荐阅读
- python - 绘制射弹射程的二阶耦合微分方程
- c++ - 确定输入数据是否“平衡”
- python - 多个集合并集以及列表理解
- r - 在空矩阵中添加矩阵
- python - 我写了这段代码,但我的输出不是应该是 2D 的,我不知道如何修复它
- javascript - 遍历 Typescript 中的键 a 并删除值为 undefined 的键
- css - 基于其父级的备用弯曲方向
- python - 返回跨多列字符串的百分比频率的函数
- sublimetext3 - 用于跳过下一个选择快速添加的 Sublime 3.2.2 快捷方式不起作用(macOS)
- batch-file - 批处理数组、关联数组以及如何在数组中导航