制作测试脚本
首先我们需要制作一个脚本来测试自启动是否有效。在终端下输入并回车新建脚本文件testboot.sh
pi@raspberry:~ $ nano testboot.sh
testboot.sh文件内容如下:
#!/bin/sh
touch /home/pi/testboot.txt
chmod 777 /home/pi/testboot.txt
echo "hello pi~" >> /home/pi/testboot.txt
测试脚本将打印字符串到文件中。按ctrl+o保存文件,再按ctrl+x退出编辑器。
给脚本文件添加执行权限:
pi@raspberry:~ $ chmod 777 testboot.sh
测试一下脚本功能:
pi@raspberry:~ $ ./testboot.sh
执行正常的话会在当前目录(pi)生成一个testboot.txt的文本文件。显示文件内容:
pi@raspberry:~ $ cat testboot.txt
添加自启动
方法一:向rc.local文件添加启动代码
修改rc.local文件,在终端输入并回车:
pi@raspberry:~ $ sudo nano /etc/rc.local
在打开的文本中找到exit 0,在此之前添加的代码在启动时都会被执行,在exit 0 之前添加一行代码:
su pi -c "exec /home/pi/testboot.sh"
ctrl+o保存,ctrl+x退出,然后在终端输入:sudo reboot ,重启系统测试。
su命令是指定在pi用户下执行这条命令,-c 表示执行完这条命令之后恢复原来的用户。
注意:系统启动时在执行这段代码时是使用root用户权限的,如果不指定pi用户,可能会因为权限问题导致脚本执行失败。。
作者:oldfool
链接:https://www.jianshu.com/p/86adb6d5347b
來源:简书
简书著作权归作者所有,任何形式的转载都请联系作者获得授权并注明出处
Python测试脚本:树莓派用Python点亮LED灯
首先要了解树莓派上的针脚,下面以树莓派3代为例子
把LED的正极插在GPIO脚上,把负极插在GND上
这里的例子是:正极插在GPIO18
代码与注释如下:
import RPi.GPIO as GPIO #导入树莓派提供的python模块
import time #导入时间包,用于控制闪烁
GPIO.setmode(GPIO.BCM) #设置GPIO模式,BCM模式在所有树莓派通用
GPIO.setup(18, GPIO.OUT) #设置GPIO18为电流输出
while True:
GPIO.output(18, GPIO.HIGH) #GPIO18 输出3.3V
time.sleep(0.05) #程序控制流程睡眠0.05秒
GPIO.output(18, GPIO.LOW) #GPIO18 输出0V
time.sleep(0.05) #程序控制流程睡眠0.05秒
注解:我这次实验使用硬件平台为Raspberry Pi 3 Model B(Made in United Kingdom),操作系统为Debian 9.4 ,树莓派上默认安装的是Python 2.7 。
遇到几个常见语法问题报错:
1.SyntaxError: invalid syntax
An invalid syntax error means that there is a line that python doesn't know what to do with. The last common type of syntax error you will likely encounter has to do with indention. You may see unindent does not match any outer indention level unexpected indent.
2. SyntaxError:Missing parentheses in call to ‘print’
print
函数:(Python3中print为一个函数,必须用括号括起来;Python2中print为class)
Python 2 的 print 声明已经被 print()
函数取代了,这意味着我们必须包装我们想打印在小括号中的对象。
Python 2
1 2 3 4 | print 'Python', python_version() print 'Hello, World!' print('Hello, World!') print "text", ; print 'print more text on the same line' |
run result:
Python 2.7.6
Hello, World!
Hello, World!
text print more text on the same line
Python 3
1 2 3 4 | print('Python', python_version()) print('Hello, World!') print("some text,", end="") print(' print more text on the same line') |
run result:
Python 3.4.1
Hello, World!
some text, print more text on the same line
Linux(树莓派) 下开机启动 Python 脚本
rc.local
将脚本写在 /etc/rc.local文件
输入命令:sudo vi /etc/rc.local
在exit 0上一行输入:/usr/bin/python /home/pi/test.py
OK
重启就可以看效果sudo reboot
注解:注意代码/usr/bin/python /home/pi/test.py
指定了脚本的解释器,经过自己尝试,即使跑马灯的gpio.py脚本开头写了#!/usr/bin/env python ,如果直接把开机启动.sh脚本时候rc.local文件exit 0语句前加入的自启动代码su pi -c "exec /home/pi/testboot.sh" 改成su pi -c "exec /home/pi/gpio.py" ,自启动依然失败。gpio.py文件执行权限已经添加成功,rc.local文件也有执行权限。原因未知。而当加入的代码是/usr/bin/python /home/pi/gpio.py
自启动gpio.py脚本成功。
遗留问题:自启动用qt写的带gui界面程序失败,没有反应。需要尝试其他方法。