Différences entre versions de « ENG-CANSAT-FEATHER-M0-SKETCH »

De MCHobby - Wiki
Sauter à la navigation Sauter à la recherche
 
(8 versions intermédiaires par le même utilisateur non affichées)
Ligne 2 : Ligne 2 :
  
 
== Forewords ==
 
== Forewords ==
The ATSAMD21 is still a newcomer in the Arduino-compatible world. '''Most''' of sketch and libraries would work on ATSAND21 but somes things have to be pointed out!
+
The ATSAMD21 is still a newcomer in the Arduino-compatible world. '''Most''' of sketch and libraries would work on ATSAMD21 but somes things have to be pointed out!
  
 
Le notes here under would apply to the M0 boards.
 
Le notes here under would apply to the M0 boards.
Ligne 49 : Ligne 49 :
  
 
== AnalogWrite / PWM on Feather M0 ==
 
== AnalogWrite / PWM on Feather M0 ==
After looking through the SAMD21 datasheet, we've found that some of the options listed in the multiplexer table don't exist on the specific chip used in the Feather M0.
+
After looking through the SAMD21 datasheet, it appears that some of the options listed in the multiplexer table don't exist on the specific chip used in the Feather M0.
  
 
For all SAMD21 chips, there are two peripherals that can generate PWM signals: The Timer/Counter (TC) and Timer/Counter for Control Applications (TCC). Each SAMD21 has multiple copies of each, called 'instances'.
 
For all SAMD21 chips, there are two peripherals that can generate PWM signals: The Timer/Counter (TC) and Timer/Counter for Control Applications (TCC). Each SAMD21 has multiple copies of each, called 'instances'.
Ligne 69 : Ligne 69 :
 
* '''TCC[0-2],WO[0-7]'''
 
* '''TCC[0-2],WO[0-7]'''
  
En suivant les signaux vers les broches rendues disponibles sir le Feather M0, <font color="red">'''les broches suivantes ne seront pas capable de produire de signal PWM'''</font>:
+
<div style="margin: 15px 0; display: block; padding: 15px 15px 15px 15px; -webkit-border-radius: 2px; -moz-border-radius: 2px; border-radius: 2px; border: 1px solid #CCC;" >
* '''broche analogique A5'''
+
By following the signals to the pins made available on a Feather M0, <font color="red">'''the following pins would not be able to produce PWM signal'''</font>:
 +
* '''Analog Pin A5'''
  
Les broches suivantes peuvent être configurées en sortie PWM (sans aucun conflit) aussi longtemps que les broches SPI, I2C et UART gardent leurs fonctions protocole:
+
The following pins can be configured as PWM (without conflict) as long as the SPI, I2C & UART keeps their protocol functions:
* '''Broches digitales 5, 6, 9, 10, 11, 12 et 13'''
+
* '''Digital pins 5, 6, 9, 10, 11, 12 et 13'''
* '''Broches analogiques A3 et A4'''
+
* '''Analog pins A3 et A4'''
  
Si seules les broches SPI gardent leur fonctions protocole, vous pouvez également faire du PWM sur les broches suivantes:
+
When only the SPI keeps the protocol function, you can also do PWM on the following pins:
* '''TX''' (broche digitale 1)
+
* '''TX''' (Digital pin 1)
* '''SDA''' (broche digitale 20)
+
* '''SDA''' (Digital pin 20)
 +
</div>
  
== analogWrite() et gamme de valeur PWM ==
+
== analogWrite() and range of PWM value ==
Sur un AVR (Arduino Uno), si vous utilisez l'instruction {{fname|analogWrite(pin, 255)}} sur une sortie PWM alors cela conduit à un signal HAUT en permanence sur la broche.  
+
When using an AVR (like Arduino Uno), the instruction {{fname|analogWrite(pin, 255)}} on a PWM output would result in a permanent HIGH signal on the output PIN.  
  
Sur un Cortex ARM, le signal PWM sera fixé à 255/256. Par conséquent, il y aura toujours une très petite 'implusion à 0v'. Si vous avez besoin que le signal soit continuellement HIGH alors il faudra ajouter un test qui remplace l'instruction {{fname|analogWrite(pin, 255)}} par {{fname|digitalWrite(pin, HIGH)}}
+
On a Cortex ARM microcontroler, the output signal would be 255/256th. As a consequence, there is always a small pulse-down to 0v. If you need a continuously HIGH signal then the {{fname|analogWrite(pin, 255)}} must be replaced by {{fname|digitalWrite(pin, HIGH)}}
  
== Fichier d'entête manquant ==
+
== Missing Header file ==
Vous pourriez avoir du code qui utilise des bibliothèques non supportée sur un coeur M0. Par exemple, si vous avez du code contenant la ligne suivante:
+
You may have some code using a library not supported by the M0 code. As example, if you have some code containing the following line:
  
 
<syntaxhighlight lang="c">
 
<syntaxhighlight lang="c">
Ligne 92 : Ligne 94 :
 
</syntaxhighlight>
 
</syntaxhighlight>
  
alors vous obtiendrez une erreur mentionnant
+
Then you will get the following error
  
 
  <nowiki>
 
  <nowiki>
Ligne 101 : Ligne 103 :
 
Error compiling.</nowiki>
 
Error compiling.</nowiki>
  
Ce qui permet de localiser la ligne (et fichier) où s'est produit l'erreur. Il suffira alors de l'inclure dans une structure #ifdef comme celle présentée ci-dessous:
+
Wich allow to identiy the line (and the file) where the error occured. You would just need to include the library loading inside a {{fname|#ifdef}} structure like showed:
  
 
<syntaxhighlight lang="python">
 
<syntaxhighlight lang="python">
Ligne 109 : Ligne 111 :
 
</syntaxhighlight>
 
</syntaxhighlight>
  
Les lignes ci-dessous font en sorte de ne pas inclure le fichier d'entête pour d'autres architectures.
+
The line here upper would not include the header for the listed architectures.
  
Si l'instruction {{fname|#include}} se trouve directement dans votre croquis Arduino alors vous pouvez essayer de retirer cette ligne.
+
If the {{fname|#include}} is present in your Arduino sketch then you may try to remove the  {{fname|#include}} line.
  
== Lancer le Bootloader ==
+
== Start the Bootloader ==
Sur la plupart des AVRs (Arduino Uno), le simple fait de presser le bouton '''reset''' avec le microcontrôleur branché en USB permet de démarrer manuellement le bootloader. Le bootloader termine automatiquement sont exécution au bout de quelques secondes.
+
On most of the AVRs (like Arduino Uno), simply press the '''reset''' button with the microcontroler connected on USB would manually start the bootloader. The bootloader would automatically exists after few seconds.
  
Sur le M0, vous aurez besoin de <font color="red">'''double cliquer'''</font> le bouton '''reset'''. Vous verrez la LED rouge pulser, ce qui indique que le bootloader est actif. Une fois dans ce mode, il n'y a pas de "time out", le M0 reste en mode bootloader indéfiniment. Cliquez une nouvelle fois sur le bouton "reset" pour redémarrer le microcontrôleur.
+
On a M0 microcontroler, you will have to <font color="red">'''double click'''</font> the '''reset''' button. You will see the LED pulsing on red meaning that the bootloader is active. Once in this mode, the M0 would stay in the bootloader mode forever (there is no "time out"). Click once again on the "reset" button to restart the microcontroler.
  
== Alignement en mémoire ==
+
== Memory alignment ==
Cela à moi de chance de vous arriver... mais autant être tenu informé.
+
There is few change that you reach this issue... but being aware of this may help.
  
Si vous avez utilisé des plateformes 8 bits alors vous savez probablement qu'il est possible de réaliser des typecast de variables. Par exemple:
+
If you are using the 8 bits plateform then you probably know that TypeCast can be performed on on variables. Example:
  
 
<syntaxhighlight lang="c">
 
<syntaxhighlight lang="c">
Ligne 128 : Ligne 130 :
 
</syntaxhighlight>
 
</syntaxhighlight>
  
Mais vous ne pouvez pas garantir que cela fonctionnera sur une plateforme 32 bits parce que '''mybuffer''' pourrait ne pas être aligné sur 2 ou 4 octets (voir [https://fr.wikipedia.org/wiki/Alignement_en_m%C3%A9moire alignement en mémoire] sur Wikipedia).  
+
But there is no warranty that this may work properly on 32 bits AVR because '''mybuffer''' may not been aligned on 2 or 4 bytes (voir [https://en.wikipedia.org/wiki/Data_structure_alignment memory alignment] on Wikipedia).  
  
Un ARM Cortex-M0 peut uniquement accéder directement aux données par bloc de 16-bit (tous les deux ou 4 octets). Essayer d'accéder à un octet impaire (octets en position 1 ou 3) provoquera une erreur matérielle et un arrêt du MCU.  
+
An ARM Cortex-M0 can only directly access to data by bloc of 16-bits (every 2 or 4 bytes). Trying to access an even byte (byte in position 1 or 3) would cause an hardware fault and will stop a MCU.  
  
Heureusement, il existe une solution simple... utiliser la fonction {{fname|memcpy}} !
+
Thankfully, there is a very simple workaround... by using the {{fname|memcpy}} function!
  
 
<syntaxhighlight lang="c">
 
<syntaxhighlight lang="c">
Ligne 140 : Ligne 142 :
 
</syntaxhighlight>
 
</syntaxhighlight>
  
== Conversion en virgule flottante (dtostrf) ==
+
== Floating point conversion (dtostrf) ==
Tout comme pour les AVR arduino, la bibliothèque M0 ne propose un support "complet" permettant de convertir une valeur en virgule flottante vers une chaine de caractères.  
+
As for the Arduino AVR, the M0 libraries doesn't offer a full support to convert floating point value to string.  
  
Les fonctions comme {{fname|sprintf}} ne feront pas la conversion de valeur en virgule flottante. Par chance, la bibliothèque standard AVR-LIBC inclus la fonction {{fname|dtostrf}} qui est capable de gérer cette conversion pour nous.
+
The functions like {{fname|sprintf}} would not convert floating point values. Thankfully, the standard AVR-LIBC includes the {{fname|dtostrf}} function able to handle this conversion.
  
Malencontreusement, les bibliothèques run-time du M0 ne dispose pas de cette fonction dtostrf! Vous pourriez rencontrer quelques fils de discussions mentionnant '''#include <avr/dtostrf.h>''' pour obtenir la fonction dtostrf. <font color="red">Mais si cela compile, le fonction '''ne fonctionne pas sur un M0'''</font>.
+
Inconveniently, the M0 AVR run-time does not have the dtostrf function! You may see some thread suggesting to '''#include <avr/dtostrf.h>''' the dtostrf function. <font color="red">But this will not work on M0 even if it compiles'''</font>.
  
A la place, voyez le fil de discussion suivant pour trouver une fonction {{fname|dtostrf}} fonctionnelle que vous pourrez inclure dans votre code:
+
Instead, have a look to this discussion thread to find a {{fname|dtostrf}} function running proprely:
 
* http://forum.arduino.cc/index.php?topic=368720.0
 
* http://forum.arduino.cc/index.php?topic=368720.0
  
== Combien de RAM disponible? ==
+
== How many RAM available ? ==
Un ATSAMD21G18 dispose de 32K de RAM mais vous pourriez avoir besoin de surveiller sa consommation pour des raisons propres à votre projet. Vous pouvez le faire à l'aide de cette fonction:
+
The ATSAMD21G18 does have 32K of RAM but you may need to monitor the memory usage for some raison. You can to this with the following function:
  
 
<syntaxhighlight lang="c">
 
<syntaxhighlight lang="c">
Ligne 162 : Ligne 164 :
 
</syntaxhighlight>
 
</syntaxhighlight>
  
Merci a  [http://forum.arduino.cc/index.php?topic=365830.msg2542879#msg2542879 ce fil de discussion] sur les forums Arduino pour ce truc!
+
Thanks to [http://forum.arduino.cc/index.php?topic=365830.msg2542879#msg2542879 this discussion thread] on the Arduino forums for the trick!
  
== Stocker des données en FLASH ==
+
== Store data in the microcontroler Flash ==
Si vous utilisez un AVR (Arduino), alors vous avez probablement déjà utilisé '''PROGMEM''' qui permet au compilateur de savoir que vous voulez placer le contenu d'une variable (ou chaine de caractère) dans la mémoire Flash (afin d'économiser de la RAM).  
+
If you use an AVR (Arduino) on regular basis, you may have a chance to use '''PROGMEM'''. PROGMEM inform the compiler to store the content of a variable (or a string) into the FLASH memory (to save RAM).  
  
Sur un ARM, c'est un peu plus facile. Il suffit d'ajouter le mot '''const''' devant le nom de la variable:
+
It is a bit more easy on an ARM microcontroler. Just add the word '''const''' before the variable name:
  
 
<syntaxhighlight lang="c">
 
<syntaxhighlight lang="c">
const char str[] = "Ma treesss lonnnnguuuue chaiiiinnnnneeee";
+
const char str[] = "A quite lonnnnnggggggg striiiiiinnnnnnng";
 
</syntaxhighlight>
 
</syntaxhighlight>
  
Cette chaîne de caractère est maintenant en FLASH. Vous pouvez manipuler la chaîne de caractère comme si c'était des données en RAM, le compilateur fera automatiquement une lecture depuis la mémoire FLASH et vous n'aurez pas besoin d'utiliser de fonction spécialement conçue pour les manipulation progmem.
+
The string is now stored in the FLASH. You can handle the string as it was stored inside the RAM, the compiler would automagically read it from the FLASH (no need for special reading function like those required for PROGMEM variables).
  
Vous pouvez vérifier l'emplacement de stockage des données en affichant leur adresse de stockage:
+
You can easily check where the data is stored! Just print the storage address of the variable:
  
 
<syntaxhighlight lang="c">
 
<syntaxhighlight lang="c">
Ligne 181 : Ligne 183 :
 
</syntaxhighlight>
 
</syntaxhighlight>
  
Si l'adresse est:
+
If the adress is:
* égale ou supérieure à $2000000 alors c'est stocker en SRAM.  
+
* equal or greater than $2000000 then the data is in the SRAM.  
* entre $0000 et $3FFFF alors c'est stocké en FLASH
+
* between $0000 and $3FFFF then the data is stored in FLASH
  
 
{{ENG-CANSAT-TRAILER}}
 
{{ENG-CANSAT-TRAILER}}

Version actuelle datée du 7 novembre 2018 à 19:21

Forewords

The ATSAMD21 is still a newcomer in the Arduino-compatible world. Most of sketch and libraries would work on ATSAMD21 but somes things have to be pointed out!

Le notes here under would apply to the M0 boards.

Analog reference

If you want to use the ARef for a voltage reference under 3.3v, the line code to use is analogReference(AR_EXTERNAL) with AR_EXTERNAL and not EXTERNAL.

Pins and pull-up

The old way of activating the pull-up resistor was:

pinMode(pin, INPUT)
digitalWrite(pin, HIGH)

Because the pullup-selection register was the same register than output-selection register.

For the M0 (as for many plateform), the code to use is:

pinMode(pin, INPUT_PULLUP)

Serial ou SerialUSB

99.9% of Arduino Sketch does use Serial.print for debugging purpose (or serial output). On the official SAMD/M0 Arduino, this instruction use the Serial5 port which is not exposed on a Feather.

Instead, the USB port on official Arduino M0 is called SerialUSB.

Adafruit did fix this on the Adafruit M0 by redirecting Serial call to USB calls. So, when using a Feather M0 everything appears to work to properly without requiring any changes.

If you want to use an official M0 without the need to change all the Serial.print() call to SerialUSB.print() , then place the following code:

#if defined(ARDUINO_SAMD_ZERO) && defined(SERIAL_PORT_USBVIRTUAL)
   // required for Serial operations on Zero based board
   #define Serial '''SERIAL_PORT_USBVIRTUAL'''
#endif

just before the first function definition in the code.

Example:

FEATHER-M0-ArduinoIDE-Croquis-01.png
Crédit: AdaFruit Industries www.adafruit.com

AnalogWrite / PWM on Feather M0

After looking through the SAMD21 datasheet, it appears that some of the options listed in the multiplexer table don't exist on the specific chip used in the Feather M0.

For all SAMD21 chips, there are two peripherals that can generate PWM signals: The Timer/Counter (TC) and Timer/Counter for Control Applications (TCC). Each SAMD21 has multiple copies of each, called 'instances'.

Each TC instance has one count register, one control register, and two output channels. Either channel can be enabled and disabled, and either channel can be inverted. The pins connected to a TC instance can output identical versions of the same PWM waveform, or complementary waveforms.

Each TCC instance has a single count register, but multiple compare registers and output channels. There are options for different kinds of waveform, interleaved switching, programmable dead time, and so on.

The biggest members of the SAMD21 family have five TC instances with two 'waveform output' (WO) channels, and three TCC instances with eight WO channels:

  • TC[0-4],WO[0-1]
  • TCC[0-2],WO[0-7]

And those are the ones shown in the datasheet's multiplexer tables.

The SAMD21G used in the Feather M0 only has three TC instances with two output channels, and three TCC instances with eight output channels:

  • TC[3-5],WO[0-1]
  • TCC[0-2],WO[0-7]

By following the signals to the pins made available on a Feather M0, the following pins would not be able to produce PWM signal:

  • Analog Pin A5

The following pins can be configured as PWM (without conflict) as long as the SPI, I2C & UART keeps their protocol functions:

  • Digital pins 5, 6, 9, 10, 11, 12 et 13
  • Analog pins A3 et A4

When only the SPI keeps the protocol function, you can also do PWM on the following pins:

  • TX (Digital pin 1)
  • SDA (Digital pin 20)

analogWrite() and range of PWM value

When using an AVR (like Arduino Uno), the instruction analogWrite(pin, 255) on a PWM output would result in a permanent HIGH signal on the output PIN.

On a Cortex ARM microcontroler, the output signal would be 255/256th. As a consequence, there is always a small pulse-down to 0v. If you need a continuously HIGH signal then the analogWrite(pin, 255) must be replaced by digitalWrite(pin, HIGH)

Missing Header file

You may have some code using a library not supported by the M0 code. As example, if you have some code containing the following line:

#include <util/delay.h>

Then you will get the following error

fatal error: util/delay.h: No such file or directory
  #include <util/delay.h>
                         ^
compilation terminated.
Error compiling.

Wich allow to identiy the line (and the file) where the error occured. You would just need to include the library loading inside a #ifdef structure like showed:

#if !defined(ARDUINO_ARCH_SAM) && !defined(ARDUINO_ARCH_SAMD) && !defined(ESP8266) && !defined(ARDUINO_ARCH_STM32F2)
 #include <util/delay.h>;
#endif

The line here upper would not include the header for the listed architectures.

If the #include is present in your Arduino sketch then you may try to remove the #include line.

Start the Bootloader

On most of the AVRs (like Arduino Uno), simply press the reset button with the microcontroler connected on USB would manually start the bootloader. The bootloader would automatically exists after few seconds.

On a M0 microcontroler, you will have to double click the reset button. You will see the LED pulsing on red meaning that the bootloader is active. Once in this mode, the M0 would stay in the bootloader mode forever (there is no "time out"). Click once again on the "reset" button to restart the microcontroler.

Memory alignment

There is few change that you reach this issue... but being aware of this may help.

If you are using the 8 bits plateform then you probably know that TypeCast can be performed on on variables. Example:

uint8_t mybuffer[4];
float f = (float)mybuffer;

But there is no warranty that this may work properly on 32 bits AVR because mybuffer may not been aligned on 2 or 4 bytes (voir memory alignment on Wikipedia).

An ARM Cortex-M0 can only directly access to data by bloc of 16-bits (every 2 or 4 bytes). Trying to access an even byte (byte in position 1 or 3) would cause an hardware fault and will stop a MCU.

Thankfully, there is a very simple workaround... by using the memcpy function!

uint8_t mybuffer[4];
float f;
memcpy(f, mybuffer, 4)

Floating point conversion (dtostrf)

As for the Arduino AVR, the M0 libraries doesn't offer a full support to convert floating point value to string.

The functions like sprintf would not convert floating point values. Thankfully, the standard AVR-LIBC includes the dtostrf function able to handle this conversion.

Inconveniently, the M0 AVR run-time does not have the dtostrf function! You may see some thread suggesting to #include <avr/dtostrf.h> the dtostrf function. But this will not work on M0 even if it compiles.

Instead, have a look to this discussion thread to find a dtostrf function running proprely:

How many RAM available ?

The ATSAMD21G18 does have 32K of RAM but you may need to monitor the memory usage for some raison. You can to this with the following function:

extern "C" char *sbrk(int i);

int FreeRam () {
  char stack_dummy = 0;
  return &stack_dummy - sbrk(0);
}

Thanks to this discussion thread on the Arduino forums for the trick!

Store data in the microcontroler Flash

If you use an AVR (Arduino) on regular basis, you may have a chance to use PROGMEM. PROGMEM inform the compiler to store the content of a variable (or a string) into the FLASH memory (to save RAM).

It is a bit more easy on an ARM microcontroler. Just add the word const before the variable name:

const char str[] = "A quite lonnnnnggggggg striiiiiinnnnnnng";

The string is now stored in the FLASH. You can handle the string as it was stored inside the RAM, the compiler would automagically read it from the FLASH (no need for special reading function like those required for PROGMEM variables).

You can easily check where the data is stored! Just print the storage address of the variable:

Serial.print("Address of str $"); Serial.println((int)&str, HEX);

If the adress is:

  • equal or greater than $2000000 then the data is in the SRAM.
  • between $0000 and $3FFFF then the data is stored in FLASH

Written by Meurisse D. from MC Hobby - License: CC-SA-BY.