forked from tdicola/AutoColorTemp
- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathArduinoHardware.py
More file actions
Latest commit
44 lines (36 loc) · 1.36 KB
/
Copy pathArduinoHardware.py
File metadata and controls
44 lines (36 loc) · 1.36 KB
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
importlogging
importtime
importserial
log=logging.getLogger(__name__)
classArduinoHardware(object):
"""Communicate with color sensor attached to an Arduino on a serial port."""
def__init__(self, port):
# Open the serial connection.
self.serial=serial.Serial(port, 115200, timeout=5)
# Wait a few seconds for the Arduino to reset and swallow any data
# received. This is necessary because the color sensor Arduino library
# writes some data to serial on startup and will interfere with later calls.
time.sleep(3.0)
self.serial.flushInput()
defget_color(self):
"""Return tuple of RGB color (with float components, 0-1.0) read from Arduino."""
# Clear input buffer and send a question mark character.
self.serial.flushInput()
self.serial.write('?')
self.serial.flush()
log.info('Sent question command.')
# Parse the response line for 3 color components.
line=self.serial.readline()
iflineisNone:
raiseRuntimeError('Received no data from serial readline().')
components=line.strip().split(',')
ifcomponentsisNoneorlen(components) !=3:
raiseRuntimeError('Error parsing response line: {0}'.format(line))
# Return RGB values.
r=float(components[0])
g=float(components[1])
b=float(components[2])
return (r, g, b)
defclose(self):
"""Close the connection with the sensor hardware."""
self.serial.close()