Hey guys
I'm trying to write a code which involves an LED, a button and a servo
The goal is that, at the start of the loop, the LED comes on and the servo gradually accelerates until it reaches a certain speed and then keeps turning at that pace.
Then, when the button is pressed, the LED and the servo have to turn off. After a random amount of time, the LED turns again on and the servo start to accelerate again up to that same speed.
I've managed to get the accelerating part to work, but then the button doesn't work.
Thanks!
long randNumber;
const int buttonPin = 2; // the number of the pushbutton pin
const int ledPin = 11; // the number of the LED pin
// variables will change:
int buttonState = 0; // variable for reading the pushbutton status
#include <Servo.h>
Servo myservo;
int pos = 0;
char val; //Data received from the serial port
int i = 0;
void setup() {
{
pinMode(ledPin, OUTPUT);
}
randomSeed (analogRead (0)); // randomize
pinMode(ledPin, OUTPUT); // sets the digital pin as output
myservo.attach(9);0;
// initialize the LED pin as an output:
pinMode(ledPin, OUTPUT);
// initialize the pushbutton pin as an input:
pinMode(buttonPin, INPUT);
Serial.begin(0);
// if analog input pin 0 is unconnected, random analog
// noise will cause the call to randomSeed() to generate
// different seed numbers each time the sketch runs.
// randomSeed() will then shuffle the random function.
randomSeed(analogRead(0));
}
void loop() {
buttonState = digitalRead(buttonPin);
if (buttonState == HIGH)
{
digitalWrite(ledPin, LOW);
delay(randNumber = random(3000, 7000));
Serial.println(randNumber);
}
else {
digitalWrite(ledPin, HIGH);
for (pos = 0; pos <= 180; pos += 5) {
myservo.write(pos); // tell servo to go to position in variable 'pos'
delay(30); // waits 15ms for the servo to reach the position
}
for (pos =180; pos >= 0; pos -= 5) {
myservo.write(pos); // tell servo to go to position in variable 'pos'
delay(100); // waits 15ms for the servo to reach the position
}
for (pos =0; pos <= 180; pos += 15) {
myservo.write(pos); // tell servo to go to position in variable 'pos'
delay(100); // waits 15ms for the servo to reach the position
}
for (pos =180; pos >= 0; pos -= 15) {
myservo.write(pos); // tell servo to go to position in variable 'pos'
delay(100); // waits 15ms for the servo to reach the position
}
for (pos = 0; pos <= 180; pos += 20) { // goes from 180 degrees to 0 degrees
myservo.write(pos); // tell servo to go to position in variable 'pos'
delay(150); // waits 15ms for the servo to reach the position
}
for (pos = 180; pos <= 0; pos -= 20) {
myservo.write(pos); // tell servo to go to position in variable 'pos'
delay(150); // waits 15ms for the servo to reach the position
}
}
while (buttonState == LOW) {
for (pos = 0; pos <= 180; pos += 20) {
myservo.write(pos); delay(150);
for (pos = 180; pos >= 0; pos - 20) {
myservo.write(pos);
delay(150);
}
}
}
}
button_random_delay_zoveelste.ino (2.79 KB)