The first thing you need to do is stop using delay().
Using delay() to control timing is probably one of the very first things you learned when experimenting with the Arduino. Timing with delay() is simple and straightforward, but it does cause problems down the road when you want to add additional functionality. The problem is that delay() is a "busy wait" that monopolizes the processor.
During a delay() call, you can’t respond to inputs, you can't process any data and you can’t change any outputs. The delay() ties up 100% of the processor. So, if any part of your code uses a delay(), everything else is dead in the water for the duration.
Remember Blink?
/* Blink Turns on an LED on for one second, then off for one second, repeatedly. This example code is in the public domain. */ // Pin 13 has an LED connected on most Arduino boards. // give it a name: int led = 13; // the setup routine runs once when you press reset: void setup() { // initialize the digital pin as an output. pinMode(led, OUTPUT); } // the loop routine runs over and over again forever: void loop() { digitalWrite(led, HIGH); // turn the LED on (HIGH is the voltage level) delay(1000); // wait for a second digitalWrite(led, LOW); // turn the LED off by making the voltage LOW delay(1000); // wait for a second }
The simple Blink sketch spends almost all of its time in the delay() function. So, the processor can't do anything else while it is blinking.
And sweep too?
Sweep uses the delay() to control the sweep speed. If you try to combine the basic blink sketch with the servo sweep example, you will find that it alternates between blinking and sweeping. But it won't do both simultaneously.
#include <Servo.h> // Pin 13 has an LED connected on most Arduino boards. // give it a name: int led = 13; Servo myservo; // create servo object to control a servo // twelve servo objects can be created on most boards int pos = 0; // variable to store the servo position void setup() { // initialize the digital pin as an output. pinMode(led, OUTPUT); myservo.attach(9); // attaches the servo on pin 9 to the servo object } void loop() { digitalWrite(led, HIGH); // turn the LED on (HIGH is the voltage level) delay(1000); // wait for a second digitalWrite(led, LOW); // turn the LED off by making the voltage LOW delay(1000); // wait for a second for(pos = 0; pos <= 180; pos += 1) // goes from 0 degrees to 180 degrees { // in steps of 1 degree myservo.write(pos); // tell servo to go to position in variable 'pos' delay(15); // waits 15ms for the servo to reach the position } for(pos = 180; pos>=0; pos-=1) // goes from 180 degrees to 0 degrees { myservo.write(pos); // tell servo to go to position in variable 'pos' delay(15); // waits 15ms for the servo to reach the position } }
So, how do we control the timing without using the delay function?
Page last edited October 27, 2014
Text editor powered by tinymce.