#define RED_BUTTON 2
#define GREEN_BUTTON 3
#define RED_LED 9
#define GREEN_LED 10
#define MOTOR 5
// values we will change with timers and interrupts
volatile bool motorOn = false;
volatile byte GREEN_STATE = LOW;
volatile byte RED_STATE = LOW;
void blink_green() {
GREEN_STATE = !GREEN_STATE;
}
void blink_red() {
RED_STATE = !RED_STATE;
}
ISR (TIMER1_COMPA_vect) {
motorOn = true;
OCR1A += 16250; // Update OCR1A for the next interrupt
}
void setup() {
cli(); // Disable global interrupts
// Timer1 configuration
TCCR1A = 0;
TCCR1B = 0;
TCCR1B |= (1 << WGM12); // CTC mode
TCCR1B |= (1 << CS12); // Prescaler 256
TCNT1 = 0;
OCR1A = 16250;
TIMSK1 |= (1 << OCIE1A) | (1 << TOIE1); // Enable Timer1 Compare A and overflow interrupts
sei(); // Enable global interrupts
Serial.begin(115200);
Serial.println("Program Start");
// Add the pin modes for the pins we will use
pinMode(RED_LED, OUTPUT);
pinMode(GREEN_LED, OUTPUT);
pinMode(GREEN_BUTTON, INPUT_PULLUP);
pinMode(RED_BUTTON, INPUT_PULLUP);
// add interrupts as they are more efficient
attachInterrupt(digitalPinToInterrupt(GREEN_BUTTON), blink_green, RISING);
attachInterrupt(digitalPinToInterrupt(RED_BUTTON), blink_red, RISING);
}
void loop() {
if (motorOn) {
analogWrite(MOTOR, 200); // Set motor speed
motorOn = false; // Reset motor state for next cycle
} else {
analogWrite(MOTOR, 0); // Stop motor
}
static int count = 0;
digitalWrite(RED_LED, RED_STATE);
digitalWrite(GREEN_LED, GREEN_STATE);
// Debug output
char buffer[50];
sprintf(buffer, "Count %d; Green Led: %d; Red Led: %d", count, GREEN_STATE, RED_STATE);
Serial.println(buffer);
// Reset the state after delay
RED_STATE = LOW;
GREEN_STATE = LOW;
count++;
delay(200);
}