-
Notifications
You must be signed in to change notification settings - Fork 0
/
i2c.py
107 lines (81 loc) · 2.32 KB
/
i2c.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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
#!/usr/bin/env python
# coding=utf-8
import locale
from math import sqrt
import smbus
import time
import curses
import sys
locale.setlocale(locale.LC_ALL, '')
# CLI experiments
# 2014-08-26 PCF8591-x.py
# Connect Pi 3V3 - VCC, Ground - Ground, SDA - SDA, SCL - SCL.
# ./PCF8591-x.py
def length(a):
return sum([x > 0 for x in a])
def mean(a):
return sum(a) / length(a)
def std(a):
m = mean(a)
return sqrt(sum([(x - m) * (x - m) for x in a])) / length(a)
bus = smbus.SMBus(1)
fs = 25
measure_time = 1000 # milliseconds
calibration = False
scr = curses.initscr()
curses.noecho()
curses.cbreak()
aout = 0
scr.addstr(6, 0, "Measure Time: ")
scr.addstr(8, 0, "Calibration: ")
scr.addstr(10, 0, "Brightness")
# scr.addstr(12, 0, "Temperature")
# scr.addstr(14, 0, "AOUT->AIN2")
# scr.addstr(16, 0, "Resistor")
scr.addstr(18, 0, "Output")
scr.nodelay(1)
brightness = [0] * (measure_time / fs)
pointer = 0
total_count = 0
low_brightness = 0
high_brightness = 0
try:
while True:
total_count += 1
for a in range(0, 4):
bus.write_byte_data(0x48, 0x40 | ((a + 1) & 0x03), aout)
v = bus.read_byte(0x48)
if a == 0: # brightness
brightness[pointer] = v
pointer += 1
pointer %= measure_time / fs
if calibration:
if low_brightness == 0 and total_count > 2 * (measure_time / fs):
low_brightness = mean(brightness)
aout = 60
if high_brightness == 0 and total_count > 4 * (measure_time / fs):
high_brightness = mean(brightness)
aout = 0
scr.addstr(10, 12, '%d ± %.2f' % (mean(brightness), std(brightness)))
scr.addstr(18, 12, str(aout) + ' ')
scr.addstr(6, 15, '%.2f s.' % (float(measure_time) / 1000))
scr.addstr(8, 15, '%d - %d' % (low_brightness, high_brightness))
scr.refresh()
time.sleep(1 / float(fs))
c = scr.getch()
if c == ord('+'):
aout += 1
if aout > 255:
aout = 255
elif c == ord('-'):
aout -= 1
if (aout < 0):
aout = 0
elif c != curses.ERR:
break
except:
print "Unexpected error:", sys.exc_info()[0]
raise
curses.nocbreak()
curses.echo()
curses.endwin()