1.树莓派显示温度
import commands
def get_cpu_temp():
tempFile = open( "/sys/class/thermal/thermal_zone0/temp" )
cpu_temp = tempFile.read()
tempFile.close()
return float(cpu_temp)/1000
# Uncomment the next line if you want the temp in Fahrenheit
#return float(1.8*cpu_temp)+32
def get_gpu_temp():
gpu_temp = commands.getoutput( '/opt/vc/bin/vcgencmd measure_temp' ).replace( 'temp=', '' ).replace( '\'C', '' )
return float(gpu_temp)
# Uncomment the next line if you want the temp in Fahrenheit
# return float(1.8* gpu_temp)+32
def main():
print "CPU temp: ", str(get_cpu_temp())
print "GPU temp: ", str(get_gpu_temp())
if __name__ == '__main__':
main()
2. 控制GPIO
先写一个模块 led.py:
import RPi.GPIO as GPIO
import time
channels = [16,18,22,24,26,19,21,23]
def init():
GPIO.setmode(GPIO.BOARD)
for x in channels:
GPIO.setup(x,GPIO.OUT)
pass
def on(i):
GPIO.output(channels[i], GPIO.HIGH)
def off(i):
GPIO.output(channels[i], GPIO.LOW)
def ctrl(data):
for i in channels:
GPIO.output(i, data & 0x1)
data = data >> 1
pass
def test():
for i in xrange(512):
ctrl(i)
time.sleep(0.1)
def clean():
GPIO.cleanup()
再写一个程序调用模块 test.py:
import led
led.init()
led.test()
led.clean()
RPi.GPIO模块函数说明:
RPi.GPIO.setmode(naming_system)
设置将GPIO针的命名方式。
naming_system可用的取值有 RPi.GPIO.BCM 和 RPi.GPIO.BOARD,分别代表boardcom命名系统和树莓派板子上的命名系统。而因为使用BCM 的时候(据说)不同的版本BVM针脚定义不一样,所以同一套程序在多个树莓派系统上使用的时候建议用BOARD。
RPi.GPIO.setup(channel, state)
将标号为channel的针设置为state模式。
channel取值为1~26,state取值为RPi.GPIO.IN 或者 RPi.GPIO.OUT,分别表示输入和输出。例如 RPi.GPIO.setup(1, RPi.GPIO.IN)表示将1号针设置为输入模式;RPi.GPIO.setup(3, RPi.GPIO.OUT)表示将3号针设置为输出模式。具体哪个号是哪根取决于setmode()中设置成什么。
RPi.GPIO.output(channel, state)
将标号为channel的针设置为state指定的电平。
channel取值为1~26,state取值为RPi.GPIO.HIGH 和 RPi.GPIO.LOW,或者1和0,或者True和False,表示高电平和低电平。例如RPi.GPIO.output(1, 1) 表示把1号针设置为高电平,RPi.GPIO.output(3, Flase) 表示将3号针设置为低电平。具体哪个号是哪根取决于setmode()中设置成什么。
RPi.GPIO.input(channel)
获取将标号为channel的针的电平砖头。
channel取值为1~26。例如RPi.GPIO.input(1) 表示获取1号针的状态。
RPi.GPIO.cleanup()
清除掉之前RPi.GPIO.setup()设置的状态。
退出程序之前一定要调用,否则下次调用的时候会报错。
led.py模块说明
channel 中保存的是连接中使用的针的标号,按顺序。
init() 是初始化GPIO接口的代码,使用控制lcd去前要调用。主要工作是设置接口命名模式和 将 channel中的针设置为输出模式
on() / off() 是将channel 中第i个针设置为高电平/低电平
ctrl() 是根据参数设置全8根针的电平。参数的低0位、低1位、低2位…分别表示channel下标为0、1、2…的针的电平状况,1为高电平、0为低电平
test() 是测试函数。用8位二进制表示8个灯的状态,每隔0.1秒到下一个状态: 0000 0000, 0000 0001, 0000 0010, 0000 0011,0000 0100 … 实际上就是从0数到255
clean() 是对 RPi.GPIO.cleanup() 的一个封装