-
Notifications
You must be signed in to change notification settings - Fork 0
/
sensor.py
56 lines (46 loc) · 1.39 KB
/
sensor.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
import RPi.GPIO as GPIO
from datetime import datetime
pin = 18 #Input pin of sensor (GPIO.BOARD)
GPIO.setmode(GPIO.BCM)
GPIO.setup(pin, GPIO.IN)
#Gets binary value
def getBinary():
#Internal vars
num1s = 0 #Number of consecutive 1s read
binary = 1 #The bianry value
command = [] #The list to store pulse times in
previousValue = 0 #The last value
value = GPIO.input(pin) #The current value
startTime = datetime.now()
while True:
#If change detected in value
if previousValue != value:
now = datetime.now()
pulseTime = now - startTime #Calculate the time of pulse
startTime = now #Reset start time
command.append((previousValue, pulseTime.microseconds)) #Store recorded data
#Updates consecutive 1s variable
if value:
num1s += 1
else:
num1s = 0
#Breaks program when the amount of 1s surpasses 10000
if num1s > 10000:
break
#Re-reads pin
previousValue = value
value = GPIO.input(pin)
#Converts times to binary
for (typ, tme) in command:
if typ == 1: #If looking at rest period
if tme > 1000: #If pulse greater than 1000us
binary = binary *10 +1 #Must be 1
else:
binary *= 10 #Must be 0
if len(str(binary)) > 34: #Sometimes, there is some stray characters
binary = int(str(binary)[:34])
return binary
#Conver value to hex
def convertHex(binaryValue):
tmpB2 = int(str(binaryValue),2) #Tempary propper base 2
return hex(tmpB2)