Jakub Janek

Arduino parallelism or multitasking

2019-07-04

As I written once before in this post arduino can do more than one thing at a time (not really). System that I use can be parallel or serial which means it can do more than one thing at a time or can be set that after certaing task it will change the task to something else. In combination this is really powerful, but it wastes some ROM and speed of a MCU.

I will show you one of many school projects that I code, which is really a model of a heating and cooling system which had:

It was requirement that 7 segment would work all the time with current temperature which could only be done if you can keep track of temperature and constantly changing a pins of arduino. It can be done two ways one of which I choose because it seemed easier at first and it was constantly writing every 10 ms.

void show(uint8_t temp) {
  uint8_t ones = temp % 10;
  uint8_t tens = temp / 10;

  PORTD |= (((table[ones] & 0b1000000) != 0) << PD2); //A
  PORTD |= (((table[ones] & 0b0100000) != 0) << PD3); //B
  PORTD |= (((table[ones] & 0b0010000) != 0) << PD4); //C
  PORTD |= (((table[ones] & 0b0001000) != 0) << PD5); //D
  PORTD |= (((table[ones] & 0b0000100) != 0) << PD6); //E
  PORTD |= (((table[ones] & 0b0000010) != 0) << PD7); //F
  PORTB |= (((table[ones] & 0b0000001) != 0) << PB0); //G

  _delay_ms(10);
  PORTB |= (1 << PB2);
  PORTB &= ~(1 << PB3) & ~(1 << PB0); //GND_2 ON and GND_1 OFF
  PORTD = 0; 

  PORTD |= (((table[tens] & 0b1000000) != 0) << PD2); //A
  PORTD |= (((table[tens] & 0b0100000) != 0) << PD3); //B
  PORTD |= (((table[tens] & 0b0010000) != 0) << PD4); //C
  PORTD |= (((table[tens] & 0b0001000) != 0) << PD5); //D
  PORTD |= (((table[tens] & 0b0000100) != 0) << PD6); //E
  PORTD |= (((table[tens] & 0b0000010) != 0) << PD7); //F
  PORTB |= (((table[tens] & 0b0000001) != 0) << PB0); //G

  _delay_ms(10);
  PORTB |= (1 << PB3);
  PORTB &= ~(1 << PB2) & ~(1 << PB0);
  
  PORTD = 0;
}

This only writes a number from table in background. Other code manipulates the data from potentiometer and ds18b20 sensors. Code in events is hidden, because it's too big to fit. This event loop is constantly repeating itself which makes the illusion of paralellism.

void loop() {
  if (event == BOOT) {
  } else if (event == SETTING) {
  } else if (event == HEATING) {
  } else if (event == COOLING) {}

  if (millis() - tempTime >= 3000) {
    displayTemp = ((dallas.getTemp(dallasAddress[tempIndex]) / 128) + currentTemp) / 2;

    tempIndex = ++tempIndex % 2;
    tempTime = millis();
  }
  
  if (millis() - tempTimeRequest >= 5000) {
    dallas.requestTemperaturesByAddress(dallasAddress[tempIndex]);
    
    tempTimeRequest = millis();
  }

  show(displayTemp);
}

For more info feel free to write a comment. Whole code is available here (in slovak).

No comments were found!