-
Notifications
You must be signed in to change notification settings - Fork 34
/
arduino.pde
151 lines (123 loc) · 2.33 KB
/
arduino.pde
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
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
// variable to store the data from the serial port
int cmd = 0;
// command arguments
int cmd_arg[2];
int serialStatus = 0;
void setup() {
// connect to the serial port
Serial.begin(115200);
setupPins();
serialStatus = 1;
}
void loop()
{
if(serialStatus==0)
{
Serial.flush();
setupPins();
}
askCmd();
{
if(Serial.available()>0)
{
cmd = int(Serial.read()) - 48;
if(cmd==0) //set digital low
{
cmd_arg[0] = int(readData()) - 48;
digitalWrite(cmd_arg[0],LOW);
}
if(cmd==1) //set digital high
{
cmd_arg[0] = int(readData()) - 48;
digitalWrite(cmd_arg[0],HIGH);
}
if(cmd==2) //get digital value
{
cmd_arg[0] = int(readData()) - 48;
cmd_arg[0] = digitalRead(cmd_arg[0]);
Serial.println(cmd_arg[0]);
}
if(cmd==3) // set analog value
{
Serial.println("I'm in the right place");
cmd_arg[0] = int(readData()) - 48;
cmd_arg[1] = readHexValue();
analogWrite(cmd_arg[0],cmd_arg[1]);
}
if(cmd==4) //read analog value
{
cmd_arg[0] = int(readData()) - 48;
cmd_arg[0] = analogRead(cmd_arg[0]);
Serial.println(cmd_arg[0]);
}
if(cmd==5)
{
serialStatus = 0;
}
}
}
}
char readData()
{
askData();
while(1)
{
if(Serial.available()>0)
{
return Serial.read();
}
}
}
//read hex value from serial and convert to integer
int readHexValue()
{
int strval[2];
int converted_str;
while(1)
{
if(Serial.available()>0)
{
strval[0] = convert_hex_to_int(Serial.read());
break;
}
}
askData();
while(1)
{
if(Serial.available()>0)
{
strval[1] = convert_hex_to_int(Serial.read());
break;
}
}
converted_str = (strval[0]*16) + strval[1];
return converted_str;
}
int convert_hex_to_int(char c)
{
return (c <= '9') ? c-'0' : c-'a'+10;
}
void askData()
{
Serial.println("?");
}
void askCmd()
{
askData();
while(Serial.available()<=0)
{}
}
void setupPins()
{
while(Serial.available()<1)
{
// get number of output pins and convert to int
cmd = int(readData()) - 48;
for(int i=0; i<cmd; i++)
{
cmd_arg[0] = int(readData()) - 48;
pinMode(cmd_arg[0], OUTPUT);
}
break;
}
}