// Define pin for LED and push button
#define LED_PIN PA5 // LED pin
#define BUTTON_PIN PC13 // Button pin
#define stepPin D3 // Step pin for stepper motor
#define dirPin D5 // Direction pin for motor driver
#define enablePin D8 // Enable pin for motor driver
// Variables to count LED states
int ledOnCount = 0; // Counter for how many times LED has been on
int ledOffCount = 0; // Counter for how many times LED has been off
// Variables to store the previous state of the LED and button
bool ledState = LOW; // Initial LED state (off)
bool lastButtonState = HIGH; // Previous button state (HIGH because of pull-up)
// Stepper motor delay for speed control (lower value = faster speed)
int stepDelay = 500; // Delay in microseconds for step pulses
void setup() {
// Initialize pin modes
pinMode(LED_PIN, OUTPUT); // LED as output
pinMode(BUTTON_PIN, INPUT_PULLUP); // Button as input with internal pull-up
pinMode(stepPin, OUTPUT); // Step pin as output for stepper motor
pinMode(dirPin, OUTPUT); // Motor direction pin as output
pinMode(enablePin, OUTPUT); // Motor enable pin as output
// Serial monitor for debugging
Serial.begin(9600);
}
void loop() {
// Read the current button state
bool currentButtonState = digitalRead(BUTTON_PIN);
// Check if the button was pressed (transition from HIGH to LOW)
if (currentButtonState == LOW && lastButtonState == HIGH) {
// Toggle the LED state
ledState = !ledState;
// If the LED is turned on
if (ledState == HIGH) {
ledOnCount++; // Increment LED on counter
digitalWrite(dirPin, HIGH); // Set motor direction
digitalWrite(enablePin, HIGH); // Enable motor driver
Serial.print("LED and Motor ON Count: ");
Serial.println(ledOnCount);
// Generate steps manually with delays
for (int i = 0; i < 10; i++) { // Run for 1000 steps (or adjust as needed)
digitalWrite(stepPin, HIGH); // Set step pin HIGH
delayMicroseconds(stepDelay); // Wait for step delay
digitalWrite(stepPin, LOW); // Set step pin LOW
delayMicroseconds(stepDelay); // Wait for step delay
}
}
// If the LED is turned off
else {
ledOffCount++; // Increment LED off counter
digitalWrite(enablePin, LOW); // Disable motor driver
Serial.print("LED and Motor OFF Count: ");
Serial.println(ledOffCount);
}
// Set the LED according to its state
digitalWrite(LED_PIN, ledState);
}
// Save the button state for the next loop cycle
lastButtonState = currentButtonState;
// Delay for button debounce (to avoid reading multiple presses quickly)
delay(50);
}