可以通过树莓派自带的GPIO针脚控制诸如继电器或是其它控制器,来实现基础的“物联网”,来达到控制家中电器的目的。

关于GPIO针脚的说明介绍如下图:

从树莓派官方下载回来的Respbian自带的python环境中,内置了RPi.GPIO包,是对树莓派的GPIO针脚的操作库。

对其进行二次封装,简化了控制针脚电平的功能操作。

代码 GPIO.py :

#!/usr/bin/env python
#coding=utf-8

import RPi.GPIO

RPi.GPIO.setwarnings(False)
RPi.GPIO.setmode(RPi.GPIO.BOARD)

class GPIO:

	OUT = RPi.GPIO.OUT
	IN = RPi.GPIO.IN

	LOW = RPi.GPIO.LOW
	HIGH = RPi.GPIO.HIGH

	def set_high(self, G_PORT):
		try:
			RPi.GPIO.setup(G_PORT, self.OUT)
			if RPi.GPIO.input(G_PORT) == self.LOW:
				RPi.GPIO.output(G_PORT, self.HIGH)
			state = RPi.GPIO.input(G_PORT)
			RPi.GPIO.cleanup()

			return True, state
		except:
			return False, -1

	def set_low(self, G_PORT):
		try:
			RPi.GPIO.setup(G_PORT, self.OUT)
			if RPi.GPIO.input(G_PORT) == self.HIGH:
				RPi.GPIO.output(G_PORT, self.LOW)
				RPi.GPIO.setup(G_PORT, self.IN)
			state = RPi.GPIO.input(G_PORT)
			RPi.GPIO.cleanup()

			return True, state
		except:
			return False, -1

	def trigger(self, G_PORT):
		try:
			RPi.GPIO.setup(G_PORT, self.OUT)
			if RPi.GPIO.input(G_PORT) == self.LOW:
				result, state = self.set_high(G_PORT)
			else:
				result, state = self.set_low(G_PORT)
			RPi.GPIO.cleanup()

			return result, state
		except:
			return False, -1

	def get_state(self, G_PORT):
		try:
			RPi.GPIO.setup(G_PORT, self.OUT)
			state = RPi.GPIO.input(G_PORT)
			RPi.GPIO.cleanup()

			return True, state
		except:
			return False, -1

if __name__ == '__main__':
	gpio = GPIO()

	# 设置高电平
	gpio.set_high(7)

	# 设置低电平
	gpio.set_low(7)

	# 切换高低电平
	gpio.trigger(7)

	# 获取针脚当前电平状态
	gpio.get_state(7)