Skip to content
This repository was archived by the owner on Apr 25, 2023. It is now read-only.
This repository was archived by the owner on Apr 25, 2023. It is now read-only.

i2C is not multithreading safe #1074

@fmuntean

Description

@fmuntean

When using background threads to read the sensors and the main thread to update the screen the board hangs.
A simple program like this hangs after few seconds:

#include <Arduino.h>
#include <mbed.h>

#include <RGB_LED.h>
#include <I2C.h>
#include <HTS221Sensor.h>

Thread _background;

RGB_LED led;

DevI2C* i2c;
HTS221Sensor* sensor;
void setupSensor(){
i2c = new DevI2C(D14, D15);
sensor = new HTS221Sensor(*i2c); //Temperature and Humidity Sensor
sensor -> init(NULL); // init the sensor
sensor -> enable();// enable
// read id
unsigned char id;
sensor -> readId(&id);
Serial.printf("HTS221 ID: %d\r\n", id);
}

void readSensor(){
// get humidity
float humidity, temperature;
sensor -> getHumidity(&humidity);
Serial.printf("Humidity: %.1f%%\n\r",humidity);
// get temperature
sensor -> getTemperature(&temperature);
Serial.printf("Temperature: %.1fC\n\r",temperature);
}

static void backgroundTask(){
while(1){
led.setColor(0,5,0);
delay(500);
led.turnOff();
delay(500);

readSensor();

}
}

void setup(){
Serial.begin(115200);

Screen.init();

Screen.print("Setup");
setupSensor();
readSensor();
_background.start(&backgroundTask);

Screen.print("Setup Complete");

}

unsigned long uptime=0;
void loop(){
Serial.println(uptime++);
delay(1000);
readSensor();
Screen.print(3,"..");

}

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions