树莓派(七)——用Python脚本控制LED灯的开关并获取光强值


在第六节,我们学习了如何编写简单的Python脚本,实现了在命令行界面收到Arduino发送来的数据。
上一节只是简单的测试,现在我们要写一个稍微复杂一点,更能满足我们需求的脚本,来实现LED灯的控制和光强值的获取。


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

1、编写Python脚本

#codinf:utf-8
import serial
port = "/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 led\ninput  '3' to get the lightnumber\n")
    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 shutdowned\n")
    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和我交流)

  • 4
    点赞
  • 19
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值