Teacup Firmware

From RepRap
Revision as of 21:37, 2 November 2010 by VikOlliver (talk | contribs) (Helpful hints for first-time git users.)
Jump to: navigation, search

FiveD on Arduino is a complete rewrite of the RepRap FiveD firmware started by Triffid Hunter, which happens to fit into an ATmega168-based board, i.e. the Arduino Diecimila, just as well as into bigger sized controllers. It's main advantage is better performance, the group of developers now also includes Traumflug and Jakepoz.

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 atmega168
  • works on atmega328p and larger atmegas
  • C89 compatibility, no C++
  • no dependence on Arduino libraries
  • easy to read, modify

Projects With Similar Goals:

How to Use

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

Simple Installation

Note: this is currently broken

  1. Get the Arduino IDE if you haven't already. Version 0018 is tested, but older or newer ones should work just as fine.
  2. Get a clone of FiveD for Arduino from the Git repository. If Git is new to you, see Is git new to you?
  3. Copy config.h.dist to config.h.
  4. Edit config.h with your favourite text editor (gedit, geany, TextEdit, WordPad, Emacs, ...) to adjust the values to suit your machine. Hints are given inside the file and in the tuning section of this page.
  5. Fire up the Arduino IDE and select your serial connection and board type from the Tools menu.
  6. Open the file FiveD_for_Arduino.pde with the IDE.
  7. Hit the UPLOAD button in the IDE's toolbar.
  8. 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, FiveD on Arduino expects commands at a baudrate of 115200 baud.

Developer Installation

  1. Install avr-libc and gcc-avr and avrdude
  2. COPY config.h.dist to config.h and edit to suit your electronics
  3. check programming settings in Makefile
    • upload baudrate is different for different chips:
      • Atmega168: 19200
      • Atmega328: 57600
      • Atmega644: 38000
    • configure the path of avrdude (I used the one in the arduino package)
  1. make
  2. make program
  3. ./sender.sh
  4. have a play, go to 1) if not right
  5. 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.

FiveD on Arduino 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

#define ACCELERATION_REPRAP

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:

#define ACCELERATION_RAMPING

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:

#define ACCELERATION_STEEPNESS    500000

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.

Transmission of Multiple Commands

FiveD on Arduino 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

FiveD on Arduino 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 FiveD on Arduino, 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 official reprap electronics (gen3 branch) 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

FiveD on Arduino is quite similar to the official firmware in some ways, and markedly different in others. FiveD on Arduino 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, create a directory to put the source in and change to it. Then try:

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

It wants triffid's username, not yours. The github instructions miss that little nugget of information. The PC should 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:

git pull origin release-candidate

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

  • 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.

  • FiveD_on_Arduino.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.