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

De MCHobby - Wiki
Sauter à la navigation Sauter à la recherche
Ligne 125 : Ligne 125 :
 
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).
 
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).
  
== Exemple complet d'utilisation de la Flash ==
+
== Full Flash example ==
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.
+
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.
  
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!
+
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!
  
 
== Lire et écrire des fichiers CircuitPython ==
 
== Lire et écrire des fichiers CircuitPython ==

Version du 23 septembre 2018 à 18:15

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!

Lire et écrire des fichiers CircuitPython

L'exemple fatfs_circuitpython montre comment lire et écrire des fichiers sur la mémoire flash de sorte qu'ils puissent être accéssible depuis CircuitPython/MicroPython. Cela signifie que vous pouvez exécuter un programme CircuitPython sur votre carte pour y stocker des données, puis utiliser un croquis Arduino qui utilise cette bibliothèque pour interagir avec ces mêmes données.

Notez qu'avant d'utiliser l'exemple fatfs_circuitpython vous devez avoir chargé CircuitPython sur votre carte. Voyez ce guide pour charger la dernière version de CircuitPython afin que le système de fichier CircuitPython soit écrit et initialisé sur la puce Flash. Une fois CircuitPython chargé sur la carte, vous pouvez exécuter le croquis fatfs_circuitpython.

Pour exécuter le croquis, il faut le charger dans Arduino IDE et le téléverser sur la carte Feather M0. Ensuite, il faut ouvrir le moniteur série à 115200 baud. Vous devriez voir des messages s'afficher lorsqu'il essaye de lire et écrire des fichiers sur la mémoire Flash.

Plus spécifiquement, l'exemple cherche les fichiers boot.py et main.py (puisque CircuitPython exécute ces fichiers au démarrage) et affiche leur contenu. Puis il ajoute une ligne à la fin du fichier data.txt présent sur la carte (le fichier est créé s'il n'existe pas encore). Après avoir exécuté le croquis, vous pouvez recharger CircuitPython sur la carte et charger et lire le fichier data.txt depuis CircuitPython!

Voyons un peu le code du croquis pour comprendre comment lire et écrire des fichiers CircuitPython. Pour commencer une instance de la classe Adafruit_M0_Express_CircuitPython est crée en lui passant un instance de la classe SPIFlash (permettant d'accéder à la mémoire Flash):

#define FLASH_SS       SS1                    // broche SSP de la Flash
#define FLASH_SPI_PORT SPI1                   // port SPI surlequel est branché la mémoire Flash

Adafruit_SPIFlash flash(FLASH_SS, &FLASH_SPI_PORT);     // Utiliser le bus SPI matériel 

// Il est possible d'utiliser d'autres broches comme bus SPI (SPI logiciel)!
//Adafruit_SPIFlash flash(SCK1, MISO1, MOSI1, FLASH_SS);

// Pour finir, créer un objet Adafruit_M0_Express_CircuitPython qui offre un accès
// à une interface de type Carte SD pour interagir avec les fichiers stockés dans 
// le système de fichier Flash de CircuitPython.
Adafruit_M0_Express_CircuitPython pythonfs(flash);

En utilisant la classe Adafruit_M0_Express_CircuitPython vous obtenez un objet de type système de fichier compatible avec en lecture et écriture avec le formattage de la mémoire Flash de CircuitPython. C'est très important pour l'interopérabilité entre CircuitPython et Arduino étant donné que CircuitPython dispose d'un partitionnement spécifique et d'un agencement particulier de la mémoire flash qui n'est pas compatible avec des bibliothèque plus "simple" (que vous pourriez rencontrer dans les autres exemples).

Une fois l'instance de la classe Adafruit_M0_Express_CircuitPython créée (instance appelée pythonfs dans le croquis) vous pouvez interagir avec elle comme s'il s'agissait de la bibliothèque carte SD d'Arduino. Vous pouvez ouvrir des fichiers en lecture ou écriture, créer des répertoires, effacer des fichiers et répertoires et plus encore.

Voici un croquis qui vérifie la présence du fichier boot.py et affiche sont contenu (un caractère à la fois):

  // Vérifie si le fichier boot.py existe puis affiche le contenu.
  if (pythonfs.exists("boot.py")) {
    File bootPy = pythonfs.open("boot.py", FILE_READ);
    Serial.println("Afficher boot.py...");
    while (bootPy.available()) {
      char c = bootPy.read();
      Serial.print(c);
    }
    Serial.println();
  }
  else {
    Serial.println("Pas de fichier boot.py...");
  }

Notez l'appel de la fonction exists qui vérifie la présence du fichier boot.py, puis l'utilisation de la fonction open pour ouvrir celui-ci en mode lecture (read en anglais). Une fois fichier ouvert vous obtenez une référence vers un objet de la classe File qui permet de lire et écrire dans le fichier comme s'il s'agissait d'un périphérique Serial (encore une fois, toutes les fonctions de la classe File sont identiques à celle de la classe carte SD).

Dans ce cas, la fonction available retournera le nombre d'octets (bytes) restant à lire jusqu'à la fin du fichier -et- la fonction read lit un caractère à la fois (pour l'afficher sur le moniteur série).

L'écriture d'un fichier est tout aussi simple, voici comment le croquis ajoute des données dans le fichier data.txt:

  // Créer et ajouter des données dans le fichier data.txt 
  // puis ajouter un retour à la ligne.
  // Le code CircuitPython pourra, plus tard, ou consulter
  // le contenu de ce fichier!
  File data = pythonfs.open("data.txt", FILE_WRITE);
  if (data) {
    // Ajouter une nouvelle ligne de donnée:
    data.println("Un bonjour a CircuitPython de la part d Arduino!");
    data.close();
    // Voir les autre exemples fatfs comme fatfs_full_usage 
    // et fatfs_datalogging pour plus d'exemples concernant 
    // les interactions avec les fichiers.
    Serial.println("Nouvelle ligne ajoutée au fichier data.txt!");
  }
  else {
    Serial.println("Erreur, ne sais pas ouvrir le fichier en écriture!");
  }

Cette fois encore, la fonction open est utilisée pour ouvrir le fichier si ce n'est que cette fois, le fichier est ouvert en lecture (write en anglais). Dans ce mode, le fichier est ouvert en ajout (les données sont ajoutées en fin de fichier) si ce dernier existe. A noter le mode écriture crée le fichier si celui-ci n'existe pas. Une fois le fichier ouvert, les fonctions tels que print et println peuvent être utilisées pour écrire des données dans le fichier (juste comme envoi des données vers le moniteur série). Une fois le traitement terminé, la fonction close ferme le fichier!

Voilà, nous en avons terminé avec les opérations fondamentales de lecture et d'écriture. Voyez l'exemple fatfs_full_usage pour un apercu des fonctionnalités avancées tels que la création de répertoire, effacement de fichiers et répertoires, obtention de la taille d'un fichier, etc! Rappelez vous que pour interagir avec les fichiers CircuitPython, il faudra utiliser la classe Adafruit_Feather_M0_CircuitPython comme indiqué dans l'exemple ci-dessus!

Accéder à la Flash SPI

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

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

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

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

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!


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