Skip to content

Instantly share code, notes, and snippets.

@lupyuen
Created August 10, 2018 05:48
Show Gist options
  • Save lupyuen/e1b6618768bd56307259acd71a52adb3 to your computer and use it in GitHub Desktop.
Save lupyuen/e1b6618768bd56307259acd71a52adb3 to your computer and use it in GitHub Desktop.
void sensor_task(void) {
// Background task to receive and process sensor data.
// This task will be reused by all sensors: temperature, humidity, altitude.
SensorContext *context = NULL; // Declared outside the task to prevent cross-initialisation error in C++.
MsgQ_t queue; Evt_t event; // TODO: Workaround for msg_post() in C++.
task_open(); // Start of the task. Must be matched with task_close().
for (;;) { // Run the sensor processing code forever. So the task never ends.
// This code is executed by multiple sensors. We use a global semaphore to prevent
// concurrent access to the single shared I2C Bus on Arduino Uno.
sem_wait(i2cSemaphore); // Wait until no other sensor is using the I2C Bus. Then lock the semaphore.
// We have to fetch the context pointer again after the wait.
context = (SensorContext *) task_get_data();
// Prepare a display message for copying the sensor data.
DisplayMsg msg;
msg.super.signal = context->sensor->info.id; // Set the ID.
memset(msg.name, 0, maxSensorNameSize + 1); // Zero the name array.
strncpy(msg.name, context->sensor->info.name, maxSensorNameSize); // Set the sensor name e.g. tmp
// Poll for the sensor data and copy into the display message.
msg.count = context->sensor->info.poll_sensor_func(msg.data, maxSensorDataSize);
// Do we have new data?
if (msg.count > 0) {
// If we have new data, send the message. Note: When posting a message, its contents are cloned into the message queue.
msg_post(context->display_task_id, msg);
}
// We are done with the I2C Bus. Release the semaphore so that another task can fetch the sensor data.
sem_signal(i2cSemaphore);
// Wait a short while before polling the sensor again.
task_wait(context->sensor->info.poll_interval);
}
task_close(); // End of the task. Should never come here.
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment