// Presets for switch 1 to change direction
volatile bool state1 = 0; // 0 = CCW, 1 = CW
volatile bool SW1;
volatile bool preSW1 = 1; // preset = 1 to start at CW
void setup() {
// Set pin D3 as output (bit 4) and pin D2 as input (bit 3)
DDRD = 0b00001000;
// Enable pull-up resistor on pin D0 (bit 4)
PORTD = 0b00000100;
// Initialize serial communication at 9600 baud
Serial.begin(9600);
}
void loop() {
// Read the state of the switch connected to pin D2 (bit 4)
SW1 = ((PIND & (1 << 2)) >> 2);
// Detect a rising edge (switch release)
if (SW1 == 1 && preSW1 == 0) {
// Toggle the direction state
if (state1 == 0) {
state1 = 1;
// Set pin D3 high (LED On)
PORTD |= (1 << 3);
} else {
state1 = 0;
// Set pin D3 low (LED Off)
PORTD &= ~(1 << 3);
}
}
// Update previous switch state
preSW1 = SW1;
// Print current direction state for debugging
Serial.println(state1);
}