Auteur Sujet: Teensy 3.1, 3.2 - Sonorisation locomotive  (Lu 93592 fois)

Jean-Luc

  • Global Moderator
  • Hero Member
  • *****
  • Messages: 1691
    • Voir le profil
Re : Teensy 3.1, 3.2 - Sonorisation locomotive
« Réponse #105 le: mars 18, 2018, 02:52:34 pm »
Juste pour être sûr, tu es revenu à l'original pour les deux modifs mentionnées ici :

Merci,
J'ai vérifié le formalisme du langage Python et j'ai modifié les lignes suivantes :
f = open(filename, "rb") --> f = open(filename, 'rb')et
ser.write("".join(encoded)) --> ser.write("".(encode())
Le script rawfile-uploader.py ne plante plus et indique :
All files uploaded (s'il le dit ?!)

Maintenant, il reste à vérifier que la SPI Flash se charge bien.
Cordialement

Benoit92

  • Full Member
  • ***
  • Messages: 200
    • Voir le profil
Re : Teensy 3.1, 3.2 - Sonorisation locomotive
« Réponse #106 le: mars 18, 2018, 06:41:39 pm »
Suivant tes explications, je suis revenu au script d'origine avec seulement la modification suivante :
FLASH_SIZE = 64
La ligne correspondant à la concaténation du fichier est bien celle du script "rawfile_uploader.py" d'origine :
ser.write("".join(encoded))
Je commence à douter.
Le script "rawfile_uploader.py" est t-il en Python 2 ou Python 3 ?

« Modifié: mars 19, 2018, 11:57:08 pm par Benoit92 »

Benoit92

  • Full Member
  • ***
  • Messages: 200
    • Voir le profil
Re : Teensy 3.1, 3.2 - Sonorisation locomotive
« Réponse #107 le: mars 20, 2018, 09:55:02 pm »
En passant en Python 3.6 (au lieu de Python 2.7), j'obtiens en lançant "rawfile-uploadr.py,  le type d’erreur suivant sur l'écran de commande Windows :
Python36>python -m serial.tools.list_ports
COM4
1 ports found
C:\Users\NexterECT\AppData\Local\Programs\Python\Python36>Python "rawfile-uploader.py" "COM4" "AABR99.TRW"
Uploading 1 files...
1: AABR99.TRWTraceback (most recent call last):
  File "rawfile-uploader.py", line 82, in <module>
    ser.write("".join(encoded))
TypeError: sequence item 17: expected str instance, int found

Nota : la ligne 82 est modifiée : ser = serial.Serial(sys.argv[1], write_timeout=0)

Donc, j'ai écrit :
ser.write("".join (str(encoded)))à la place de :
ser.write("".join(encoded))Il n'y a plus de messages d'erreur, mais le fichier AABR99.trw défile sur l'écran de commande Windows, mais ne monte pas sur le COM4 !
« Modifié: mars 20, 2018, 11:55:20 pm par Benoit92 »

Jean-Luc

  • Global Moderator
  • Hero Member
  • *****
  • Messages: 1691
    • Voir le profil
Re : Re : Teensy 3.1, 3.2 - Sonorisation locomotive
« Réponse #108 le: mars 20, 2018, 11:52:05 pm »
J'avais pas fait gaffe :

Tout d'abord, tu devrais éliminer les lignes de code commentée, c'est pas lisible.

#include <SerialFlash.h>
#include <SPI.h>

//#define FlashChipSelect  6   //6
const int FlashChipSelect = 10 ; // digital pin for flash chip CS pin
//const int FlashChipSelect = 21; // Arduino 101 built-in SPI Flash

void setup() {
  //uncomment these if using Teensy audio shield
  //SPI.setSCK(14);  // Audio shield has SCK on pin 14
  //SPI.setMOSI(7);  // Audio shield has MOSI on pin 7

  //uncomment these if you have other SPI chips connected
  //to keep them disabled while using only SerialFlash
//  pinMode(4, INPUT_PULLUP);
//  pinMode(10, INPUT_PULLUP);
//************************************
//  Set up SPI Teensy without audio Card
  SPI.setMOSI(11);  // uncomment these if using the alternate pins
  SPI.setMISO(12);// 12
  SPI.setSCK(14); //14


J'enlèverais les 3 lignes qui précèdent


//************************************

  Serial.begin(9600);

  // wait for Arduino Serial Monitor
  while (!Serial) ;
  delay(100);
  Serial.println("All Files on SPI Flash chip:");

//  if (!SerialFlash.begin(FlashChipSelect)) {
//    error("Unable to access SPI Flash chip");
//  }


Si ces 3 lignes sont commentées, ça ne peut pas marcher

  SerialFlash.opendir();
  while (1) {
    char filename[64];
    uint32_t filesize;

    if (SerialFlash.readdir(filename, sizeof(filename), filesize)) {
      Serial.print("  ");
      Serial.print(filename);
      spaces(20 - strlen(filename));
      Serial.print("  ");
      Serial.print(filesize);
      Serial.print(" bytes");
      Serial.println();
    } else {
      break; // no more files
    }
  }
}

void spaces(int num) {
  for (int i=0; i < num; i++) {
    Serial.print(" ");
  }
}

void loop() {
}

void error(const char *message) {
  while (1) {
    Serial.println(message);
    delay(2500);
  }
}
Cordialement

Benoit92

  • Full Member
  • ***
  • Messages: 200
    • Voir le profil
Re : Teensy 3.1, 3.2 - Sonorisation locomotive
« Réponse #109 le: mars 21, 2018, 09:28:56 pm »
CopyFromSerial
/*
 * This is free and unencumbered software released into the public domain.
 *
 * Anyone is free to copy, modify, publish, use, compile, sell, or
 * distribute this software, either in source code form or as a compiled
 * binary, for any purpose, commercial or non-commercial, and by any
 * means.
 *
 * In jurisdictions that recognize copyright laws, the author or authors
 * of this software dedicate any and all copyright interest in the
 * software to the public domain. We make this dedication for the benefit
 * of the public at large and to the detriment of our heirs and
 * successors. We intend this dedication to be an overt act of
 * relinquishment in perpetuity of all present and future rights to this
 * software under copyright law.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
 * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
 * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
 * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
 * OTHER DEALINGS IN THE SOFTWARE.
 *
 * For more information, please refer to <http://unlicense.org>
 * -------------------------------------------------------------------------
 *
 * This is example code to 1) format an SPI Flash chip, and 2) copy raw
 * audio files (mono channel, 16 bit signed, 44100Hz) to it using the
 * SerialFlash library.  The audio can then be played back using the
 * AudioPlaySerialflashRaw object in the Teensy Audio library.
 *
 * To convert a .wav file to the proper .RAW format, use sox:
 * sox input.wav -r 44100 -b 16 --norm -e signed-integer -t raw OUTPUT.RAW remix 1,2
 *
 * Note that the OUTPUT.RAW filename must be all caps and contain only the following
 * characters: A-Z, 0-9, comma, period, colon, dash, underscore.  (The SerialFlash
 * library converts filenames to caps, so to avoid confusion we just enforce it here).
 *
 * It is a little difficult to see what is happening; aswe are using the Serial port
 * to upload files, we can't just throw out debug information.  Instead, we use the LED
 * (pin 13) to convey state.
 *
 * While the chip is being formatted, the LED (pin 13) will toggle at 1Hz rate.  When
 * the formatting is done, it flashes quickly (10Hz) for one second, then stays on
 * solid.  When nothing has been received for 3 seconds, the upload is assumed to be
 * completed, and the light goes off.
 *
 * Use the 'rawfile-uploader.py' python script (included in the extras folder) to upload
 * the files.  You can start the script as soon as the Teensy is turned on, and the
 * USB serial upload will just buffer and wait until the flash is formatted.
 *
 * This code was written by Wyatt Olson <wyatt@digitalcave.ca> (originally as part
 * of Drum Master http://drummaster.digitalcave.ca and later modified into a
 * standalone sample).
 *
 * Enjoy!
 */
// SPI Flash 25Q64BVSIG
#include <SPIFlash.h>
#include <SerialFlash.h>
#include <SPI.h>

//Buffer sizes
#define USB_BUFFER_SIZE      128
#define FLASH_BUFFER_SIZE    4096

//Max filename length (8.3 plus a null char terminator)
#define FILENAME_STRING_SIZE      13

//State machine
#define STATE_START      0
#define STATE_SIZE      1
#define STATE_CONTENT    2

//Special bytes in the communication protocol
#define BYTE_START      0x7e
#define BYTE_ESCAPE      0x7d
#define BYTE_SEPARATOR    0x7c

#define CSPIN  10

void setup(){
  Serial.begin(9600);  //Teensy serial is always at full USB speed and buffered... the baud rate here is required but ignored
  pinMode(13, OUTPUT);
   
//  Set up SPI Teensy without audio Card
  SPI.setMOSI(11);
  SPI.setMISO(12);
  SPI.setSCK(14);

  if (!SerialFlash.begin(CSPIN)) {
    while (1) {
      Serial.println("Unable to access SPI Flash chip");
      delay(1000);
    }
  }
  //We start by formatting the flash...
  uint8_t id[5];
  SerialFlash.readID(id);
  SerialFlash.eraseAll();
 
  //Flash LED at 1Hz while formatting
  while (!SerialFlash.ready()) {
    delay(500);
    digitalWrite(13, HIGH);
    delay(500);
    digitalWrite(13, LOW);
  }

  //Quickly flash LED a few times when completed, then leave the light on solid
  for(uint8_t i = 0; i < 10; i++){
    delay(100);
    digitalWrite(13, HIGH);
    delay(100);
    digitalWrite(13, LOW);
  }
  digitalWrite(13, HIGH);

  //We are now going to wait for the upload program
  while(!Serial.available());
  SerialFlashFile flashFile;
 
  uint8_t state = STATE_START;
  uint8_t escape = 0;
  uint8_t fileSizeIndex = 0;
  uint32_t fileSize = 0;
  char filename[FILENAME_STRING_SIZE];
 
  char usbBuffer[USB_BUFFER_SIZE];
  uint8_t flashBuffer[FLASH_BUFFER_SIZE];
 
  uint16_t flashBufferIndex = 0;
  uint8_t filenameIndex = 0;
 
  uint32_t lastReceiveTime = millis();
 
  //We assume the serial receive part is finished when we have not received something for 3 seconds
  while(Serial.available() || lastReceiveTime + 3000 > millis()){//3000
    uint16_t available = Serial.readBytes(usbBuffer, USB_BUFFER_SIZE);
    if (available){
      lastReceiveTime = millis();
    }

    for (uint16_t usbBufferIndex = 0; usbBufferIndex < available; usbBufferIndex++){
      uint8_t b = usbBuffer[usbBufferIndex];
     
      if (state == STATE_START){
        //Start byte.  Repeat start is fine.
        if (b == BYTE_START){
          for (uint8_t i = 0; i < FILENAME_STRING_SIZE; i++){
            filename[i] = 0x00;
          }
          filenameIndex = 0;
        }
        //Valid characters are A-Z, 0-9, comma, period, colon, dash, underscore
        else if ((b >= 'A' && b <= 'Z') || (b >= '0' && b <= '9') || b == '.' || b == ',' || b == ':' || b == '-' || b == '_'){
          filename[filenameIndex++] = b;
          if (filenameIndex >= FILENAME_STRING_SIZE){
            //Error name too long
            flushError();
            return;
          }
        }
        //Filename end character
        else if (b == BYTE_SEPARATOR){
          if (filenameIndex == 0){
            //Error empty filename
            flushError();
            return;
          }
         
          //Change state
          state = STATE_SIZE;
          fileSizeIndex = 0;
          fileSize = 0;
         
        }
        //Invalid character
        else {
          //Error bad filename
          flushError();
          return;
        }
      }
      //We read 4 bytes as a uint32_t for file size
      else if (state == STATE_SIZE){
        if (fileSizeIndex < 4){
          fileSize = (fileSize << 8) + b;
          fileSizeIndex++;
        }
        else if (b == BYTE_SEPARATOR){
          state = STATE_CONTENT;
          flashBufferIndex = 0;
          escape = 0;
         
          if (SerialFlash.exists(filename)){
            SerialFlash.remove(filename);  //It doesn't reclaim the space, but it does let you create a new file with the same name.
          }
         
          //Create a new file and open it for writing
          if (SerialFlash.create(filename, fileSize)) {
            flashFile = SerialFlash.open(filename);
            if (!flashFile) {
              //Error flash file open
              flushError();
              return;
            }
          }
          else {
            //Error flash create (no room left?)
            flushError();
            return;
          }
        }
        else {
          //Error invalid length requested
          flushError();
          return;
        }
      }
      else if (state == STATE_CONTENT){
        //Previous byte was escaped; unescape and add to buffer
        if (escape){
          escape = 0;
          flashBuffer[flashBufferIndex++] = b ^ 0x20;
        }
        //Escape the next byte
        else if (b == BYTE_ESCAPE){
          //Serial.println("esc");
          escape = 1;
        }
        //End of file
        else if (b == BYTE_START){
          //Serial.println("End of file");
          state = STATE_START;
          flashFile.write(flashBuffer, flashBufferIndex);
          flashFile.close();
          flashBufferIndex = 0;
        }
        //Normal byte; add to buffer
        else {
          flashBuffer[flashBufferIndex++] = b;
        }
      }
    }
  }

  //Success!  Turn the light off.
  digitalWrite(13, LOW);
}

void loop(){
  //Do nothing.
}

void flushError(){
  uint32_t lastReceiveTime = millis();
  char usbBuffer[USB_BUFFER_SIZE];
  //We assume the serial receive part is finished when we have not received something for 3 seconds
  while(Serial.available() || lastReceiveTime + 3000 > millis()){
    if (Serial.readBytes(usbBuffer, USB_BUFFER_SIZE)){
      lastReceiveTime = millis();
    }
  }
}

rawfile_uploader.py
#!/usr/bin/python
#
# Uploads raw audio files to Teensy + Audio board with SPI Flash on board.  To use this program, first
# load the 'CopyFromSerial' example sketch.  When it first runs, it will format the SPI flash chip
# (this may take a long time for larger chips; a 128MB chip that I am using can take almost 10 minutes,
# but smaller 16MB ones should be faster).
#
# While the chip is being formatted, the LED (pin 13) will toggle at 1Hz rate.  When the formatting is
# done, it flashes quickly (10Hz) for one second, then stays on solid.  When nothing has been received
# for 3 seconds, the upload is assumed to be completed, and the light goes off.
#
# You can start this program immediately upon plugging in the Teensy.  It will buffer and wait until
# the Teensy starts to read the serial data from USB.
#
###################

import serial, sys, os, time

if (len(sys.argv) <= 2):
print("Usage: '" + sys.argv[0] + " <port> <files>' where:\n\t<port> is the TTY USB port connected to Drum Master\n\t<files> is a list of .RAW files (bash globs work).")
sys.exit()

#Special bytes
BYTE_START = "(\x7e)"
BYTE_ESCAPE = "\x7d"
BYTE_SEPARATOR = "\x7c"

#Flash size (in MB).  Change this to match how much space you have on your chip.
FLASH_SIZE = 64

totalFileSize = 0;
for i, filename in enumerate(sys.argv):
if (i >= 2):
totalFileSize = totalFileSize + os.path.getsize(filename)

flashSizeBytes = FLASH_SIZE * 1024 * 1024
if (totalFileSize > flashSizeBytes):
print("Too many files selsected.\n\tTotal flash size:\t" + "{:>14,}".format(flashSizeBytes) + " bytes\n\tTotal file size:\t" + "{:>14,}".format(totalFileSize) + " bytes")
sys.exit()

ser = serial.Serial(sys.argv[1], write_timeout=0)

print("Uploading " + str(len(sys.argv) - 2) + " files...")
for i, filename in enumerate(sys.argv):
if (i >= 2):
startTime = time.time();
sys.stdout.write(str(i - 1) + ": ")
sys.stdout.write(filename)
sys.stdout.flush()

f = open(filename, 'rb')
fileLength = os.path.getsize(filename)
try:
encoded = []
#Start byte
encoded.append(BYTE_START)
#Filename
for byte in os.path.basename(filename):
encoded.append(byte)
#End of filename
encoded.append(BYTE_SEPARATOR)

#File length (uint32_t)
encoded.append(chr((fileLength >> 24) & 0xFF));
encoded.append(chr((fileLength >> 16) & 0xFF));
encoded.append(chr((fileLength >> 8) & 0xFF));
encoded.append(chr((fileLength >> 0) & 0xFF));
encoded.append(BYTE_SEPARATOR)

#Binary data, with escaping

for byte in f.read():
if byte == BYTE_START or byte == BYTE_ESCAPE:
encoded.append(BYTE_ESCAPE)
encoded.append(chr(ord(byte) ^ 0x20))
else:
encoded.append(byte);

#Write end of data byte
encoded.append(BYTE_START)
ser.write("".join (str(encoded)))


finally:
f.close()

endTime = time.time();
print(" (" + str(round(fileLength / 1024 / (endTime - startTime), 2)) + " KB/s)");

print("All files uploaded")

Résultat sur l'invite de commande Windows :

1) Avec ser.write("".join ((encoded)))
C:\Python36>python -m serial.tools.list_ports
COM4
1 ports found

C:\Python36>Python "rawfile-uploader.py" "COM4" "AABR99.TRW"
Uploading 1 files...
1: AABR99.TRWTraceback (most recent call last):
  File "rawfile-uploader.py", line 85, in <module>
    ser.write("".join ((encoded)))
TypeError: sequence item 17: expected str instance, int found

2) Avec ser.write("".join (str(encoded)))
C:\Python36>python -c "import serial, sys; print(sys.platform, serial.VERSION)"
win32 3.4

C:\Python36>python -m serial.tools.list_ports
COM4
1 ports found

C:\Python36>Python "rawfile-uploader.py" "COM4" "AABR99.TRW"
Uploading 1 files...
1: AABR99.TRWTraceback (most recent call last):
  File "rawfile-uploader.py", line 85, in <module>
    ser.write("".join (str(encoded)))
  File "C:\Python36\lib\site-packages\serial\serialwin32.py", line 308, in write
    data = to_bytes(data)
  File "C:\Python36\lib\site-packages\serial\serialutil.py", line 63, in to_bytes
    raise TypeError('unicode strings are not supported, please encode to bytes: {!r}'.format(seq))
TypeError: unicode strings are not supported, please encode to bytes: "['(~)', 'A', 'A', 'B', 'R', '9', '9', '.', 'T', 'R', 'W', '|', '\\x00', '\\\\', 'û', '\\x04', '|', 125, 125, 46, 129, 255, 255, 2, 0, 254, 255, 3, 0, 253, 255, 2, 0, 255, 255, 0, 0, 0, 0, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 0, 0, 255, 255, 255, 255, 2, 0, 254, 255, 3, 0, 254, 255, 1, 0, 0, 0, 255, 255, 2, 0, 254, 255, 0, 0, 2, 0, 252, 255, 5, 0, 253, 255, 1, 0, 2, 0, 253, 255, 3, 0, 253, 255, 0, 0, 0, 0, 254, 255, 255, 255, 1, 0, 251, 255, 5, 0, 251, 255, 4, 0, 253, 255, 3, 0, 253, 255, 3, 0, 254, 255, 1, 0, 0, 0, 0, 0, 255, 255, 1, 0, 254, 255, 3, 0, 254, 255, 1, 0, 0, 0, 255, 255, 2, 0, 253, 255, 3, 0, 254, 255, 1, 0, 0, 0, 255, 255, 2, 0, 253, 255, .........................................................
 255, 255, 253, 255, 4, 0, 251, 255, 3, 0, 253, 255, 0, 0, 0, 0, 0, 0, '(~)']"

Jean-Luc

  • Global Moderator
  • Hero Member
  • *****
  • Messages: 1691
    • Voir le profil
Re : Teensy 3.1, 3.2 - Sonorisation locomotive
« Réponse #110 le: mars 21, 2018, 09:44:35 pm »
Mais ça marchait ça en Python 2.7  :)

Moi je pense que le premier téléversement en Python 2.7 a fonctionné.

Le sketch utilisé pour lister les fichiers avait des lignes commentées sauvagement : pas d'init du SPI, aucune chance que ça marche

Pourquoi avoir installé Python 3.6 ce qui entraine des erreurs dans l'exécution du script ?
« Modifié: mars 22, 2018, 09:09:18 am par Jean-Luc »
Cordialement

Benoit92

  • Full Member
  • ***
  • Messages: 200
    • Voir le profil
Re : Teensy 3.1, 3.2 - Sonorisation locomotive
« Réponse #111 le: mars 21, 2018, 11:51:30 pm »
A priori, avec Python 2.7, le script se déroulait jusqu'à la fin (All files uploaded) avec ta modification "write_timeout 0", mais rien ne montait dans la Flash.
Donc, je suis passé en Python 3.6. Et là, j'ai un message d'erreur lié au format des données :  raise TypeError('unicode strings are not supported, please encode to bytes: {!r}'.format(seq))
1) D'ailleurs, je ne sais pas si Python 2 est compatible avec Python 3 ?
2) Si c'est un problème de port COM4 sur Windows, j'ai :
- Réinstaller les ports USB
- Appliquer les updates
......?

Jean-Luc

  • Global Moderator
  • Hero Member
  • *****
  • Messages: 1691
    • Voir le profil
Re : Teensy 3.1, 3.2 - Sonorisation locomotive
« Réponse #112 le: mars 21, 2018, 11:54:38 pm »
Mais j'ai souligné là : http://forum.locoduino.org/index.php?topic=427.msg5090#msg5090

que ces trois lignes commentées :

//  if (!SerialFlash.begin(FlashChipSelect)) {
//    error("Unable to access SPI Flash chip");
//  }

Faisait que le listing du directory ne pouvait pas marcher !

Comment sais-tu que la flash n'a pas été écrite ?
Cordialement

Benoit92

  • Full Member
  • ***
  • Messages: 200
    • Voir le profil
Re : Teensy 3.1, 3.2 - Sonorisation locomotive
« Réponse #113 le: mars 22, 2018, 10:18:00 am »
1) Selon toi, il vaut mieux que je repasse en Python 2.7 ?
2) j'avais momentanément mis en commentaire les lignes suivantes :
//  if (!SerialFlash.begin(FlashChipSelect)) {
//    error("Unable to access SPI Flash chip");
//  }
Maintenant, elle sont réintégrées.

3) Comment sais-tu que la flash n'a pas été écrite ?
- Le LED du Teensy reste allumée "fixe" : le Teensy est en attente de donnée provenant du COM4
- Quand j'exécute le programme "ListFiles.ino", il y a juste écrit sur le moniteur série :"All Files on SPI Flash chip:" et rien derrière !

Benoit92

  • Full Member
  • ***
  • Messages: 200
    • Voir le profil
Re : Teensy 3.1, 3.2 - Sonorisation locomotive
« Réponse #114 le: mars 25, 2018, 05:44:34 pm »
Bon, cela semble enfin marcher :
Résultats Invite commande Windows :
C:\Python27>python -c "import serial, sys; print(sys.platform, serial.VERSION)"
('win32', '3.4')

C:\Python27>python -m serial.tools.list_ports
COM4
1 ports found

C:\Python27>Python "rawfile-uploader.py" "COM4" "AR2BR99.TRW"
Uploading 1 files...
1: AR2BR99.TRW (1437.38 KB/s)
All files uploaded


ListFiles.ino (résultats moniteur série):
All Files on SPI Flash chip:
  AR2BR99.TRW           764164 bytes


Procédure :
1) Téléverser CopyFromSerial vers le Teensy
2) Fermer l'IDE ARDUINO (tout ce qui est susceptible d'interférer avec le bus série "COM"
3) Débrancher la prise USB
4) Rebrancher le bus USB (CopyFromSerial se lance automatiquement)
5) Dés que la prise USB est branchée, lancer le script :
python -c "import serial, sys; print(sys.platform, serial.VERSION)"
python -m serial.tools.list_ports
Python "rawfile-uploader.py" "COM4" "AR2BR99.TRW"
Pause
Le chargement dans la SPI Flash est un peu long (10 s pour environ  1 Mo).
Je dois maintenant récupérer les données de la SPI Flash et les sortir sur la pin14 du Teensy (Convertisseur Numérique / Analogique).
puis gérer finement (et rapidement) les fichiers "son" en fonction des commandes DCC (Mobile Station 2 Märklin) et de la vitesse de la locomotive.

Merci Jean-Luc pour tes conseils et ton soutien.






Jean-Luc

  • Global Moderator
  • Hero Member
  • *****
  • Messages: 1691
    • Voir le profil
Re : Teensy 3.1, 3.2 - Sonorisation locomotive
« Réponse #115 le: mars 25, 2018, 11:34:23 pm »
Ahhhh. Super  :)

10s pour 1Mo, ça fait quand même presque du 1Mb/s, c'est pas mal :-)
Cordialement

Benoit92

  • Full Member
  • ***
  • Messages: 200
    • Voir le profil
Re : Teensy 3.1, 3.2 - Sonorisation locomotive
« Réponse #116 le: mars 30, 2018, 11:49:31 pm »
J'ai passé le programme "ReadBenchmark.ino" pour vérifier les caractéristiques de la Flash et du fichier enregistré :
#include <SerialFlash.h>
#include <SPI.h>

const int FlashChipSelect = 10; // digital pin for flash chip CS pin

void setup() {
//************************************
//  Set up SPI Teensy without audio Card
  SPI.setMOSI(11);  // uncomment these if using the alternate pins
  SPI.setMISO(12);// 12
  SPI.setSCK(14); //14

//************************************

  Serial.begin(9600);

  // wait for Arduino Serial Monitor
  while (!Serial) ;
  delay(100);
  Serial.println("All Files on SPI Flash chip:");

  if (!SerialFlash.begin(FlashChipSelect)) {
    while (1) {
      Serial.println("Unable to access SPI Flash chip");
      delay(2500);
    }
  }

  SerialFlash.opendir();
  int filecount = 0;
  while (1) {
    char filename[64];
    uint32_t filesize;

    if (SerialFlash.readdir(filename, sizeof(filename), filesize)) {
      Serial.print(filename);
      Serial.print(" = ");
      Serial.print(filesize);
      Serial.println(" bytes");
      SerialFlashFile file = SerialFlash.open(filename);
      if (file) {
        unsigned long usbegin = micros();
        unsigned long n = filesize;
        char buffer[256];
        while (n > 0) {
          unsigned long rd = n;
          if (rd > sizeof(buffer)) rd = sizeof(buffer);
          file.read(buffer, rd);
          n = n - rd;
        }
        unsigned long usend = micros();
        Serial.print("Read in = ");
        Serial.println(usend - usbegin);
        Serial.print("usbegin = ");             
        Serial.println(usbegin);
        Serial.print("usend = ");
        Serial.println(usend);

        Serial.print("us, speed = ");
        Serial.print((float)filesize * 1000.0 / (float)(usend - usbegin));
        Serial.println(" kbytes/sec");
        file.close();
      } else {
        Serial.println(" error reading this file!");
      }
      filecount = filecount + 1;
    } else {
      if (filecount == 0) {
        Serial.println("No files found in SerialFlash memory.");
      }
      break; // no more files
    }
  }
}

void loop() {
}
et j’obtiens sur le moniteur série :
All Files on SPI Flash chip:
AR2BR99.TRW = 764164 bytes
Read in = 401308
usbegin = 2168146
usend = 2569454
us, speed = 1904.18 kbytes/sec

----> usbegin : c'est l'adresse de départ du fichier ? en décimal ?
----> usend : c'est l'adresse de fin du fichier ? en décimal ?

Sinon, pour le son à envoyer sur le DAC, j'ai le choix entre  :
1) lire les données par paquets de 16 bits en synchronisant la vitesse de lecture avec "IntervalTimer myTimer;" et les envoyer sur le DAC.
2) utiliser les bibliothèques des exemples donnés sur PRJC :
#include <Audio.h>
#include <Wire.h>
#include <SPIFlash.h>
#include <SerialFlash.h>
#include <SPI.h>
#include "play_serialflash.h"
Mais je pense que la bibliothèque "Audio.h" ne marche que si l'on dispose d'une audioshield compatible du teensy.

Jean-Luc

  • Global Moderator
  • Hero Member
  • *****
  • Messages: 1691
    • Voir le profil
Re : Re : Teensy 3.1, 3.2 - Sonorisation locomotive
« Réponse #117 le: mars 31, 2018, 12:17:14 am »
...
et j’obtiens sur le moniteur série :
All Files on SPI Flash chip:
AR2BR99.TRW = 764164 bytes
Read in = 401308
usbegin = 2168146
usend = 2569454
us, speed = 1904.18 kbytes/sec

----> usbegin : c'est l'adresse de départ du fichier ? en décimal ?
----> usend : c'est l'adresse de fin du fichier ? en décimal ?

 :D. Analyse le sketch, je ramasse les copies dans 1 heure :)

Citer
Sinon, pour le son à envoyer sur le DAC, j'ai le choix entre  :
1) lire les données par paquets de 16 bits en synchronisant la vitesse de lecture avec "IntervalTimer myTimer;" et les envoyer sur le DAC.
2) utiliser les bibliothèques des exemples donnés sur PRJC :
#include <Audio.h>
#include <Wire.h>
#include <SPIFlash.h>
#include <SerialFlash.h>
#include <SPI.h>
#include "play_serialflash.h"
Mais je pense que la bibliothèque "Audio.h" ne marche que si l'on dispose d'une audioshield compatible du teensy.

Non je ne crois pas, ça marche sans le shield. Il y a un outil en ligne pour construire ta chaine audio https://www.pjrc.com/teensy/gui/index.html
À partir duquel tu génères ton code. J'y vois une source qui s'appelle playRawFlash.
Cordialement

Benoit92

  • Full Member
  • ***
  • Messages: 200
    • Voir le profil
Re : Teensy 3.1, 3.2 - Sonorisation locomotive
« Réponse #118 le: mars 31, 2018, 02:21:41 pm »
Citer
:D. Analyse le sketch, je ramasse les copies dans 1 heure :)
Ou dans 3600000000 Microsecondes.
Ok, ce sont des temps en Microsecondes qui permettent, in fine, de calculer le débit (1904.18 kbytes/sec !).

J'espérais obtenir l'adresse de début du fichier sur la SPI Flash.

Benoit92

  • Full Member
  • ***
  • Messages: 200
    • Voir le profil
Re : Teensy 3.1, 3.2 - Sonorisation locomotive
« Réponse #119 le: avril 02, 2018, 11:48:17 pm »
Suite à tes conseils, j'ai utilisé l'outil graphique de configuration du Teensy.
Ma configuration est :
 - Teensy 3.2 + SPI Flash Winbond 25Q64BVSIG (sans carte audio)
 - Pins used are 11(DOUT),12(DIN),14(SCK),10(CS).
 - AR2BR99.TRW chargé dans la SPI Flash.

J'aimerais envoyer ce fichier vers le DAC (A14).
Mais, je n'ai aucun son.
#include <Audio.h>
#include <Wire.h>
#include <SPI.h>
#include <SD.h>
#include <SerialFlash.h>

#define FLASH_CHIP_SELECT 10
 
// GUItool: begin automatically generated code
AudioPlaySerialflashRaw  playFlashRaw1;  //xy=114,184
AudioOutputAnalog        dac1;           //xy=751,337
AudioConnection          patchCord1(playFlashRaw1, dac1);
// GUItool: end automatically generated code

void setup() {
  AudioMemory(10);
  analogReference(EXTERNAL);
//************************************
//  Set up SPI Teensy without audio Card
  SPI.setMOSI(11);
  SPI.setMISO(12);
  SPI.setSCK(14);
//************************************
    Serial.begin(9600);
    while (!Serial) ;
    delay(100);
   
    if (!SerialFlash.begin(FLASH_CHIP_SELECT)) {
        while (1){
      Serial.println ("Cannot access SPI Flash chip");
      delay (1000);
        }
      }

   playFile("AR2BR99.TRW");
   delay(20000);
}
      void playFile(const char *filename){
        Serial.print("Playing file: ");
        Serial.println(filename);
        // Start playing the file. This sketch continues to
        // run while the file plays.
        playFlashRaw1.play("AR2BR99.TRW");
        delay(20000);
       }   
void loop() {

}