版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/guzhou_diaoke/article/details/89431124
1.模拟霍尔传感器
#/usr/bin/env python3
import RPi.GPIO as GPIO
import PCF8591 as ADC
import time
def setup():
ADC.setup(0x48)
def Print(x):
if x == 0:
print('')
print('*************')
print('* No Magnet *')
print('*************')
print('')
if x == 1:
print('')
print('****************')
print('* Magnet North *')
print('****************')
print('')
if x == -1:
print('')
print('****************')
print('* Magnet South *')
print('****************')
print('')
def loop():
status = 0
while True:
res = ADC.read(0)
print('Current intensity of magnetic field : ', res)
if res - 133 < 5 and res - 133 > -5:
tmp = 0
if res < 128:
tmp = -1
if res > 138:
tmp = 1
if tmp != status:
Print(tmp)
status = tmp
time.sleep(0.2)
if __name__ == '__main__':
setup()
loop()
2.模拟温度传感器
#!/usr/bin/env python3
import PCF8591 as ADC
import RPi.GPIO as GPIO
import time
import math
DO = 17
GPIO.setmode(GPIO.BCM)
def setup():
ADC.setup(0x48)
GPIO.setup(DO, GPIO.IN)
def Print(x):
if x == 1:
print('')
print('***********')
print('* Better~ *')
print('***********')
print('')
if x == 0:
print('')
print('************')
print('* Too Hot! *')
print('************')
print('')
def loop():
status = 1
tmp = 1
while True:
analogVal = ADC.read(0)
Vr = 5 * float(analogVal) / 255
Rt = 10000 * Vr / (5 - Vr)
temp = 1/(((math.log(Rt / 10000)) / 3950) + (1 / (273.15+25)))
temp = temp - 273.15
print('temperature = ', temp, 'C')
# For a threshold, uncomment one of the code for
# which module you use. DONOT UNCOMMENT BOTH!
#################################################
# 1. For Analog Temperature module(with DO)
#tmp = GPIO.input(DO);
#
# 2. For Thermister module(with sig pin)
if temp > 33:
tmp = 0;
elif temp < 31:
tmp = 1;
#################################################
if tmp != status:
Print(tmp)
status = tmp
time.sleep(0.2)
if __name__ == '__main__':
try:
setup()
loop()
except KeyboardInterrupt:
pass
3.声音传感器
#!/usr/bin/env python3
import PCF8591 as ADC
import RPi.GPIO as GPIO
import time
GPIO.setmode(GPIO.BCM)
def setup():
ADC.setup(0x48)
def loop():
count = 0
while True:
voiceValue = ADC.read(0)
if voiceValue:
print('Value:', voiceValue)
if voiceValue < 50:
print("Voice detected! ", count)
count += 1
time.sleep(0.2)
if __name__ == '__main__':
try:
setup()
loop()
except KeyboardInterrupt:
pass
4.光敏传感器
#!/usr/bin/env python
import PCF8591 as ADC
import RPi.GPIO as GPIO
import time
DO = 17
GPIO.setmode(GPIO.BCM)
def setup():
ADC.setup(0x48)
GPIO.setup(DO, GPIO.IN)
def loop():
status = 1
while True:
print('Value: ', ADC.read(0))
time.sleep(0.2)
if __name__ == '__main__':
try:
setup()
loop()
except KeyboardInterrupt:
pass