Issue with multithreading

Hello,

I am currently building a temperature sensing device. Unlike other sensing device on this website, i am using 4 7-segments displays (5161as, common cathode) that i had.
To display a certain number on the displays, i break them down into 4 digits and send each digit to the corresponding display, while interpoling HIGH, LOW for each digits, so that each digit appear at 5 milliseconds intervalls, therefore allowing the viewer to see full numbers.

Everything works well and i can count from 0001 to 9999 without issue. But after adding the Temperature and humidity sensor (the DHT11) and using "multithreading", the displays lose their steps and visualy, there is a small but noticeable slow down, then everything goes to normal, till the temperature values are read.

After some tests, i noticed that the sensor has a 25 milliseconds delay (probably used to get and convert values from the sensor).

Is there a way to multitask the reading of the sensor data and the display of the values, so there isn't any interferances?

Details:
Controller board: Arduino Uno
OS: Windows 10.
P.S: Example code in Attachments.

Thanks

DHT11Default.ino (716 Bytes)

Is there a way to multitask the reading of the sensor data and the display of the values, so there isn't any interferances?

Sure. Use an Arduino that has multiple processors. Oh, wait. There aren't any.

The code you posted doesn't display data on seven segment displays.

PaulIS,

sorry, the code i uploaded was just the test code.
Attached is the code that displays the values to the displays. I have to mention, that it is still a work in progress and that other areas of code might not look professional.

Yes, the arduino has one core, but is there a way to keep one operation running undisturbed from a second? Single core computers were able to run multiple operations in parallel.

EDIT: I also have an ESP32, i guess i should use it instead: Reading an converting values on a core and display them on the other.

sketch_apr12a.ino (5.1 KB)

The sampling time of DHT11 is about 1.5-sec, and it is certainly not 25 ms!

You have two jobs to take care of simultaneously:
(1) Refreshing the cc-type multiplexed display unit
(2) Acquiring DHT11 signal at 1.5-sec interval.

The Algorithm:

void loop()
{
    while (1.5 sec has not elapsed)   //can be implemented using millis() or dedicated TC1 of UNO
    {
        keep refreshing the multiplexed display
     }

     Acquire and process DHT11 Signal
     //Repeat the process
}

1

That will still cause a glitch when the DHT needs to be read.

I don't know if the DHT needs some form of atomic operation. If not, maybe a timer interrupt can be a solution.

And else a redesign is in place.

OP, please post your code in the post (using code tags) instead of attaching. It's small enough.

GolamMostafa,

i tried doing something similar in my code:

  1. Multiplexing the displays and at the last display, a BOOLEAN called "finished" becomes TRUE, at the beginning of the iteration, "finished" turns to false
  2. After 2 seconds and if "finished" is true, the data from the sensor is read and outputed to the algorithm that breaks down the numbers in digits
  3. The digits are sent to the displays.

But still no help.

Actually, about the 25 seconds.
In the test code, the duration of each loop is calculated and outputed (= 3/4 miliseconds), after 2 minutes, using multitasking, the sensor values are read and then displayed and i get 3, 24, 0, 1, 2, 3 milliseconds successively.
I also changed libraries for the sensors, but still nothing. I tried reading the data from the sensor (without processing them) and still i get the flickering.

Link to demo video.Video
Link to Test Screenshot:
Image

sterretje,

sorry again.

#include <SimpleDHT.h>

int pinDHT11 = A1;
SimpleDHT11 dht11;

const int zahlen[10][7] = {{1, 1, 1, 1, 1, 1, 0}, {0, 1, 1, 0, 0, 0, 0}, {1, 1, 0, 1, 1, 0, 1}, {1, 1, 1, 1, 0, 0, 1}, {0, 1, 1, 0, 0, 1, 1}, 
                    {1, 0, 1, 1, 0, 1, 1}, {1, 0, 1, 1, 1, 1, 1}, {1, 1, 1, 0, 0, 0, 0}, {1, 1, 1, 1, 1, 1, 1}, {1, 1, 1, 1, 0, 1, 1}};
const int led[8] = {9, 4, 3, 2, 6, 8, 7};
const int signPins[3] = {11, 12, 13};
const int zeichen[3][7] = {{1, 1, 0, 0, 0, 1, 1}, {1, 0, 0, 0, 1, 1, 1}, {0, 0, 0, 1, 1, 1, 0}};
const int extra[2][7] = {{1, 0, 0, 1, 1, 1, 1}, {1, 1, 1, 0, 1, 1, 1}}; //E R
int werte[3] = {0, 0, 0};
int stelle[3] = {0, 0, 0};
int x = 0;
int n = 0;
boolean button_alt, button_neu;
unsigned long zeit_alt, zeit_neu;
boolean error = false;
int errornr = 0;
boolean alr_on = false;
boolean mode_on = true;
boolean finished = false;
byte temperature = 0;
byte humidity = 0;
int counter = 0;
int counter_off = 0;

void empty(){
  for (int i = 0; i < 7; i++){
    digitalWrite(led[i], LOW);
  }
}
void ZAHL(int var){
  empty();
  for (int i = 0; i < 7; i++){
    if (zahlen[var][i] == 0){
      digitalWrite(led[i], LOW);
    } else{
      digitalWrite(led[i], HIGH);
    }
  }
}
void ZEICHEN(int var){
  empty();
  for (int i =0; i < 7; i++){
    if (zeichen[var][i] == 0){
      digitalWrite(led[i], LOW);
    } else{
      digitalWrite(led[i], HIGH);
    }
  }
}
void EXTRA(int var){
   empty();
  for (int i =0; i < 7; i++){
    if (extra[var][i] == 0){
      digitalWrite(led[i], LOW);
    } else{
      digitalWrite(led[i], HIGH);
    }
  }
}
void setup() {
  
  Serial.begin(9600);
  pinMode(2, OUTPUT); //D
  pinMode(3, OUTPUT); //C
  pinMode(4, OUTPUT); //B
  pinMode(5, OUTPUT); //DOT
  pinMode(6, OUTPUT); //E
  pinMode(7, OUTPUT); //G
  pinMode(8, OUTPUT); //F
  pinMode(9, OUTPUT); //A
  pinMode(A0, INPUT); //Button
  pinMode(A2, OUTPUT); //LED Red
  pinMode(A3, OUTPUT); //LED Green
  pinMode(A4, OUTPUT); //LED Blue

  pinMode(10, OUTPUT); //4
  pinMode(11, OUTPUT); //3
  pinMode(12, OUTPUT); //2
  pinMode(13, OUTPUT); //1
  
  digitalWrite(10, LOW);
  digitalWrite(11, HIGH);
  digitalWrite(12, HIGH);
  digitalWrite(13, HIGH);

  digitalWrite(A2, LOW);
  digitalWrite(A3, LOW);
  digitalWrite(A4, LOW);

  button_alt = digitalRead(A0);
  ZEICHEN(n);
  
}
void loop() {
  zeit_neu = millis();
  button_neu = digitalRead(A0);
  if (error){
    if (zeit_neu - zeit_alt > 1000){
      if (alr_on == false){
        // TURN RED LIGHT ON
        digitalWrite(A2, HIGH);
        digitalWrite(A3, LOW);
        digitalWrite(A4, LOW);
        alr_on = true;
      } else{
        digitalWrite(A2, LOW);
        digitalWrite(A3, LOW);
        digitalWrite(A4, LOW);
        alr_on = false;
      }
      zeit_alt = zeit_neu;   
   }

   digitalWrite(10, HIGH);
   digitalWrite(11, HIGH);
   digitalWrite(12, HIGH);
   digitalWrite(13, LOW);
   EXTRA(0);
   delay(5);

   digitalWrite(10, HIGH);
   digitalWrite(11, LOW);
   digitalWrite(12, LOW);
   digitalWrite(13, HIGH);
   EXTRA(1);
   delay(5);

   digitalWrite(10, LOW);
   digitalWrite(11, HIGH);
   digitalWrite(12, HIGH);
   digitalWrite(13, HIGH);
   ZAHL(errornr);
   delay(5);
  }
  else if (mode_on == false){
      digitalWrite(10, HIGH);
      digitalWrite(11, HIGH);
      digitalWrite(12, HIGH);
      digitalWrite(13, HIGH);
    
      digitalWrite(A2, LOW);
      digitalWrite(A3, LOW);
      digitalWrite(A4, LOW);

//      if (button_neu == HIGH){ 
//        if (button_neu != button_alt){
//          counter_off = zeit_neu;
//        } else {
//          if (zeit_neu - counter_off > 2000){
//            mode_on = true;
//          }
//         }
//      } else{
//      counter_off = 0;
//      }
//    button_alt = button_neu;
 } 
 
  else{
    // BUTTON

    digitalWrite(A2, LOW);
    digitalWrite(A3, LOW);
    digitalWrite(A4, HIGH);

    if (button_neu == HIGH){ 
      if (button_neu != button_alt){
        n = (n+1) % 3;
        counter = zeit_neu;
      } else {
      if (zeit_neu - counter > 2000){
        mode_on = false;
      }
      }
    } else{
      counter = 0;
    }
    button_alt = button_neu; 
    if (zeit_neu - zeit_alt > 5000 && finished == true){
      zeit_alt = zeit_neu;
      int err = SimpleDHTErrSuccess;
      if (dht11.read(pinDHT11, &temperature, &humidity, NULL) != SimpleDHTErrSuccess){
        error = true;
        errornr = 1;
        return; 
      }
      werte[0] = temperature;
      werte[1] = humidity;
    }
    finished = false;
    stelle[0] = int(werte[n] /100);
    stelle[1] = int((werte[n] % 100)/10);
    stelle[2] = int((werte[n] % 100) % 10);
    digitalWrite(10, LOW);
    digitalWrite(11, HIGH);
    digitalWrite(12, HIGH);
    digitalWrite(13, HIGH);
    ZEICHEN(n);
    delay(5);
  
    digitalWrite(10, HIGH);
    digitalWrite(11, HIGH);
    digitalWrite(12, HIGH);
    digitalWrite(13, LOW);
    ZAHL(stelle[0]);
    delay(5);
  
    digitalWrite(10, HIGH);
    digitalWrite(11, HIGH);
    digitalWrite(12, LOW);
    digitalWrite(13, HIGH);
    ZAHL(stelle[1]);
    delay(5);
  
    digitalWrite(10, HIGH);
    digitalWrite(11, LOW);
    digitalWrite(12, HIGH);
    digitalWrite(13, HIGH);
    ZAHL(stelle[2]);
    delay(5); 
    finished = true;
  }
}

Let me share with you my experience of successful multiplexing of a 16-digit cc-type 7-segment display unit with the polling of a counter (based on 16 pulses coming from tachometer signal of a taxicab).

Try these codes:

//include header files as needed
unsigned long presentmillis;
//initialize global variables as needed

void setup() 
{
  // initialize as needed
 //testing pinMode(13, OUTPUT);

}

void loop() 
{
  while(millis() - presentmillis <1500)  //less than 1.5 sec
  {
    refreshDisplay();
  }
  presentmillis = millis();
  acquireDHT();
}

void refreshDisplay()
{
  //enter codes here
}

void acquireDHT()
{
   //enter codes here
   //testing digitalWrite(13, !digitalRead(13));
}

GolamMostafa,

interessting! Thank you. But i think the issue, is with the sensor (Please take a look, at the test code and the screenshot, i added. The code runs well, then later after the sensors values are read and displayed, there is a pertubartion). I will try your code and some other sensors later.

Thanks.

const int zahlen[10][7] = {{1, 1, 1, 1, 1, 1, 0}, {0, 1, 1, 0, 0, 0, 0}, {1, 1, 0, 1, 1, 0, 1}, {1, 1, 1, 1, 0, 0, 1}, {0, 1, 1, 0, 0, 1, 1},
                    {1, 0, 1, 1, 0, 1, 1}, {1, 0, 1, 1, 1, 1, 1}, {1, 1, 1, 0, 0, 0, 0}, {1, 1, 1, 1, 1, 1, 1}, {1, 1, 1, 1, 0, 1, 1}};
const int led[8] = {9, 4, 3, 2, 6, 8, 7};
const int signPins[3] = {11, 12, 13};
const int zeichen[3][7] = {{1, 1, 0, 0, 0, 1, 1}, {1, 0, 0, 0, 1, 1, 1}, {0, 0, 0, 1, 1, 1, 0}};
const int extra[2][7] = {{1, 0, 0, 1, 1, 1, 1}, {1, 1, 1, 0, 1, 1, 1}}; //E R

Why are those arrays int? None of the values exceed what would fit in a byte.

void ZAHL(int var){
  empty();
  for (int i = 0; i < 7; i++){
    if (zahlen[var][i] == 0){
      digitalWrite(led[i], LOW);

After you have set the pins LOW, why do you need to set them LOW again?

    stelle[0] = int(werte[n] /100);
    stelle[1] = int((werte[n] % 100)/10);
    stelle[2] = int((werte[n] % 100) % 10);

You don't seem to realize that an int divided by an int IS an int.

For someone who wants faster code, your code has an amazing number of calls to delay().

Think of the sensor like a queue - it takes a finite amount of time to get through,

The problem is to wait in the queue, but keep breathing.
If you stop breathing when you enter the queue, you may be dead before your reach the cashier.

In your case the LEDs are more important (in time) than the sensor - so treat them that way.

  • When you're ready to take a sample, initialise the sensor process, set a boolean flag, and return immediately to the LEDs.
  • Next cycle around the LED refresh, check if the sensor is finished, if not - just keep going with the LEDs
  • When finally the sensor says 'ok, I'm done' - process the sensor data as quickly as possible, and return to the LEDs
  • Rinse & repeat.
    The challenge may be to re-code around the sensor to have two distinct operations...
  • Initialise the sensing process
  • Get the sensor result
    As two completely separate operations

Adding to lastchancename's comment:
The reading of the sensor 'starts' with a 20ms delay. Rework the library.

Based on below I suspect that counter should be an unsigned long and not an int

     if (button_neu != button_alt)
      {
        n = (n + 1) % 3;
        counter = zeit_neu;
      }
      else
      {
        if (zeit_neu - counter > 2000)
        {
          mode_on = false;
        }
      }

It will work as long as zeit_neu is less than 32767 + 2000; after that the if (zeit_neu - counter > 2000) will always evaluate to true because counter can't exceed 32767 (it's an int).

Your use of the finished variable is useless (no offense intended).

   if (zeit_neu - zeit_alt > 5000 && finished == true)
    {
      ...
      ...
    }

    finished = false;
    ...
    ...
    finished = true;

Once you have executed that last line once, the test for finished in the if will always evaluate to true.

Further your code never sets mode_on to true (except when defining it). Why?

PaulS

All your points are valid. I will try to improve the code.

Thank you.

Can you please post the connection diagram of your 7-segment display unit?

What do you think if I present, for your reference, a 2x4-digit direct driven cc-type multiplexed display unit where DP0-DP3 will show Temperature reading and DP4-DP7 will show Humidity reading? (Sensor would be DHT11/DHT22 with UNO.)

GolamMostafa,

I used 4 7-segment displays of model 5161as. The connection is similar to that on the following picture:

Use the DHT11, instead of the DHT 22, since the DHT 22 is faster.

I tested other sensors, like the air quality sensor (MQ135) and everything seemed to work fine. I check the libraries of the DHT11 and they seem to include multiple delays in their code. I was able to recreate the flickering, by adding a little delay at the place where the reading of the sensor took place.

I will later try to manipulate the library, so that the timing work along the frame rates of the displays.

Thanks for your help guys.

Having done quite a few programs for other mcu's, I would do such things like mutiplexing a display with an ISR (interrupt service routine)

As I do this in assembler I have no idea how that works with c++ and arduino (avr) but as far as I know, it will work quite easy.

Flo

8-digit cc-type 7-segment Multiplexed Display Unit.

#include <SimpleDHT.h>

int pinDHT22 = 2;
SimpleDHT22 dht22;

unsigned long presentmillis;

byte lupTable[] = {
0x3F, 0x06, 0x5B, 0x4F, 0x66, 0x6D, 0x7D, 0x07, 0x7F, 0x6F, 0x77, 0x7C, 0x39, 0x5E, 0x79, 0x71
                };  //cc-code for 0, 1, 2, 3, ........E, F               

byte ccArray[8];

void setup() 
{
  Serial.begin(9600);
  pinMode(7, OUTPUT);
  pinMode(6, OUTPUT);
  pinMode(4, OUTPUT);
  pinMode(5, OUTPUT);
  DDRB = 0xFF;
  DDRC = 0xFF;
}

void loop() 
{
 while((millis()-presentmillis) <1500)
 {
    refreshDisplay(); 
 }
 presentmillis = millis();
 acqDHT22();
}

void refreshDisplay()
{
  byte y1 = 0b111111;
  byte y2 = 0b111111;
  for (int i=0; i<8; i++)
  {
    byte x = ccArray[i];
    PORTB = x;
    digitalWrite(6, bitRead(x, 6));
    digitalWrite(7, bitRead(x, 7));
    byte y3 = y1;
    bitClear(y3, i);
    PORTC = y3;
    //-----------------------------------------
    if (i <=5)
    {
      digitalWrite(4, HIGH);
      digitalWrite(5, HIGH);
    }
    if (i == 6)
    {
      digitalWrite(4, LOW);
      digitalWrite(5, HIGH);
    }

    if (i == 7)
    {
      digitalWrite(4, HIGH);
      digitalWrite(5, LOW);
    }
    delay(2);
  }
}

void acqDHT22()
{
  float temperature = 0;
  float humidity = 0;
  dht22.read2(pinDHT22, &temperature, &humidity, data);
  
//--------------------------------------------------------- 
 unsigned long *ptr;
  ptr = (unsigned long*) &temperature;
  unsigned long m = *ptr;
 
  unsigned long m1 = m;
  m1 = m1 >> 23;
  unsigned long m2 = pow(2, m1-127);
  
  uint32_t dec=0;
  for (int i=22, j=-1; i>=0, j>=-23; i--, j--)
  {
    dec += (uint32_t)bitRead(m, i)*pow(2, j)*1000000; 
  }

  dec = dec + 1000000;
  uint32_t dec1 = (uint32_t) m2*dec;
  
 /* --- alternate codes to convert the float into fixed point integer value : 27.80 ----> 2780
   temperature = temperature*100.00;   //say temperature = 27.80
   unit16_t dec1 = (uint16_t)temperature;  //dec1 = 2780 = 0x0ADC

*/

  byte inDex[8];
  for (int i=0; i<8; i++)
  {
    inDex[i] = dec1%10;
    dec1 = dec1/10;
  }

 for (int i=0, j=7; i<4, j>=4; i++, j--)
 {
    ccArray[i] = lupTable[inDex[j]];
 }

  ccArray[1] = ccArray[1]|0x80;        //place point
  
//-------------------------------------------------------
 unsigned long *ptrx;
  ptrx = (unsigned long*) &humidity;
  unsigned long mx = *ptrx;

  unsigned long m1x = mx;
  m1x = m1x >> 23;
  unsigned long m2x = pow(2, m1x-127);
  
  uint32_t decx=0;
  for (int i=22, j=-1; i>=0, j>=-23; i--, j--)
  {
    decx += (uint32_t)bitRead(mx, i)*pow(2, j)*1000000; 
  }

  decx = decx + 1000000;
  uint32_t dec1x = (uint32_t) m2x*decx;
  
  byte inDexx[8];
  for (int i=0; i<8; i++)
  {
    inDexx[i] = dec1x%10;
    dec1x = dec1x/10;
  }

 for (int i=4, j=7; i<8, j>=4; i++, j--)
 {
    ccArray[i] = lupTable[inDexx[j]];
 }

  ccArray[5] = ccArray[5]|0x80;        //place point
  
  
}

With post #16
ADD current limiting resistors!
DO NOT turn on multiple digits at the same time (even accidentally)
More than 2/3 simultaneously could damage the column output pin, and will dim the segments even if current limiting resistors are in place.

The diagram of Post#16 has been modified to include current limiting resistors for the segments. Thanks for the observation.

The action described in

GolamMostafa:
The diagram of Post#16 has been modified to include current limiting resistors for the segments.

was noted as a violation of the forum rules/standards. :wink:

Never change technical parts of posts that have been commented in any way,
doing so makes the comments look unbased/stupid/strange, always post such changes in a new response.