Search code examples
pythonarrayscarduinoesp32

Send Boolean Array to ESP32 using Python


I am trying to send a data package (+- 67,000 points) of Boolean type to an ESP32. The 'code works and can get the data, but as soon as I start saving the data in an array logic no longer works

Code ESP32:

#include <Arduino.h>

#define LED 3

bool Finished = false;

bool Values[] = {};
unsigned long N = 0, K = 0;

void setup() {
  
  Serial.begin(115200);
  pinMode(LED, OUTPUT);
  Serial.println("Start");

}

void loop() {
  
  digitalWrite(LED, true);
  while (!Finished){
    while(Serial.available()){
      int buf = Serial.read();
      if(buf == 2){
        digitalWrite(LED, false);
        Finished = true;
      }
      if(buf == 1){
        Serial.println("true");
        //Values[N] = 1;
        N++;
      }
      if(buf == 0){
        Serial.println("false");
        //Values[N] = 0;
        N++;
      }
    }
  }

  Serial.print("Count:");
  Serial.println(N);

  for(K = 0; K < N; K++){
    Serial.println(Values[K]);
    digitalWrite(LED, Values[K]);
    delay(1000);
  }
  
  while (true){
    Serial.println("ENDING");
    delay(10000);
  }
}

Code PYTHON EXAMPLE:

from socket import timeout
import time
import serial

values = [1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 1, 1, 1, 0, 0, 0, 1, 0, 1]
PARAM_ASCII = str(chr(2))       # Equivalente 116 = t

def InfoComSerial():
    
    ESP32 = serial.Serial('COM2', 115200)
    
    time.sleep(1.8)  # Entre 1.5s a 2s
    
    ESP32.write(values)
    ESP32.write(PARAM_ASCII.encode())

    #VALUE_SERIAL = ESP32.readline().decode()

    #print ('\nRetorno da serial: %s' % (VALUE_SERIAL))

    ESP32.close()

""" main """
if __name__ == '__main__':
    InfoComSerial()

Response without array

Response without array

Response with array

Response wit array

Any idea what is happening?


Solution

  • bool Values[] = {}; defines an empty array which is just a pointer. No memory is allocated.

    So writing into that array writes into memory that could be used by something else. You could very well change your other variables by doing so. If you know how many values you're going to receive provide a size to your array.

    Provide a size to that array. You know how many values you'll receive.