forked from lekum/pyduino
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpyduino.py
More file actions
90 lines (79 loc) · 2.83 KB
/
pyduino.py
File metadata and controls
90 lines (79 loc) · 2.83 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
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
"""
A library to interface Arduino through serial connection
"""
import serial
class Arduino():
"""
Models an Arduino connection
"""
def __init__(self, serial_port='/dev/ttyACM0', baud_rate=9600,
read_timeout=5):
"""
Initializes the serial connection to the Arduino board
"""
self.conn = serial.Serial(serial_port, baud_rate)
self.conn.timeout = read_timeout # Timeout for readline()
def set_pin_mode(self, pin_number, mode):
"""
Performs a pinMode() operation on pin_number
Internally sends b'M{mode}{pin_number} where mode could be:
- I for INPUT
- O for OUTPUT
- P for INPUT_PULLUP
"""
command = (''.join(('M',mode,str(pin_number)))).encode()
self.conn.write(command)
def digital_read(self, pin_number):
"""
Performs a digital read on pin_number and returns the value (1 or 0)
Internally sends b'RD{pin_number}' over the serial connection
"""
command = (''.join(('RD', str(pin_number)))).encode()
self.conn.write(command)
line_received = self.conn.readline().decode().strip()
header, value = line_received.split(':') # e.g. D13:1
if header == ('D'+ str(pin_number)):
# If header matches
return int(value)
def digital_write(self, pin_number, digital_value):
"""
Writes the digital_value on pin_number
Internally sends b'WD{pin_number}:{digital_value}' over the serial
connection
"""
command = (''.join(('WD', str(pin_number), ':',
str(digital_value)))).encode()
self.conn.write(command)
def analog_read(self, pin_number):
"""
Performs an analog read on pin_number and returns the value (0 to 1023)
Internally sends b'RA{pin_number}' over the serial connection
"""
command = (''.join(('RA', str(pin_number)))).encode()
self.conn.write(command)
line_received = self.conn.readline().decode().strip()
header, value = line_received.split(':') # e.g. A4:1
if header == ('A'+ str(pin_number)):
# If header matches
return int(value)
def analog_write(self, pin_number, analog_value):
"""
Writes the analog value (0 to 255) on pin_number
Internally sends b'WA{pin_number}:{analog_value}' over the serial
connection
"""
command = (''.join(('WA', str(pin_number), ':',
str(analog_value)))).encode()
self.conn.write(command)
if __name__ == '__main__':
import time
a = Arduino()
time.sleep(3)
a.set_pin_mode(13,'O')
a.set_pin_mode(12,'I')
time.sleep(1)
a.digital_write(13,1)
a.analog_write(5,245)
print(a.digital_read(12))
print(a.analog_read(2))
time.sleep(5)