I am currently doing a mini-project on top of a research assignment. I am using an ELEGOO "The most complete starter kit mega 2560 project."
I am not too familiar with Arduino coding and have only used an Arduino UNO once in the past. I downloaded the Arduino IDE software on my laptop. I am using a continuous servo motor and two push switch buttons. In the code I want the servo motor to always be on HIGH (on) until one of the push switch buttons is pressed. Once one of the switches is pressed I want it to delay for 15 seconds then rotate the other way and vice versa. Also, I want this looped so it just keeps running until I turn it off. Once I get this done maybe I might implement a third switch that turns off the code altogether. I feel like this should be simple but I could be wrong. I have a code written as well but am unsure if it is anywhere close to what it is supposed to do.
Here is the code I currently have. Please feel free to comment and suggest proper coding.
#include <Servo.h>
// Define servo and button pins
const int servoPin = 9;
const int button1Pin = 2;
const int button2Pin = 3;
Servo myServo;
void setup() {
// Attach servo to its pin
myServo.attach(servoPin);
// Set button pins as inputs with internal pull-up resistors
pinMode(button1Pin, INPUT_PULLUP);
pinMode(button2Pin, INPUT_PULLUP);
}
void loop() {
// Read the state of the buttons
int button1State = digitalRead(button1Pin);
int button2State = digitalRead(button2Pin);
// Check if button 1 is pressed
if (button1State == LOW) {
rotateServoClockwise();
delay(15000); // 15-second delay
rotateServoCounterClockwise();
}
// Check if button 2 is pressed
if (button2State == LOW) {
// Stop the servo when button 2 is pressed
myServo.write(90); // Center position
delay(100); // Small delay for stability
}
}
void rotateServoClockwise() {
// Rotate the servo clockwise
myServo.write(180);
}
void rotateServoCounterClockwise() {
// Rotate the servo counter-clockwise
myServo.write(0);
}
Hi this isn't really a school assignment. This is a mini project that I am doing on top of a research that I am doing that is chemistry-based. I want to make a functioning model.
I want it to rotate CW until switch one is pressed then 15 second delay, rotate CCW until switch two is pressed. I dont really know what I am doing. I tried my best writing this code. I am unsure if it is correct.
Waiting for a switch press while rotating a motor needs an interrupt or non-blocking motor movement. I think "Servo.h" creates blocking code during servo movement.