We are running a survey to help us improve the experience for all of our members. If you see the survey appear, please take the time to tell us about your experience if you can.
I have written code for sensing input and then output port to respond. I want to add delay between the two actions. Can any one help me out.
Don't you think you need even further corrections than the following?
void delay(U32 cycles) { U32 tmp = *DWT_CYCCNT + cycles; while(*DWT_CYCCNT < tmp) {} }
What if DWT_CYCCNT + cycles overflows, resulting in tmp being set to a value less than DWT_CYCCNT? How long will your delay become then?
That is of course if DWT_CYCCNT has the same numeric range as your U32. If it has less range, then tmp can be set to a value that is larger than DWT_CYCCNT can ever reach, which can cause an infinite delay.
It doesn't hurt to make a full analysis of written code, to check all boundary cases, and figure out if the code can always be trusted or if there might be situations not covered.
"What if DWT_CYCCNT + cycles overflows, resulting in tmp being set to a value less than DWT_CYCCNT? How long will your delay become then?"
You can reset the register at first
But if the register is reset, then it can't be used by other parts of the code that might need to measure time. It's quite common to busy-loop short delays, but using a free-running timer and potentially a timer interrupt to keep track of longer delays or for measuring the time between two events.
Isn't it much better to rewrite the code so it doesn't matter if DWT_CYCCNT overflows during the delay?