Teacup Firmware/fr

From RepRap
Jump to: navigation, search

Firmware Teacup

Le firmware Teacup Firmware découle de la réécriture complète du firmware RepRap FiveD initié par Triffid Hunter. Il peut s'installer sur une carte basée sur l'ATmega168, c'est-à-dire une carte Arduino Diecimila, mais aussi sur des contrôleurs plus grands. Son principal avantage est qu'il offre de meilleures performances. Le groupe des développeurs comprend aussi Traumflug et Jakepoz. Vous pouvez aussi aller sur la page Ralith's reprap-firmware qui a les mêmes buts que ce projet.

Le firmware Teacup est également disponible pour l'électronique R2C2 qui fonctionne sur un micro-contrôleur ARM 32bits @ 100MHz. Triffid Hunter améliore le firmware Teacup pour l'électronique R2C2.

Ce firmware est uniquement basé de façon approximative sur le firmware officiel FiveD, cependant il s'appuie entièrement sur le langage C au lieu du C++, utilise 100% de nombres mathématiques entiers, et cherche surtout à minimiser/éliminer les longs calculs in interrupt context.

Buts recherchés

  • Garder la compatibilité avec FiveD "officiel"
  • 100% integer computations
  • Serial transmit buffer
  • Peut être contenu dans une ATmega168
  • Fonctionne sur ATmega328P et au-dessus
  • Fonctionne sur une ATmega32U4 utilisée par Teensy (http://www.pjrc.com/teensy) ~18176 bytes with LUFA serial -- 2012-01-12
  • Compatibilité avec C89, pas de C++
  • Pas de dépendance aux librairies Arduino
  • Facile de lire et de modifier le code source

Comment l'utiliser

L'installation du Teacup Firmware est à peu près la même que le firmware officiel, mis à part qu'il y a plus d'options pour les développeurs.

Simple Installation

  1. En particulier sous Windows, assurez-vous d'afficher les extensions de fichiers. Vista est réputé pour faire des choses bizarres lorsqu'elles sont masquées.
  2. Téléchargez le Arduino IDE pour votre plate-forme si ce n'est pas déjà fait. Teacup est indépendant des bibliothèques Arduino et utilise l'IDE seulement comme un outil pour compiler ou téléverser, donc la version importe peu.
  3. Au cas où vous auriez une électronique basée sur un ATmega644, -644P ou -1284P, installez aussi Gen7 Arduino IDE Support.
  4. Allez sur le Git du firmware Teacup et téléchargez l'archive zip à l'aide du gros bouton "Download" sur la droite.
  5. Décompactez cette archive à l'endroit qui vous convient.
  6. Avant de l'ouvrir avec l'IDE Arduino, renommez le répertoire décompacté en Teacup_Firmware. Par exemple, le répertoire Traumflug-Teacup_Firmware-448df5d en Teacup_Firmware.
  7. Copiez config.default.h ou config.yourboardhere.h sous le nom de fichier config.h. Par exemple, si vous utilisez une carte RAMPS, vous devez saisir la commande suivante :
    cp config.ramps.h config.h
  8. Faites de même pour le fichier ThermistorTable.default.h -> ThermistorTable.h.
  9. Éditez config.h avec votre éditeur de texte préféré pour adapter les valeurs qui conviennent à votre machines. Des indications sont données dans le fichier et dans la section réglages de cette page.
  10. Lancez l'IDE Arduino et sélectionnez votre connection série et le type de carte dans le menu Outils (Tools menu).
  11. Ouvrez le fichier Teacup_Firmware.pde avec l'IDE.
  12. Cliquez sur le bouton UPLOAD de la barre de tâche de l'IDE.
  13. Une fois ceci effectué, votre contrôleur est maintenant prêt à recevoir le GCode à partir de RepRap Host, de send.py de Skeinforge, d'un terminal série ou de n'importe quel logiciel pouvant envoyer du GCode. N'oubliez pas que le firmware Teacup attend des instructions à une vitesse baudrate de 115200 baud.

Installation pour Développeur

  1. Installez git, avr-libc, gcc-avr et 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/Traumflug/Teacup_Firmware.git && cd Teacup_Firmware
  3. COPY config.default.h 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. The programming protocol is set after the -c argument
      • ArduinoMEGA 2560 needs stk500v2
      • Arduino Duemilanove needs arduino
      • 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!

Particularités du firmware et Ajustements

Même s'il y a de grandes chances que tout fonctionne bien après l'installation, pas mal de détails peuvent être ajustés pour plus de confort, limiter l'usure de la machine ou pour accélérer l'impression.

Configuration des broches dans Teacup

Dans le fichier config.h il faut attribuer à chaque fonction une broche du microcontrôleur. Les noms attendu sont de la forme DIOx ou AIOx, x étant un nombre.

Ces noms font référence aux broches des cartes Arduino :

  • DIO signifie Digital Input / Output (entrée sortie numérique)
  • AIO signifie Analog Input Output (entrée sortie numérique)

Si vous utilisez la documentation de votre microcontrôleur pour affecter les broches, vous vous retrouvez avec des noms en Port / numéro de broche à convertir en DIOx ou AIOx. Pour cela, deux solutions :

  • soit vous regarder la correspondance sur le plan d'une carte Arduino utilisant le même microcontrôleur que vous, les numéros qui vous intéressent sont ceux qui sont indiqué à coté du connecteur de la carte.
  • soit vous chercher le nom correspondant à votre broche dans le fichier arduino_.h . Dans ce fichier les broches sont nommées PINxy avec x la lettre du port et y le numéro de la broche.

Extrait du fichier arduino_168_328p.h

#define AIO3_PIN      PINC3
#define AIO3_RPORT    PINC
#define AIO3_WPORT    PORTC
...

On voit que la broche 3 du port C est appelée AIO3 par Teacup

Réglages des pas des moteurs

Le réglage se fait dans le fichier config.h du firmware. Josef Prusa a mis à disposition un outil permettant de calculer les différentes valeurs à indiquer dans le firmware concernant les moteurs pas à pas : calculateur de Josef Prusa

Accélération constante

Le firmare officiel FiveD change la vitesse selon un niveau fixé à chaque pas, cependant ceci altère d'un autre côté la rapidité. Accélération = 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.

Accélération, Type de RepRap

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.

Gestion des Endstops

Pour des raisons de rendement (et pour éviter des impressions désastreuses à cause d'endstops mal configurés) les endstops sont seulement vérifiés au début de l'impression, durant l'initialisation de la position de départ (homing).

Pour tester un endstop, envoyez le gcode "G161 X0" (pour l'axe X par exemple). Le moteur devrait se déplacer jusqu'à ce que le endstop soit déclenché. Si G161 fait que l'axe se déplace dans le mauvais sens, mais que nudging (+/-) le fait déplacer dans le bon sens, il faut que vous retourniez votre endstop car Teacup croit qu'il est déjà déclenché, ce qui lance la routine de la mise à zéro (homing) pour rejoindre directement le côté en essayant de revenir en arrière par rapport au endstop.

Quand vous branchez un endstop, il est recommandé de le connecter en position NC (Normally Closed) entre les pattes Sig et Gnd (ceci garantit que le endstop est en position déclenchée même s'il est débranché). Décommentez USE_INTERNAL_PULLUPS dans votre fichier "config.h" ainsi que toutes les lignes [X|Y|Z]_INVERT_[MIN|MAX].

Transmission de plusieurs instructions

Le firmware Teacup a la capacité de recevoir d'autres instructions alors qu'il travaille déjà avec une précédente. Ceci permet d'éviter les légers arrêts entre les instructions, ce qui dans le futur favorisera des transitions plus fluides d'un mouvement à l'autre.

Contrôle de flux XON/XOFF

Le firmaware Teacup peut exécuter le contrôle de flux XON/XOFF. Ceci n'est pas nécessaire lorsqu'on envoie des fichiers GCode via le logiciel de l'ordinateur commandant la RepRap, mais plutôt utile quand on envoie des fichiers avec un émulateur de terminal série (GtkTerm, CoolTerm, HyperTerminal, etc.).

Cette possibilité est désactivée par défaut, activez-là dans le fichier "config.h" en décommentant la ligne :

#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/Traumflug/Teacup_Firmware.git

It wants Traumflug'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.