Society of Robots - Robot Forum

Software => Software => Topic started by: jocatch on August 04, 2010, 03:50:15 PM

Title: Putting it all together
Post by: jocatch on August 04, 2010, 03:50:15 PM
As I learn and play with my new Arduino Mega and C  language, I am studying bits and pieces of C code (sonar, IR, line tracing, PWM, etc). (I am working on a small robot.)

But what I haven't seen much discussion on has been putting all these code fragments together into one master program for controlling a robot. I know there are things to consider like how much CPU time should be used to control, say, PWM and motors. Of course the program should loop but are there any ideas out like for program strategy and flow?

JC
Title: Re: Putting it all together
Post by: Razor Concepts on August 04, 2010, 04:00:14 PM
The "easy" method would be to go through a setup phase once, then loop through a code that goes to each item individually, like this:

Code: [Select]
int main(void)
{
setup_everything();
while(1)
{
readSonar();
readIR();
driveMotors();
}
}

That works well for 95% of programs.

But that does waste a lot of time as you mentioned - the sonar may only need reading once every second, but the IR every 0.1 seconds, so there is no need to go read the sonar that fast. So you use interrupts!

Code: [Select]
int main(void)
{
setup_everything();
enable_interrupts();
while(1)
{
   do_stuff_that_doesnt_need_interrupts();
}
}

interrupt_vector_sonar
{
do_sonar_stuff()
}

interrupt_vector_IR
{
do_IR_stuff
}

So the sonar interrupt can be set to trigger every 1 second, and the IR every 0.1 seconds. The while loop runs, and automatically after the correct interval passes, the code takes a brief little detour, executes the interrupt code, and returns back to the while loop.