【问题标题】:Arduino serial data processing from Python来自 Python 的 Arduino 串行数据处理
【发布时间】:2018-10-26 17:44:07
【问题描述】:

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

我的问题是:

  • 我应该像在 Python 示例代码中那样发送颜色字节,还是应该单独发送颜色字节或以其他方式发送?发送的字节如下所示:b'255 32 28'。

  • 如何将此字节转换为单独的整数或列表? 例如: b'255 32 28 ' ,转为 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();
}  

有什么好的建议吗?

【问题讨论】:

    标签: python arduino


    【解决方案1】:

    现在你正在发送这个:RRR GGG BBB

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多