Search code examples
cassemblydelaywinavr

Assign delays for 1 ms or 2 ms in C?


I'm using code to configure a simple robot. I'm using WinAVR, and the code used there is similar to C, but without stdio.h libraries and such, so code for simple stuff should be entered manually (for example, converting decimal numbers to hexadecimal numbers is a multiple-step procedure involving ASCII character manipulation).

Example of code used is (just to show you what I'm talking about :) )

.
.
.
    DDRA = 0x00;
    A = adc(0); // Right-hand sensor
    u = A>>4;
    l = A&0x0F;
    TransmitByte(h[u]);
    TransmitByte(h[l]);
    TransmitByte(' ');
.
.
.

For some circumstances, I must use WinAVR and cannot external libraries (such as stdio.h). ANYWAY, I want to apply a signal with pulse width of 1 ms or 2 ms via a servo motor. I know what port to set and such; all I need to do is apply a delay to keep that port set before clearing it.

Now I know how to set delays, we should create empty for loops such as:

int value= **??**
for(i = 0; i<value; i++)
    ;

What value am I supposed to put in "value" for a 1 ms loop ?


Solution

  • Chances are you'll have to calculate a reasonable value, then look at the signal that's generated (e.g., with an oscilloscope) and adjust your value until you hit the right time range. Given that you apparently have a 2:1 margin, you might hit it reasonably close the first time, but I wouldn't be much on it.

    For your first approximation, generate an empty loop and count the instruction cycles for one loop, and multiply that by the time for one clock cycle. That should give at least a reasonable approximation of time taken by a single execution of the loop, so dividing the time you need by that should get you into the ballpark for the right number of iterations.

    Edit: I should also note, however, that (at least most) AVRs have on-board timers, so you might be able to use them instead. This can 1) let you do other processing and/or 2) reduce power consumption for the duration.

    If you do use delay loops, you might want to use AVR-libc's delay loop utilities to handle the details.