I am controlling multiple ESCs, and I don't use Servo Library. Separately, each of these void loops works perfectly but once I want to add more than one, there is a problem. I need to separate the loop because the delay of the following code will be have an effect to the loop before. If the earlier loop is HIGH-1300ms-LOW, and the following is HIGH-1300ms-LOW, then the earlier loop will become HIGH-1300ms-LOW-1300ms, before loopiing again, and this change the whole sequence of digital code. After I separated the code, it said "error, can't have more than one void loop", or so. How to fix this? Please help me, please. An example code is below.
void loop() {
//read potentiomenter pin analog value
int valSide = map (analogRead(potPinSide), 0, 1023, 1150, 1900);
//Set ESC high for valSide milliseconds, before dropping to low for one bit, and then high again, forever
digitalWrite(ESCside,HIGH);
delayMicroseconds(valSide);
digitalWrite(ESCside, LOW);
}
//do the same for the second esc
void loop() {
int valBack = map (analogRead(potPinBack), 0, 1023, 1150, 1900);
digitalWrite(ESCback,HIGH);
delayMicroseconds(valBack);
digitalWrite(ESCback, LOW);
}
You can't use delay() or delayMicroseconds() if you want things to run in parallel. Have look at how millis() is used to manage timing in Several Things at a Time. The same technique can be used with micros().
Why not take the easy way out and use the Servo library ?
loop() is just a standard C/C++ function that is called over and over. Having multiple functions with the code you already have would not solve the timing problem because the Arduino can only do one thing at a time.
the basic pattern is "what do I do now"? Each time through the loop, you look at the current millis() or even micros() and ask the question, "ok, I raised the pin at timestamp x millis. given that the time is now y millis, is it now time to lower the pin?"
And you do this for each thing needing attention.
Oh: I have a page ArduinoTheOOWay which … probably won't help. But I'll mention it anyway.
Suphanat, you put each ESC code inside of the same void loop()!
The two you show, here one will run then the other, over and over.
void loop() {
//read potentiomenter pin analog value
int valSide = map (analogRead(potPinSide), 0, 1023, 1150, 1900);
//Set ESC high for valSide milliseconds, before dropping to low for one bit, and then high again, forever
digitalWrite(ESCside,HIGH);
delayMicroseconds(valSide);
digitalWrite(ESCside, LOW);
}
int valBack = map (analogRead(potPinBack), 0, 1023, 1150, 1900);
digitalWrite(ESCback,HIGH);
delayMicroseconds(valBack);
digitalWrite(ESCback, LOW);
}