/*
Uno with Scope https://github.com/Dlloydev/Wokwi-Chip-Scope
and https://github.com/Dlloydev/Wokwi-Chip-PWM
and https://github.com/drf5n/Wokwi-Chip-FrequencyCounter
Wokwi Uno https://wokwi.com/projects/390819301187622913
Wokwi Nano https://wokwi.com/projects/426440872904255489
Wokwi Mega: https://wokwi.com/projects/390819455604080641
Wokwi ESP32: https://wokwi.com/projects/408508221519641601
Wokwi ESP32S3 https://wokwi.com/projects/404720144387009537
See also https://wokwi.com/projects/359331973918199809
*/
/*
The monitors a pin for and if the changes are faster than a threshold,
recongnizes it as ACTIVE, and if not, INACTIVE
*/
const byte ACTIVE = 1;
const byte INACTIVE = 10;
int systemState = INACTIVE;
const byte IN_PIN = 2;
const byte ON_LED = 3;
const byte ACTIVE_LED = 4;
const uint32_t threshholdTimeMs = 1000UL / 10;
byte last_AC_state = -1;
uint32_t lastActivatedMs = -1;
uint32_t lastDeactivatedMs = -1;
uint32_t last_AC_ms = 0;
uint32_t lastOffPeriod = 0;
uint32_t lastOnPeriod = 0;
uint32_t now;
float duty = 0;
byte recalcDuty = 0;
// the setup function runs once when you press reset or power the board
void setup() {
// initialize digital pin LED_BUILTIN as an output.
pinMode(LED_BUILTIN, OUTPUT);
pinMode(ACTIVE_LED, OUTPUT);
pinMode(ON_LED, OUTPUT);
Serial.begin(115200);
}
// the loop function runs over and over again forever
void loop() {
now = millis();
byte ac_state = digitalRead(IN_PIN);
if (ac_state != last_AC_state) {
last_AC_ms = now;
last_AC_state = ac_state;
if (systemState == INACTIVE) {
systemState = ACTIVE;
lastActivatedMs = now;
lastOffPeriod = now - lastDeactivatedMs;
recalcDuty = true;
Serial.println("Activated");
}
}
if ((systemState == ACTIVE)
&& ((now - last_AC_ms) > threshholdTimeMs) ) {
systemState = INACTIVE;
lastDeactivatedMs = now;
lastOnPeriod = now - lastActivatedMs;
recalcDuty = true;
Serial.println("Deactivated");
}
if (recalcDuty) {
duty = float(lastOnPeriod) / (lastOnPeriod + lastOffPeriod);
Serial.print("\nDuty_st:");
Serial.print(duty);
recalcDuty = false;
}
report();
}
void report() {
const uint32_t period = 1000;
static uint32_t lastReportMs = -1;
float myDuty;
if ( now - lastReportMs > period ) {
uint32_t nowOnPeriod = now - lastActivatedMs;
uint32_t nowOffPeriod = now - lastDeactivatedMs;
switch (systemState) {
case ACTIVE:
myDuty = float(nowOnPeriod) / (lastOffPeriod + nowOnPeriod);
Serial.print(" ^");
break;
case INACTIVE:
myDuty = 1.0-float(nowOffPeriod) / (lastOnPeriod + nowOffPeriod);
Serial.print(" v");
break;
default:
Serial.print("default?");
}
//Serial.print(' ');
Serial.print(myDuty);
lastReportMs = now;
}
}
Wokwi UnoScope
https://wokwi.com/projects/390819301187622913
cnt/meas
en/!dis