-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathcmd_set.cpp
102 lines (93 loc) · 2.21 KB
/
cmd_set.cpp
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
#include "arduino_cli.h"
/**
* Set output to a digital/analog pin
*/
void cmd_set(String *cmd, String *args) {
// Make sure cmd parameter isn't null
if(cmd == NULL) {
Serial.println("ERROR: 1st param of cmd_set must not NULL");
return;
}
// Show usage if there is no argument
if(args == NULL) {
help(cmd);
return;
}
// Prepare variables
String pinStr = "";
String valueStr = "";
// Tokenize arguments
byte argIndex = 0;
for(byte i = 0; i < args->length(); i++) {
char each = args->charAt(i);
if(each == ' ') {
if(argIndex >= 1) {
Serial.println("Excessive arguments");
Serial.println("");
help(cmd);
return;
} else {
argIndex++;
}
} else {
switch(argIndex) {
case 0:
pinStr += each;
break;
case 1:
valueStr += each;
break;
}
}
}
// Abort if not enough argument
if(argIndex < 1) {
Serial.println("Missing required argument");
Serial.println("");
help(cmd);
return;
}
// Parse pin string
byte pin = parsePin(&pinStr);
if(pin == PIN_INVALID) {
// CONDITION: Invalid Pin ID
Serial.println("Pin ID \"" + pinStr + "\" is not valid");
Serial.println("");
help(cmd);
return;
}
// Read and print the data
if(pinStr.charAt(0) == 'A') {
// CONDITION: Analog pin
// Parse value string
float value = valueStr.toFloat();
if(value == 0 && valueStr != "0") {
// CONDITION: Invalid value
Serial.println("Pin ID \"" + pinStr + "\" is analog, so the value must number");
Serial.println("");
help(cmd);
return;
}
// Write value
pinMode(pin, OUTPUT);
analogWrite(pin, value);
} else {
// CONDITION: Digital pin
if(valueStr == "on") {
pinMode(pin, OUTPUT);
digitalWrite(pin, HIGH);
} else if(valueStr == "off") {
pinMode(pin, OUTPUT);
digitalWrite(pin, LOW);
} else {
// CONDITION: Invalid value
Serial.println("Pin ID \"" + pinStr + "\" is digital, so the value must either on or off");
Serial.println("");
help(cmd);
return;
}
}
// Print response
Serial.println("ok");
Serial.println("");
}