缘由
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
方法一
运行 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,灭
方法二
安装 pyFirmata 包,Arduino 写入程序 Standard Firmata,运行
from pyfirmata import Arduino, util
import time
board = Arduino('COM3')
while (True):
board.digital[13].write(0)
time.sleep(1)
board.digital[13].write(1)
time.sleep(1)
蓝色LED闪烁
方法三
安装 pymata_aio 包
Arduino 写入程序 StandardFirmataPlus,运行
from pymata_aio.pymata3 import PyMata3
from pymata_aio.constants import Constants
BOARD_LED = 13
board = PyMata3(com_port="/dev/ttyACM0")
def setup():
board.set_pin_mode(BOARD_LED, Constants.OUTPUT)
#board.enable_analog_reporting(0)
board.set_pin_mode(0,Constants.ANALOG)
def loop():
try:
print("LED On")
board.digital_write(BOARD_LED, 1)
board.sleep(1.0)
print("LED Off")
board.digital_write(BOARD_LED, 0)
board.sleep(1.0)
print( board.analog_read(0) )
except:
board.shutdown()
if __name__ == "__main__":
setup()
while (True):
loop()
注:方法三未验证