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

De MCHobby - Wiki
Sauter à la navigation Sauter à la recherche
 
(19 versions intermédiaires par le même utilisateur non affichées)
Ligne 2 : Ligne 2 :
  
 
== Forewords ==  
 
== Forewords ==  
{{traduction}}
 
 
One of the most exciting feature of the M0 Express board is this small FLASH chip wired on the SPI bus. That memory could be used to provide lot of services like storing files, python script and many more.
 
One of the most exciting feature of the M0 Express board is this small FLASH chip wired on the SPI bus. That memory could be used to provide lot of services like storing files, python script and many more.
  
Ligne 21 : Ligne 20 :
 
Thoses exemples would allow you to format the Flash memory with the FAT filesystem (the same filesytem than used on SD card), read and write files like we do with SD card.
 
Thoses exemples would allow you to format the Flash memory with the FAT filesystem (the same filesytem than used on SD card), read and write files like we do with SD card.
  
== Formatter  la mémoire Flash ==
+
== Format the Flash memory ==
L'exemple '''fatfs_format''' formattera le contenu de la FLASH SPI avec un système de fichier flambant neuf. '''ATTENTION, ce croquis effacera toutes les données de la mémoire flash, inluant tout le code python et autres données que vous pourriez avoir stocké dans la mémoire FLASH!'''.
+
The example '''fatfs_format''' will format the SPI FLASH with a brand new FileSystem. '''WARNING: this sketch will erase all the data stored in the FLASH memory, including any data, python script!'''.
  
Le croquis de formatage est utile si vous avez besoin d'effacer TOUS les élément pour redémarrer avec un environnement propre. Le croquis permet également de retrouver un état stable si, pour une raison ou une autre, le système de fichier était corrompu.
+
The sketch is useful when you need to erase ALL the items to start a fresh setup. This sketch would also allow you to recover the board when the file system is corrupted.
  
{{ambox|text=Le croquis fatfs_format et les exemples ci-dessous ne sons pas compatibles avec le système de fichier CircuitPython!'''. Si vous avez besoin de partager des données entre Arduino et CircuitPython alors prenez le temps de consulter l'exemple '''fatfs_circuitpython''' ci-dessus.}}
+
{{ambox|text=The sketch '''fatfs_format''' and exemples here under are not compatible with the CircuitPython file system!'''. If you need to share data between Arduino and CircuitPython then you should have a look to the example '''fatfs_circuitpython''' described here below.}}
  
Pour executer le croquis de formattage, chargez le dans Arduino IDE et téléversez le sur la carte Feather M0. Ouvrez ensuite le moniteur série (à 115200 baud). Vous devriez voir un message demandant une confirmation avant de formatter la mémoire Flash.  
+
To execute the formatting sketch, just load the Arduino IDE and updload it on the Feather M0 board. Then open the serial monitor (at 115200 baud). You should see a message requiring a confirmation before formatting the Flash.  
  
Si vous ne voyez pas ce message alors fermez le moniteur série, appuyez sur le bouton rest et réouvrez le moniteur série.
+
If you do not see the message, close the serial monitor, press the reset button then open the serial monitor again.
  
 
{{ADFImage|FEATHER-M0-ArduinoIDE-SPI-Flash-01.png}}
 
{{ADFImage|FEATHER-M0-ArduinoIDE-SPI-Flash-01.png}}
  
Saisissez '''OK''' dans le moniteur série et pressez le bouton d'envoi pour confirmer votre intention de formater la mémoire Flash. '''Il est nécessaire de saisir OK en capital! '''
+
Type in '''OK''' in the serial monitor and press the "send" button to confirm the format operation of the Flash memory. '''It is necessary to type the OK in capital! '''
  
Une fois confirmé, le croquis formattera la mémoire Flash SPI. La processus d'effacement et formatage prend environ une minute. Le croquis affiche un message une fois le formatage terminé. Voilà, vous disposez d'une mémoire FLASH prête à l'emploi et avec un tout nouveau système de fichier.
+
Once done, the sketch would start to format the SPI Flash memoryt. The formating procedure need 1 minute to get complete. The sketch will display a message when done. Great, you have a drand new file system.
  
=== Erreur de formattage ===
+
=== Error while formatting ===
Si vous n'arrivez pas à formater la mémoire Flash et recevez ce message d'erreur:
+
If you can't get the Flash memory formated and receive the following error:
 
  <nowiki>Adafruit SPI Flash FatFs Format Example
 
  <nowiki>Adafruit SPI Flash FatFs Format Example
 
Flash chip JEDEC ID: 0x1401501
 
Flash chip JEDEC ID: 0x1401501
Ligne 50 : Ligne 49 :
 
Error, f_fdisk failed with error code: 1</nowiki>
 
Error, f_fdisk failed with error code: 1</nowiki>
  
Alors il faut revenir à une version plus ancienne de la bibliothèque en attendant le correction de la bibliothèque.
+
Then you will need to use an older library version (until a fixed version is released).
  
Voir [https://forums.adafruit.com/viewtopic.php?f=57&t=128979&p=641983#p641983 ce lien sur les forums d'Adafruit].
+
See [https://forums.adafruit.com/viewtopic.php?f=57&t=128979&p=641983#p641983 this thread on the Adafruit forums].
  
== Exemple de Datalogging ==
+
== Datalogging example ==
Une utilisation pratique de la mémoire flash SPI flash est le stockage de données, comme le datalogging des données des senseurs. L'exemple '''fatfs_datalogging''' montre quelques opérations de datalogging/écriture. Ouvrez l'exemple dans the Arduino IDE et téléversez le sur votre carte Feather M0. Ouvrez ensuite le moniteur série (à 115200 baud), vous devriez voir un message s'afficher toutes les minutes lorsque le croquis écrit une nouvelle ligne dans le système de fichier de la mémoire flash.
+
A common usage of the SPI Flash memory is the datalogging. The example '''fatfs_datalogging''' shows some datalogging/writing operation. Open the sketch into Arduino IDE then upload the Feather M0 board. Next, open the serial monitor (at 115200 baud) and you should see a message displayed every minutes when the sketch writes a new line in the SPI Flash file system.
  
Voyez le contenu de la fonction {{fname|loop()}} pour comprendre comment écrire dans le fichier:
+
See the content of the {{fname|loop()}} function to understand how to write into a file:
  
 
<syntaxhighlight lang="c">
 
<syntaxhighlight lang="c">
   // Ouvrir le fichier de datalogging en écritureLe mode FILE_WRITE ouvrira
+
   // Open the datalogging file in write modethe FILE_WRITE mode will
   // le fichier en mode ajout (ajoutera les données en fin de fichier).
+
   // open the file for appending (it will add the data a the end
 +
  //  of the file).
 
   File dataFile = fatfs.open(FILE_NAME, FILE_WRITE);
 
   File dataFile = fatfs.open(FILE_NAME, FILE_WRITE);
   // Vérifie si le fichier est ouvert et écrit des données.
+
   // Check if the file is open and write datas.
 
   if (dataFile) {
 
   if (dataFile) {
     // Obtenir les données depuis les senseurs, etc. Dans ce exemple
+
     // Grab the data from sensors. In this sample
     // nous créons juste un nombre aléatoire.
+
     // the data would be a random number.
 
     int reading = random(0,100);
 
     int reading = random(0,100);
     // Ecrire une nouvelle ligne dans le fichier.   
+
     // Write a new line in the file.   
     // Vous poyvez utiliser les mêmes fonctions print que celles
+
     // The user can use the same functions as print function
     // utilisées pour afficher des données sur le moniteur série.  
+
     // sending data to the serial monitor.  
     // Par exemple, pour écrire deux valeurs CSV (séparées par une virgule):
+
     // EG: to write 2 CSV entries (coma separated):
 
     dataFile.print("Sensor #1");
 
     dataFile.print("Sensor #1");
 
     dataFile.print(",");
 
     dataFile.print(",");
 
     dataFile.print(reading, DEC);
 
     dataFile.print(reading, DEC);
 
     dataFile.println();
 
     dataFile.println();
     // Pour finir, fermer le fichier lorsque l'opération
+
     // The file must be closed at the end of writing operation.
    // d'écriture est achevée. C'est une facon adéquate pour
+
     // This is the right way to ensure that data are writtebn
     // s'assurer que les données soient bien écrites dans
+
     // into the file.
     // le fichier.
 
 
     dataFile.close();
 
     dataFile.close();
     Serial.println("Nouvelle mesure écrite dans le fichier!");
+
     Serial.println("New value written to the file!");
 
   }
 
   }
 
</syntaxhighlight>
 
</syntaxhighlight>
  
Comme vous le feriez avec la bibliothèque Arduino de la carte SD, vous pouvez créer un objet '''File''' en appelant la fonction '''open''' en indiquant le nom de fichier et le mode d'accès (le mode '''FILE_WRITE''', écrit de nouvelles données en fin de fichier). <font color="red">'''Notez cependant'''</font> qu'à la place d'appeler la fonction global {{fname|open}}, c'est la méthode {{fname|fatfs.open()}} de l'objet système_de_fichier nouvellement créé qu'il faut appeler (voyez les valeurs de configurations juste après #define).
+
As you would do with the SD library for Arduino, you first need to create a '''File''' object by calling the '''open''' function with the filename and file access mode ('''FILE_WRITE''' mode appends data at the end of the file). <font color="red">'''However'''</font> instead of calling the {{fname|open}} global function, you have to call the {{fname|fatfs.open()}} on a fatfs object created to access the file system on the SPI Flash (see the config values just behing the #define).
  
Une fois le fichier ouvert, il suffit simplement d'appeler les fonctions '''print''' et '''println''' sur l'objet fichier pour écrire des données en fin de fichier. C'est exactement comme envoyer des données vers le moniteur série pour y afficher du texte, des valeurs numériques et autres types de donnée.  
+
Once the file opened, calling the '''print''' and '''println''' method on the file object would write the data to the file. It is the exact same way than sending data over the serial monitor for sending text, numerical values and other types of data.  
  
Assurez-vous d'avoir correctement fermé le système de fichier pour être certain que les données soient enregistrées correctement dans le fichier!
+
Just check twice that you closed the file system (otherwise you way lost data or even the complete file)!
  
== Lecture et affichage de fichiers ==
+
== Read and display file content ==
L'exemple '''fatfs_print_file''' ouvrira un fichier (le fichier data.csv par défaut, le fichier créé par l'exemple '''fatfs_datalogging''' présenté ci-dessus) et affiche tout son contenu dans le moniteur série. Ouvrez l'exemple '''fatfs_print_file''' et téléversez le sur votre carte Feather M0, puis ouvrez le moniteur série (à 115200 baud).
+
The example '''fatfs_print_file''' would open a file (the file {{fname|data.csv}} per default, the file created with the '''fatfs_datalogging''' example) then it displays the file content in the serial monitor. Open the '''fatfs_print_file''' sketch and upload it to the Feather M0 board before opening the serial monitor (at 115200 baud).
  
Vous devriez voir le croquis afficher le contenu du fichier data.csv (si la mémoire flash ne contient pas de fichier data.csv alors vous pouvez ouvrir l'exemple datalogging ci-dessus pour le créer).
+
You should see the content of the data.csv file (if the Flash Memory doesn't yet have the data.csv file, then run the datalogging example to create it).
  
Voyez le contenu de la fonction {{fname|setup()}} pour comprendre comment s'effectue la lecture du fichier:
+
Please, see the content of {{fname|setup()}} function to understant how to read a file:
  
 
<syntaxhighlight lang="c">
 
<syntaxhighlight lang="c">
   // Ouvrir le fichier en lecture et vérifier s'il est correctement ouvert
+
   // Open the file in read only mode (check if opens succeed).
   // Le mode FILE_READ ouvre le fichier en lecture.
+
   // The FILE_READ opens the file to read it.
 
   File dataFile = fatfs.open(FILE_NAME, FILE_READ);
 
   File dataFile = fatfs.open(FILE_NAME, FILE_READ);
 
   if (dataFile) {
 
   if (dataFile) {
     // Le fichier a été ouvert.  
+
     // The file is now open.  
     // Afficher le contenu caractère par caractère jusqu'à
+
     // Display the content char by char until the
     // la fin du fichier.
+
     // end of file.
     Serial.println("Fichier ouvert, contenu affiché ci-dessous:");
+
     Serial.println("File open, content displayed here under:");
 
     while (dataFile.available()) {
 
     while (dataFile.available()) {
       // Utilisé la fonction read() pour lire le prochain caractère.
+
       // Use the read() function to extract next char.
       // Il est également possible d'utiliser des fonctions telles
+
       // The readUntil or readString functions can also be use.
      //    que readUntil, readString, etc.
+
       // See the exemple fatfs_full_usage for more information.
       // Voyez l'exemple fatfs_full_usage pour plus de détails.
 
 
       char c = dataFile.read();
 
       char c = dataFile.read();
 
       Serial.print(c);
 
       Serial.print(c);
Ligne 118 : Ligne 116 :
 
</syntaxhighlight>
 
</syntaxhighlight>
  
Tout comme pour l'écriture de donnée dans l'exemple datalogging, il est nécessaire de créer un objet '''File''' en appelant la fonction '''open''' de l'objet fatfs. Cependant, cette fois, le mode utilisé est '''FILE_READ''', indiquant que l'on désire lire le système de fichier.
+
In the same way as datalogging example, you need to create a '''File''' object by calling the '''open''' method of the {{fname|fatfs}} object.  
  
Après avoir ouvert le fichier en lecture, la fonction '''available''' permet de facilement savoir si des données sont disponibles dans le fichier. Ensuite, la fonction '''read''' permet de lire un caractère depuis le fichier. La combinaison de ces deux fonctions permet de réaliser facilement une boucle de lecture qui vérifie la disponibilité de donnée puis la lecture et l'affichage de celle-ci (un caractère à la fois).
+
This time, the mode used to access the file is '''FILE_READ''' indicating our intention to read the content of the file.
  
Il existe également des fonctions de lecture avancées que vous pouvez voir dans l'exemple '''fatfs_full_usage''' ou soit dans la [https://www.arduino.cc/en/reference/SD documentation de la classe SD d'Arduino] (la bibliothèque Flash SPI implémente les mêmes fonctions).
+
Once the file open in read mode, the '''available''' function let you know if some data are available in the file. Then, the '''read''' function read a byte from the file. The combination of those 2 functions allow us to create a read loop which check the availability of date before reading it (on byte at the time).
  
== Exemple complet d'utilisation de la Flash ==
+
It also exists advanced read functions like those used in the '''fatfs_full_usage''' and explained indide the [https://www.arduino.cc/en/reference/SD Arduino SD class documentation] (the Flash SPI library implements the same functions).
Vous pouvez vous référer à l'exemple '''fatfs_full_usage''' pour une démonstration complète concernant la lecture et l'écriture de fichiers. Cet exemple utilise toutes les fonction de la bibliothèque et démontre des opérations tels que le test d'existence d'un fichier, la création de répertoire, effacement de fichier, effacement de fichier, etc.
 
  
Rappelez vous que la bibliothèque SPI flash est conçue pour exposer les mêmes fonctions et mêmes interfaces que la [https://www.arduino.cc/en/reference/SD la bibliothèque SD d'Arduino]. Par conséquent, les code et exemples stockant des données sur une carte SD seront très facile à adapter pour fonctionner avec la bibliothèque SPI flash. Créez simplement un objet fatfs comme dans les exemples ci-dessus et utilisez la fonction open sur cet objet (en lieu et place de la fonction globale). Une fois que vous avez obtenu une référence sur un fichier, toutes les fonctions et utilisations sont identiques entre la bibliothèque SPI flash et la bibliothèque SD d'Arduino!
+
== Full Flash example ==
 +
The '''fatfs_full_usage''' is a complete example demonstrating reading and writing operations on files. This example use all the library functions and advanced feature like file existence, folder creation, file wiping, etc.
  
== Accéder à la Flash SPI ==
+
Remember that SPI Flash library is designed to expose the same interface than [https://www.arduino.cc/en/reference/SD Arduino's SD library]. So the codes and samples storing data on SD card would would be easy to adapt to the SPI Flash library. Just create a {{fname|fatfs}} object like the examples here upper. You will also have to use the {{fname|open}} method on the object (instead of the global open function). Once the reference to the file object, all the functions and usages would be identifcal between the SPI Flash and Arduino's SD library!
Arduino n'est malheureusement pas capable d'exposer un périphérique de stockage (dit "''mass storage''" en anglais). Par conséquent, il faut utiliser CircuitPython qui, lui, est capable de faire cela pour nous. Voici la technique à utiliser.Here's the full technique:
+
 
* Démarrer le bootloader de votre carte Express. Faites un glisser/déposer de la dernière version du fichier uf2 '''circuitpython'''.
+
== Read and Write CircuitPython files ==
* Après un moment, vous devriez voir apparaître le lecteur '''CIRCUITPY''' contenant un fichier '''boot_out.txt'''. Voilà, le système de fichier est initialisé sur la Flash SPI.
+
The example '''fatfs_circuitpython''' demonstrate how to read and write the files from the SPI Flash from CircuitPython file system.  This means that you can execute CircuitPython script to store data in the CircuitPython file system, then use an Arduino sketch using this library to interact with those data.
* Ouvrez maintenant Arduino IDE et téléversez l'exemple '''fatfs_circuitpython''' disponible dans la bibliothèque SPI d'Adafruit. Ouvrez la console série pour démarrer le croquis. Voilà, le système de fichier CircuitPython sera correctement monté et le fichier '''data.txt''' créé et initialisé.
+
 
 +
Note: before running the exemple '''fatfs_circuitpython''' you '''must''' have loaded the CircuitPython on the board. [https://learn.adafruit.com/adafruit-feather-m0-express-designed-for-circuit-python-circuitpython/what-is-circuitpython|Please, see the Adafruit's M0 Express guide] to initialize the CircuitPython file system in the SPI Flash. Once the CircuitPython loaded on the board, you can execute the sketch '''fatfs_circuitpython'''.
 +
 
 +
To execute the sketch, you have to load it inside Arduino IDE then upload it to the Feather M0 board. Then, you have to open a serial monitor a 115200 baud. You should see messages displayed when the sketch tries to read and write files on the Flask memory.
 +
 
 +
Specifically, the example looks for the files '''boot.py''' and '''main.py''' (since CircuitPython execute thos file when starting the board) to display their content. After, the sketch add a line at the end of the '''data.txt''' file available in the CircuitPython file system (the file is created if not yet existing).
 +
 
 +
When done, you can reload CircuitPython on the board to load and read the  exécuté le croquis, vous pouvez recharger CircuitPython sur la carte pour lire le fichier '''data.txt''' directement depuis CircuitPython!
 +
 
 +
Let's have a loot to the sketch code to understant how to read and write files in CircuitPython. First, an instance of the '''Adafruit_M0_Express_CircuitPython''' class is created with the instance of the SPIFlash class (SPIFlash is used to access the Flash content):
 +
 
 +
<syntaxhighlight lang="c">
 +
#define FLASH_SS      SS1                    // SSP pin from Flash
 +
#define FLASH_SPI_PORT SPI1                  // SPI port where the Flash is wired
 +
 
 +
Adafruit_SPIFlash flash(FLASH_SS, &FLASH_SPI_PORT);    // Use the hardware SPI bus
 +
 
 +
// Other pins can also be used for the SPI bus (software SPI)!
 +
//Adafruit_SPIFlash flash(SCK1, MISO1, MOSI1, FLASH_SS);
 +
 
 +
// Finally, create an Adafruit_M0_Express_CircuitPython object to gain access
 +
// to a SD alike interface. The Adafruit_M0_Express_CircuitPython would allow
 +
// the sketch to access the CircuitPython file system stored inside the Flash.
 +
Adafruit_M0_Express_CircuitPython pythonfs(flash);
 +
</syntaxhighlight>
 +
 
 +
By using the '''Adafruit_M0_Express_CircuitPython''' class, you get a "File System" objet type compatible with read/write operations over a CircuitPython file system.  This point is important for the interoperability between CirctuitPython and Arduino. CircuitPython use a particular partitioning of the Flash which is not compatible simpler library (like those mentionned in another examples).
 +
 
 +
One the '''Adafruit_M0_Express_CircuitPython''' class instance created  (instance named '''pythonfs''' in the sketch) you can interact with the file system like [https://www.arduino.cc/en/Reference/SD an Arduino's SD library]. You can open files in read/write mode, create folder, drop files and folders (and even more).
 +
 
 +
Here a sketch looking for the '''boot.py''' file and displaying its content on the screen (char by char):
 +
 
 +
<syntaxhighlight lang="c">
 +
  // Check the boot.py file existence THEN display it on the screen
 +
  if (pythonfs.exists("boot.py")) {
 +
    File bootPy = pythonfs.open("boot.py", FILE_READ);
 +
    Serial.println("Display boot.py...");
 +
    while (bootPy.available()) {
 +
      char c = bootPy.read();
 +
      Serial.print(c);
 +
    }
 +
    Serial.println();
 +
  }
 +
  else {
 +
    Serial.println("No boot.py file...");
 +
  }
 +
</syntaxhighlight>
 +
 
 +
Le file write operation is also very simple, the following sketch will add data to the '''data.txt''' file:
 +
 
 +
<syntaxhighlight lang="c">
 +
  // Create and add data in the file data.txt
 +
  // then append a carriage return.
 +
  // Later, the CircuitPython script will be able to
 +
  // read the file content!
 +
  File data = pythonfs.open("data.txt", FILE_WRITE);
 +
  if (data) {
 +
    // Add a new line of data:
 +
    data.println("A great day to CircuitPython from our beloved Arduino sketch!");
 +
    data.close();
 +
    // See also the examples from the fatfs_full_usage
 +
    // and fatfs_datalogging for mode information about
 +
    // interaction with files.
 +
    Serial.println("A new line was added to the data.txt file!");
 +
  }
 +
  else {
 +
    Serial.println("Erreur, ne sais pas ouvrir le fichier en écriture!");
 +
  }
 +
</syntaxhighlight>
 +
 
 +
== Access to the SPI Flash ==
 +
Arduino is not able to expose himself as a storage device (a "''mass storage''" device). Instead you will have to switch to CircuitPython to expose the SPI Flash as storage device. Here is the technique to use:
 +
* Start the bootloader of the Express board. Drag and drop the last version of the '''circuitpython''' (the UF2 file).
 +
* After a while, you should see a '''CIRCUITPY''' drive containing the file '''boot_out.txt'''. Great, the Circuit Python filesystem is initialized on the SPI Flash.
 +
* Open the Arduino IDE and upload the '''fatfs_circuitpython''' sketch available in the Adafruit's SPI FLASH library. Open the serial console and start the sketch. Voila! the CircuitPython file system is properly mounted and the file '''data.txt''' created and initialized.
 +
 
 +
{{ambox|text=So, the Arduino Sketch did manipulated a file onto the SPI Flash owning the CircuitPython filesystem!}}
  
 
{{ADFImage|FEATHER-M0-ArduinoIDE-SPI-Flash-02.png}}
 
{{ADFImage|FEATHER-M0-ArduinoIDE-SPI-Flash-02.png}}
  
* Revenons sur notre ordinateur, redémarrez le bootloader de la carte Express --ET-- re-glissez/re-déposez '''circuitpython.uf2''' sur le lecteur '''BOOT''' rendu accessible par le bootloader. Voilà, CircuitPython est résintallé sur la carte Express.
+
This time, we will open the file created by the Arduino sketch.
* Au bout d'un moment, le lecteur '''CIRCUITPY''' redevient accessible. Celui-ci expose a nouveau le système de fichier MicroPython de la Flash SPI. Vous pouvez maintenant voir le fichier '''data.txt''', l'ouvrir et en consulté le contenu!
+
 
 +
* Let plug again the board on the computer, restart the bootloader on the Express board --AND-- drag/drop  the '''circuitpython.uf2''' on the drive '''BOOT''' made accessible by the bootloader. Great, CircuitPython is now installed (again) on the board.
 +
* After a a while, the '''CIRCUITPY''' drive is made available by CircuitPyhton. This would expose the SPI Flash content as a Mass Storage device. You can now see the file '''data.txt''' created by our Arduino Sketch, Open it and read it's content :-) !
  
 
{{ADFImage|FEATHER-M0-ArduinoIDE-SPI-Flash-03.png}}
 
{{ADFImage|FEATHER-M0-ArduinoIDE-SPI-Flash-03.png}}
  
Une fois que votre croquis de datalogging Arduino fonctionne comme attendu, vous pouvez simplifier la procédure en copiant '''CURRENT.UF2''' depuis le lecteur '''BOOT''' pour faire une copie de sauvegarde de votre programme Arduino. Vous pourrez ensuite charger CircuitPython pour accéder au système de fichier de la Flash SPI et enfin recopier votre '''CURRENT.UF2''' sur le lecteur '''BOOT''' de la carte Express pour réactiver votre croquis Arduino!
+
Once your datalogging sketch finish, you can simplify the procedure by copying the '''CURRENT.UF2''' from the '''BOOT''' drive to make "ready to use copy" of your sketch. You could now load the CircuitPython to access the CircuitPython file system and then switch back to you Arduino sketch by restoring the '''CURRENT.UF2''' on the Express Board!
  
 
{{ENG-CANSAT-TRAILER}}
 
{{ENG-CANSAT-TRAILER}}

Version actuelle datée du 23 septembre 2018 à 19:47

Forewords

One of the most exciting feature of the M0 Express board is this small FLASH chip wired on the SPI bus. That memory could be used to provide lot of services like storing files, python script and many more.

You can see that additional FLASH chip like a small SD card continously wired on the board. This flash memory is available through a library very similar to the Arduino's SD card. You can even read and write the files on the CircuitPython filesystem (Circuit Python use this Flash to store the Python Script and files)!

You will need to install the Adafruit SPI Flash Memory library in Arduino IDE to use the SPI Flash with your Arduino sketch. Click on the link below to download the library source code, open the zip file and copy the file files into a subfolder named Adafruit_SPIFlash (remove the '-master' added by GitHub on the front of the folder name). Place this new library next to your other Arduino libraries:

link=https://github.com/adafruit/Adafruit_SPIFlash AdafruitAdafruit Adafruit SPI Flash library

Once the library installed, start your Arduino IDE to access the various examples available in the library:

  • fatfs_circuitpython
  • fatfs_datalogging
  • fatfs_format
  • fatfs_full_usage
  • fatfs_print_file
  • flash_erase

Thoses exemples would allow you to format the Flash memory with the FAT filesystem (the same filesytem than used on SD card), read and write files like we do with SD card.

Format the Flash memory

The example fatfs_format will format the SPI FLASH with a brand new FileSystem. WARNING: this sketch will erase all the data stored in the FLASH memory, including any data, python script!.

The sketch is useful when you need to erase ALL the items to start a fresh setup. This sketch would also allow you to recover the board when the file system is corrupted.

To execute the formatting sketch, just load the Arduino IDE and updload it on the Feather M0 board. Then open the serial monitor (at 115200 baud). You should see a message requiring a confirmation before formatting the Flash.

If you do not see the message, close the serial monitor, press the reset button then open the serial monitor again.

{{{2}}}
Crédit: AdaFruit Industries www.adafruit.com

Type in OK in the serial monitor and press the "send" button to confirm the format operation of the Flash memory. It is necessary to type the OK in capital!

Once done, the sketch would start to format the SPI Flash memoryt. The formating procedure need 1 minute to get complete. The sketch will display a message when done. Great, you have a drand new file system.

Error while formatting

If you can't get the Flash memory formated and receive the following error:

Adafruit SPI Flash FatFs Format Example
Flash chip JEDEC ID: 0x1401501
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
This sketch will ERASE ALL DATA on the flash chip and format it with a new filesystem!
Type OK (all caps) and press enter to continue.
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
Partitioning flash with 1 primary partition...
Couldn't read sector before performing write!
Error, f_fdisk failed with error code: 1

Then you will need to use an older library version (until a fixed version is released).

See this thread on the Adafruit forums.

Datalogging example

A common usage of the SPI Flash memory is the datalogging. The example fatfs_datalogging shows some datalogging/writing operation. Open the sketch into Arduino IDE then upload the Feather M0 board. Next, open the serial monitor (at 115200 baud) and you should see a message displayed every minutes when the sketch writes a new line in the SPI Flash file system.

See the content of the loop() function to understand how to write into a file:

  // Open the datalogging file in write mode.  the FILE_WRITE mode will
  // open the file for appending (it will add the data a the end
  //  of the file).
  File dataFile = fatfs.open(FILE_NAME, FILE_WRITE);
  // Check if the file is open and write datas.
  if (dataFile) {
    // Grab the data from sensors. In this sample
    // the data would be a random number.
    int reading = random(0,100);
    // Write a new line in the file.  
    // The user can use the same functions as print function 
    // sending data to the serial monitor. 
    // EG: to write 2 CSV entries (coma separated):
    dataFile.print("Sensor #1");
    dataFile.print(",");
    dataFile.print(reading, DEC);
    dataFile.println();
    // The file must be closed at the end of writing operation.
    // This is the right way to ensure that data are writtebn
    // into the file.
    dataFile.close();
    Serial.println("New value written to the file!");
  }

As you would do with the SD library for Arduino, you first need to create a File object by calling the open function with the filename and file access mode (FILE_WRITE mode appends data at the end of the file). However instead of calling the open global function, you have to call the fatfs.open() on a fatfs object created to access the file system on the SPI Flash (see the config values just behing the #define).

Once the file opened, calling the print and println method on the file object would write the data to the file. It is the exact same way than sending data over the serial monitor for sending text, numerical values and other types of data.

Just check twice that you closed the file system (otherwise you way lost data or even the complete file)!

Read and display file content

The example fatfs_print_file would open a file (the file data.csv per default, the file created with the fatfs_datalogging example) then it displays the file content in the serial monitor. Open the fatfs_print_file sketch and upload it to the Feather M0 board before opening the serial monitor (at 115200 baud).

You should see the content of the data.csv file (if the Flash Memory doesn't yet have the data.csv file, then run the datalogging example to create it).

Please, see the content of setup() function to understant how to read a file:

  // Open the file in read only mode (check if opens succeed).
  // The FILE_READ opens the file to read it.
  File dataFile = fatfs.open(FILE_NAME, FILE_READ);
  if (dataFile) {
    // The file is now open. 
    // Display the content char by char until the 
    // end of file.
    Serial.println("File open, content displayed here under:");
    while (dataFile.available()) {
      // Use the read() function to extract next char.
      // The readUntil or readString functions can also be use.
      // See the exemple fatfs_full_usage for more information.
      char c = dataFile.read();
      Serial.print(c);
    }
  }

In the same way as datalogging example, you need to create a File object by calling the open method of the fatfs object.

This time, the mode used to access the file is FILE_READ indicating our intention to read the content of the file.

Once the file open in read mode, the available function let you know if some data are available in the file. Then, the read function read a byte from the file. The combination of those 2 functions allow us to create a read loop which check the availability of date before reading it (on byte at the time).

It also exists advanced read functions like those used in the fatfs_full_usage and explained indide the Arduino SD class documentation (the Flash SPI library implements the same functions).

Full Flash example

The fatfs_full_usage is a complete example demonstrating reading and writing operations on files. This example use all the library functions and advanced feature like file existence, folder creation, file wiping, etc.

Remember that SPI Flash library is designed to expose the same interface than Arduino's SD library. So the codes and samples storing data on SD card would would be easy to adapt to the SPI Flash library. Just create a fatfs object like the examples here upper. You will also have to use the open method on the object (instead of the global open function). Once the reference to the file object, all the functions and usages would be identifcal between the SPI Flash and Arduino's SD library!

Read and Write CircuitPython files

The example fatfs_circuitpython demonstrate how to read and write the files from the SPI Flash from CircuitPython file system. This means that you can execute CircuitPython script to store data in the CircuitPython file system, then use an Arduino sketch using this library to interact with those data.

Note: before running the exemple fatfs_circuitpython you must have loaded the CircuitPython on the board. see the Adafruit's M0 Express guide to initialize the CircuitPython file system in the SPI Flash. Once the CircuitPython loaded on the board, you can execute the sketch fatfs_circuitpython.

To execute the sketch, you have to load it inside Arduino IDE then upload it to the Feather M0 board. Then, you have to open a serial monitor a 115200 baud. You should see messages displayed when the sketch tries to read and write files on the Flask memory.

Specifically, the example looks for the files boot.py and main.py (since CircuitPython execute thos file when starting the board) to display their content. After, the sketch add a line at the end of the data.txt file available in the CircuitPython file system (the file is created if not yet existing).

When done, you can reload CircuitPython on the board to load and read the exécuté le croquis, vous pouvez recharger CircuitPython sur la carte pour lire le fichier data.txt directement depuis CircuitPython!

Let's have a loot to the sketch code to understant how to read and write files in CircuitPython. First, an instance of the Adafruit_M0_Express_CircuitPython class is created with the instance of the SPIFlash class (SPIFlash is used to access the Flash content):

#define FLASH_SS       SS1                    // SSP pin from Flash
#define FLASH_SPI_PORT SPI1                   // SPI port where the Flash is wired

Adafruit_SPIFlash flash(FLASH_SS, &FLASH_SPI_PORT);     // Use the hardware SPI bus 

// Other pins can also be used for the SPI bus (software SPI)!
//Adafruit_SPIFlash flash(SCK1, MISO1, MOSI1, FLASH_SS);

// Finally, create an Adafruit_M0_Express_CircuitPython object to gain access
// to a SD alike interface. The Adafruit_M0_Express_CircuitPython would allow
// the sketch to access the CircuitPython file system stored inside the Flash.
Adafruit_M0_Express_CircuitPython pythonfs(flash);

By using the Adafruit_M0_Express_CircuitPython class, you get a "File System" objet type compatible with read/write operations over a CircuitPython file system. This point is important for the interoperability between CirctuitPython and Arduino. CircuitPython use a particular partitioning of the Flash which is not compatible simpler library (like those mentionned in another examples).

One the Adafruit_M0_Express_CircuitPython class instance created (instance named pythonfs in the sketch) you can interact with the file system like an Arduino's SD library. You can open files in read/write mode, create folder, drop files and folders (and even more).

Here a sketch looking for the boot.py file and displaying its content on the screen (char by char):

  // Check the boot.py file existence THEN display it on the screen
  if (pythonfs.exists("boot.py")) {
    File bootPy = pythonfs.open("boot.py", FILE_READ);
    Serial.println("Display boot.py...");
    while (bootPy.available()) {
      char c = bootPy.read();
      Serial.print(c);
    }
    Serial.println();
  }
  else {
    Serial.println("No boot.py file...");
  }

Le file write operation is also very simple, the following sketch will add data to the data.txt file:

  // Create and add data in the file data.txt 
  // then append a carriage return.
  // Later, the CircuitPython script will be able to 
  // read the file content!
  File data = pythonfs.open("data.txt", FILE_WRITE);
  if (data) {
    // Add a new line of data:
    data.println("A great day to CircuitPython from our beloved Arduino sketch!");
    data.close();
    // See also the examples from the fatfs_full_usage 
    // and fatfs_datalogging for mode information about 
    // interaction with files.
    Serial.println("A new line was added to the data.txt file!");
  }
  else {
    Serial.println("Erreur, ne sais pas ouvrir le fichier en écriture!");
  }

Access to the SPI Flash

Arduino is not able to expose himself as a storage device (a "mass storage" device). Instead you will have to switch to CircuitPython to expose the SPI Flash as storage device. Here is the technique to use:

  • Start the bootloader of the Express board. Drag and drop the last version of the circuitpython (the UF2 file).
  • After a while, you should see a CIRCUITPY drive containing the file boot_out.txt. Great, the Circuit Python filesystem is initialized on the SPI Flash.
  • Open the Arduino IDE and upload the fatfs_circuitpython sketch available in the Adafruit's SPI FLASH library. Open the serial console and start the sketch. Voila! the CircuitPython file system is properly mounted and the file data.txt created and initialized.

{{{2}}}
Crédit: AdaFruit Industries www.adafruit.com

This time, we will open the file created by the Arduino sketch.

  • Let plug again the board on the computer, restart the bootloader on the Express board --AND-- drag/drop the circuitpython.uf2 on the drive BOOT made accessible by the bootloader. Great, CircuitPython is now installed (again) on the board.
  • After a a while, the CIRCUITPY drive is made available by CircuitPyhton. This would expose the SPI Flash content as a Mass Storage device. You can now see the file data.txt created by our Arduino Sketch, Open it and read it's content :-) !

{{{2}}}
Crédit: AdaFruit Industries www.adafruit.com

Once your datalogging sketch finish, you can simplify the procedure by copying the CURRENT.UF2 from the BOOT drive to make "ready to use copy" of your sketch. You could now load the CircuitPython to access the CircuitPython file system and then switch back to you Arduino sketch by restoring the CURRENT.UF2 on the Express Board!


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