Skip to content

Commit aab67ce

Browse files
committed
feat: Add sample sketch for context usage
1 parent 7b9e3a0 commit aab67ce

File tree

1 file changed

+78
-0
lines changed

1 file changed

+78
-0
lines changed
Lines changed: 78 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,78 @@
1+
/*--------------------------------------------------------------------
2+
Author : Pedro Pereira
3+
License : BSD
4+
Repository : https://github.com/ppedro74/Arduino-SerialCommands
5+
6+
SerialCommands Simple Demo
7+
8+
--------------------------------------------------------------------*/
9+
#include <Arduino.h>
10+
#include <SerialCommands.h>
11+
12+
// Pin 13 has an LED connected on most Arduino boards.
13+
// Pin 11 has the LED on Teensy 2.0
14+
// Pin 6 has the LED on Teensy++ 2.0
15+
// Pin 13 has the LED on Teensy 3.0
16+
const int kLedPin = 13;
17+
18+
class SampleClass {
19+
20+
char serial_command_buffer_[32];
21+
SerialCommands serial_commands_(&Serial, serial_command_buffer_,
22+
sizeof(serial_command_buffer_), "\r\n", " ");
23+
uint8_t myAttribute;
24+
25+
public:
26+
// called for ON command
27+
void cmd_led_on(SerialCommands *sender) {
28+
29+
SampleClass *parent = static_cast<SampleClass *>(sender->context);
30+
parent->ledOnCounter++;
31+
sender->GetSerial()->print("Led was on ");
32+
sender->GetSerial()->print(parent->ledOnCounter);
33+
sender->GetSerial()->println("times");
34+
35+
digitalWrite(kLedPin, HIGH);
36+
sender->GetSerial()->println("Led is on");
37+
}
38+
39+
// called for OFF command
40+
void cmd_led_off(SerialCommands *sender) {
41+
digitalWrite(kLedPin, LOW);
42+
sender->GetSerial()->println("Led is off");
43+
}
44+
45+
// Note: Commands are case sensitive
46+
SerialCommand cmd_led_on_("ON", cmd_led_on);
47+
SerialCommand cmd_led_off_("OFF", cmd_led_off);
48+
};
49+
50+
void SampleClass() {
51+
ledOnCounter = 0;
52+
serial_commands_.context = this;
53+
serial_commands_.SetDefaultHandler(cmd_unrecognized);
54+
serial_commands_.AddCommand(&cmd_led_on_);
55+
serial_commands_.AddCommand(&cmd_led_off_);
56+
}
57+
void loop() { serial_commands_.ReadSerial(); }
58+
59+
// This is the default handler, and gets called when no other command matches.
60+
void cmd_unrecognized(SerialCommands *sender, const char *cmd) {
61+
sender->GetSerial()->print("Unrecognized command [");
62+
sender->GetSerial()->print(cmd);
63+
sender->GetSerial()->println("]");
64+
}
65+
66+
SampleClass sampleClass;
67+
68+
void setup() {
69+
Serial.begin(57600);
70+
71+
// Configure the LED for output and sets the intial state to off
72+
pinMode(kLedPin, OUTPUT);
73+
digitalWrite(kLedPin, LOW);
74+
75+
Serial.println("Ready!");
76+
}
77+
78+
void loop() { sampleClass.loop(); }

0 commit comments

Comments
 (0)