cancel
Showing results for 
Search instead for 
Did you mean: 

Can someone explain how to read these line ?

ChristenTen
Associate II

Hello everyone !

I'm new here and i wanted to know how these lines say please??

I wanted to have microsecond delay for my ultrasonic sensor.

Thanks for all your help!

void usDelay(uint32_t uSec)
{
	if(uSec < 2) uSec = 2;
	usTIM->ARR = uSec - 1; 	
	usTIM->EGR = 1; 			
	usTIM->SR &= ~1; 		
	usTIM->CR1 |= 1; 		
	while((usTIM->SR&0x0001) != 1);
	usTIM->SR &= ~(0x0001);
}

3 REPLIES 3

First, read the timer chapter in reference manual.

    void usDelay(uint32_t uSec)
    {
    	if(uSec < 2) uSec = 2;   // sanitize input value, minimum possible duration using this method is 2usec
    	usTIM->ARR = uSec - 1; 	 // counter counts up to 0 to ARR inclusive
    	usTIM->EGR = 1; 	// generate update, this ensures ARR value is copied to the "active" register even its shadowing is on
    	usTIM->SR &= ~1; 	// clear bit 0 i.e. update flag in status register - this is incorrectly written, it should be = rather than &=
    	usTIM->CR1 |= 1; 		// start counter
    	while((usTIM->SR&0x0001) != 1);  // wait until update
    	usTIM->SR &= ~(0x0001); // clear update again, again incorrectly (and here, it's better to stop the counter  first)
    }

> I wanted to have microsecond delay for my ultrasonic sensor.

There's more to that, e.g. you have to switch on optimization.

JW

turboscrew
Senior III

I don't think these:

usTIM->SR &= ~1;

are wrong. At least timer 1 has a reserved bit in the status register. It shouldn't be written "1".

Then it's better not to alter the other bits.

https://community.st.com/s/feed/0D50X00009bLSAZSA4

(formatting and videos did not survive migration from jive)

JW