树莓派3(B)的引脚图
1.控制风扇随温度变化
import time
import RPi.GPIO as GPIO
GPIO.setmode(GPIO.BOARD)
pinFan = 40
pinBeep = 38
MAX_TEMP = 40
MAX_BEEP_TEMP = 60
GPIO.setup(pinBeep, GPIO.OUT)
GPIO.setup(pinFan, GPIO.OUT)
GPIO.output(pinBeep,GPIO.LOW)
GPIO.output(pinFan,GPIO.LOW)
def read_temp():
file = open("/sys/class/thermal/thermal_zone0/temp")
temp = float(file.read()) / 1000
file.close()
print "temp : %.1f" %temp
return temp
def toggle_fan(runable):
exe = GPIO.LOW
if runable :
exe = GPIO.HIGH
print "Fan is running"
GPIO.output(pinFan,exe)
def toggle_beep(runable):
exe = GPIO.LOW
if runable :
exe = GPIO.HIGH
GPIO.output(pinBeep,exe)
try:
while 1:
toggle_fan(False)
temp = read_temp()
if temp >= MAX_TEMP:
toggle_fan(True)
time.sleep(120)
temp = read_temp()
if temp >= MAX_BEEP_TEMP:
toggle_beep(True)
else:
toggle_fan(False)
toggle_beep(False)
time.sleep(3)
except KeyboardInterrupt:
pass
GPIO.cleanup()
2.树莓派控制Nrf24系列无线模组
# -*- coding: utf-8 -*-
from nrf24 import NRF24
import time
from time import gmtime, strftime
#设定从机的发送地址pipes[0],pipes[1],本机的发送pipes[0]
pipes = [[0x10, 0x10, 0x10, 0x10, 0x20], [0x10, 0x10, 0x10, 0x10, 0x22]]
radio = NRF24()
radio.begin(0, 0,25,18) #set gpio 25 as CE pin,gpio 18 as IRQ pin
radio.setRetries(15,15)
radio.setPayloadSize(32)
radio.setChannel(0x4c)
radio.setDataRate(NRF24.BR_250KBPS)
radio.setPALevel(NRF24.PA_MAX)
radio.setAutoAck(1)
radio.openReadingPipe(1, pipes[1])
radio.startListening()
radio.stopListening()
radio.printDetails()
radio.startListening()
while True:
pipe = [0] #pipe为接收到的信息的从机从机身份标识
while not radio.available(pipe, True):
time.sleep(100/1000000.0)
recv_buffer = []
radio.read(recv_buffer)
out = ''.join(chr(i) for i in recv_buffer)
print "Message from "+str(pipe[0])+":"+out
3.树莓派获取DHT11温湿度
#!/usr/bin/python
import RPi.GPIO as GPIO
import time
channel =4 #GPIO4
data = []
j = 0
GPIO.setmode(GPIO.BCM)
time.sleep(1)
GPIO.setup(channel, GPIO.OUT)
GPIO.output(channel, GPIO.LOW)
time.sleep(0.02)
GPIO.output(channel, GPIO.HIGH)
GPIO.setup(channel, GPIO.IN)
while GPIO.input(channel) == GPIO.LOW:
continue
while GPIO.input(channel) == GPIO.HIGH:
continue
while j < 40:
k = 0
while GPIO.input(channel) == GPIO.LOW:
continue
while GPIO.input(channel) == GPIO.HIGH:
k += 1
if k > 100:
break
if k < 8:
data.append(0)
else:
data.append(1)
j += 1
print "sensor is working."
print data
humidity_bit = data[0:8]
humidity_point_bit = data[8:16]
temperature_bit = data[16:24]
temperature_point_bit = data[24:32]
check_bit = data[32:40]
humidity = 0
humidity_point = 0
temperature = 0
temperature_point = 0
check = 0
for i in range(8):
humidity += humidity_bit[i] * 2 ** (7-i)
humidity_point += humidity_point_bit[i] * 2 ** (7-i)
temperature += temperature_bit[i] * 2 ** (7-i)
temperature_point += temperature_point_bit[i] * 2 ** (7-i)
check += check_bit[i] * 2 ** (7-i)
tmp = humidity + humidity_point + temperature + temperature_point
if check == tmp:
print "temperature :", temperature, "*C, humidity :", humidity, "%"
else:
print "wrong"
print "temperature :", temperature, "*C, humidity :", humidity, "% check :", check, ", tmp :", tmp
GPIO.cleanup()
4.也可以用pi4j来实现Java端开发
import com.pi4j.io.gpio.*;
/**
* Created by Oliver on 2016/11/23.
*/
public class Demo {
public static void main(String[] args) {
GpioController gpio = GpioFactory.getInstance();
//M1
GpioPinDigitalOutput pin22 = gpio.provisionDigitalOutputPin(RaspiPin.GPIO_22,"LED", PinState.LOW);
GpioPinDigitalOutput pin23 = gpio.provisionDigitalOutputPin(RaspiPin.GPIO_23,"LED", PinState.LOW);
//M2
GpioPinDigitalOutput pin24 = gpio.provisionDigitalOutputPin(RaspiPin.GPIO_24,"LED", PinState.LOW);
GpioPinDigitalOutput pin25 = gpio.provisionDigitalOutputPin(RaspiPin.GPIO_25,"LED", PinState.LOW);
while (true){
pin22.high();
pin23.low();
pin24.low();
pin25.high();
System.out.println("open");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
pin22.low();
pin23.high();
pin24.high();
pin25.low();
System.out.println("close");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
5.模拟将温湿度,PM2.5,等信息通过Socket传输
from simpletcp.clientsocket import ClientSocket
import threading
import queue
import time
import json
import random
HOST = "127.0.0.1"
PORT = 6969
queue = queue.Queue()
def getJsonStr(type,temp,hum,meth,pm2_5):
data = {
'time': time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time())),
'type':type,
'tem':temp,
'hum':hum,
'meth':meth,
'pm2_5':pm2_5
}
return json.dumps(data)
def sendThread():
c = ClientSocket(HOST, PORT, single_use=False)
for i in range(5):
str = getJsonStr(0,random.uniform(0,100),random.uniform(0,100),random.uniform(0,100),random.uniform(0,100))
c.send(str)
c.close()
threads = []
t1 = threading.Thread(target=sendThread)
threads.append(t1)
if __name__ == '__main__':
for t in threads:
t.start()
未完待续