Wednesday, March 28, 2012

How To Connect A Servo To Arduino


Servo problems seem to be one of the most commonly recurring topics in the Arduino world. This post will address some of the most common pitfalls in driving one or more servos from an Arduino.

   1) The Basics
   2) Code
   3) Power
   4) Multiple Servos - High Performance Battery Power

For driving multiple servos, as a first step to trouble shooting its still worth checking each servo individually with the procedure outlined in the basics below -

1) The Basics

Lets start with the real basics - does your servo work with the Sweep example ? If so skip to part 2), if not,  still skip to part 2), if your not sure because you haven't tried it, read on and try now.

The sweep example is in the Arduino IDE, check the 'examples' menu, under 'servo' you should see two examples, 'knob' and 'sweep'. Load sweep and upload it to your Arduino.

Disconnect your Arduino and build the following circuit before reconnecting it to power.

Using a bread board - 

1) Connect the red wire from the servo to the 5V pin of your Arduino.
2) Connect the black ground wire from the servo to one of the ground (GND) pins on your Arduino
3) Connect the signal (normally white or yellow) wire from the servo to pin 9 of your Arduino

Note that in the picture below I have used a 3-Pin male header as an easy way to connect the female servo to the female bread board.



Now add power and your servo should be sweeping back and forth. If not, check 1-3, double check 1-3 and try again. If your still not having any success, is your circuit stripped back so that it is just the Arduino and the servo as in the picture ? If it isn't try stripping it back and just test the Arduino and the Servo on thier own.

If it is still not working with just the Arduino and servo connected, it is possible that your servo is damaged or pin 9 is damaged.

Try another servo or edit the following line in the code to use another pin -

myservo.attach(9);  // attaches the servo on pin 9 to the servo object

Disconnect your servo from pin 9 and connect it to the new pin. If its still not working, the servo may be damaged.

To test multiple servos simultaneously use the multi sweep code here -

http://rcarduino.blogspot.com/2012/01/can-i-control-more-than-x-servos-with.html


One of the reasons for a lot of the confusion is that servos are quite happy working with the 5 Volts available from an Arduino, but what is most often overlooked is the Amps. Servos like Amps, lots of Amps.

Many Arduinos are powered through onboard regulators or USB sockets that are limited to one Amp or less. This is sufficient to drive an Arduino and one servo that is not acting against a load. When this same servo is installed in a project with other components or is acting against a load, the project as a whole may drawn several amps at which point the Arduino will at best brown out.

If your servo passes the test suggested in part 1) The Basics, but still causes problems in your project it could be down to 1) Your wiring, 2) Your code, 3) Your power supply.

2) Your Code


To determine if the cause is power or your code try the following -

Add A Test Servo To Your Code. 

This test servo will tell us whether we have sufficient power, or the problem is in the code.


To do this, copy the line of code that creates your original servo and edit it by adding the word test -

Servo myServo;
Servo myServoTest;

Now in your setup function copy the line that attaches your original servo and edit it to copy the name of our test servo and change the pin number to a free pin -

myServo.attach(9);

myServoTest.attach(10);

At this point we have created a new servo within our code and the servo library will be doing its job by instructing the test servo to maintain the center position. We will use this as a test.

Disconnect the servo signal wire from pin 9 (or whatever pin its connected to in your project) and reconnect it to the test servo pin (pin 10 in our case).

If you project still misbehaves, its is either your wiring or your power supply. If however your project remains stable and the servo resists pressure to turn -i.e. is on and centered then the problem is very likely in your code.


3) Power Supply

If you have reached this point the possibilities are likely 1) Wiring 2) Power Supply

At the start of part 2 we discussed how servos within a project can combine with the project as a whole to draw more current than the Arduino Regulator or USB socket can supply.

One common approach is to try and power the Servo directly from a battery, while the basic idea is correct, there are some common mistakes here -

Common Battery Pitfalls -

1) The servo power supply and the Arduino power supply must share the same ground connection. If the two power supplies are not connected to a common (shared) ground, your project will not work. This is a very common mistake, so check yours now.

Refer to the previous picture if you need to.

2) Servos are normally rated to work with 4.8 to 6 volts. A common mistake is to try and power a servo directly with a 9v battery, this can damage the servo as unlike the Arduino, the servo does not have an on board regulator to bring this down to a usable 5 Volts.

There are several low cost and low performance options here, one is to build a quick regulator circuit using a 7805 regulator or similar. This will give upto 1 Amp at 5 volts and can be driven from a 9V Square battery. 

Its okay for simple projects, but low cost, low performance. Don't forget to connect the (-) ground of the regulator with the ground of the Arduino.

Another option is to build a small dedicated battery pack from 4 or 5 AA rechargeable nimh batteries ( 4 * 1.2 = 4.8 Volts, 5 * 1.2 = 6 Volts) or 4 AA high power batteries (4 * 1.5 = 6 Vlts) , again this is low cost and low performance and can drive the servo directly provided it shares a common group with the Arduino.

Another option is a dedicated high performance battery, if your project includes several servos or shields you might have no choice but to take this option. If your project does not need to be portable an adjustable lab power supply is the best option and you can stop reading here.


High Performance Battery Power

If your planning a mobile or portable project that you know will require reasonable power you might want to consider this next option.


 8.4 Volt LIPO Battery from my RC Race cars and a corner store 9V Square Battery.


Servos can require more current (remember those Amps) than a corner store battery can deliver. In the world of radio controlled models where high currents are required for racing and flight, the preferred battery technologies are NIMH and LIPO. Unfortunately these batteries tend to be available in odd voltages like 7.2 and 8.4.

As we discussed under 'Common Battery Pitfalls' connecting a standard servo to voltages higher than 6 Volts can cause permanent damage. In fact when 8.4 volt LIPO batteries first become popular a lot of people who had been getting away with running their servos at lower voltages suddenly found themselves with burnt out servos.

There are readily available solutions for getting a stable 5 volts of high current from these performance batteries in the form of 'regulators'. These regulators differ from the one supplied on the Arduino board in that they are designed to supply enough current to drive multiple servos. A quick scan of an online hobby store shows one available for 12 dollars that supplies upto 6 Amps, enough for at least 6 Servos, many more if the loads will be light.

One Battery, One Regulator, Lots of Servos, Add Arduino and Go !


At this point, you may be thinking, yes but I don't want to invest in a regulator or battery until I know my project works. This is a chicken and egg situation, your project is unlikely to ever go anywhere without sufficient power. My recommendation is to get the power sorted.

Any other way ?

If your project doesn't need to be portable you can source a variable voltage power supply that will deliver 5 Volts and all the Amps that you need. Note that the 'wall wart' type power supplies which you probably already have around the house are not likely to supply the current you need at a stable voltage, they are easy to overheat and pose a fire risk if they do. Look at a purpose designed adjustable power supply.

That covers the most common mistakes, I hope it has helped however if you are still stuck and have tried each of the tests and suggestions all is not lost, you can still ask for help from the Arduino community in the knowledge that you have covered all the basics.

Duane B.






Friday, March 23, 2012

Need More Interrupts To Read More RC Channels ?

One limitation of the Arduino platform is that it only supplies two external interrupts, yet many RC Systems support 8 or more channels. Even in a two channel system you may want additional interrupts to handle inputs, so what can we do to interface an Arduino with these additional channels and sensors ?

The answer is to use the ATMega Pin Change Interrupt facility. If you want to read up on it, its covered in the datasheet, however you will quickly find that its limited.

Limitations of Pin Change Interrupts - 

1) The interrupt is handled per port, so groups of pins share a single interrupt handler
2) You will need to write your own code to work out which of the group of pins caused the interrupt
3) The interrupt is triggered for any pin change so you have no control over the interrupt 'sense' as you do with the Arduino function attachInterrupt which supports the following - RISING, CHANGE, FALLING and LOW senses.

It is possible to code around these limitations to build equivalent functionality to the 2 standard interrupts, and that is just what a group has been collaborating to produce. The pinChangeInt library provides near identical functionality to the built in interrupts (INT0,INT1) but provides this function for any of the Arduino IO pins, this gives us up to a total of 21 external interrupts.

Features of PinChangeInt - 

1) Available as a library to download from google code group
2) Provides individual interrupt handler functions for upto 21 external interrupts
3) The pin number is available for access inside the interrupt handler
4) The pin state is available inside the interrupt handler
5) The functionality is near identical with the Arduino attachInterrupt function including the ability to set the interrupt sense (RISING,FALLING,CHANGE,LOW)

So how do we use this library ?

Part 1) Installation

1) Download the zip file from the google code group http://code.google.com/p/arduino-pinchangeint/
2) Copy the three directories cppfix, MemoryFree and PinChangeInt into the libraries folder of your Arduino directory, mine is here - 'C:\arduino-1.0-windows\arduino-1.0\libraries\PinChangeIn'

Part 2) Adding the library to a project

1) To add the library to a project, open the project in the IDE
2) In the 'Sketch' menu you should see a menu item 'Import Library'
3) Select import library and you should see a drop down list of the libraries you have installed, from this list select 'pinChangeInt'
4) You should now see the line #include <PinChangeInt.h> added near the start of you sketch

The library is now installed and included in your project ready for use.

Using and Comparing PinChangeInt with Arduino attachInterrupt

The project group have worked hard in designing the library to work just like the built-in attachInterrupt function. The only major difference in usage is that PCIntPort::attachInterrupt is defined as a static member function of a class PCIntPort. This class does the work of figuring out which interrupt service routine to call for which pin. The use of a static function within a class means that we need to call the attachInterrupt function with the following syntax PCintPort::attachInterrupt.

If your interested to see the work that is being done for you, open the PinChangeInt.h file in a text editor and have a look.


Usage Comparison

// standard Arduino attachInterrupt function
attachInterrupt(THROTTLE_IN_PIN,captThrottle,CHANGE);
attachInterrupt(STEERING_IN_PIN,captSteering,CHANGE);
// stop here, cant add any more channels, 
// we have used all 2 of our external interrupts !
 

// PinChangeInt library attachInterrupt function
PCintPort::attachInterrupt(THROTTLE_IN_PIN, calcThrottle,CHANGE);
PCintPort::attachInterrupt(STEERING_IN_PIN, calcSteering,CHANGE);
PCintPort::attachInterrupt(AUX_IN_PIN, calcAux,CHANGE);
 
PCintPort::attachInterrupt(FRONT_LEFT_PIN, captFrontLeft,RISING);
PCintPort::attachInterrupt(FRONT_RIGHT_PIN, captFrontRight,RISING);
PCintPort::attachInterrupt(REAR_LEFT_PIN, captRearLeft,RISING);
PCintPort::attachInterrupt(REAR_RIGHT_PIN, captRearRight,RISING);
// we can keep on going until we run out of pins
// or need to keep some pins for outputs !


Whats the cost ?

Using the prefix PCIntPort:: seems like a very low price to pay for getting access to ten times as many interrupts.

There must be some cost right ?

No, not really.

I have tested the library performance by using the Servo library to generate two servo signals. One of the servo signals goes to four Arduino pins to represent one each of the wheel speed sensors on my traction control project. The other servo signal is fed to three Arduino pins to represent the throttle, steering and auxiliary channels of my RC Transmitter. The impact of monitoring these seven inputs using the pinChangeInt library was measured at less than one percent (0.7%) of the available Arduino processing power.

I double checked the results with a quick calculation - 

The maths - 

Servo signal frequency 50Hz
Number of servo inputs 7
Number of interrupts  = 50 * 7 * 2 (2 = one for rising edge, one for  falling edge)

=  700 interrupts per second

Available Arduino Instructions in 1 second = 16,000,000
Possible available instructions per interrupt = 16,000,000/700 = 22,857

Measured impact using a timer and a busy loop suggested a 0.7% impact on available processing power while processing 700 pin change interrupts per second.

0.7% of 22,857 = 68.5 which suggests around 68 instructions are used to handle each pin change interrupt using the pinChangeInt library.

Conclusion

The minimal impact of the pinChangeInt library is a very reasonable trade off for access to more than 20 external interrupts.

Update: In subsequent tests, the performance impact of attaching an interrupt with PCintPort::attachInterrupt has been measured to be near negligible. In the worst case test there was a 5% overhead (over INT0,INT1 ), in the best case it was actually 15% faster. This out performance of PCintPort happens when one or more interrupts trigger more or less at the same instant. The pinChangeInt library is able to handle these within a single hardware interrupt. It will loop through the pins that have changed calling the user supplied interrupt service routines before passing control back to the hardware. This is more efficient than completing a single routine and then passing control back to the hardware each time. Note that this is a special case and most applications will not see any advantage from this. 

Notes - 

1) The interrupt service routing used in testing is very small as it should be. High frequency interrupts with long service routines are not a good idea with this or any other approach.

2) The four simulated wheel sensors are triggering interrupts, but they are attached with the 'RISING' sense so the library is trapping and ignoring them 50% of the time.

3) My assumptions and or maths may contain errors.

Stay Tuned ...

Duane B

Wednesday, March 21, 2012

Reading From An RC Reveiver - Do you need a new Radio ?

In the original series of posts relating to reading an RC Receiver with a microcontroller I included a number of charts showing how the RC signal quality degraded under realworld conditions. To summarise - as the distance between the transmitter and receiver increased, or the complexity of the built up environment increased, the variance (aka 'chatter') in the signal increased to the extent that a steering servo can be seen to rapidly chatter back and forth. This can happen at distances as little as ten meters so imagine the effect at the furthest point of the race track.

Steering Channel Of A 27Mhz AM Receiver At 10 meters Distance In A Domestic Environment. 
 
So do you need a new radio ?  Try the 'Walk Away Test' and see - 

I don't recall ever having seen this simple test described online or in print, so next time you are out with your RC Equipment, place the transmitter on the ground and walk away with the car in your hands. If you are using a 27Mhz system like me you will find your steering servo begins to chatter. As you keep walking, the chatter will get worse and worse, you may even find that your ESC begins to start and stop erratically. In my case testing in a street lined with steel reinforced concrete villas, the chatter was severe at only 20 meters.

In the original series of posts, I suggested that I would expect a more stable signal from more modern equipment and invited readers to repeat my tests so that I could publish the results. A reader ( Erni ) replied through the Arduino forum with results from a modern 2.4Ghz system that showed complete stability under similar test conditions.

While I did not rush out and buy a new transmitter, the opening of a new RC Race track in Dubai got me thinking about the probable effect of servo chatter on lap times. A few days later I saw a Spectrum DX3S 2.4Ghz system at a good price in a local hobby shop (thank you Extreme Hobbies) and now I have one.

The transmitter comes with two receivers and the following telemetry sensors -

Left to Right - 1 * RPM and 2 * Temperature



The RPM sensor is a very compact surface mount Infra Red Emitter/Detector which would be an improvement on the wheel speed sensors I am currently using for the traction control project.

Size Comparison - Home Built IR Transceiver, Packaged Surface Mount IR Transceiver Supplied With Spectrum Radio - Less Than Half The Size.



2.4Ghz Radio Signal Quality

As for the signal quality, a quick test around the house showed complete stability. The older 27Mhz system offered particularly bad performance in the same domestic environment (television, dishwasher, fluorescent lights, all switched on). A follow up test with the car carried as far from the transmitter as I could reasonably see and control it, again showed complete stability with no chatter or glitching from either the steering or the ESC.

A New Channel

Aside from the superior signal performance, another feature of the radio I am interested in is the Auxiliary channel. This could be used to switch program modes on the micro controller running in the car, however I already have a nice solution for this using the 'dead zones' within the existing channels. Where I see the auxiliary channel being useful is for applying settings remotely and without the need to include mechanical potentiometers on the in car circuitry.

Using The Auxiliary Channel To Set Parameters

As an example, to set the throttle range in child mode, put the car into child mode using the 'extra channels on the cheap' approach - http://rcarduino.blogspot.com/2012/01/how-to-read-rc-receiver-with_25.html - then activate the auxiliary channel, move the throttle to the desired maximum and minimum, then deactivate the aux channel to store and use this new range. Its simple, can be done remotely and does not require any additional components.

The same approach could be used to program traction control sensitivity or any other parameters that need to be tuned in car.

I always swore off buying a new radio on the basis that 'How can a radio possibly make you a better driver' however now that I have seen and measured the difference I am quite certain that a more stable receiver signal through the furthest corners of the track can only help traction and lap times.

Do you need a new radio ? Try the walk away test with your own equipment and find out.

Stay tuned...

Duane B

Friday, March 9, 2012

Tyre Testing - 3Racing M-Chassis Tyres

Today was the worst possible day for tyre testing -

Every now and then, the wind turns to blow in from the desert and remind the population of Dubai of the cities desert origin.The best sand storms are brief, 15 minutes of darkness and mayhem as the wind drives a mile high wall of sand across the city.

Today was not like that. Today began with a haze and a wind strong enough to push furniture around the garden. Hours have passed and still no great wall of sand has crashed across the city, but everywhere, inside and outside is covered by a growing film of dust.


Not the best day for tyre testing -


3Racing M-Chassis Tyres

 
I keep A rally car for days like today, it's an M03 with M05 ra uprights, a sport tuned motor and a NICAD battery. The 7.2 volt battery can make the car feel  slow after running my on road LIPO powered cars. As a quick fix I have been waiting for the rally block tyres to wear out so that I can replace them with a set of larger m-grips for a higher top speed.

When I first saw the 3racing tyres, they looked very big. Comparing them with other m-chassis tyres, they are the largest I have seen and so they went straight onto a spare set of rims and the rally car.

Straight on ?

Not really, at over 60 revolutions per second we have to glue our tyres on to keep them on.



Tyre gluing 101
 
1) Wash Everything.

Superglue is incredible stuff, but it won't stick to oil or grease. A lot of RC parts including tyres and the rims are created using molds. In order to be able to remove parts from the mold it is coated with a non stick release agent, if we don't wash this off our parts, paint and glue will struggle to hold.

2) Use The Right Glue

Most glue sold as superglue is a variation of cyanoacrylate, the different variations can work for or against you. If you are gluing tyres with a gap or wedge between the tyre and rim, you can use a thin formula which will run into and around the gap. Thin formulas tend to be fast setting, so if you have a tyre and rim combination that mate without a gap you might be better using a gel formula which gives you time to manually spread the glue between tyre and rim and readjust the fit during the longer set time. 

The 3Racing tyres mate to the rims without a gap and so I used a gel formula.

3) Use A Rubberised Superglue If You Can

If you can find a rubberised formula use it. One of the weaknesses of standard formulas is an inability to flex and withstand shocks. The rubberised formulas are a step towards overcoming this and should perform better in most RC applications.

 
Testing
Testing the tyres was great fun, one of the corners on my test track exits along a wall where a drift of accumulated dust had settled. Coming out of the corner and getting onto the throttle early would get the car power sliding through the dust.
 



Braking was impossible, the car would take upto 10 meters to stop with every speck of dust working as a ball bearing between the tyres and brickwork. Acceleration was reasonable enough, my guess is that the car scrubs the road clean of dust as it claws its way forward.



Tyre Sizes
The 3Racing tyres have a very square edge to them, this gives them the impression of being much larger than other M-Chassis tyres however having measured them they are only 1mm larger in diameter than the popular Tamiya M-Grip tyres.


Tyre                            Diameter                     Circumference                                 %
3Racing 60 188.57 109
M-Grip 59 185.43 107
Tamiya Rally Block 55 172.86 100
Slicks (Spice etc) 55 172.86 100


This small difference has a big effect on the distance travelled due to the multiplying factor of pi. The table above shows the diameter and circumference of some popular m-chassis tyres. Taking racing slicks as the standard, the 3-Racing tyres travel  9% further per revolution, while this is a huge advantage in the straights, it can easily be lost in corner grip and especially braking.


So are the tyres any good ? its impossible to say based on todays testing, but the ultimate test of any tyre is in the lap time. As soon as the sand clears I will be out with the personal lap timer for an M-Grip, Rally Block and 3Racing show down.

Saturday, March 3, 2012

Fun With The Personal Lap Timer

I still have some bugs and a long 'to do' list, but I have just spent a very enjoyable 100 laps with the personal lap timer. If it has the same effect on my kart driving as it has on my mini driving I will be delighted.

Its the simplest things that are making me happy, for every lap that the timer captures, it makes a beep. If the lap is faster than the current session best, it beeps twice. Its so simple but its amazing how much harder I can work on a lap to get that second beep.

If I get ten double beeps in a twenty lap session, how much better must my later laps be than if I had carried on driving my first lap again and again without the lap timer feedback ?

Duane B

 




Friday, March 2, 2012

Punk Consoles, Lap Timers and IR Transmitters, The 555 Timer

The Personal Lap Timer Infra Red Transmitter has now passed daylight testing - with the aid of a matt black hood for the IR receiver. 

No false laps detected and all genuine laps captured ! 

I know I am late in discovering the 555 timer and the even nicer 556 timer. The web is full of simple, useful circuits using these two chips. Some example applications for RC Include -

As a switched LED Driver, this allows you to drive more LEDs by switching between LEDs so fast that it appears they are all on all of the time, but your power source only has to power some of them at any one point in time !

As an LED Flasher for emergency or track vehicle lights, the same chip is able to switch tens of thousands of times per seconds or once every 10 or more seconds and anything else in between, this makes it ideal for warning lights, police lights etc.

My favorite application of the 555 Timer is the 'Atari Punk Console', look it up, its a nasty sounding little square wave generator that acts as a very crude synthesizer, very little practical use for anything, but its got a cool name and a cool sound.

The 555 is great, but the 556 is so much nicer, for a start its two timers in one package, the pinout is also easier to work with. On the 556 one timer is available through the left side pins and the other through the right side pins this makes bread boarding so much easier.

Personal Lap Timer Transmitter Version 1.0 and 2.0


On the left is version 1.0 using two 555 Timers, version 2.0 on the right uses a single 556 Timer. On the right, you can see the white wire across the IC, this is connecting the output of the control timer on the right side of the chip to the reset pin of the IR Oscillator timer on the left side of the chip. This turns the IR Signal on and off at a frequency we can read on the receiver side, we examine the frequency to confirm that this is a lapping car and not environmental noise.

The current version of the personal lap timer transmitter uses the two timers provided by a 556 Timer IC. The first timer (the IR Signal oscillator), is configured as an astable generating an on/off pulse at 38Khz. This is the frequency required by many popular infrared decoder ICs. The output of this timer drives an infrared emitter LED through a current limiting resistor.

The IR LED has a very tight focus which is great for lap timing. If your looking to build something similar pay attention to the 'view angle' or the equivalent terminology that the data sheet uses to describe the effective signal angle, for lap detection you want as small an angle as possible, for infra red remote control a much wider angle is more useful. 

The second Timer is also configured as an astable, but oscillating at a much lower frequency, I am currently testing 1Khz and 100 Hz versions. The output of this timer connects to the reset pin of the first timer, this causes the infrared emitter to transmit a series of pulses .5ms or 5ms long. On the lap timer side I am looking for pulses in this range, this helps to separate environment noise from actual laps.

If this stage of testing proves successful I will try working with the duty cycle and frequency of the control timer to see if it is possible to create a scheme for determining unique identities for upto 8 cars using a cascade of two or if need be three 555 timers.

Rather than me repeat the excellent work of others I would suggest that anyone interested in more information should have a read through the following links -

Background on the 38Khz IR signal and the ICs Used to detect it see the following link - also take note of the very simple IR Test circuit using just batteries, detector and an LED.

http://www.ladyada.net/learn/sensors/ir.html

There is a nice background on the 555 timer and its different uses and configurations here -

http://www.kpsec.freeuk.com/555timer.htm

There are also a several online 555 Timer calculators that will allow you to find the component values you need to produce a given frequency or period, use your favorite search site and look for '555 calculator'

My current circuit uses -

Control Timer - 
R1 670
R2 8K (3.3 + 4.7 in series)
C1 .1uf

IR Oscillator
R1 220
R2 1K in series with 1K potentiometer to give adjustment from 1K to 2K
C1 .01uf

These values are in part determined by what I had available so just use the calculators to work with what you have.


Finally I should mention that the 555 Timer can generate a lot of electrical noise in your circuits so be sure to use decoupling capacitors if its going to share power with anything else.

Duane B