Hello, I'm struggling with writing a code for my engineering project.
I managed to have the delay functions worked for the DC motor. However, I need help with the coding for the servo. I want to code a delay function to have the button pressed once, and wait for 8 seconds for the servo to sweep from 0 to 180 degrees.
Image attached below:
Here's my code:
// C++ code
//
const int buttonPin = 7;
int sensorPin = 7;
int sensorValue = 0;
#include <Servo.h>
int servoPin = 10;
Servo myservo;
int angle = 0;
int motorPin = 11;
int speed = 0;
// set button states
int buttonState = 0;
int lastbuttonState = LOW;
int currentbuttonState = HIGH;
// set motor states
int motorState1 = HIGH;
int motorState2 = LOW;
void setup()
{
Serial.begin(9600);
pinMode(buttonPin, INPUT);
Serial.println("The button is pressed once");
pinMode(servoPin, OUTPUT);
myservo.attach(servoPin);
myservo.write(angle);
currentbuttonState = digitalRead(buttonPin);
pinMode(motorPin, OUTPUT);
Serial.println("Speed 0 to 255");
}
void loop()
{
delay(1000); // wait for a second for motor to rotate
digitalWrite(motorPin, HIGH);
delay(27000); // wait for 27 seconds for motor to stop rotating
digitalWrite(motorPin, LOW);
delay(1000); // wait for a second for motor to stop rotating
exit(0);
buttonState = digitalRead(buttonPin);
lastbuttonState = currentbuttonState;
currentbuttonState = digitalRead(buttonPin);
if (lastbuttonState == LOW) {
digitalWrite(servoPin, HIGH);
if (angle == 0)
angle = 360;
else
myservo.write(angle);
delay(8000); // wait for 8 seconds for servo to sweep from 0 to 180 degrees
}
}