LattePanda使用Python控制Arduino
缘由
LattePanda 是一块信用卡大小的运行Win10系统的开发板,并且集成了一块Arduino Leonardo单片机,可以外拓各种传感器模块。在重新安装了精简Win10系统后占用磁盘6G多空间。实验在 LattePanda 上使用 Python 编写程序控制板载 Arduino 的调试方法。
准备工作
下载安装 Arduino IDE(地址:https://www.arduino.cc/en/Main/Software?setlang=cn)
下载安装 Thonny(Python IDE,https://thonny.org/),3.0.8版本自带Python 3.7.1
LattePanda
运行 Arduino IDE,输入
const int led = LED_BUILTIN;
void setup()
{
Serial.begin(115200);
pinMode(led, OUTPUT);
}
void loop()
{
if (Serial.available())
{
if (Serial.read() == 'h')
{
digitalWrite(led, HIGH);
}
else
{
digitalWrite(led, LOW);
}
}
}
下载到板载 Arduino,关闭 Arduino IDE
运行 Thonny,输入
import matplotlib.pyplot as plt
from matplotlib.widgets import Button
import serial
ser = serial.Serial('COM3', 115200, timeout=0)
def send(val):
data = bytes(val, 'UTF8')
ser.write(data)
class Index(object):
def on(self, event):
send('h')
return
def off(self, event):
send('l')
return
callback = Index()
axOn = plt.axes([0.3, 0.6, 0.1, 0.075])
axOff = plt.axes([0.5, 0.6, 0.1, 0.075])
bOn = Button(axOn, 'ON')
bOff = Button(axOff, 'OFF')
bOn.on_clicked(callback.on)
bOff.on_clicked(callback.off)
plt.show()
打开菜单 Tools,安装包
在 PyPI 里Find并安装 matplotlib 和 pyserial
运行py
点击 ON,蓝色LED亮,点击 OFF,灭