首页 > 编程知识 正文

python基础灯光开关,树莓派python编程led

时间:2023-05-04 05:17:55 阅读:216472 作者:611

文章目录 1、编写Python脚本2、编写Arduino侧的代码,并且烧录到板子上3、运行Python脚本,查看效果
在第六节,我们学习了如何编写简单的Python脚本,实现了在命令行界面收到Arduino发送来的数据。
上一节只是简单的测试,现在我们要写一个稍微复杂一点,更能满足我们需求的脚本,来实现LED灯的控制和光强值的获取。

前面已经介绍过相应的内容了,现在直接上代码

1、编写Python脚本 #codinf:utf-8import serialport = "/dev/ttyACM0" //由于树莓派和Arduino的连接并不是那么稳定,可能会莫名其妙地断开又重连,导致ACM口经常变,所以要记得及时修改,否则会报错 single = serial.Serial(port,9600)single.flushInput()while True: print("Please input '1' to open the led,input '2' to shutdown the ledninput '3' to get the lightnumbern") num = int(input("Input your num:")) if num == 1: single.flushOutput() single.write('5') print("The led is opened~n") elif num == 2: single.flushOutput() single.write('6') print("THe led is shutdownedn") elif num == 3: Input = single.readline() f = open('/home/pi/arduino/light.txt', mode='w') f.write(Input) f.close() Output = int(Input) print('The light number is: ',Output) else: print("Please input 1-3 to control me!!!") break 2、编写Arduino侧的代码,并且烧录到板子上 const int led = 13;void setup() { Serial.begin(9600); pinMode(led, OUTPUT);}void loop() { int val; char a; val = analogRead(1); Serial.println(val); if (Serial.available()) { a = Serial.read(); Serial.print(a) ; if (a == '5' ) { digitalWrite(led, HIGH); } else { digitalWrite(led, LOW); } delay(1000); } 3、运行Python脚本,查看效果


如上图所示,当运行代码之后,首先会跳出一些提示信息。当我们输入1的时候,LED灯会打开;当输入2的时候,LED灯会熄灭;当输入3的时候,会返回检测到的光强值。说明我们的实验成功!

(关于Python脚本和Arduino程序,或者其他问题有疑惑,大家可以在评论区留言,或者直接QQ和我交流)

版权声明:该文观点仅代表作者本人。处理文章:请发送邮件至 三1五14八八95#扣扣.com 举报,一经查实,本站将立刻删除。