Voir les contributions

Cette section vous permet de consulter les contributions (messages, sujets et fichiers joints) d'un utilisateur. Vous ne pourrez voir que les contributions des zones auxquelles vous avez accès.


Messages - Benoit92

Pages: 1 2 3 [4] 5 6 ... 14
46
Composants / Re : Teensy 3.1, 3.2 - Sonorisation locomotive
« le: mai 01, 2018, 09:11:55 pm »
Bon, après un certain nombre de discussion et d'essai sur le forum PRJC, tout marche ! ! !
A la base, il y avait un problème de synchro entre le flux de données sur la liaison "Arduino" et le script Python.
Le sketch Arduino (CopyFromSerialMC.ino) permet de charger dans la SPI Flash les données de fichier "son" sont remontées par le script Python (rawfile-uploader-mc.py)
Le sketch Arduino est lancé et démarre, puis, il s'arrête et attend le caractère "c" que le fournit le script Python lorsque celui-ci est lancé (fenêtre de commande Windows).
Ci-joint, les codes en question :
CopyFromSerialMC.ino
/*
 * This is free and unencumbered software released into the public domain.
 * ARDUINO / Teensy Modified Monitor Control added.....Apr2018......
 * 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!
 *
 *     // xxxx ... MONITOR CONTROL ADDED ........Apr 2018.........
 *
 */

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

const int FlashChipSelect = 10; // digital pin for flash chip CS pin
//const int FlashChipSelect = 21; // Arduino 101 built-in SPI Flash
// I coul;dn't get #define CSPIN 6 to work so put in the FlashChipSelect = 6 line .....xxxxxxxxxxxxxxxxxxxx

//Buffer sizes
#define USB_BUFFER_SIZE      256   // was 128
#define FLASH_BUFFER_SIZE    8192  //was 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


//SPI Pins (these are the values on the Audio board; change them if you have different ones)
//#define MOSI               11 //7
//#define MISO              12
//#define SCK               14
// #define CSPIN              6
//#define CSPIN           21  // Arduino 101 built-in SPI Flash


void setup(){
 
   pinMode(13, OUTPUT);    // Teensy LED pin
   
  Serial.begin(9600);  //Teensy serial is always at full USB speed and buffered... the baud rate here is required but ignored
 
  delay(1000);
 
  Serial.println("Enter char...  c  ...to Start Erase and Copy Files Sketch");

  while(Serial.read() != 'c');

  Serial.println("Erase and Copy Sketch Started");
 
   
  //Set up SPI
  SPI.setMOSI(11);  // uncomment these if using the alternate pins
  SPI.setMISO(12);  // these are the standard pins for the Teensy 3.2 & Audio Adaptor board conbination
  SPI.setSCK(14);
 

 if (!SerialFlash.begin(FlashChipSelect)) {
    while (1) {
      Serial.println("Unable to a access SPI Flash chip");
      delay(1000);
    }
  }
 
// Double flash LED a few times to warn Erase is about to begin ..........
  for(uint8_t i = 0; i < 3; i++){
    delay(100);
    digitalWrite(13, HIGH);
    delay(100);
    digitalWrite(13, LOW);
  delay(100);
    digitalWrite(13, HIGH);
    delay(100);
    digitalWrite(13, LOW);
    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);
 
  delay(1000);
 
  Serial.println("Full Erase Has Completed...Now Unplug USB & Plug in USB again to reset COMMS");
  Serial.println("Close Arduino Serial Monitor");
  Serial.println("Run Python rawfile-uploader-mc script from a new CMDline or batch file.");
  Serial.println("Teesny LED goes out when Copy Files has completed");
 
  //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
    // ..... parenthesis added around this bit on line below........... (lastReceiveTime + 3000) > millis()....reads better...
 
  while(Serial.available() || (lastReceiveTime + 3000) > millis()){
    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;
        }
       
        //The buffer is filled; write to SD card
        if (flashBufferIndex >= FLASH_BUFFER_SIZE){
          flashFile.write(flashBuffer, FLASH_BUFFER_SIZE);
          flashBufferIndex = 0;
        }
      }
    }
  }

  //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
  // ..... parenthesis added around this bit on line below........... (lastReceiveTime + 3000) > millis()....reads better...
  while(Serial.available() || (lastReceiveTime + 3000) > millis()){
    if (Serial.readBytes(usbBuffer, USB_BUFFER_SIZE)){
      lastReceiveTime = millis();
    }
  }
}

rawfile-uploader-mc.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 = 8

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], 9600, timeout=0, writeTimeout=None)
ser = serial.Serial(sys.argv[1])
ser.write("c")
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(encoded))

finally:
f.close()

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

print("All files uploaded")

Pour la lecture du son à partir de la SPI Flash vers le DAC (convertisseur Numérique -> Analogique), ci-joint un petit sketch "Teensy" - le choix du fichier à lire est réalisé en tapant sur une touche du clavier :
#include <Audio.h>
#include <Wire.h>
#include <SPI.h>
#include <SD.h>
#include <SerialFlash.h>

//#define FLASH_CHIP_SELECT 10

const int FLASH_CHIP_SELECT = 10; 
// GUItool: begin automatically generated code
AudioPlaySerialflashRaw  playFlashRaw1;  //xy=228,273
AudioOutputAnalog        dac1;           //xy=751,337
AudioConnection          patchCord1(playFlashRaw1, 0, dac1, 0);
// GUItool: end automatically generated code
int lu;
void setup() {
    Serial.begin(9600);
    while (!Serial && millis()<500 );
    AudioMemory(50);
    analogReference(EXTERNAL);

//************************************
//  Set up SPI Teensy without audio Card
  SPI.setMOSI(11); //7
  SPI.setMISO(12);
  SPI.setSCK(14);
//************************************
    delay(2000);
    if (!SerialFlash.begin(FLASH_CHIP_SELECT)) {
        while (1){
            Serial.println ("Cannot access SPI Flash chip");
            delay (10000);
        }
    }
}
void playFile(const char *filename)
{
  SerialFlashFile ff = SerialFlash.open(filename);
  Serial.print("Playing file: ");
  Serial.println(ff);

  playFlashRaw1.play(filename);
  // Simply wait for the file to finish playing.
  while (playFlashRaw1.isPlaying()) {
   }
}   

void loop() {
if ( Serial.available() ) {
    lu = Serial.read();
    Serial.println(lu);
  }
//  else {
//    Serial.println("Rien");
//  }
switch (lu) {
  case 'a': {
    playFile("A0A814.TRW");
    break;
   }
  case 'z':{ 
    playFile("A1A814.TRW");
    break;
   }   
  case 'e':{   
    playFile("A2A814.TRW");
    break;
   }   
  case 'r':{ 
    playFile("A3A814.TRW");
    break;
   }   
  case 't':{ 
    playFile("A4A814.TRW");
    break;
   }   
  case 'y':{ 
    playFile("A5A814.TRW");
    break;
   }   
  case 'u':{ 
    playFile("A6A814.TRW");
    break;
   }       
  case 'i':{ 
    playFile("A7A814.TRW");
    break;
   }   
  case 'o':{ 
    playFile("A8A814.TRW");
    break;
   }   
//  default:
//    // statements
//  }
  }
}

47
Composants / Re : Teensy 3.1, 3.2 - Sonorisation locomotive
« le: avril 04, 2018, 09:35:08 pm »
J'ai l'impression qu'il ne doit pas être possible de sortir le son issu de la SPI Flash vers le DAC du Teensy (pin A14).

Sur le site PRJC : https://www.pjrc.com/store/teensy3_audio.html , le Teensy est couplé à une carte audio qui elle possède un lecteur SD et un emplacement permettant de souder une SPI Flash. Cette carte possède en particulier un DAC qui doit être mis en œuvre grâce à la bibliothèque Audio.h (PlayFlashRaw).
Le Teensy pilote la carte audio par un bus I2C (SDA - SCL) et le bus série (Tx - Rx).
IL semble que la bibliothèque PlayRawFlash ne puisse ne mettre en œuvre que le DAC de la carte audio.
Y at-il une possibilité que le son de la SPI Flash puisse attaquer la sortie DAC A14 du Teensy?

48
Composants / Re : Teensy 3.1, 3.2 - Sonorisation locomotive
« 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() {

}


49
Composants / Re : Teensy 3.1, 3.2 - Sonorisation locomotive
« 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.

50
Composants / Re : Teensy 3.1, 3.2 - Sonorisation locomotive
« 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.

51
Composants / Re : Teensy 3.1, 3.2 - Sonorisation locomotive
« 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.






52
Composants / Re : Teensy 3.1, 3.2 - Sonorisation locomotive
« 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 !

53
Composants / Re : Teensy 3.1, 3.2 - Sonorisation locomotive
« 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
......?

54
Composants / Re : Teensy 3.1, 3.2 - Sonorisation locomotive
« 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, '(~)']"

55
Composants / Re : Teensy 3.1, 3.2 - Sonorisation locomotive
« 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 !

56
Composants / Re : Teensy 3.1, 3.2 - Sonorisation locomotive
« 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 ?


57
Composants / Re : Teensy 3.1, 3.2 - Sonorisation locomotive
« le: mars 18, 2018, 02:50:44 pm »
Pour l'instant, j'essaie de voir si le fichier a été chargé dans la "Flash" avec "ListFiles.ino"
ListFiles.ino
#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

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

  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");
//  }

  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);
  }
}

Résultat sur le moniteur arduino/Teensy :
All Files on SPI Flash chip:

--> aucun fichier n'est présent dans la Flash !

58
Composants / Re : Teensy 3.1, 3.2 - Sonorisation locomotive
« le: mars 18, 2018, 01:08:51 am »
C:\Python27>python -m serial.tools.list_ports
COM4
1 ports found

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

C:\Python27>Pause
Appuyez sur une touche pour continuer...

Merci Jean-Luc. Cela semble fonctionner. il faut que je regarde ce qu'il y a d'écrit dans la Flash.

59
Composants / Re : Teensy 3.1, 3.2 - Sonorisation locomotive
« le: mars 17, 2018, 09:32:49 pm »
J'ai vu éventuellement quelque chose sur la ligne de "serialwin32.py" ------>            n = win32.DWORD().
Dans l'aide Windows :
https://support.microsoft.com/fr-fr/help/817900/usb-port-may-stop-working-after-you-remove-or-insert-a-usb-device
Il propose de modifier le registre :
Si l'entrée de Registre DisableSelectiveSuspend est présente, double-cliquez dessus.
Si elle ne l'est pas, créez l'entrée.
Pour créer l'entrée, procédez comme suit :

    Dans le menu Edition, pointez sur Nouveau, puis cliquez sur DWORD.
    Tapez DisableSelectiveSuspend, puis appuyez sur ENTRÉE.
    Dans le menu Edition, cliquez sur Modifier.

Dans le champ Données de la valeur, tapez 1 pour désactiver la fonction de suspension sélective, puis cliquez sur OK.

Qu'en penses-tu ?
Cela n'a peut-être rien à voir ?

60
Composants / Re : Teensy 3.1, 3.2 - Sonorisation locomotive
« le: mars 17, 2018, 08:21:42 pm »
 Ligne 301
def write(self, data):
        """Output the given byte string over the serial port."""
        if not self.is_open:
            raise portNotOpenError
        #~ if not isinstance(data, (bytes, bytearray)):
            #~ raise TypeError('expected %s or bytearray, got %s' % (bytes, type(data)))
        # convert data (needed in case of memoryview instance: Py 3.1 io lib), ctypes doesn't like memoryview
        data = to_bytes(data)
        if data:
            #~ win32event.ResetEvent(self._overlapped_write.hEvent)
            n = win32.DWORD()
            success = win32.WriteFile(self._port_handle, data, len(data), ctypes.byref(n), self._overlapped_write)
            if self._write_timeout != 0:  # if blocking (None) or w/ write timeout (>0)
                if not success and win32.GetLastError() not in (win32.ERROR_SUCCESS, win32.ERROR_IO_PENDING):
                    raise SerialException("WriteFile failed ({!r})".format(ctypes.WinError()))

                # Wait for the write to complete.
                #~ win32.WaitForSingleObject(self._overlapped_write.hEvent, win32.INFINITE)
                win32.GetOverlappedResult(self._port_handle, self._overlapped_write, ctypes.byref(n), True)
                if win32.GetLastError() == win32.ERROR_OPERATION_ABORTED:
                    return n.value  # canceled IO is no error
                if n.value != len(data):
Ligne 323                    raise writeTimeoutError
                return n.value
            else:
                errorcode = win32.ERROR_SUCCESS if success else win32.GetLastError()
                if errorcode in (win32.ERROR_INVALID_USER_BUFFER, win32.ERROR_NOT_ENOUGH_MEMORY,
                                 win32.ERROR_OPERATION_ABORTED):
                    return 0
                elif errorcode in (win32.ERROR_SUCCESS, win32.ERROR_IO_PENDING):
                    # no info on true length provided by OS function in async mode
                    return len(data)
                else:
                    raise SerialException("WriteFile failed ({!r})".format(ctypes.WinError()))
        else:
            return 0

Pages: 1 2 3 [4] 5 6 ... 14