Friday, January 9, 2009

Mardus-Kreutz DIY Unipolar MicroStepper Drive. The Firmware.

Let's talk Today about the firmware design:

Most of the design goals become constrains on the development of the firmware:
  • Step-direction Command interface
  • Micro-Step modes: Full-Step, Half Step, 1/4, 1/8, 1/16, 1/5 and 1/10.
  • Current Reduction after 1 second inactivity.
  • Reference current "Morphing" versus Speed.
  • Automatic Torque compensation.
  • Active "high" (logic low to high transition) Step and Direction signals.
  • 100Khz Maximum Step frequency.

The chosen microcontroller (ATtiny2313-20) adds extra constrains to the firmware:

Features of the Attiny2313-20 :

(The features used as advantages in our firmware are highlighted in bold, firmware constraining characteristics are in red)

Utilizes the AVR® RISC Architecture
• AVR – High-performance and Low-power RISC Architecture
120 Powerful InstructionsMost Single Clock Cycle Execution
32 x 8 General Purpose Working Registers
– Fully Static Operation
Up to 20 MIPS Throughput at 20 MHz
• Data and Non-volatile Program and Data Memories
2K Bytes of In-System Self Programmable Flash
Endurance 10,000 Write/Erase Cycles
128 Bytes In-System Programmable EEPROM
Endurance: 100,000 Write/Erase Cycles
128 Bytes Internal SRAM
– Programming Lock for Flash Program and EEPROM Data Security
• Peripheral Features
One 8-bit Timer/Counter with Separate Prescaler and Compare Mode
One 16-bit Timer/Counter with Separate Prescaler, Compare and Capture Modes
Four PWM Channels
– On-chip Analog Comparator
Programmable Watchdog Timer with On-chip Oscillator
– USI – Universal Serial Interface
– Full Duplex USART
• Special Microcontroller Features
– debugWIRE On-chip Debugging
– In-System Programmable via SPI Port
External and Internal Interrupt Sources
– Low-power Idle, Power-down, and Standby Modes
Enhanced Power-on Reset Circuit
Programmable Brown-out Detection Circuit
– Internal Calibrated Oscillator
• I/O and Packages
– 18 Programmable I/O Lines
20-pin PDIP, 20-pin SOIC, 20-pad QFN/MLF
• Operating Voltages
– 1.8 - 5.5V (ATtiny2313V)
– 2.7 - 5.5V (ATtiny2313)
• Speed Grades
– ATtiny2313V: 0 - 4 MHz @ 1.8 - 5.5V, 0 - 10 MHz @ 2.7 - 5.5V
– ATtiny2313: 0 - 10 MHz @ 2.7 - 5.5V, 0 - 20 MHz @ 4.5 - 5.5V
• Typical Power Consumption
– Active Mode
1 MHz, 1.8V: 230 μA
32 kHz, 1.8V: 20 μA (including oscillator)
– Power-down Mode

Let's go a little deeper on some of the highlighted areas:

Flash Memory: The ATtiny2313 contains 2K bytes On-chip In-System Reprogrammable Flash memory for program storage. Since all AVR instructions are 16 or 32 bits wide, the Flash is organized as 1K x 16.

SRAM Data Memory:
The lower 224 data memory locations address both the Register File, the I/O memory, Extended I/O memory, and the internal data SRAM.

The first 32 locations address the Register File, the next 64 location the standard I/O memory, and the next 128 locations address the internal data SRAM.

The five different addressing modes for the data memory cover: Direct, Indirect with Displacement, Indirect, Indirect with Pre-decrement, and Indirect with Post-increment. In the Register File, registers R26 to R31 feature the indirect addressing pointer registers.

The direct addressing reaches the entire data space.

The Indirect with Displacement mode reaches 63 address locations from the base address given by the Y- or Z-register.

When using register indirect addressing modes with automatic pre-decrement and postincrement, the address registers X, Y, and Z are decremented or incremented.

The 32 general purpose working registers, 64 I/O Registers, and the 128 bytes of internal data SRAM in the ATtiny2313 are all accessible through all these addressing modes.

EEPROM Data Memory: The ATtiny2313 contains 128 bytes of data EEPROM memory. It is organized as a separate data space, in which single bytes can be read and written. The EEPROM has an endurance of at least 100,000 write/erase cycles.

8-bit Timer/Counter 0 with PWM: Timer/Counter0 is a general purpose 8-bit Timer/Counter module, with two independent Output Compare Units, and with PWM support. It allows accurate program execution timing (event management) and wave generation. The main features are:

• Two Independent Output Compare Units
• Double Buffered Output Compare Registers
• Clear Timer on Compare Match (Auto Reload)
• Glitch Free, Phase Correct Pulse Width Modulator (PWM)
• Variable PWM Period
• Frequency Generator
• Three Independent Interrupt Sources (TOV0, OCF0A, and OCF0B)

16-bit Timer/Counter1: The 16-bit Timer/Counter unit allows accurate program execution timing (event management), wave generation, and signal timing measurement. The main features are:

• True 16-bit Design (i.e., Allows 16-bit PWM)
• Two independent Output Compare Units
• Double Buffered Output Compare Registers
• One Input Capture Unit
• Input Capture Noise Canceler
• Clear Timer on Compare Match (Auto Reload)
• Glitch-free, Phase Correct Pulse Width Modulator (PWM)
• Variable PWM Period
• Frequency Generator
• External Event Counter
• Four independent interrupt Sources (TOV1, OCF1A, OCF1B, and ICF1)

External Interrupts

The External Interrupts are triggered by the INT0 pin, INT1 pin or any of the PCINT7..0 pins. Observe that, if enabled, the interrupts will trigger even if the INT0, INT1 or PCINT7..0 pins are configured as outputs. This feature provides a way of generating a software interrupt. The pin change interrupt PCIF will trigger if any enabled PCINT7..0 pin toggles. The PCMSK Register control which pins contribute to the pin change interrupts. Pin change interrupts on PCINT7..0 are detected asynchronously. This implies that these interrupts can be used for waking the part also from sleep modes other than Idle mode.

The INT0 and INT1 interrupts can be triggered by a falling or rising edge or a low level. When the INT0 or INT1 interrupt is enabled and is configured as level triggered, the interrupt will trigger as long as the pin is held low. Note that recognition of falling or rising edge interrupts on INT0 and INT1 requires the presence of an I/O clock. Low level interrupt on INT0 and INT1 is detected asynchronously. This implies that this interrupt can be used for waking the part from sleep modes other than Idle mode. The I/O clock is halted in all sleep modes except Idle mode.

Note that if a level triggered interrupt is used for wake-up from Power-down, the required level must be held long enough for the MCU to complete the wake-up to trigger the level interrupt. If the level disappears before the end of the Start-up Time, the MCU will still wake up, but no interrupt will be generated

Interrupt Response Time

The interrupt execution response for all the enabled AVR interrupts is four clock cycles minimum. After four clock cycles the program vector address for the actual interrupt handling routine is executed. During this four clock cycle period, the Program Counter is pushed onto the Stack. The vector is normally a jump to the interrupt routine, and this jump takes three clock cycles. If an interrupt occurs during execution of a multi-cycle instruction, this instruction is completed before the interrupt is served. If an interrupt occurs when the MCU is in sleep mode, the interrupt execution response time is increased by four clock cycles. This increase comes in addition to the start-up time from the selected sleep mode.

A return from an interrupt handling routine takes four clock cycles. During these four clock cycles, the Program Counter (two bytes) is popped back from the Stack, the Stack Pointer is incremented by two, and the I-bit in SREG is set.

Brown-out Detection

The ATtiny2313 has an On-chip Brown-out Detection (BOD) circuit for monitoring the VCC level during operation by comparing it to a fixed trigger level. The trigger level for the BOD can be selected by the BODLEVEL Fuses. The trigger level has a hysteresis to ensure spike free Brown-out Detection.

Watchdog Timer

The ATtiny2313 has an Enhanced Watchdog Timer (WDT). The main features are:
• Clocked from separate On-chip Oscillator
• 3 Operating modes
– Interrupt
– System Reset
– Interrupt and System Reset
• Selectable Time-out period from 16ms to 8s
• Possible Hardware fuse Watchdog always on (WDTON) for fail-safe mode.

The Watchdog Timer (WDT) is a timer counting cycles of a separate on-chip 128 kHz oscillator. The WDT gives an interrupt or a system reset when the counter reaches a given time-out value. In normal operation mode, it is required that the system uses the WDR - Watchdog Timer Reset - instruction to restart the counter before the time-out value is reached. If the system doesn't restart the counter, an interrupt or system reset will be issued.

In Interrupt mode, the WDT gives an interrupt when the timer expires. This interrupt can be used to wake the device from sleep-modes, and also as a general system timer. One example is to limit the maximum time allowed for certain operations, giving an interrupt when the operation has run longer than expected. In System Reset mode, the WDT gives a reset when the timer expires. This is typically used to prevent system hang-up in case of runaway code. The third mode, Interrupt and System Reset mode, combines the other two modes by first giving an interrupt and then switch to System Reset mode. This mode will for instance allow a safe shutdown by saving critical parameters before a system reset.

The Watchdog always on (WDTON) fuse, if programmed, will force the Watchdog Timer to System Reset mode. With the fuse programmed the System Reset mode bit (WDE) and Interrupt mode bit (WDIE) are locked to 1 and 0 respectively.

To further ensure program security, alterations to the Watchdog set-up must follow timed sequences. The sequence for clearing WDE and changing time-out configuration is as follows:
1. In the same operation, write a logic one to the Watchdog change enable bit (WDCE) and WDE. A logic one must be written to WDE regardless of the previous value of the WDE bit.
2. Within the next four clock cycles, write the WDE and Watchdog prescaler bits (WDP) as desired, but with the WDCE bit cleared. This must be done in one operation.

(to be continued)..........

Monday, November 24, 2008

Mardus-Kreutz Unipolar Micro-stepper. 4th Part.

The Unipolar Power Stage

The power stage receives Sync pulses from the translator as well as the following signals: Phase_A, Phase_A\, Phase_B, Phase_B\, Vref_Channel A, Vref_Channel B and regulates the current flowing on the stepper motor's coils. Channel A and B are identical, so we are going to describe only one of them.

Power Stage Channels.

Each channel drives the coils corresponding to one phase of the Stepper motor and includes the Dual Mosfet Driver, Power Mosfets, Chopper circuit and the reference adjustment circuit for the respective phase.

The reference Adjusting circuit.

The reference analog waveform comes from the translator, half of the low pass filter is physically located on the power stage board and its function is to attenuate noise introduced on the ribbon cable, delivering an analog signal to the chopper's comparator comprising unattenuated frequencies from zero to about 1.5Khz and attenuated at about 12 dB/octave over 1.5 Khz. Potentiometers R18 and R19 set the peak coil current that is going to be regulated by the chopper stage.

1/10 Micro-step Reference Waveforms

The chopper Stages.
Our unipolar stepper drive's current regulation circuit is based on a fixed frequency chopper with "blanking time".
Each channel's chopper stage is basically integrated by a SET dominant S-R latch, a dual Mosfet driver and a voltage comparator.

The result of the comparison between the actual coil current and the reference voltage resets the S-R latch when the actual current produces a voltage on the sense resistor whose value exceeds the reference voltage. The resetted latch inhibits the Mosfet driver which turns-off the conducting Mosfet, the coil current begins to decay until the next Sync signal triggers the Set input of the latch in the next cycle. The coil current Decay Mode is called "Fast Decay" mode and is the only mode available on unipolar stepper drives.

Reference (blue) versus Current Sense Resistor voltage (yellow).

Upon receiving the sync signal the Latch changes state forcing the proper Mosfet in the sequence to turn-on, the SET dominance characteristic of the latch makes the Set signal to force the output into conduction even if a reset signal is received from the comparator, so while the SYNC signal is LOW the proper Mosfet is kept turned ON, that is what is called "Blanking time".

Blanking time versus Switching transients.

The objective of the introduction of a "Blanking time" is to overcome the problem presented with switching transient currents as soon as a power Mosfet is Turned-ON. Those transient currents create short duration peak voltages (from 0.5 to 2 micro-seconds) on the Low side sense resistors, whose values exceed the reference voltage and otherwise would affect the normal function of the current regulator circuit by prematurely switching Off the Mosfets.

Part of the chopper stage is the Mosfet Driver. The dual Mosfet driver chips employed in our circuit have an external inhibit input (one per individual Mosfet driver) which is driven by the corresponding latch output.

The logic Step sequence.

A-B phase switching sequence.

The input signals to the Mosfet drivers come from the translator, they are: Phase_A, Phase_A\, Phase_B, and Phase_B\. Each signal is activated following a pre-defined switching sequence, stored in the firmware, depending on the direction of rotation of the motor. Phase A, and Phase A\ are never activated at the same time, the same applies to the other two signals respectively.

Reference vs Phase Switching Channel A

The logic sequence depends only on the rotational direction and always correspond with the Two phases ON Full Step driving mode. The actual reference waveform (on each channel) is the only factor that changes with the micro-step mode.

Reference vs Phase Switching channel B

The Mosfet Drivers

The Mosfet driver chips are the Texas Instruments UCC27424D (SMD components), as we already know, a special characteristic (Inhibit inputs) of this particular chip is used in our design as a means to avoid having to include extra logic gates to disable the outputs. This component is a really critical component on our design.

The gate driving voltage is the 9 Volts coming from the 7809 linear regulator. We use "Logic Gate" power Mosfets (IRL640), the maximum gate voltage is limited to 10 Volts, hence the use of the 9 Volts regulator. The 4 amp Mosfet driving current capability of the driver chips makes the switching times short, so switching losses are kept to the minimum. The gate resistors are calculated in order to control dV/dt to less than 3 Volts/nanosecond.

Thursday, November 20, 2008

DIY Approach to the Mardus-Kreutz Unipolar Micro Stepper Drives

At least the power stage should be made on a double side PCB following the Rev2.1D or higher design. I provide the Gerber files for all the interested people who want to send them to a PCB fab, or want to etch or mill them by themselves. On the other side, there are a few people selling the bare boards or kits for both the M-K and the translators.

Another option is to use the K-4 four axis SMD PC Interface board (not a DIY board) to avoid ordering and assembling the individual translator boards and having to buy/assemble a B.O.B. (Break Out Box). The K-4 includes four translators and B.O.B. functionality.

The K-4 PC Interface board has the following specifications:

  • Operating Modes: Full Step, 1/2, 1/4, 1/8, 1/16, 1/10, 1/5.
  • Opto-isolated Inputs and Outputs (except External Output interface signals). RF isolated Step-direction signals up to 2500 volts.
  • +3.3 Volt or+ 5 Volt PC interface (jumper selectable).
  • Automatic torque compensation.
  • Automatic Reference waveform "morphing".
  • Firmware Upgrade capability built in.
  • External Output connector for interfacing the rest of the LPT port pins.
  • Idle current reduction (50%) after 1 second inactivity independently for each axis.
  • Charge-Pump (watch dog) circuit disables the outputs if the 12 KHz signal is not received from the software, protecting against Software "freezes" and LPT cable disconnections.
  • A logic LOW at the EMG_STOP pin will disable all Axes and trigger a software E-Stop by pulling pin 10 of the Lpt port LOW.
  • A Fault signal received from any of the Axes will trigger an Emergency Stop.

Individual Axis Specifications:

  • Maximum Step rate: 100 Khz
  • Minimum Step and Direction pulse width = 2 uSec @ 100 Khz.
  • Step and direction signals are Active "High" (Low to High Transition).
  • 40 Khz chopper frequency.

Bare PCBs Rev 2.1d

Some photos taken during prototype assembly:

Wednesday, November 19, 2008

Tools required for Assembly and Testing the Mardus-Kreutz Drives

  • Soldering Iron 25 or 30W, (temperature control is desirable but not necessary)

  • Soldering wire (Rosin core, 37/63 or 40/60 0.032 diameter or equivalent) or PB free.

  • Desoldering pump (Soldapult or equivalent with anti-static tip). Desirable, will be handy if some rework is needed.

  • Small wire/cable cutter Tool.

  • Multimeter.

  • Oscilloscope (desirable but not necessary).

  • Lab power supply (desirable but not necessary).

  • Fine Long nose pliers or equivalent tool.

  • Small screwdrivers (flat and Phillips tips)

  • Insulated wrapping wire AWG 30 (solid copper twisted telephone wire or Cat5 solid twisted pair network wires could be used too) for prototype perforated-board wiring (not required if the translator PCB is ordered)

  • 10 Conductor ribbon cable and two 10 pin female IDC connectors (Translator to Power Stage interface cable) Lenght is user dependent (the shorter the better) maximum 12".
  • Anti-Static mat with ground cable (the link is only one example)
  • Anti-Static Velcro wrist-strap with ground cable (the link is only one example)

Sunday, November 16, 2008

Mardus-Kreutz Unipolar Micro-stepper. 3rd Part.

Translator's Block Diagram

In this part of the series we will open the translator black box and explain what is inside each of the smaller boxes.

Opto-Isolator Stage.

The opto-isolator stage's function is isolate the signals coming into the translator, specially, isolate the PC Ground from the motor power supply ground.

Isolation is used to protect the Lpt port of the PC from dangerous voltages and current leakage from the motor power supply, but its main function is really protect the Pc user from nasty/dangerous electrical shocks should the protective ground connection, on the motor power supply circuit, fail by any reason (the protective ground is the green wire connected to the building's ground).

Micro Controller Circuit.

The micro-controller used in our design is the ATtiny2313-20 from Atmel. This circuit includes, the micro-controller chip, Reset circuit, 20 Mhz oscillator's Xtal, Some LEDs for status display and the programming Jumpers connected to some of the chip's I/O pins.
Reference signal Processing.
The output of the micro-controller to the reference processing circuit are two 39.2 Khz 16 bits hardware generated PWM signals. Both signals have to be processed in order to obtain two analog waveforms which will respectively become the Channel A and Channel B current reference waveforms.
The processing circuit is a Second order low pass filter (two cascaded first order filters).
Another logic level signal coming from the micro-controller (STANDBY) will reduce the reference voltage to 50% after 1 second inactivity. This is done by means of a switched resistive voltage divider, the switching is done by means of two low power Mosfets.
Half of the Reference signal processing circuit is located on the Translator board, the other half is located on the Power Stage board. The reason of the splitting is simple, the reference signals are sent to the Power stage by means of a ribbon cable, noise captured on the cable is attenuated by the second low pass filter, located at the power board, before the analog signal amplitude is divided at the respective current setting potentiometer (more detailed explanation on this subject will be offered later).
SYNC signal.
This is one of the most important signals, its function is to serve as reference frequency for the choppers at the Power Stage, but it serves a second and very important function: It defines the "blanking time" on the chopper comparator circuits. We will be talking about the "blanking time" when we get to the chopper's circuit description, and a little more when we discuss the blanking time relationship with the minimum step current regulation.
The Sync signal is generated on a hardware 8 bits PWM generator inside the Micro-controller Chip, the "blanking time" is adjustable in the firmware. More information about this subject is going to be posted in the next parts of this blog.
Micro-controller's Watch-Dog.
The internal watchdog time base generator of the micro-controller is used as reference for a software controlled speed measurement circuit, it is also used as reference signal for the 1 Second inactivity Standby signal control.
The Speed measurement circuit is the responsible of controlling the variable morphing reference waveform versus motor speed, details about both features will be discussed on the firmware description part of this series.


Translator and Power stage (click to enlarge)

Translator's bottom side (click to enlarge)

Thursday, November 13, 2008

Mardus-Kreutz Unipolar Micro-Stepper. 2nd Part.

Block diagram of the Mardus-Kreutz drive (Click to enlarge).


What is a Translator?

A "Translator" is the part of the Micro-Stepper Drive circuit whose function is to "translate" Step and Direction input signals into the proper sequence of digital and analog signals required to drive the power output stage.
Basically, the translator contains the brain and soul of the stepper drive. The brain is a cheap but powerful micro-controller, the ATTiny2313 from Atmel. The soul is a simple but effective firmware (micro-controller software) able to handle a maximum step frequency of 100 Khz and providing all the micro-step functionality, as well as current waveform morphing with speed, standby motor current reduction, and automatic torque compensation. The translator includes also the opto-isolation circuit for the Step and Direction signals coming from the PC Lpt port or controlling device.

The Firmware.

The firmware is written in BASCOM AVR, a simple to understand flavor of the Basic language for the AVR micro-controllers, which is also free (the free version is limited to 2K bytes of code, just the capacity of our controller chip). Why Basic and not C or assembly?. We used Basic, as programming language, because the code was intended to be used as a learning tool, and well commented Basic code is simpler to digest.

Power Stage.

The output signals of the "translator" are logic level signals which can't provide the voltage and current levels necessary to drive most stepper motors. The power stage is the part of the circuit that provides the the power handling on the drive. It includes the current control as well as the coil switching, motor power supply filtering, and safety circuits.
The current control circuit is the heart of the Power stage. In our case we selected a fixed frequency chopper circuit. A detailed explanation of the discrete chopper circuit will be addressed in the respective circuit description. On the power stage there are also two voltage regulators: +5 Vdc regulator for the logic circuits, and +9 Vdc for the gate driver chips. The former is also used by the translator board.
Stepper Motor and Micro-stepper Theory
Stepper Motor theory is beyond the scope of this blog, there is a fine tutorial on the subject I would like the reader to familiarize with before continuing reading this blog.
We will be referring to some concepts explained on that tutorial on the description of the circuits on the following posts. My intention is to go deeper into each block (of our Block diagram), opening its contents into increasingly finer details, finalizing at the component level.
I will also talk about design decisions and compromises, as well as the solutions we implemented, in order to overcome some of the fixed frequency chopper inherent dis-advantages.
What I want to make clear is that there are many ways to get any stepper motor running, our design objectives were always focused into micro-stepping driving unipolar motors, but also to get the most of them, in terms of power, accuracy, efficiency and performance.
Our design is neither a mere copy of a text book circuit nor just a discretization of an integrated controller, it was intended as a design exercise with the objective of using it as a learning tool, nevertheless, the final product has an exceptional quality, as you can witness on the many videos taken during the early tests.

Tuesday, November 11, 2008

Mardus-Kreutz Unipolar Micro-stepper Drive.


The Mardus-Kreutz unipolar micro-stepper board was born from a thread in CNCzone.

One of the members, Mardus, asked why DIY discrete unipolar micro-stepper drives were not available. Some of the participants tried to find a logical explanation and a challenge was created to provide a working DIY unipolar micro-stepper.

A few weeks later the first prototype Mardus-Kreutz board was designed and successfully tested. This blog will try to provide information about the design as well as step by step instructions of how to build a working, high quality, unipolar micro-stepper drive.

Mardus-Kreutz board specifications:

Maximum motor voltage: 80Volts
Maximum current: 8 Amps (peak) per phase
Current regulation type: fixed frequency chopper at 39.2 Khz
Micro-step modes: Full, Half, 1/4, 1/8, 1/16, 1/5, 1/10.
Standby current reduction (to 50%) after 1 second inactivity.
Automatic torque compensation and Current waveform morphing on all micro-step modes.
Command interface: Step-Direction (opto-isolated inputs), Motor Enable.
Minimum Step/Dir Pulse width: 2 microSeconds
Auxiliary power supply: 12 - 15 volts DC, non regulated.
Minimum motor current: 1.5 Amp r.m.s. per phase
Stepper motor types: Unipolar, 6 and 8 wires.
The design uses low cost components.
Modular approach: Translator and Power stage (two separated boards).
PCB Assembly complexity: Low/Medium (most components are trough-hole, uses only a couple of SMD components). The translator boards could be made on perforated prototype boards.