Wixel with HC-SR04

Hello Jeremy, thanks for the reply,

I did a small robot controlled by the computer using a pair of wixels to communicate. Wixel in robot also controls the pulses to stepper motors. A few months ago I opened a topic here to show the result:

After that I made some improvements in robot and now would like to add a distance sensor in it, so I bought the HC-SR04.

From what I saw in other topics, I was wondering what would be tricky to measure intervals of less than millisecond, so I thought I’d create my own ticks using something like the code below. Certainly would not be very accurate, but perhaps solve, then I can put the result here.

My ticks are loops in a while statement. At startup I make an estimate of how many “ticks” per second can be produced.

uint32 ticks4sec = 0;
#define BIGnumber 1000000

void initTicks(){
	uint16 ms;
        uint32 tk;

    tk= BIGnumber;
    ms= getMs();
    while(tk) 
        tk--;
    ms= getMs()-ms;
    if(ms)
        ticks4sec = (BIGnumber*1000) / ms;
    // else need a bigger number
}

The idea is count “ticks” during pulse and then calculate time based on estimate made before:

#define pnTrigg P0_0
#define pnEcho  P0_1

uint32 ultraSonicTicks()
{   uint32 tcks=0;

    pnTrigg = 0;
    delayMicroseconds(2);
    pnTrigg = 1;
    delayMicroseconds(10);
    pnTrigg = 0;

    LED_RED(true);
    while (!pnEcho);    // <---- Problem here
    LED_RED(false);

    LED_YELLOW(true);
    while(pnEcho) 
        tcks++;
    LED_YELLOW(false);

    return tcks;
}

But is not working, first while never stop and now im trying find out why. Bellow my startup code:

void main()
{
    systemInit();
    usbInit();
    radioComInit();
    initTicks();

    // pin 00 to digital output - trigger
    setDigitalOutput(00, LOW);
    // pin 01 to digital input - echo
    setDigitalInput(01, true);

    . . . 
}

Since Wixel pins are not 5V tolerant, pin P0_1 is being fed through a voltage divider as showed in user guide at pololu.com/docs/0J46/5.b

About interrupts, I have no experience, but I would really like to learn to use. I have searched on the matter but it would be very instructive to see a specific code example for Wixel.

regards