i’m using the blink without delay to try and code a potentiometer to vary the speed of the blink:
int ledPin = 13;
int value = LOW;
long nextTime = 0;
long interval = 1000;
int offset(int duration) {
int newDuration;
int rate = analogRead(0);
newDuration = ((rate+512)/1023)*duration;
return (int)newDuration;
}
void setup()
{
pinMode(ledPin, OUTPUT);
}
void loop()
{
if (millis() > nextTime) {
nextTime = millis() + offset(interval);
if (value == LOW)
value = HIGH;
else
value = LOW;
digitalWrite(ledPin, value);
}
}
when it is going really fast, and you change the potentiometer to get a slower rate it works fine, but when it is going slow, the speed doesn’t change immediately because i have to wait for the next frame to come and then the speed gets updated. is there a way to avoid this?
Move the call to update the interval outside the update routine.
What you really want to do is constantly check the pot, and update the offset.
After that, check the time, and update LED state if its past due to change.
Untested code follows, but should be something similar to this:
int ledPin = 13;
void setup()
{
pinMode(ledPin, OUTPUT);
}
void loop()
{
int pot_Read;
int delay_in_ms;
int value = LOW;
long lastTime = 0;
int update_value;
while(1)
{
delay(1); //Let the analog stabilize a bit
pot_Read=analogRead(0);
delay_in_ms=map(pot_Read,0,1023,200,2000); //Our pot will select from 200ms to 2000ms
if (millis() > lastTime + long(delay_in_ms))
{
if (value == LOW)
value = HIGH;
else
value = LOW;
digitalWrite(ledPin, value);
lastTime=millis();
}
}
}