5 years, 5 months ago.

how to use the timeout ?

I would like to realise a function every x seconds. But the timeout I can not send my value val in the void flip. Early val = 5000, there is no increment. Can you help me please ? here is my program :

void flip(void);

int val=0;

int main() { led2 = 0; spi.format(16,1); Setup the spi for 8 bit data, high steady state clock, spi.frequency(1000000); second edge capture, with a 1MHz clock rate cs1=1;

while (val<4000) { cs1=0; flipper.attach(&flip, 2.0); setup flipper to call flip after 2 seconds val=val+1000; cs1=1; } }

void flip() { spi.write(val); lcd.printf("val=%d \n\n", val); led2 = !led2; }

Thank you

Question relating to:

Please put your code between <<code>> and <</code>> (seperate lines) to get it properly formatted.

posted by Erik Olieman 04 Jun 2014
Comment on this question

1 Answer

5 years, 5 months ago.

There are several problems with the above code. You dont need to continously attach the timeout to the flip function inside the while loop. This will reset the timeout. Secondly, you will need to toggle cs1 pin inside the flip function for every spi write otherwise the slave will probably ignore the new data. Third problem: the while loop will finish within a fraction of a second...

//add declarations for cs1, led, spi, lcd...

void flip(void);

int val=0;

int main() {
  led2 = 0;
  spi.format(16,1); //Setup the spi for 16 bit data, high steady state clock,
  spi.frequency(1000000); //second edge capture, with a 1MHz clock rate

  cs1=1;

 flipper.attach(&flip, 2.0); // setup flipper to call flip after 2 seconds 

while (val<4000) {
   val=val+1000;
  
   //add delays here or the while loop will finish in a fraction of a second....
 }
}

void flip() {
  cs1=0; 
  spi.write(val);
  cs1=1;
 
 lcd.printf("val=%d \n\n", val);
 led2 = !led2;
}

I think that the intended result is to send 0, 1000, 2000 etc... over the SPI bus with 2 seconds between each value. The easiest way to do that is to increase val in the flip function rather than the main code:

void flip(void);
 
Ticker flipper;
volatile int val=0; // mark as volatile so that the main loop notices it's been changed by an interrupt
 
int main() {
  led2 = 0;
  spi.format(16,1); //Setup the spi for 16 bit data, high steady state clock,
  spi.frequency(1000000); //second edge capture, with a 1MHz clock rate
 
  cs1=1;
 
 flipper.attach(&flip, 2.0); // setup flipper to call flip after 2 seconds 
 
while (val<4000) {
  wait(0.1);
 }

flipper.detach() // stop the automated transmit or it will keep going.

}
 
void flip() {
  cs1=0; 
  spi.write(val);
  cs1=1;
 
 lcd.printf("val=%d \n\n", val);
 val +=1000;
 led2 = !led2;
}
posted by Andy A 05 Jun 2014