PDA

View Full Version : Code to control 4 LEDs and 2 servos



The Master
- 26th November 2008, 12:11
Hi, I finally got around to testing this again and i now have working code. Its not quite finished but it works so i thought id share it with everyone. This code controlls 4 LEDs and 2 servos and is controlled by a serial connection.

The first thing i changed was the interrupts. Instead of using ON INTERRUPT i check the flags manually in the loop. There is a good reason for this. It lets me have more control over what events have a higher priority and it removes all that extra code that ON INTERRUPT adds in.

My servos seem a little different to most. Ive read a few webpages that say the pulse is between 1ms and 2ms with an 18ms pause. My servo ranges from about 590us to 2222us and seems happy with a pause of anything between 2ms and 30ms. I wanted it to be as accurate as possible so i decided to alternate between servos. A pulse gets sent to servo1 then after 9ms a pulse gets sent to servo2.

The timing for the servo pulses is controlled by TMR1. Because im not using interrupts it could be a while before the chip gets around to checking the interrupt flag for TMR1's overflow. The solution is to jump into a seperate loop that only checks that 1 flag. Because i dont want to miss any serial data i only jump into that loop 38.4us before the server should be turned off.

The LED code is pretty much the same as it was before. Every time TMR0 overflows it decrements a variable. When that variable is equal to or below the value for each of the LEDs it turns that LED output on then turns them all back off again when it reaches 0.

The code works really well. The servos can move over 180 degrees without twitching. The LEDs fade properly without flickering and no serial data gets lost. Im sure theres a better way of doing it but thats what i came up with. If anyone has any better ideas i would like to see how you would do it.

I apologise for not being very good at explaining things :P

mackrackit
- 26th November 2008, 13:28
Should have posted this in the Code Example section.

The explanations are fine. You tell the problems and work a rounds.

Nice project.

The Master
- 26th November 2008, 13:33
Should have posted this in the Code Example section.

Sorry, i didnt see that forum. Would someone mind moving this thread please?