Skip to content

Commit

Permalink
feat: Add sample sketch for context usage
Browse files Browse the repository at this point in the history
  • Loading branch information
arcadien committed Nov 6, 2023
1 parent 7b9e3a0 commit aab67ce
Showing 1 changed file with 78 additions and 0 deletions.
78 changes: 78 additions & 0 deletions examples/SerialCommandsSimpleContext/SerialCommandsSimple.ino
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
/*--------------------------------------------------------------------
Author : Pedro Pereira
License : BSD
Repository : https://github.com/ppedro74/Arduino-SerialCommands
SerialCommands Simple Demo
--------------------------------------------------------------------*/
#include <Arduino.h>
#include <SerialCommands.h>

// Pin 13 has an LED connected on most Arduino boards.
// Pin 11 has the LED on Teensy 2.0
// Pin 6 has the LED on Teensy++ 2.0
// Pin 13 has the LED on Teensy 3.0
const int kLedPin = 13;

class SampleClass {

char serial_command_buffer_[32];
SerialCommands serial_commands_(&Serial, serial_command_buffer_,
sizeof(serial_command_buffer_), "\r\n", " ");
uint8_t myAttribute;

public:
// called for ON command
void cmd_led_on(SerialCommands *sender) {

SampleClass *parent = static_cast<SampleClass *>(sender->context);
parent->ledOnCounter++;
sender->GetSerial()->print("Led was on ");
sender->GetSerial()->print(parent->ledOnCounter);
sender->GetSerial()->println("times");

digitalWrite(kLedPin, HIGH);
sender->GetSerial()->println("Led is on");
}

// called for OFF command
void cmd_led_off(SerialCommands *sender) {
digitalWrite(kLedPin, LOW);
sender->GetSerial()->println("Led is off");
}

// Note: Commands are case sensitive
SerialCommand cmd_led_on_("ON", cmd_led_on);
SerialCommand cmd_led_off_("OFF", cmd_led_off);
};

void SampleClass() {
ledOnCounter = 0;
serial_commands_.context = this;
serial_commands_.SetDefaultHandler(cmd_unrecognized);
serial_commands_.AddCommand(&cmd_led_on_);
serial_commands_.AddCommand(&cmd_led_off_);
}
void loop() { serial_commands_.ReadSerial(); }

// This is the default handler, and gets called when no other command matches.
void cmd_unrecognized(SerialCommands *sender, const char *cmd) {
sender->GetSerial()->print("Unrecognized command [");
sender->GetSerial()->print(cmd);
sender->GetSerial()->println("]");
}

SampleClass sampleClass;

void setup() {
Serial.begin(57600);

// Configure the LED for output and sets the intial state to off
pinMode(kLedPin, OUTPUT);
digitalWrite(kLedPin, LOW);

Serial.println("Ready!");
}

void loop() { sampleClass.loop(); }

0 comments on commit aab67ce

Please sign in to comment.