Transfering float data between PC and Teensy

TeensyPhonon

Active member
I am trying to transfert float data between a PC (python) and a teensy 4.1, but my attempt with serial is a little bit... ugly.

python code :

Python:
# -*- coding: utf-8 -*-

import numpy as np
import matplotlib.pyplot as plt
import serial
import time
import scipy.signal as signal

Fs = 44100
arduinos = [serial.Serial(port='COM17',  baudrate=115200, timeout=1)]

arduinos[0].write(bytes("ready",'utf-8'))
time.sleep(0.05)
nc = int(arduinos[0].readline().decode("utf-8")[:-2])

#signal
t = np.linspace(0,nc/Fs,nc)
f0 = 200
f1 = 2000
chirp = signal.chirp(t,f0,t[-1],f1).astype(np.float32)

time.sleep(0.05)
arduinos[0].write(bytes("chirp",'utf-8'))
arduinos[0].write(bytes(chirp))

x = arduinos[0].read(nc*4) # nc 32 bits floats = 4*nc bytes
for i in range(nc):
    try:
        y[i] = struct.unpack('>f', x[4*i:4*(i+1)])[0]
    except: pass

teensy code :

C:
#include                     <arm_const_structs.h>

bool bool_record = true;

const uint32_t nc = 12800;
#define BUFFSIZE 4*nc
uint8_t buffer[BUFFSIZE] DMAMEM;



void setup() {

  pinMode(0,INPUT_PULLDOWN);
  pinMode(LED_BUILTIN,OUTPUT); 


  while(bool_record){
    Serial.begin(115200);
    while(!Serial);
    while(Serial.readString()!="ready"){}
    Serial.println(nc);

    digitalWrite(LED_BUILTIN,HIGH);
    while(bool_record){
      if(Serial.readString()=="chirp"){
        Serial.readBytes((char *)&buffer, 4*nc);
        Serial.write((unsigned char *)&buffer[0], 4*nc);

        digitalWrite(LED_BUILTIN,LOW);
      
      }

    }

  }

}


void loop() {

  if(digitalRead(0) == HIGH){SCB_AIRCR = 0x05FA0004;} //reset
    
 
}

Unfortunately, the data didn't survive the trip...

Before :

original.png

After :

teensy.png
 
You should probably packetize your data using something like SLIP encoding, which should help ensure everything stays aligned, or at least that you detect it if data go AWOL. For Teensyduino there's an implementation of SLIP as part of the OSC library, and a quick Google suggests there are a few options available for the Python end of things.

Note that Teensy 4.1 USB serial is entirely capable of sending data far too fast for a PC to keep up with - banging out half a megabyte of data in one chunk is very liable to overwhelm it, particularly if Python is being used to process the data. This forum has many threads on the subject...
 
I made the code simpler :
Code:
const int nb = 2;
byte buffer[4*nb] DMAMEM;
Serial.readBytes((char *)&buffer, 4*nb);
Serial.write(buffer,4*nb);

And I am sending the data with :

Code:
 data = np.array([1,0.5]).astype(np.float32)
 arduino.write(bytes(data))

The data from the teensy can be read with arduino.read(8).

When we look closer, we see something interesting :

original bytes : b'\x00\x00\x80?\x00\x00\x00?'
teensy bytes : b'\x00\x80?\x00\x00\x00?c'

They looks close but have there is some "\x00" are missing and a "c" is added...
 
Back
Top