I have this code, which I am using with a potentiometer to control the speed of a automotive fuel injector. In it, I have specified how long the injector shall stay open by using the delay functions. However, whenever the code runs into a delay call, it pauses the whole code for that amount of time. Although it's not significantly long, it would still be better if it could keeping running analogInput and at the same time run through the if statements, without any interference from either. So basically run two different process simultaneously.
I remember reading somewhere that this is possible with threading? But do you need a library for that? I know Python has a threading library built in, and you can actually use it pretty easily, but what about Arduino? How could I run these two process at the same time?
Here's my code:
#define in1 12
void setup(){
Serial.begin(9600);
pinMode(in1, OUTPUT);
}
void loop(){
float rotationValue = analogRead(A1); //read raw input from potentiometer
float percentValue = rotationValue / 10.23; //convert to percent 0-100
Serial.println(percentValue); //print it to screen
if(percentValue >= 0.0 && percentValue <= 1.0){
digitalWrite(in1, LOW); //injector 1 off
}
else if(percentValue > 1.0 && percentValue <= 25.00){ //cycle at 100 millisec.
digitalWrite(in1, HIGH);
delay(100);
digitalWrite(in1, LOW);
delay(100);
}
else if(percentValue > 25.00 && percentValue <= 50.00){ //cycle at 50 millis.
digitalWrite(in1, HIGH);
delay(50);
digitalWrite(in1, LOW);
delay(50);
}
else if(percentValue > 50.00 && percentValue <= 75.00){ //cycle at 25 millis.
digitalWrite(in1, HIGH);
delay(25);
digitalWrite(in1, LOW);
delay(25);
}
else{ //cycle at 10 millis.
digitalWrite(in1, HIGH);
delay(10);
digitalWrite(in1, LOW);
delay(10);
}
}
analogRead()
and move to interrupt-based ADC operation. – Ignacio Vazquez-Abrams Dec 22 '14 at 20:19