-
Notifications
You must be signed in to change notification settings - Fork 2
/
Software
93 lines (74 loc) · 2.64 KB
/
Software
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
int ledPin = 9; // LED connected to digital pin 9
int brightness = 0; // variable to store the read value
boolean stringStart = false; // whether the string is start
char delimiter_start = 's';
char delimiter_end = 'e';
String inputString = ""; // a string to hold incoming data
boolean stringComplete = false; // whether the string is complete
// *************************************************************************************
// ******************** Serial Event ******************************
// *************************************************************************************
void serialEvent() {
while (Serial.available()) {
// get the new byte:
char inChar = (char)Serial.read();
//start messege
if (!stringStart && inChar == delimiter_start) {
stringStart = true;
continue;
}
if (stringStart)
{
//echo
//Serial.print(inChar);
// add it to the inputString:
inputString += inChar;
// end messege
if (inChar == delimiter_end) {
stringComplete = true;
stringStart = false;
}
//check accumulated lengh of the massege
if(inputString.length() > 11) {
inputString = "";
stringStart = false;
}
}
}
}
// *************************************************************************************
// *************************************************************************************
// *************************************************************************************
void setup()
{
pinMode(ledPin, OUTPUT); // sets the pin as output
analogWrite(ledPin, 0); // analogRead values go from 0 to 1023, analogWrite values from 0 to 255
Serial.begin(9600);
inputString.reserve(10);
}
void loop()
{
if (stringComplete)
{
String command = inputString; //Serial.readString();
inputString = "";
stringComplete = false;
if (command[1] == delimiter_end)
{
brightness = (int(command[0]) - 48);
}
else if (command[2] == delimiter_end)
{
brightness = ((int(command[0]) - 48) * 10) + (int(command[1]) - 48);
}
else
{
brightness = ((int(command[0]) - 48) * 100) + ((int(command[1]) - 48) * 10) + (int(command[2]) - 48);
if (brightness > 255) brightness = 255;
}
//brightness = Serial.read();
Serial.print(String(delimiter_start) + String(brightness) + String(delimiter_end));
// set the brightness of the LED:
analogWrite(ledPin, brightness);
}
}