Skip to content

Instantly share code, notes, and snippets.

@t3db0t
Created April 1, 2019 15:43
Show Gist options
  • Save t3db0t/44e6f538ac99e4b318b1a7feebaaf697 to your computer and use it in GitHub Desktop.
Save t3db0t/44e6f538ac99e4b318b1a7feebaaf697 to your computer and use it in GitHub Desktop.
A general schematic for an asynchronous timer on the Arduino. (Untested conceptual sketch)
// constants won't change. They're used here to set pin numbers:
const int motorPin = 4;
// int high_in_millisecond = 50; // how long 5V is sent (in ms)
// int low_in_millisecond = 500; // how long 0V is sent (in ms)
// variables will change:
// int motorState = LOW;
//int ledState = HIGH;
int switchPin = 8;
int data = 1;
int val = 0;
const motor_on_duration = 500; //ms, independent of heartbeat period
// beat FREQUENCY (v) is 1.333 beats per second. You want beat PERIOD, 1/v = 750ms
// Inverting beat frequency: (frequency would be 80/60, but we're taking the reciprocal so the whole thing is flipped)
// 60 seconds 1 minute
// ---- x ---- = .75 seconds = 750 ms
// 1 minute 80 beats
const beat_frequency = 80; // beats per minute
const beat_frequency_seconds = beat_frequency / 60;
const heartbeat_period = 1 / beat_frequency_seconds; // ms; i.e 1 / 1.333s = 0.75s = 750ms
// Stores 'timestamps'
unsigned long current_millis = 0;
unsigned long heartbeat_started = 0;
unsigned long motor_started = 0;
void setup() {
Serial.begin(9600);
pinMode(motorPin, OUTPUT);
pinMode(switchPin, INPUT);
}
void loop() {
// millis() gives a 'timestamp', the number of milliseconds since the processor was started
current_millis = millis();
if(current_millis - heartbeat_started >= heartbeat_period){
// Time to beat the heart, so to speak
// turn the motor on and start the motor timer
motor_started = current_millis;
digitalWrite(motorPin, HIGH);
heartbeat_started = current_millis; // reset the timer
}
if(current_millis - motor_started >= motor_on_duration){
// turn the motor off
digitalWrite(motorPin, LOW);
}
// val = digitalRead(switchPin); // read the input pin
// Serial.println (val);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment