go_away

Author Topic: Putting it all together  (Read 770 times)

0 Members and 1 Guest are viewing this topic.

Offline jocatchTopic starter

  • Jr. Member
  • **
  • Posts: 29
  • Helpful? 0
Putting it all together
« 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

Offline Razor Concepts

  • Supreme Robot
  • *****
  • Posts: 1,856
  • Helpful? 53
Re: Putting it all together
« Reply #1 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.

 


Get Your Ad Here