Last active
September 5, 2021 23:29
-
-
Save billykwok/8ee27dd9146f0951d2552c0446f53b3c to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#define _TASK_MICRO_RES | |
#include <TaskScheduler.h> | |
#include <TaskSchedulerDeclarations.h> | |
#include <TaskSchedulerSleepMethods.h> | |
#define PWM_PERIOD 10000 | |
#define SAMPLING_FREQUENCY 150 | |
#define LED_BLUE LED_BUILTIN | |
#define LED_RED PIN_SPI_MISO | |
bool shouldBlink = true; | |
class Led { | |
bool high = false; | |
unsigned int pwmClock = 0; | |
uint8_t pin; | |
unsigned int phase; | |
public: | |
Led(uint8_t pin, unsigned int phase) : pin(pin), phase(phase) {} | |
void init() { pinMode(pin, OUTPUT); } | |
void on() { | |
high = true; | |
digitalWrite(pin, HIGH); | |
} | |
void off() { | |
high = false; | |
digitalWrite(pin, LOW); | |
} | |
static void blink(Led& led, Task& task, const TaskCallback& callback) { | |
if (shouldBlink) { | |
led.toggle(); | |
led.delay(task, callback); | |
} | |
} | |
private: | |
bool toggle() { | |
high = !high; | |
digitalWrite(pin, high ? HIGH : LOW); | |
return high; | |
} | |
void delay(Task& task, const TaskCallback& callback) { | |
pwmClock = (pwmClock + 1) % SAMPLING_FREQUENCY; | |
double dutyCycle = | |
0.5 * (1 + sin((pwmClock + phase) * 2 * PI / SAMPLING_FREQUENCY)); | |
task.setCallback(callback); | |
task.delay(PWM_PERIOD * (high ? dutyCycle : (1 - dutyCycle))); | |
} | |
}; | |
Scheduler ts; | |
Led ledBlue = Led(LED_BLUE, 0); | |
Led ledRed = Led(LED_RED, SAMPLING_FREQUENCY / 2); | |
void blinkBlue(); | |
void blinkRed(); | |
Task taskBlue(TASK_IMMEDIATE, TASK_FOREVER, &blinkBlue, &ts, true); | |
Task taskRed(TASK_IMMEDIATE, TASK_FOREVER, &blinkRed, &ts, true); | |
void blinkBlue() { Led::blink(ledBlue, taskBlue, &blinkBlue); } | |
void blinkRed() { Led::blink(ledRed, taskRed, &blinkRed); } | |
void setup() { | |
Serial.begin(9600); | |
ledBlue.init(); | |
ledRed.init(); | |
} | |
void loop() { | |
if (Serial.available()) { | |
String command = Serial.readStringUntil('\n'); | |
command.trim(); | |
command.toUpperCase(); | |
Serial.println("Rev: " + command); | |
if (command.equalsIgnoreCase("START") && !shouldBlink) { | |
shouldBlink = true; | |
Serial.println("Started..."); | |
} else if (command.equalsIgnoreCase("STOP") && shouldBlink) { | |
shouldBlink = false; | |
ledBlue.off(); | |
ledRed.off(); | |
Serial.println("Stopped..."); | |
} | |
} | |
ts.execute(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment