best code organization to read multiple sensors

ChibiOS public support forum for all topics not covered by a specific support forum.

Moderators: RoccoMarco, lbednarz, tfAteba

lesto
Posts: 55
Joined: Thu May 22, 2014 11:27 am

best code organization to read multiple sensors

Post by lesto »

Hi,
this is a bit more architecture than chibios dependant, but here the question;
if you have to read multiple sensor, maybe on different bus, witch may or may not be work togheder, and read may be from an external interrupt or from a polling, how would you do?

i've done this: interrupt set the "sensor read variable", as VirtualTimer do for polling sensor. Ther the "read thread" sequentialli read all sensor.

This is not the best; i was thinking use a "read thread" for every bus (i2c, spi, and so on); or maybe one for every sensor, with a fixed "grid" with tell witch sensor may run parallel respect each others.

Is this a good idea? would you use dinamic thread allocation (maybe with pool) and kill it when read is over? as far as i know i can't stop/restart thead, unless using some lock-trick, and trigger this lock-trick instead of setting a flag and polling it.

i'm asking here because maybe someone has thinked about it and there are ready solution, or special case i'm not taking into account.
User avatar
Giovanni
Site Admin
Posts: 14895
Joined: Wed May 27, 2009 8:48 am
Has thanked: 1202 times
Been thanked: 997 times

Re: best code organization to read multiple sensors

Post by Giovanni »

Hi,

I would use threads instead of virtual timers because code readability unless you have scarce RAM. There is no need to kill threads, if a thread is waiting for something then it takes no CPU cycles.

There are a lot of ways this could be done.

I would make a sensor-scheduler thread that decides when it is time to read a certain sensor and performs the operation. Sensor data would go in memory for use from other threads.

Alternatively you could dedicate a thread for each "sensor bus" meaning each SPI/I2C connecting sensors. If a single thread access a bus then there is no need for mutual exclusion (xxxAcquire/xxxRelease).

Giovanni
User avatar
Korken
Posts: 270
Joined: Wed Apr 02, 2014 4:09 pm
Has thanked: 5 times
Been thanked: 6 times

Re: best code organization to read multiple sensors

Post by Korken »

I have solved this problem with one "Sensor read thread" that is listening for events.
Periodic reads are caused by a virtual timer sending the event and the interrupt driven sensors have their own.

Example thread:

Code: Select all

thread_t *thread_sensor_read_p;

static THD_FUNCTION(ThreadSensorRead, arg)
{
  eventmask_t events;
  thread_sensor_read_p = chThdGetSelfX();

  while (1)
  {
    /* Waiting for an event to happen.*/
    events = chEvtWaitAny(ACCGYRO_DATA_AVAILABLE_EVENTMASK |  MAG_DATA_AVAILABLE_EVENTMASK | BARO_DATA_AVAILABLE_EVENTMASK);

    if (events & ACCGYRO_DATA_AVAILABLE_EVENTMASK)
    {
      /* Read sensor */
    }

    if (events & MAG_DATA_AVAILABLE_EVENTMASK)
    {
      /* Read sensor */
    }

    if (events & BARO_DATA_AVAILABLE_EVENTMASK)
    {
      /* Read sensor */
    }
  }
}

Example callback:

Code: Select all

void MPU6050cb(EXTDriver *extp, expchannel_t channel)
{
  (void)extp;
  (void)channel;

  if (thread_sensor_read_p != NULL)
  {
    /* Wakes up the sensor read thread */
    chSysLockFromISR();
    chEvtSignalI(thread_sensor_read_p, ACCGYRO_DATA_AVAILABLE_EVENTMASK);
    chSysUnlockFromISR();
  }
}
User avatar
Giovanni
Site Admin
Posts: 14895
Joined: Wed May 27, 2009 8:48 am
Has thanked: 1202 times
Been thanked: 997 times

Re: best code organization to read multiple sensors

Post by Giovanni »

Nice but you don't need a virtual timer for that, the function chThdSleep() internally uses a virtual timer for you.

Giovanni
User avatar
Korken
Posts: 270
Joined: Wed Apr 02, 2014 4:09 pm
Has thanked: 5 times
Been thanked: 6 times

Re: best code organization to read multiple sensors

Post by Korken »

This will only work if the "polled" sensor runs the fastest, else the thread will be waiting for the timeout and block the other readouts.
In my example ACCGYRO event is triggered in 666 Hz (by external interrupt), MAG event is triggered at 75 Hz (by external interrupt) and the BARO is trigger at 15 Hz by polling (no external interrupt).
Just for clarification, I realized my code was somewhat ambiguous. :) So if there was a chThdSleep() waiting for the barometer quite a few samples of the other sensors would be lost.

But, most likely, there are many ways to solve this problem. :) Cheers!
lesto
Posts: 55
Joined: Thu May 22, 2014 11:27 am

Re: best code organization to read multiple sensors

Post by lesto »

i'm doing a very similar thing (@Korken actually, we talked in the taulab forum about port to chibios, and i've learned a lot from your code)

Giovanni is right, as you know before setting up the sleep the frequency of all sensor, you can just find out with is the "nearest" wakeup and use the sleep. if you assume first reading is at time "0", it is easy to find out next sensor to read (just find the first multiple from actual time), and also if you save the time of last "update", and start finding sensor update from there, you'll also catch sensor read that should have been triggered. I use this concept on chip like arduino where every bit of resource is valuable. leOs, a scheduler for arduino form leonardo miliani use this concept and it is surerly clearer than my codes :)

the idea of a single reading thread is easy, and it is the code i've written (just chnage "reading thread" with "main thread"), and also i've generalized a bit, as sensor register a callback with contains the specific code to make the reading. (see https://github.com/MauroMombelli/testCh ... ca6/main.c)

Actually on my board there is DMA conflict so i cant do a parallel reading, but you can easily see how on a more "intelligent" chip you can save a lot of time parallelizing the reads, especially if one or more bus are slow.
User avatar
Korken
Posts: 270
Joined: Wed Apr 02, 2014 4:09 pm
Has thanked: 5 times
Been thanked: 6 times

Re: best code organization to read multiple sensors

Post by Korken »

Ahh, I remember.
lesto wrote:Giovanni is right, as you know before setting up the sleep the frequency of all sensor, you can just find out with is the "nearest" wakeup and use the sleep.
Here you should be careful since it only holds if your sensors have a slow sampling rate or if you know their sampling rate very accurately.
Else you can/will miss samples. This comes from the internal MEMS oscillators usually having an accuracy of ~1-3% making it difficult to use Sleep functionality.

So I'd recommend to have it interrupt driven and measure the time between interrupts.
For example I had a case where the MPU6000 sensor had a bad clock that gave about 9% error in the sampling time, this was no problem when measuring the sampling time (all integrators works correctly when you have the time).
But before I "assumed" that the sampling time was 5 ms but it was in fact closer to 5.5 ms. So tread carefully when working with MEMS sensors. :)
Usually the underlying signal processing requires very accurate knowledge of the sampling time.
lesto
Posts: 55
Joined: Thu May 22, 2014 11:27 am

Re: best code organization to read multiple sensors

Post by lesto »

ok, as i want people to find easy toimplement their own sensors, here the trick: (you'll see i'm a object oriented boy)

first of all lets put all we need into a struct. We need to know if is is polling(and its frequency), interrupt(mode, witch is pin+port, autostart is added by default), a pointer to init function, and a pointer to the read function.

so here what i produced: (still working on)

Code: Select all

struct sensor_interrupt{
   expchannel_t interrupt_channel;
   uint32_t mode;
};

struct sensor_polling{
   uint16_t frequencyHz;
};

struct sensor{
   /*fill this struct if you want an interrupt-driven sensor, else set it to NULL*/
   struct sensor_interrupt interrupt;
   /*fill this struct if you want a polling-driven sensor, else set it to NULL*/
   struct sensor_polling polling;
   /*attention: if the 2 struct above are filled, interrupt will be used by default*/

   /* pointer to the init function */
   void (*init_sensor)(void);
   /* pointer to the read function */
   void (*read_sensor)(void);
};


then we weill have some .h file witch will just istantiate and initialize the sensors (still todo)

read thread, on init will do something similar:

Code: Select all

   /*
    * register all interrupt and polling info
    */
   for (i = 0; i < sensors_reader; i++) {
      if (sensors_reader[i].interrupt != NULL) {
         extcfg.channels[sensors_reader[i].interrupt.interrupt_channel].mode |= EXT_CH_MODE_AUTOSTART | sensors_reader[i].interrupt.mode;
         extcfg.channels[sensors_reader[i].interrupt.interrupt_channel].cb = set_flag_and_wake_up_thread_to_read_this_sensor(i); //TODO: thing how implement this
      } else if (sensors_reader[i].polling != NULL) {
         /*
          * TODO: calculate time of execution and sort add to polling list, ordered by time of execution;
          * so every "wait" we just poll the first element, get the waiting time,
          * recalculate next execution time and sort insert the polled element to the task list.
          */
      } else {
         //TODO: FAIL sensor cannot be used
      }
   }

   extStart(&EXTD1, &extcfg);

   /*
    * start listening the interrupt, and initialize all sensors
    */
   for (i = 0; i < sensors_reader; i++) {
      if (sensors_reader[i].interrupt != NULL) {
         extChannelEnable(&EXTD1, sensors_reader[i].interrupt.interrupt_channel);
      }
      sensors_reader[i].init_sensor();
   }


then the read loop will start, weaked up by polling,witch will set read flag and wake up specific bus Thread to read the sensor ( witch will call read_sensor() ).
Interrupt bypass this, and directly wake up the thread of the bus.

well, this last passage is what i'm thinking about, it seems a bit too much elaborated, but i'll think about it. Your opinion?
Also how the sensor will "talk back" to the main thread may be a bit complicated. In my case i was going to assume all sensor return an array of byte, and use soem pointer trick to get value into what i want.
But this leaveproblem to the "sensor's implementer".
Maybe a specific and shared global struct, in witch the read_sensor will leave data in the right spot is better; just a couple of funtion to set the value, so again sensor implementer does not have to worry about underlaing mechanics, and also will know what the rest of the code may handle.

Alsonote that i like this a lot because sensor are "just" a struct, in its own file, so it will be easy to ifdefsensors, even in automated way

Here you should be careful since it only holds if your sensors have a slow sampling rate or if you know their sampling rate very accurately.

didn't seen that coming!
because i've thinked callback to bypass polling i'm not too-early (or too-late) read prone, but if i add a "last tick read"and use it to find the REAL sensor reading frequency (witch may change as clock's temperature dependency, right?)

btw i'm planning to send all data toPC by CDT (i think i'm fine with bandwidth), and then i've some "to polish a lot but working" code witch will display (3d raw + DCM) and store the data. very usefull to analyze what is going on
User avatar
Korken
Posts: 270
Joined: Wed Apr 02, 2014 4:09 pm
Has thanked: 5 times
Been thanked: 6 times

Re: best code organization to read multiple sensors

Post by Korken »

To have a generic way of defining sensors is very good I believe. But how to globally store the generic sensor data is a design challenge.
Tell me if you come up with something good. :)
lesto
Posts: 55
Joined: Thu May 22, 2014 11:27 am

Re: best code organization to read multiple sensors

Post by lesto »

yes, it is.
This is what i'm thinking as solution and why.

Everything is about the main GOAL (let's call it "the algorithm", even if everithing is it). It should always win.
And to be a winner itshould be easy to port it.

Senors are NOT the algoritm, but just a way to get data FOR the algoritm.
That is why i'm generalizing them; you can hide under the hood wathever you want, even FakeSensor (read from file, usb, fixed value, etc)

Now, back to how pass the sensors's data to the algoritm:
The algoritmh win. It state WHAT and HOW data is needed (a struct), and who write the "sensor_read" implementation should take care of this.
BUT
i don't want sensor nor alorithm "play with lock" or generally how store the data, as the user must find easy to just "drop in" a new sensor implementation. So there are 2 basic problem to solve: how store data so the algorithm will find it as it likes and how hide to user sincronization of the data storage.

I think that the "glue" is provided by a syncronization layer: if your algoritm need different data, or structured in a different way you'll change that layer. This "sync/glue" layer will provide a lot of set_xxx() (used by sensors), and inside that functions syncronization and storage to the algoritm's structure will happen. Algorithm will also use a get_struct() function, so it will not have to worry about sincronzation but just use the struct as it is, with no special precautions. (i'm thinking about a double buffer, one used by algortim while the other is beaing updated by sensors, the get_struct() just swap them)

-implementation detail-
Please note that yesterday i've changed a lot the structure due to code organization: as it has been posted, sensor's struct contains struct for interrupt or polling.
Now i use struct sensor_interrupt and sensor_polling witch contains the struct sensor; that is because struct sensor will be user defined, and based on that data (statically) the struct sensor_interrupt and struct sensor_polling are initialized.

notice that i'm statically defining everything, trying to not use *alloc(), as i want check as most as possible at compile time. (and get a good estimation of used RAM at compile time, very important if working with different MCU), so my code will NOT support plug-n-play (but will support error resuming, so how-swap with same sensor should work by design).
Post Reply