Teacup Firmware

From RepRap
Revision as of 06:34, 3 October 2011 by Casainho (talk | contribs) (Added link to internal RepRap wiki for R2C2.)
Jump to: navigation, search

Teacup Firmware

Teacup Firmware is a complete rewrite of the RepRap FiveD firmware started by Triffid Hunter. It fits into an ATmega168-based board, i.e. the Arduino Diecimila, as well as larger controllers. Its main advantage is better performance. The group of developers also includes Traumflug and Jakepoz. You can also check out Ralith's reprap-firmware that has similar goals to this project.

Teacup firmware is also available for the R2C2 electronics which runs on a microcontroller ARM 32bits @ 100MHz. Triffid Hunter is improving Teacup firmware on R2C2 electronics.

This firmware is only loosely based on the official FiveD firmware, however it avoids C++ in favour of plain C, uses 100% integer math, and works very hard to minimize/eliminate long math operations in interrupt context.

Design Goals

  • Keep compatibility with "official" FiveD
  • 100% integer computations
  • Serial transmit buffer
  • Can fit onto an ATmega168
  • Works on ATmega328P and larger ATmega's
  • C89 compatibility, no C++
  • No dependence on Arduino libraries
  • Easy to read and modify the source code

How to Use

Installation of Teacup Firmware is pretty much the same as with the official firmware, except there are more options for developers.

Simple Installation

  1. Download the Arduino IDE for your platform if you haven't already. Versions 0018 and 0022 have been used the most, but the other versions should work just fine. If you are running Ubuntu Linux, you can just do:
    apt-get install arduino
  2. Go to the Teacup Git repository and download the Zip archive with the big download button to the right.
  3. Unpack that archive somewhere convenient.
  4. Rename the unpacked folder to "Teacup_Firmware" (before opening it with the Arduino IDE).
  5. Copy config.h.dist or config.yourboardhere.h to the config.h file. For example, if you were using a RAMPS board, you would do the following:
    cp config.ramps.h config.h
  6. Edit config.h with your favourite text editor to adjust the values to suit your machine. Hints are given inside the file and in the tuning section of this page.
  7. Fire up the Arduino IDE and select your serial connection and board type from the Tools menu.
  8. Open the file Teacup_Firmware.pde with the IDE.
  9. Hit the UPLOAD button in the IDE's toolbar.
  10. Done. Your controller is now ready to receive GCode from RepRap Host, Skeinforge's send.py, a serial terminal or whatever sending tool you prefer. Not to forget, Teacup Firmware expects commands at a baudrate of 115200 baud.

Developer Installation

  1. Install git, avr-libc, gcc-avr and avrdude.
  2. Get a copy of the source from the Teacup Git repository. If you are not familiar with Git, see Is Git new to you?.
    git clone https://github.com/triffid/Teacup_Firmware.git && cd Teacup_Firmware
  3. COPY config.h.dist to config.h and edit to suit your electronics.
  4. Check programming settings in Makefile.
    1. Upload baudrate depends on your bootloader. The following are apparently common values:
      • Arduino with Atmega168: 19200
      • Arduino with Atmega328: 57600
      • Arduino with Atmega644: 38400
      • Arduino with Atmega2560: 115200
      • Generation 7 Electronics: 115200
    2. Configure the path of avrdude and avrdude.conf. If there are errors, you can use the one that comes with the Arduino IDE, under hardware/tools.
    3. Check that the programming protocol is the right one.
      • ArduinoMEGA 2560 needs stk500v2
      • Most boards use stk500v1
  5. make
  6. make program
  7. ./sender.sh
  8. Have a play, go to 1) if not right.
  9. Try printing something!

Design Details and Tuning

While chances are good things start to work right after installation, a lot of details can be adjusted for more comfort, less machine wear or faster operation.

Constant Acceleration

The official FiveD firmware changes speed by a fixed amount each step, however this also alters the step time. Acceleration = dv/dt, so with a fixed dv but a changing dt, acceleration changes during a move. This makes high speeds quite unattainable as the acceleration quickly outstrips the motor's ability to keep up.

Teacup Firmware contains a constant acceleration implementation.

Acceleration, RepRap Style

This is the default and matches the strategy of the official firmware. Each movement starts at the speed of the previous command and accelerates or decelerates to reach target speed at the end of the movement.

Goal of this strategy is to allow calculation of smooth movements in the host software. If communication between host and controller gets delayed, hard stops and starts are to be expected. This strategy isn't useful for commands issued by hand, either.

You can disable this behaviour in config.h by commenting out


Acceleration, Start/Stop Ramping

This variation guarantees always smooth starts and stops, as all acceleration and deceleration is calculated in firmware (and actually uses less code than the above). Each movement starts at (almost) no speed, linearly accelerates to target speed and decelerates just in time to smoothly stop at the target. The steepness of acceleration and deceleration is configurable.

A drawback of the current implementation is, it stops after each move. This means slow average speeds in case of many short moves. It'll be possible to improve this situation by taking the next move into account when ramping down. A not-so-trivial task though, predestined for a hacking week sometimes in the future.

Please note real-world machines in fact can't gain full speed instantly. Trying to do so results in bending and early wear out of the mechanical parts. Also, if acceleration is reliable, you can approximately double the speed of stepper motors without risking loss of steps. In tests with my setup I got over 1000 rpm with an ordinary NEMA-23 stepper!

As most current GCode generators expect RepRap-style acceleration and you can use only one style of acceleration, this feature is turned off by default. To use it, turn off ACCELERATION_REPRAP in config.h and turn on:


This is enough for first tests (always recompile and re-upload the firmware, btw.), but to get best results, you should adjust ramping steppness as well:


Smaller values give quicker acceleration. Tune it to what you think your machine can achieve. Sturdier machines with powerful motors can accelerate quick, weak machines with light motors need a bigger value.

Endstop Handling

For efficiency reasons (and to avoid ruined prints when endstops get false triggers) the endstops are only checked during homing operations.

To test an endstop, send gcode "G161 X0" (for the X axis for example). The motor should move until you trigger the endstop. If G161 causes the axis to move the wrong way, but nudging (+/-) moves the correct way, you need to invert your endstop because teacup thinks it's already triggered, which causes the homing routine to jump straight to the part where it tries to back out of the endstop.

When connecting mechanical endstops, it is best to connect them NC (normally Closed) between the Sig and Gnd pins for the endstop in question. (This should ensure that the endstop triggers if it comes unplugged). Uncomment USE_INTERNAL_PULLUPS in your config.h and also uncomment all of the [X|Y|Z]_INVERT_[MIN|MAX] lines.

Transmission of Multiple Commands

Teacup Firmware has the capability to receive additional commands while working on the first one. This avoids short stops between commands and will allow for even more smooth transitions from one movement to the next in the future.

XON/XOFF Flow Control

Teacup Firmware has XON/XOFF flow control implemented. This is not needed when sending GCode files via RepRap Host software, but quite helpful when sending files with a serial terminal emulator (GtkTerm, CoolTerm, HyperTerminal, etc.).

This feature is off by default, turn it on in config.h by uncommenting

#define XONXOFF

Patches, Enhancements

If you have a change or a patch you want to discuss, or if you don't have github commit access, please upload the patch here.

To apply patches, type git apply in your terminal, inside your local copy of git repo, then copy the text given here into the terminal and hit ctrl-d.

If you work with git on Teacup Firmware, please do commits in small pieces, one topic/bug at a time. This helps a lot in reviewing patches. That done, you can create a set of patches easily:

git format-patch --keep-subject -o out origin

You'll find each of your patches in the out/ directory, nicely equipped with a mail header and a proper file name.

Rationale and History

I started building my electronics with only a regular arduino to test with. This was perfectly sufficient for playing with the pololu stepper controllers and the max6675 I bought after reading about all the issues with thermistors that people were having. After a while I decided to check out the official firmware but it required an atmega644. I wondered why. So, I decided to skim through the code to see what took up so much space. From what I could see, it was written by someone who was familiar with programming desktop systems and larger embedded devices, but didn't have much experience with small devices such as the atmega168 and atmega644. This showed in the use of C++ which served only to make the code harder to read, and the prolific use of floating-point math, with some appearing even in interrupt context! I came to the conclusion that there was no reason that the main body of code couldn't fit onto an atmega168 except for the burdensome and unnecessary overheads from object-oriented code and floating point math. A quick count assured me that the atmega168 had enough pins, but only barely, and I started reading the official firmware properly, with an eye to rewriting as much as possible in a fashion suitable for small microcontrollers.

Starting with an arduino skeleton library I had assembled over time, some of my test code and the official firmware, I hacked up a passable integer-only, straight C implementation of the dda, and wrote my own gcode parser from scratch which processed each character as it arrived (with some buffering of course) instead of waiting for a whole line and then trying to process it all at once.

As soon as my new firmware was able to run a few consecutive moves, I released it for peer review.

The forum thread http://forums.reprap.org/read.php?147,33082 has much of the history from this point on.

Traumflug was the first to send patches, and has done a significant amount of work on a number of different parts of this firmware. Jakepoz ported it to gen3 branch electronics. Cefiar posted me some thermistors to sponsor addition of thermistor-reading code

Many others have given encouragement and suggestions without which this firmware may never be what it is today.

Architectural Overview

Teacup Firmware is quite similar to the official firmware in some ways, and markedly different in others. Teacup Firmware has as much modularity as I could get away with without sacrificing efficiency.

At startup, the code in mendel.c is run first. This initialises all the modules that need it, then starts polling the clock flags and feeding incoming serial characters to the gcode parser. The gcode parser processes each character individually, keeping track via internal state rather than buffering a line and skipping back and forth. The gcode parser converts floating values to integer or fixed-point representations as soon as it encounters a non-numeric character. It calls many module functions directly, but the most interesting part is move creation, where it passes a target position and speed to enqueue()[dda_queue.c] which adds it to the queue, and fires up dda_start()[dda.c] if the queue was empty. dda_start initialises the dda, figures out the stepper directions and first step timeout and a few other bits of housekeeping, then sets the timer for the appropriate timeout. When the timer fires, it calls dda_step()[dda.c] which sends all the step signals then figures out the next step timeout based on acceleration and speed settings. When the last step has been made, the dda "dies" (sets 'live' property to 0) after which queue_step[dda_queue.c] advances the queue read pointer and starts the next dda.

It is necessary to keep interrupts very short on small microcontrollers, and I have endeavoured to keep them all as short as possible. Unfortunately, dda_step[dda.c] is fairly large. I simply hope that it doesn't take so much time that it interferes with the other interrupts too much.

Interesting code sections

The serial ringbuffers are critical for good communication, but for some reason the official arduino libraries don't implement a tx queue, all but preventing sending stuff from interrupt context. As long as the queues have a length of 2^n, we can use bitwise operations rather than numerical comparison to trim the read and write pointers. The serial send function (serial_writechar[serial.c]) is necessarily careful about checking if it's in an interrupt and only waiting for space in the queue if it's not. The dda queue is also a ringbuffer, although its implementation is harder to see as it's embedded in lots of other stuff.

The gcode parser shows how to parse each character as it comes in, so 99% of a command can be processed before the EOL is even received. It started off as a simple state machine, which then grew and shrank and morphed until it was both smaller and more functional.

The fixed-point stuff is fun, although we have to manually ensure that the decimal point stays in the right spot. decfloat_to_int[gcode.h] is used to convert incoming floats to integer implementations by starting off with a (very!) crude floating point implementation, then choosing appropriate scaling factors within the gcode parser itself. This allows us to do a little stuff that looks like floating-point math without the burdensome overhead of a full fp implementation.

The PID code in heater.c is probably quite generalisable, and seems to work well when tuned. Google knows of plenty of PID tuning guides.

Is git new to you?

Git can be heavy going. You probably want to go to the github.com site, make an account and get the recommended git tools for your system. Once you've done that, try:

git clone git://github.com/triffid/Teacup_Firmware.git

It wants triffid's username, not yours. The github instructions miss that little nugget of information. The PC should create a new directory and respond with something like:

remote: Counting objects: 1680, done.
remote: Compressing objects: 100% (639/639), done.
remote: Total 1680 (delta 1189), reused 1465 (delta 1021)
Receiving objects: 100% (1680/1680), 428.26 KiB | 118 KiB/s, done.
Resolving deltas: 100% (1189/1189), done.

Now go:

cd Teacup_Firmware
git pull origin master

If it says you're up-to-date, awesome. If not, it should grab a few files.

This should get you started. You'll pick git up as you go along.

File descriptions

Teacup File descriptions
File Description
analog.[ch] This is the analog subsystem. Only used if you have a Thermistor or AD595.
arduino.h Pin mappings and helper functions for various arduinos ('168/'328-based, '644-based, '1280-based.
clock.[ch] A system clock for periodic tasks. Supports a long-running clock, but this is disabled by default as nothing uses it (yet!).
copier.[ch] A totally untested and currently unused chunk of code for copying firmware to another identical chip.
dda.[ch] A rather complex block of math that figures out when to step each axis according to speed and acceleration profiles and received moves.
dda_queue.[ch] The queue of moves received from the host.
debug.[ch] Debugging aids.
Teacup.pde Allows firmware to be built in Arduino IDE
func.sh Lots of host-side shell scripts for talking to firmware.
gcode.[ch] Gcode interpreter. Scaling of factors to internally used integer or fixed point happens here too.
heater.[ch] Heater management, including PID and PWM algorithms, and some configuration parameters.
machine.h Configuration variables to match firmware to your hardware.
Makefile instructions for make on how to build firmware. has a list of modules to build which may need to be updated every so often.
mendel.c Firmware startup and main loop code.
pinout.h This file associates various functions with particular pins on your avr.
README This file.
sender.sh A simple talker. Needs "waitfor"
serial.[ch] Serial management and buffers.
sermsg.[ch] Functions for sending messages and values to host.
sersendf.[ch] A small, crude printf implementation.
temp.[ch] Temperature sensor management, includes some configuration parameters.
timer.[ch] Timer management, used primarily by dda.c for timing steps.
watchdog.[ch] Watchdog management. Resets chip if firmware locks up or does something strange.