15
Low Cost ATmega8A Based RA Stepper Motor Controller and Focuser Page 1 A Low Cost ATmega8A Based RA Stepper Motor Controller and Electronic Focuser for Small Telescopes by Astrotux Introduction After many years away from astronomy I recently decided that I would like to take it up again and buy myself a small telescope to start with. After some time debating I stumbled across a second-hand Celestron AstroMaster 130-EQ on a well known auction website and secured it for a much smaller sum than new. Other more advanced options were available but the budget was tight and I wanted a 'scope to learn on. This seemed ideal as everything I picked up along the way would be useful if I decided to upgrade at some time in the future. Whilst getting to grips with my new 'toy', I learnt how to collimate it and added a few eyepieces and filters to my collection along with a motor drive for the mount. My only concern was the motor drive. Getting it to track at the correct rate was very difficult. The speed control would fluctuate depending upon the state of the battery. These do no work well on cold nights so even for visual work it was sometimes inadequate. Even using an AC power adapter it still fluctuated a bit. After getting a cheap Phillips SPC900 web-cam I tried to take images of Jupiter and the Moon. The motor drive was just not up to the job!! Keeping anything in the field of view for more than 3 minutes was nearly impossible. No chance of long exposure shots then......... I had an old ink-jet printer that I was going to throw away but decided to take it to bits and see if anything was salvageable. I discovered that it contained two rather nice stepper motors. Maybe these could be of use driving my telescope? Overview The RA Controller and Electronic Focuser has been designed to provide an economical solution for precise control of a small telescope whilst tracking stellar objects. It also features an electronic focuser and is principally for use with a web-cam on a small telescope, but could well be of use in other situations ( such as barn-door trackers ) and on larger telescopes. The user can choose sidereal, solar or lunar tracking rate and the hemisphere of operation from a handset. This is also used to control the focuser motor or perform small timings adjustments 'on the fly'. The user's preferred settings can be stored for use when the device is first powered on. Please note that this system is not designed to provide an alternative to the more expensive computer controlled tracking systems found on a number of telescopes and so will not GOTO defined objects or provide high slewing rates, but is aimed as a replacement for the inaccurate motors used on smaller 'scopes. The hardware is based on an Atmel ATmega8A. An LCD and the three buttons act as the user interface and two ULN2003As Darlington arrays control the stepper motors. Each can be driven from either the regulated 5V line or the unregulated DC input to the system. Although this project is based on the ATmega8A it should work with most AVR microcontrollers, and it may be possible to port the code to work with a PIC or other device. It should not be difficult to adapt it for use with an Arduino system. The code has been written to be extremely flexible in the choice of stepper motors and telescopes that it can be used with. After all, a lot of stepper motors used in this sort of project have been 'rescued' from another device. Different motor configurations and modes of operation, as well as the gear ratios required to interface these to the telescope are all defined in one header file – StepperMotor.h. The code calculates the required system timings from this at compile time removing the need for the user to do this beforehand. The project was written in C using the cross-platform Eclipse IDE ( Integrated Development Environment ) featuring the CDT C/C++ and the AVR Eclipse plug-ins, all of which can be freely downloaded from the Internet. Although developed on a Linux based system, this code should be able to be compiled and the device programmed from both Windows and Mac OS based systems as well. 20/09/2012 Page 1

A Low Cost ATmega8A Based RA Stepper Motor Controller and

  • Upload
    others

  • View
    4

  • Download
    0

Embed Size (px)

Citation preview

Page 1: A Low Cost ATmega8A Based RA Stepper Motor Controller and

Low Cost ATmega8A Based RA Stepper Motor Controller and Focuser Page 1

A Low Cost ATmega8A Based RA Stepper MotorController and Electronic Focuser for Small Telescopes

by AstrotuxIntroductionAfter many years away from astronomy I recently decided that I would like to take it up again and buy myself a small telescope to start with. After some time debating I stumbled across a second-hand Celestron AstroMaster 130-EQ on a well known auction website and secured it for a much smaller sum than new. Other more advanced options were available but the budget was tight and I wanted a 'scope to learn on. This seemed ideal as everything I picked up along the way would be useful if I decided to upgrade at some time in the future.

Whilst getting to grips with my new 'toy', I learnt how to collimate it and added a few eyepieces and filters to my collection along with a motor drive for the mount.

My only concern was the motor drive. Getting it to track at the correct rate was very difficult. The speed control would fluctuate depending upon the state of the battery. These do no work well on cold nights so even for visual work it was sometimes inadequate. Even using an AC power adapter it still fluctuated a bit.

After getting a cheap Phillips SPC900 web-cam I tried to take images of Jupiter and the Moon. The motor drive was just not up to the job!! Keeping anything in the field of view for more than 3 minutes was nearly impossible. No chance of long exposure shots then.........

I had an old ink-jet printer that I was going to throw away but decided to take it to bits and see if anything was salvageable. I discovered that it contained two rather nice stepper motors. Maybe these could be of use driving my telescope?

OverviewThe RA Controller and Electronic Focuser has been designed to provide an economical solution for precise control of a small telescope whilst tracking stellar objects. It also features an electronic focuser and is principally for use with a web-cam on a small telescope, but could well be of use in other situations ( such as barn-door trackers ) and on larger telescopes.

The user can choose sidereal, solar or lunar tracking rate and the hemisphere of operation from a handset. This is also used to control the focuser motor or perform small timings adjustments 'on the fly'. The user's preferred settings can be stored for use when the device is first powered on.

Please note that this system is not designed to provide an alternative to the more expensive computer controlled tracking systems found on a number of telescopes and so will not GOTO defined objects or provide high slewing rates, but is aimed as a replacement for the inaccurate motors used on smaller 'scopes.

The hardware is based on an Atmel ATmega8A. An LCD and the three buttons act as the user interface and two ULN2003As Darlington arrays control the stepper motors. Each can be driven from either the regulated 5V line or the unregulated DC input to the system.

Although this project is based on the ATmega8A it should work with most AVR microcontrollers, and it may be possible to port the code to work with a PIC or other device. It should not be difficult to adapt it for use with an Arduino system.

The code has been written to be extremely flexible in the choice of stepper motors and telescopes that it can be used with. After all, a lot of stepper motors used in this sort of project have been 'rescued' from another device. Different motor configurations and modes of operation, as well as the gear ratios required to interface these to the telescope are all defined in one header file – StepperMotor.h. The code calculates the required system timings from this at compile time removing the need for the user to do this beforehand.

The project was written in C using the cross-platform Eclipse IDE ( Integrated Development Environment ) featuring the CDT C/C++ and the AVR Eclipse plug-ins, all of which can be freely downloaded from the Internet. Although developed on a Linux based system, this code should be able to be compiled and the device programmed from both Windows and Mac OS based systems as well.

20/09/2012 Page 1

Page 2: A Low Cost ATmega8A Based RA Stepper Motor Controller and

Low Cost ATmega8A Based RA Stepper Motor Controller and Focuser Page 2

The Original BoardThe picture on the left shows the device during its testing phase. Note the rewiring and re-soldering that has taken place.

The picture to the right shows the motor this system is designed to replace.

Although the board has been constructed using surface-mount components on a PCB, it could just as easily be built using through-hole devices on a piece of Veroboard, or similar material.

This photograph also shows the control buttons attached to the board, but these have since been moved to a handset with a cable to the device so that remote operation can be achieved. From top to bottom they are 'Up', 'Menu' and 'Down', although the order can easily be changed in the code. At the bottom are the connectors for the stepper motors.

Those who zoom into the picture on the left may see that the PCB appears to have been manufactured by 'Torridon Electronics'; this is simply a spoof name I put on all my projects.

Using the ControllerAt start-up the following screen will be shown. This is where the user can either accept the default settings for the device, or their saved settings. This is simply done by selecting one or the other using the 'Up' or 'Down' buttons and then pressing the 'Menu' button.

Please accept my apologies for the dust in these photographs, I should have given everything a good clean first............

The contents of the next screen will depend upon the user's choice above, but here I have shown the default.

It can be seen from this that the chosen tracking rate is sidereal, the device is set for Northern hemisphere operation and the 'Up' and 'Down' buttons control the focuser.

The figure in the bottom right hand corner of the screen shows that no adjustment has been made to the tracking rate. Adjustments are shown in parts per million ( in the original this updates in increments of ±20ppm – see the section on Accuracy for an explanation ), but the code could easily be rewritten to give percentage or some other figure.

This, or something similar, is the screen that the user should normally see during device operation.

20/09/2012 Page 2

Page 3: A Low Cost ATmega8A Based RA Stepper Motor Controller and

Low Cost ATmega8A Based RA Stepper Motor Controller and Focuser Page 3

Using the MenuBy pressing the 'Menu' button the user can alter the operation of the device.

Note: the device continues working when the menu has been selected, but the buttons control menu operations only.

The first choice is the tracking rate in use.

By pressing the 'Up' or 'Down' buttons the user can select whether they require sidereal, solar or lunar rate.

Note: if selecting solar rate to track the Sun, please ensure that you take all necessary precautions and also use a solar filter for your 'scope.

Pressing 'Menu' again shows this option.

Here the user can select either Northern or Southern hemisphere operation of the RA motor by using the 'Up' and 'Down' buttons.

This is very useful during testing if you are not sure which direction your motor should rotate!!

Pressing 'Menu' again displays the mode the buttons are in during normal operation.

The focuser is normally controlled using the 'Up' and 'Down' buttons, but here the user can set the buttons to control the timing rate of the RA motor using minor incremental adjustments when normal operation resumes.

This picture shows the device set to adjust the tracking rate timing.

Pressing 'Menu' again displays the final screen. This allows the user to store the parameters they have set into EEPROM allowing these to be recalled when the system starts up.

One more press of 'Menu' returns the device to normal operation using the parameters selected.

20/09/2012 Page 3

Page 4: A Low Cost ATmega8A Based RA Stepper Motor Controller and

Low Cost ATmega8A Based RA Stepper Motor Controller and Focuser Page 4

This final picture shows the device back in normal operation but with the buttons controlling the tracking rate adjustment.

NOTE: when the user saves their settings any timing rate adjustment is also saved.

AccuracyThe main use for this device will be tracking stellar objects and planets. To do this it must ensure that the telescope moves at the same rate as the apparent movement of the night sky. A quick piece of mathematics shows this rate as:

360 ° /86164.1 sec=0.00417° / sec=15.041arcsec/ sec

The accuracy of this device will depend upon a number of factors. Probably the most important are:

1. Getting the gear ratios of your 'scope right. Without this you will have no chance of success.

2. Using an accurate time-base for the device. I have chosen a ± 20 ppm crystal but a number of the commercially available parts are only ± 50 ppm.

3. Understanding that microcontrollers use an integer to count timings.

The top two are these are fairly easily understood, but what about the third? Simply put, this means that a microcontroller has to count whole numbers to time things. We are used to using terms like “86,164.1”, but a microcontroller can only count without the decimal point ( 86164, 86165, 86166, etc. ).

Luckily, because of the speed at which it operates a microcontroller can count a lot faster than we can. When clocked at 10MHz it can count every 100ns ( 0.0000001 of a second ). A faster system clock will provide smaller resolution, but the ATmega8A can only go up to 16MHz which does not improve accuracy a great deal. This means that we can time events to the nearest 100ns, but what does this mean for the accuracy of the device?

Controlling a stepper motor to run at an accurate rate simply involves waiting for a predetermined period of time ( the step time ) and then turning on the power to the next pole of the motor. Whist all the mathematics in our microcontroller are performed using floating point arithmetic for the highest accuracy, the step time has to be converted into an integer before it can be used. If the mathematics come up with a count such as 87296.015 ( as in my original ) then the number 87296 is used by the counter, introducing an inaccuracy.

From this it can be seen that the longer the step time, the greater our accuracy will be. As an example make the step time of the motor 1ms ( 0.001 of a second ), then the accuracy in parts per million will be:

100ns x1000000 /1ms=0.0000001 x1000000/0.001=100 or ±100 ppm

If the step time of the motor is made to be 20ms, the accuracy will be:

100ns x1000000 /20ms=0.1/0.02=5 or ± 5 ppm

How does this affect the overall accuracy?

In my original the accuracy is ± 11.46 ppm. We know that the crystal has an accuracy of ± 20 ppm so the overall accuracy will be ± 31.46 ppm ( 11.46 + 20 ). Over a solar day the inaccuracy will be:

86400 secs×31.46/1000000=2.72 secs=40.884arsecs/day

This equates to about 0.0284 arcsec per minute ignoring such effects as gears not meshing properly, wind effect on the 'scope, etc. I think this should be accurate enough for what I want to do, especially as the visual limit of my 'scope is about 1 arcsec!!

20/09/2012 Page 4

Page 5: A Low Cost ATmega8A Based RA Stepper Motor Controller and

Low Cost ATmega8A Based RA Stepper Motor Controller and Focuser Page 5

To provide some degree of control over any inaccuracies in timings this project provides the user with the ability to set a tracking rate adjustment increment, defined as PPM in the code. This is primarily intended for small adjustments while tracking the Moon but can also be used to account for other inaccuracies.

From the discussion above it can be seen that setting this rate at less than the timing rate inaccuracy would be fruitless. I use ± 20 ppm to reflect possible variations in the crystal.

Caveats1. The description of this device is solely intended for reference as some or all of it may be of interest to

others who wish to design and/or build a similar device. I cannot take any responsibility for misuse of this information or the final design and build of any device.

2. This project had been designed to drive unipolar stepper motors in full-step or half-step mode only.

If you wish to use bipolar motors the code and design would have to be adapted accordingly. Some driver chips that may be worth investigating for this include the L298 and the L2603.

3. Similarly this project has not been designed to provide micro-stepping of the motors.

Again it would have to be modified in both the code and the circuitry. Possible driver chips include the L6470 and the Allegro A3977.

4. When using stepper motors be aware of the current they can draw when driven from higher voltages.

It is always a good idea to remember Ohm's Law. If you try to drive a 30Ω stepper motor coil from a 30V line then you will be taking 1A of current!! Whilst this may seem like a good idea, it can have some disastrous consequences. The ULN2003A Darlington array is rated to a maximum peak current of 600mA ( 500mA continuous ). Exceeding these limits will damage the chip and possibly the rest of the circuitry.

Drawing a higher current than is necessary to move the motor results in heat being dissipated in either the motor, the Darlington array or both. Unless you want to keep your 'scope warm on a winter's night I would not recommend you do this. Wasting electricity as heat simply increases the power demand of the device and shortens the life of any battery or power tank used.

It is best to drive the stepper motor with just enough voltage to move it. My RA motor was originally rated for 24V operation but I actually drive it from 6V. The fact that it drives a worm gear means that we can rely on the detent torque of the motor to stop everything from slipping backwards.

5. When using any form of AC power adaptor the user should take all necessary precautions, including the use of a circuit breaker if the device is to be powered outside from the mains.

20/09/2012 Page 5

Page 6: A Low Cost ATmega8A Based RA Stepper Motor Controller and

Low Cost ATmega8A Based RA Stepper Motor Controller and Focuser Page 6

What Do I Need to Build It?In addition to the stepper motors, for the main circuit board you will need:

1. An Atmel ATmega8A ( or similar ) microcontroller.

The main requirement is for a device that can run at around 10 MHz and features a 16-bit timer that can be used to reset itself automatically when a compare value has been reached. It should also have at least 17 input/output pins after a crystal clock source has been added.

Prices vary from as little as 50p per unit to around £3 depending upon where you buy them from.

2. A crystal and its associated capacitors.

The better the accuracy of the crystal ( e.g. ±20ppm ) the more accurate the system will be. The only thing to keep in mind is the 'order of magnitude' this is in – a 12 MHz device does not provide a lot more accuracy than a 10 MHz one, but both are at least ten times more accurate than a 1 MHz crystal. Wouldn't it be nice to be able to run at 1GHz!!

3. 2x ULN2003A Darlington arrays.

Two of these are used as the drive voltages required for the stepper motors may differ, but if you wish to power both motors from the same source a single ULN2004A could be used instead.

4. An HD44780 based LCD.

These are readily available for around £2-4 but it is advisable to get one that features red characters on a black background in order not to interfere with night vision.

5. A 5V regulator and its associated circuitry.

If you only intend to power the microcontroller and LCD with this then a 100mA device should suffice.

If you wish to power either, or both the stepper motors as well then it should be upgraded accordingly. A good compromise is the AMS1117 as it can handle currents up to 800mA which should be sufficient for one small motor.

It should be noted here that stepper motors are often powered from a different source to the control circuitry as they frequently require a different voltage to work. This also protects the circuitry from any inherent voltage spikes caused by the inductive load of a stepper motor. In my original I power the RA motor from the raw DC feed before the voltage regulator.

6. Three momentary action push buttons.

My original featured these mounted on the board, but I have since modified this so that they are on a separate board attached via a cable allowing remote operation.

7. A small supply of resistors, connectors, capacitors, etc.

8. A soldering iron and some other basic tools.

You will also need some bits and pieces to provide a way of connecting the motors to the 'scope, and some way of programming the microcontroller. These topics are covered in following sections.

Also required is some method of compiling the code as the requirements for your system are unlikely to be the same as mine. There are many ways of doing this from direct use of the avr-gcc or WinAVR compilers and linkers at the command line, to using a fully functioning IDE such as Eclipse.

If you are new to all this, be aware that you are likely to need to recompile quite often as you establish all the parameters for your 'scope and the way you have it connected to the RA controller.

My own recommendation is for the Eclipse IDE featuring the aforementioned plug-ins, but other freely available IDEs such as the Arduino environment, AVR Studio and KontrollerLab can all be used.

20/09/2012 Page 6

Page 7: A Low Cost ATmega8A Based RA Stepper Motor Controller and

Low Cost ATmega8A Based RA Stepper Motor Controller and Focuser Page 7

Connecting It All to the 'ScopeFor me, the major problem with a project like this is not the electronics but rather how to attach everything to the telescope so that it works!!!

Things to considerOne of the first things I realised was that it was likely the RA stepper motor would need a gearbox in able to drive the telescope at the correct speed. There are three main factors here:

1. The RA axis of the telescope needs to rotate once every 86164.1 seconds to track at sidereal rate. Solar and lunar rates are obviously quite similar.

The gear ratio between the RA slow motion shaft and the RA axis has to be established to have any chance of success. Luckily on my scope this is a simple worm and gear mechanism and a count of the gear teeth showed this ratio to be 136:1.

Thus the RA shaft needs to turn once every 86164.1/136≈633.6 seconds to track at sidereal rate.

2. To reduce the possibility of vibration being visible through the eyepiece, the stepper motor should be driven at a rate of approximately 50 steps per second.

From this it can be seen that the stepper motor will take 633.6∗50=31680 steps for each rotation of the RA shaft.

3. Stepper motors are normally specified by the number of steps required for one full turn. The ones I had salvaged were both 48 step motors meaning that they would take 48 steps in full-step mode and 96 steps if used in half-step mode.

From this it can be seen that we need a gearbox with a ratio of 31680/96=330 :1 or similar if we are to meet the criteria required using half-step mode to drive the motor. Obviously full-step mode would double this figure.

Where could I get such a gearbox from, and how could I connect it to the RA shaft?

Luckily the motor I already had for the 'scope was connected to the RA shaft using a 5mm to 6mm CNC shaft coupler. I simply had to provide my new device with an output shaft 5mm in diameter to hook it up with the 'scope so that solved one problem.

If you do not already have a motor drive for your 'scope then you can purchase CNC shaft couplers to suit many different shaft sizes for about £5-10 each from that well known auction website.

At this point it is probably worth pointing out the amount of torque that will be required to turn the RA shaft of your telescope. On smaller 'scopes it is quite high!! If you don't believe me, remove the slow motion cable from the RA shaft of your telescope and try to move it by hand. Any motor and gearbox combination will have to overcome this.

What could I do about the gearbox? I went down many different lines of enquiry here:

1. Buy a cheap electric screwdriver and steal the gearbox. I could not find one but you may be luckier. You will have to investigate the gear ratios very carefully if you are going to use one.

2. Use a cheap 28BYJ-48 stepper motor instead as these have a gearbox attached and cost around £2 each. Unfortunately their specification is misleading, they claim a 64 step rotation with a 64:1 reduction through the gearbox giving a 4096:1 ratio. After a number of tests I discovered it to be more like 4075.771:1. They feature some rather interesting gearing!!!

They simply do not have enough torque to turn the RA shaft, although I am thinking of using one for the focuser.

3. I had a number of small push-fit nylon gears and a 2mm shaft that I had bought cheaply for another project but never used. In the end these are what I used.

20/09/2012 Page 7

Page 8: A Low Cost ATmega8A Based RA Stepper Motor Controller and

Low Cost ATmega8A Based RA Stepper Motor Controller and Focuser Page 8

Working Out GearingThe smaller of the two stepper motors I had salvaged had a brass worm gear attached. A closer look showed the pitch appeared to be about 16 teeth per inch. The nylon gears that I had purchased earlier were all metric mod 0.5 pitch, but these are close enough to be able to work together.

A worm gear on the motor has the benefit that as it will be mounted at a right-angle to the first ( idler ) gear, very little torque is required from it. It also means that the motor will take the same number of turns as the number of teeth on the first gear to turn it once. My first gear had 30 teeth giving me a ratio of 30:1 straight away.

I experimented with the gears by drilling holes for their shafts in an off-cut of wood and by using just three I was able to get a ratio of 756:1. I achieved this by using two idler gears, each of which had a 10 tooth centre spindle, and a final driven gear. The ratios were:

30/10 * 42/10 * 60 = 756 : 1

( i.e. 30 tooth with 10 tooth spindle, 42 tooth with 10 tooth spindle, 60 tooth )

Making the GearboxTo construct the gearbox casing I used a sheet of 2mm thick aluminium that I had lying around. The beauty of this is that everything can be done with simple hand tools: a metal ruler, a hacksaw, a hand drill, a couple of Swiss files and a clamp. I cut two rectangular sides just big enough to cover the layout of the gearing I had worked out and clamped them together. By marking out the top sheet with the positions of the 2mm gear axles and a 3mm hole in each of the four corners, I could then drill through them so that both sheets were identical. When separated I could lay the gears into their respective holes and then use a 3mm nut and bolt at each corner with 6mm spacers between the sheets to hold everything together. I was surprised how rigid it was.

To connect the 2mm shaft from the driven gear ( the last gear in the chain ) to the RA shaft I used a push-fit nylon worm gear with a diameter of slightly more than 5mm. By sliding this onto the outboard end of the driven gear axle and filing it a bit I was able to 'fudge' a 5mm flatted shaft end that the CNC coupler could get hold of.

By fashioning another piece of aluminium sheet I made a bracket to hold the motor in the correct position to drive the first gear and another became a bracket to hold the whole assembly to the 'scope mount. Unfortunately testing revealed that some modification was required.....

2mm push-fit nylon gears cannot take the torque required to turn the RA shaft of my 'scope. The driven gear would simply spin around its axle and not move it.

To solve this I used JB Weld ( a strong two part epoxy adhesive ) to glue the driven gear and my improvised flatted shaft end to their 2mm shaft. By roughening up the shaft with a Swiss file where the gears were to sit and by scoring the centre holes of the gears JB Weld made an excellent bond between the gear and the shaft after being allowed to cure. Now it works!!

The pictures show the gearbox and motor fitted to the telescope for testing. Note that no user protection has been added at this stage.

20/09/2012 Page 8

Page 9: A Low Cost ATmega8A Based RA Stepper Motor Controller and

Low Cost ATmega8A Based RA Stepper Motor Controller and Focuser Page 9

Putting the Code Together

Build FilesIncluded in the .ZIP file you will find:

1. A folder labelled 'code' which contains:

1. main.c - the main code for the RA Motor Drive and Focuser control.

2. lcd.c - the code to implement an HD44780 LCD using 4 data pins & 2 control pins.

3. lcd.h - the header file for lcd.c, this defines the port and pins the LCD is connected to.

4. StepperMotor.h - the header file that defines the requirements for both stepper motors and is used to calculate the system timing information.

2. A folder labelled 'hardware' which contains:

1. The Eagle files of the circuit schematic and an SMT board layout.

2. The circuit schematic as a .jpg file - RAcircuit.jpg.

Please note that the files in this folder are only provided as a guide to how to make this project and should not be taken as being completely accurate. I have changed some things as I have gone along. You have been warned!!!!

Compiling and LinkingTo use the code, extract the contents of the folder 'code' to a location where you can easily find it again. If you are using an IDE such as Eclipse you should then start a new project and use the import function to pull the four files mentioned into your new project.

Before doing anything take some time to read through the definitions in the file StepperMotor.h and make sure that they reflect your system requirements ( see System Timing for an explanation of these definitions ).

If you are unsure about terms such a half-step or full-step mode, unipolar or bipolar stepper motors, etc. then spend some time on the Internet looking these up. There is a lot of good information already out there that is easy to find and understand.

You should also check that the PORT and other definitions in lcd.c and main.c reflect how you have set up your device and how you want it to behave.

If you are using a device other than the ATmega8A, you may have to check the naming of some hardware registers used in the code as other Atmel devices sometimes use different mnemonics.

Before you compile and link the code you should ensure that certain project settings are made:

1. The project environment knows the path to the avr-gcc include files and libraries.

This project uses a number of the AVR specific header files. These are:

avr/io.h, avr/pgmspace.h, avr/eeprom.h, avr/interrupt.h, util/delay.h and math.h

If you are porting this code to another architecture you will have to change all of these.

2. The target hardware matches the device you are using.

3. The environment is set for the correct hardware clock speed ( e.g. 10 MHz ). This is vital as it defines F_CPU which is used to calculate all the system timings.

4. Your project settings reflect which programmer you are going to use for the device and that you wish to programme both FLASH and EEPROM.

20/09/2012 Page 9

Page 10: A Low Cost ATmega8A Based RA Stepper Motor Controller and

Low Cost ATmega8A Based RA Stepper Motor Controller and Focuser Page 10

5. You are linking the code against the specific AVR libraries libm.a and libc.a.

The mathematics library libm.a has been produced by the maintainers of avr-gcc to ensure that floating point operations are optimised for use within Atmel devices.

The code will compile without this step but the code size will be rather large. During testing it was about 7500 bytes before using libm.a but reduced to around 4000 bytes afterwards.

Under Eclipse I have found that the best way to make this happen is to go to:

Project>>Properties>>C/C++ Build>>Settings>>AVR C Linker>>Libraries and then add 'm' and 'c' to the empty library list in that order.

If you cannot do this through your project settings ensure that your makefile includes the switches -lm and -lc in that order when linking the code.

You should now be able to compile and link the code ready for programming the device.

Programming the DeviceThere are a number of possible ways to programme this device and a huge numbers of programmers that can be used, all of which would take too long to go through here. Again, there is a lot of good information available on the Internet so it is worth looking. One site dedicated to AVR devices is http://www.avrfreaks.net/ which contains a lot of valuable information and many other projects.

Hardware to programme an Atmel chip can be as simple as just a few resistors if your system features a parallel port. To find out more about this visit Steve Bolt's excellent website at http://sbolt.home.xs4all.nl/e-spider_prog.html. You may not need the software, but the tips on how to programme through the parallel port are invaluable.

If you want to use a USB interface to programme your device an excellent solution is Thomas Fischl's USBasp, details of which can be found at http://www.fischl.de/usbasp/ . A number of USBasp clones are available through auction websites for as little as £3 and feature a 10-pin header connector to the board to be programmed. All you would need to do is connect the correct pins on the header connector to the necessary pins on your device.

For information regarding the pin-outs of the device you are using datasheets can be downloaded from the Atmel website at http://www.atmel.com/.

Probably the most popular software to download code to an Atmel AVR device is Avrdude which has hardware support for a very large number of programmers. It runs on both Linux and Windows and is included in the AVR Eclipse plug-in, as well as many other IDEs. These normally automatically invoke Avrdude when a request to programme the device is made, negating the need to use it at the command line.

From all of this I think you can see that my favourite tool for this sort of work is Eclipse with the necessary plug-ins. I have tried several IDEs for programming Atmel devices and in my opinion this is the best – although some Arduino users may take issue with this statement.

NOTE: One thing that you should be aware of when programming AVR devices is the FUSE settings. Most devices are shipped with the internal 1MHz oscillator programmed as the default clock source. The first time you programme the device change these settings afterwards to reflect the fact that you are using an external crystal as a clock source or the device will operate strangely.

Take care when changing these settings as it is possible to render the device unusable, although most times it can be rescued if you know what you are doing.

20/09/2012 Page 10

Page 11: A Low Cost ATmega8A Based RA Stepper Motor Controller and

Low Cost ATmega8A Based RA Stepper Motor Controller and Focuser Page 11

System TimingIt can be seen that timing is critical so the original device is clocked at 10MHz using a ±20ppm crystal for accuracy. This gives a system clock resolution of 100ns ( 1/10MHz ) but any reasonably high speed crystal can be used as the code calculates all system timings using the defined system clock speed ( F_CPU ). Ensure that you have this set, and also that your time base has good accuracy if you intend to use something else.

Remember that a low clock speed ( e.g. 1MHz ) will give a lower system clock resolution and mean that event timing will lose its accuracy.

To calculate the step time for the RA motor we need to know several things and most of these should be defined in the include file StepperMotor.h:

1. How many steps the motor takes to complete one turn ( NUMSTEP in StepperMotor.h ).

2. How many turns are required on the RA shaft of the telescope to turn it through 360° of right ascension ( RA_TURNS ).

Quite often this is simply a worm and gear system so the number of teeth on the RA shaft gear will define this.

3. What gear ratio is being used between the motor and the RA shaft, if any ( GEAR_RATIO ).

4. The mode the motor is being run in ( e.g. RA_MODEHALFSTEP ).

5. The system clock speed ( F_CPU which is normally defined in your project settings ).

The port that the stepper motors are run from is defined by STEP and STEPDIR as well as the pin numbers that each pole of each motor is attached to.

Also defined in StepperMotor.h are three constants:

1. SIDEREAL - the time of a sidereal day in seconds.

2. SOLAR - the time of a solar day in seconds.

3. LUNAR - the time of a 'lunar day' in seconds.

From these definitions the avr-gcc system preprocessor will calculate three step timings for the RA motor, one each for sidereal, solar and lunar rate. These are defined in an array of type 'float' that resides in system memory and is declared in the file main.c as 'float trackingRates []'.

Whilst the sidereal and solar times are reasonably accurate it has to be seen that the term 'lunar day' is a bit of a fudge. The rate at which the moon moves through the sky varies from night to night depending upon its position in its orbit, so the user may have to vary the system timings through the control interface to achieve highly accurate lunar tracking. To calculate the 'lunar day' I have simply averaged out the time differences between lunar transits over a month. Maybe someone would like to come up with a better method, but this would probably involve setting time and date and using an ephemeris table.

StepperMotor.h also declares two arrays in system memory const char raSteps [] and const char fSteps [] that contain the stepping information for each motor, regardless of which pins they are connected to.

20/09/2012 Page 11

Page 12: A Low Cost ATmega8A Based RA Stepper Motor Controller and

Low Cost ATmega8A Based RA Stepper Motor Controller and Focuser Page 12

What does the Code Do?

The System Status RegisterTo keep track of system operation a status register has been implemented. This is declared in main.c as struct statusReg status and contains:

1. 1 bit to control the hemisphere of operation ( North ). This bit is used by the TIMER1_COMPA interrupt routine to ensure the correct direction of rotation by the RA stepper motor.

2. 1 bit to control the operations of the buttons ( Keys ). This is used by the main forever loop to determine whether to control the focuser motor or incrementally adjust the tracking rate timing.

3. 2 bits to control the tracking rate in use ( Rate ). These bits are primarily used as a pointer in the function void calcRate () to retrieve the correct timing from float trackingRates [].

4. 1 bit to control saving parameters ( Save ). This bit is used by the function void displayMenu () and writes the user settings to EEPROM if set.

5. 1 bit to restore parameters ( Restore ). This bit is used by the function void startUpChoice () and reads the user settings from EEPROM if set.

In addition to this the fields in the status register are often used as pointers into arrays of strings and many of the display functions use these to show information on the LCD.

System Start-up and OperationAt start-up the systems performs a number of steps. These are:

1. Set the pins attached to the buttons to be input pins and configure them to use internal pull-ups.

2. Set the pins for the stepper motors as output pins.

3. Initialise the LCD. This is performed by the external function void lcdInit ( void ) declared in lcd.c. It sets the LCD pins as output pins then performs the necessary commands to start the LCD up.

4. Display a menu on the LCD asking the user whether they wish to use the default or stored settings for device operation. This is performed by the function void startUpChoice ( void ) and reads the required settings from EEPROM consisting of the status register information and any timing rate adjustment count in use ( signed int adjustCount ).

5. Calculate the tracking rate timing from the restored status register and adjustCount information.

6. Stop and clear TIMER1.

7. Load the value calculated into OCR1A.

8. Enable the Output Compare Interrupt Enable flag for OCR1A and global interrupts.

9. Start TIMER1 with no system clock pre-scaler and CTC mode set.

10. Display the normal operating information on the LCD. This is performed by the function void displayInfo ( void ).

The device then enters a forever loop which does the following:

1. Check if the 'Menu' button has been pressed. If so go and display the menu and act according to the user's requirements. This is performed by the function void menu ( void ).

2. Check if the 'Up' button has been pressed. If so either move the focuser motor up or increment the timing rate adjustment count depending upon the state of the Keys bit in the status register.

3. Check if the 'Down' button has been pressed. If so either move the focuser motor down or decrement the timing rate adjustment count depending upon the state of the Keys bit in the status register.

20/09/2012 Page 12

Page 13: A Low Cost ATmega8A Based RA Stepper Motor Controller and

Low Cost ATmega8A Based RA Stepper Motor Controller and Focuser Page 13

Whilst in this forever loop the RA stepper motor is controlled by OCR1A interrupts and the TIMER1_COMPA Interrupt routine.

Operation of the RA Stepper Motor CodeTo time the RA motor steps, the code uses Timer1 with the Output Compare A ( OCR1A ) register set for CTC ( Clear Timer on Compare ) mode and its associated interrupt ( TIMER1_COMPA ). This mode generates an interrupt every time the count in Timer1 equals the value in the OCR1A register and resets Timer1 to zero allowing us to generate any small time-base we require.

At 10MHz, Timer1 will increment every 100ns and OCR1A is a 16-bit register which theoretically means we can time events up to 6,553,600ns ( 6,553.6µs or 6.5536ms ). Unfortunately we require event timing of up to 20ms as we may be using a gearbox that requires longer delay times to operate properly or to increase the accuracy of the timing. The longer the delay we can use the less the resolution of Timer 1 affects accuracy. We would not really wish to go beyond 20ms as any vibration at this rate could be visible through the eyepiece or camera of the telescope, but this should be investigated during the build for each individual project as longer delays may be feasible.

To achieve longer delays a count register 'unsigned char passCount' is updated in the TIMER1_COMPA Interrupt routine and means that a number of passes through the routine can be completed before issuing a step command to the motor. This effectively breaks the required delay time down into a number of manageable chunks.

The calcRate FunctionThe heart of the code is the function 'void calcRate ()' which calculates the values to be used in OCR1A register during the TIMER1_COMPA interrupt routine by:

1. Retrieving the timing for the tracking rate in use from the array 'float trackingRates []'.

The pointer to this information is formed from the address of this array and the current tracking rate held in the status register ( status.Rate ).

2. Taking the value held in 'signed int adjustCount' and multiplying it by PPM / 1,000,000 to give any timing adjustment required. PPM is defined in main.c as the parts per million we require for each incremental increase or decrease in the tracking rate.

This is added to the timing from step 1 and the result is stored as an integer in 'unsigned long integerRate'.

This is the step where any timing inaccuracy can occur as we are taking a float and converting it to an integer.

3. Any value of 'unsigned long integerRate' over 65,535 ( the size of the OCR1A register ) would be truncated and lead to incorrect timing so this value is then divided by 60,000 and 1 is added to the result to calculate a number of passes through TIMER1_COMPA. This is held in 'unsigned char numPasses'.

We add one to the result as a delay shorter than 60,000 would give 'numPasses' = 0. We always need another pass to add any remainder from the next calculation.

4. 'unsigned long integerRate' is then divided by the contents of 'unsigned char numPasses' to give a value to be used in the OCR1A register during the initial passes through TIMER1_COMPA. This is stored in 'unsigned int firstPass'.

5. The remainder of the division is added to the value of 'unsigned int firstPass' and stored in 'unsigned int lastPass' register to ensure that the complete delay time is accounted for.

The number 60,000 used in step 3 is arbitrary but has been chosen to give some head room for the interrupt routine and also ensures that if we require more than one pass through it, the lowest possible value of either 'firstPass' or 'lastPass' will be 30,000. This means that at least 30,000 instructions can be executed between setting the OCR1A register and any output compare interrupt occurring.

20/09/2012 Page 13

Page 14: A Low Cost ATmega8A Based RA Stepper Motor Controller and

Low Cost ATmega8A Based RA Stepper Motor Controller and Focuser Page 14

The TIMER1_COMPA Interrupt RoutineThe RA stepper motor is controlled by the TIMER1_COMPA Interrupt routine which operates by:

1. Clearing the bits in the stepper motor control register so that the motor does not draw excessive amounts of current when it does not need to.

2. If this is the last pass through the routine, step the motor by updating the stepper motor control register with the value for the next step. This is retrieved from the array 'const char raSteps []' ( declared in system memory by StepperMotor.h ) and the reference into it in 'unsigned char raStepNumber' is updated.

Ensure that OCR1A contains the value held in 'unsigned int firstPass' ready for the next run through the routine.

3. If this is the last but one pass, update OCR1A with the value held in 'unsigned int lastPass' so that the full delay time is accounted for.

4. Update 'unsigned char passCount' to keep track of the number of passes through the interrupt routine.

Other FunctionsA number of other functions are declared in the code that are mainly associated with display of information on the LCD. These are:

void menu ( void );

void displayInfo ( void );

void displayMenu ( unsigned char *info, unsigned char *choice );

void lcdString ( unsigned char *string );

void writeLCDAdjust ( void );

The following functions simply change the information held in the system status register:

void changeHemi ();

void changeKeyMode ();

void changeRestore ();

void changeSave ();

20/09/2012 Page 14

Page 15: A Low Cost ATmega8A Based RA Stepper Motor Controller and

Low Cost ATmega8A Based RA Stepper Motor Controller and Focuser Page 15

TestingThe initial test of this device was to see if the tracking rate was anywhere near accurate. This was simply achieved by setting the 'scope up in daylight ( indoors for comfort ) and selecting solar tracking rate. The RA setting circle was then set to the time of day and the 'scope allowed to run.

When I returned 8 hours later the RA setting circle had advanced by 8 hours exactly. This indicated that all my calculations on gearings, etc. were correct, and that the device would run with reasonable accuracy, but the acid test would be sidereal tracking of an object.

The original of this device saw first light on 19 th September 2012 and performed beyond expectations. It was not a night of good seeing or visibility, so was perfect for just testing.

Initial tests showed that no vibration was visible through the eyepiece, even when using higher powers.

The tracking test simply consisted of tracking Altair with the highest power eyepiece available, I knew that 4mm would come in useful one day!! This has a field of view very similar to that of the SPC900 web-cam. It happily tracked Altair for over 30 minutes without it moving from the centre of the field of view. I was happy!

Further tests are planned including establishing the life of a 9V battery if used to power the device.

I have yet to make the bracket, etc. for the focuser, but all in due time.

ConclusionIn traditional music circles, when someone writes a new tune we say “Let the boys ( and girls ) kick it around for a while and see what comes back”. I think it is time for this to happen with this project.

With luck this information will be of use to someone, and I wish you luck if you decide to make something based on this project.

If you have any feed back or improvements then please feel free to publish these through Stargazer's Lounge so that others may benefit from your work.

Astrotux.

20/09/2012 Page 15