[solved] Variable global (Arduino Due )

Hi,
project PIO with Arduino Due,
problems it variable Global (dly) not see in all code source.

simple delay custom with timer, not running.

see code.

//----------------------------------------
#include <Arduino.h>
uint32_t dly;
void delay_ms( uint32_t );
void startTimer(Tc *tc, uint32_t , IRQn_Type , uint32_t);

void setup() {

     while(!SerialUSB);
    startTimer(TC1, 0, TC3_IRQn, 1000); //TC1 channel 0, the IRQ for that channel and the desired frequency
         
}

void loop() {
 

             SerialUSB.write( "USB \r\n");
             delay_ms( 2000);  // call delay timer, not return
            //   delay(1000);

}
//-----------------------------------------------------------------------------------------------------
void delay_ms( uint32_t dl){
	dly = dl;
   while (  dly )    // not see val, 
   {
   }
}
//-----------------------------------------------------------------------------------------------------
void TC3_Handler()
{
    TC_GetStatus(TC1, 0);

        if(dly){
        dly--;       // dec ok
        }
		
         
}
//-------------------------------------------------------------------------------
void startTimer(Tc *tc, uint32_t channel, IRQn_Type irq, uint32_t frequency) {
        pmc_set_writeprotect(false);
        pmc_enable_periph_clk((uint32_t)irq);
        TC_Configure(tc, channel, TC_CMR_WAVE | TC_CMR_WAVSEL_UP_RC | TC_CMR_TCCLKS_TIMER_CLOCK4);
        uint32_t rc = VARIANT_MCK/128/frequency; //128 because we selected TIMER_CLOCK4 above
        TC_SetRA(tc, channel, rc/2); //50% high, 50% low
        TC_SetRC(tc, channel, rc);
        TC_Start(tc, channel);
        tc->TC_CHANNEL[channel].TC_IER=TC_IER_CPCS;
        tc->TC_CHANNEL[channel].TC_IDR=~TC_IER_CPCS;
        NVIC_EnableIRQ(irq);
}
//-----------------------------------------------------------------------------------

thanks,
Carlos.

Must be volatile uint32_t dly; otherwise the compiler will do optimizations and assumptions and create an infinite loop.

1 Like

thanks your help for my,
Carlos.

1 Like