-
Notifications
You must be signed in to change notification settings - Fork 0
/
arduino_API.py
81 lines (61 loc) · 2 KB
/
arduino_API.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
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import serial
class API(object):
__OUTPUT_PINS = -1
def __init__(self, port, baudrate=9600):
self.serial = serial.Serial(port, baudrate, timeout = 5)
#self.serial.write(b'99')
def __str__(self):
return "Arduino_chip is on port %s at %d baudrate" %(self.serial.port, self.serial.baudrate)
def write(self, serial_data):
self.serial.write(serial_data)
def output(self, pinArray):
self.__sendData(len(pinArray))
if(isinstance(pinArray, list) or isinstance(pinArray, tuple)):
self.__OUTPUT_PINS = pinArray
for each_pin in pinArray:
self.__sendData(each_pin)
return True
def setLow(self, pin):
self.__sendData('0')
self.__sendData(pin)
return True
def setHigh(self, pin):
self.__sendData('1')
self.__sendData(pin)
return True
def getState(self, pin):
self.__sendData('2')
self.__sendData(pin)
return self.__formatPinState(self.__getData()[0])
def analogWrite(self, pin, value):
self.__sendData('3')
self.__sendData(pin)
self.__sendData(value)
return True
def analogRead(self, pin):
self.__sendData('4')
self.__sendData(pin)
return self.__getData()
def turnOff(self):
for each_pin in self.__OUTPUT_PINS:
self.setLow(each_pin)
return True
def __sendData(self, serial_data):
while(self.__getData()[0] != "w"):
pass
serial_data = str(serial_data).encode('utf-8')
self.serial.write(serial_data)
def __getData(self):
input_string = self.serial.readline()
input_string = input_string.decode('utf-8')
return input_string.rstrip('\n')
def __formatPinState(self, pinValue):
if pinValue == '1':
return True
else:
return False
def close(self):
self.serial.close()
return True