首页 > 解决方案 > 来自 Python 的 Arduino 串行数据处理

问题描述

我是 Arduino 新手,我正在尝试制作一个 LED 灯条控制器。我正在使用 Python 将串行数据发送到 Arduino。我使用三个刻度来控制 LED 的颜色。

我的问题是:

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();
}  

有什么好的建议吗?

标签: pythonarduino

解决方案


现在你发送这个:RRR GGG BBB

我建议添加一些分隔符,让您的 Arduino 更容易解码。EG:&RRR GGG BBB!

当您的 arduino 看到“&”时,它知道要存储数据,直到看到“!”。当它出现时,您就知道您已经拥有了一个完整的数据集。从那里,拆分“”上的数据。


推荐阅读