#include "TimedPin.h" TimedPin::TimedPin(uint8_t pin_id, bool inverted) { PinId = pin_id; PinInvert = inverted; TPinMode = TPM_OFF; OnTime = 0; OffTime = 0; } TimedPin::TimedPin() { PinId = 0xFF; TPinMode = TPM_OFF; OnTime = 0; OffTime = 0; } void TimedPin::begin() { if (PinId < 0xFF) pinMode(PinId, OUTPUT); PinOff(); } void TimedPin::update() { uint32_t t = millis(); int32_t tdif = t - RefTime; switch (TPinMode) { case TPM_OFF: break; case TPM_ON: break; case TPM_BLINK: { if (PinState) { // pin == on if (tdif >= OnTime) { // on time expired RefTime = t; PinOff(); // toggle pin } } else { // pin == off if (tdif >= OffTime) { // off time expired if (CycleCnt) { // cycle count defined: counting down if (--CycleCnt == 0) { // last cycle reached: TPinMode = TPM_OFF; // stop blinking break; } } RefTime = t; PinOn(); // toggle pin } } } break; case TPM_TIMED_ON: { if (tdif >= OnTime) { // on time expired PinOff(); TPinMode = TPM_OFF; } } break; case TPM_TIMED_OFF: { if (tdif >= OffTime) { // off time expired PinOn(); TPinMode = TPM_ON; } } break; default: { TPinMode = TPM_OFF; } break; } } void TimedPin::OffTimed(uint32_t t) { PinOff(); TPinMode = TPM_TIMED_OFF; RefTime = millis(); OffTime = t; } void TimedPin::OnTimed(uint32_t t) { PinOn(); TPinMode = TPM_TIMED_ON; RefTime = millis(); OffTime = t; } void TimedPin::Blink(uint32_t t_on, uint32_t t_off, uint16_t cycles) { if (TPinMode != TPM_BLINK) { TPinMode = TPM_BLINK; PinOn(); } RefTime = millis(); OnTime = t_on; OffTime = t_off; CycleCnt = cycles; } void TimedPin::On() { PinOn(); TPinMode = TPM_ON; } void TimedPin::Off() { PinOff(); TPinMode = TPM_OFF; } // ============================================================================= // Internal functions // ============================================================================= void TimedPin::PinOn() { PinState = true; if (PinId < 0xFF) digitalWrite(PinId, PinInvert ? LOW : HIGH); } void TimedPin::PinOff() { PinState = false; if (PinId < 0xFF) digitalWrite(PinId, PinInvert ? HIGH : LOW); }