ENG-CANSAT-FEATHER-M0-SPI

De MCHobby - Wiki
Sauter à la navigation Sauter à la recherche

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("Afficher boot.py...");
    while (bootPy.available()) {
      char c = bootPy.read();
      Serial.print(c);
    }
    Serial.println();
  }
  else {
    Serial.println("No boot.py file...");
  }

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.