RTOS Basic Sample: Blinking in Realtime

Can someone please show how to make this sample on a Photon (or a Spark) work?

http://jeelabs.org/2013/05/24/blinking-in-real-time/index.html

Note that despite the delay call, the LED still blinks in the proper rate.
Thanks in advance!

You mean like something the Timer object does?

That’d be the intended way for such tasks, but there also is the yet undocumented (“beta”) way that’d look like this

void blink() {
  digitalWrite(D7, HIGH);
  delay(500);
  digitalWrite(D7, LOW);
  delay(500);
}

void hardware_fn() {
  // do setup
  pinMode(D7, OUTPUT);
  // loop forever
  for(;;) {
    blink();
  }
}
void setup() {
  // Thread will start and run hardware_fn
  Thread("hardware", hardware_fn, OS_THREAD_PRIORITY_DEFAULT + 1);
  // Use a slightly higher priority to make sure it interrupts the system and application thread
}

This code was donated by the incredible @jvanier :+1:

Thanks for the mention @ScruffR.

At the moment it’s necessary to use HAL_Delay_Milliseconds inside of Thread functions instead of delay since the latter runs the Wi-Fi connection code which should only be run in the application thread. This is on my list of things to fix.

3 Likes

Hello everyone.
Here is an example by me for all who want to try the RTOS functionality.
It works by Electron.

    // This #include statement was automatically added by the Spark IDE.
    #include "application.h"
    
    STARTUP(setup_PINS());
    
    SYSTEM_THREAD(ENABLED);
    SYSTEM_MODE(SEMI_AUTOMATIC);
    
    ApplicationWatchdog wd(60000, System.reset);
    
    Thread hardwareThread;
    
    int REL1 = D7;
    int REL2 = D6;
    
    void setup_PINS()
    {
        
         pinMode(REL1, OUTPUT);
         pinMode(REL2, OUTPUT);
        
         digitalWrite(REL1, LOW);
         digitalWrite(REL2, LOW);
         
    }
    
    void controlRelay1() {
    
     while(true)
    {   
     digitalWrite(REL1, HIGH);
     HAL_Delay_Milliseconds(5000);
    
     digitalWrite(REL1, LOW);
     HAL_Delay_Milliseconds(5000);
     }
     
    }
    
    void controlRelay2() {
    
    while(true)
    {
    digitalWrite(REL2, HIGH);
     HAL_Delay_Milliseconds(8000);
    
     digitalWrite(REL2, LOW);
    HAL_Delay_Milliseconds(8000);
    }
    
    }
    
    void setup() {
        
      hardwareThread = Thread("hardware1", controlRelay1, OS_THREAD_PRIORITY_DEFAULT + 1);
      hardwareThread = Thread("hardware2", controlRelay2, OS_THREAD_PRIORITY_DEFAULT + 1);
    
      Particle.connect();  // for semi automatic mod
       
    }
    
    void loop()
    
    {
       
    }
3 Likes