chipKIT® Development Platform

Inspired by Arduino™

pulsein() for MPLAB

Created Fri, 02 Mar 2012 15:55:58 +0000 by Taygan


Taygan

Fri, 02 Mar 2012 15:55:58 +0000

I am using the Cerebot MX4cK with MPLAB X from microchip and trying to implement a pulsein() function. The function itself is seems easy enough the problem I am having is figuring out an easy to to send the function the Port and Pin number I want it to measure the pulse width on. For example I would like to do something like this.

pulsein(PORTBbits.RB0,timeout);

Then my function would look something like this

int pulsein(int portpin, int timeout) { if(portpin == 1) --do something cool }

Obviously this doesn't work as PORTBbits.RB0 would send the value of that input, but is there a label or something that refers to the address maybe? Then it might not be too hard to modify the function to be:

pulsein(PORTB, PIN, timeout)

or something like that, anyway I realize I could try to attempt something really annoying like create an array of all the PORT addresses and do some mapping or something but I am hoping there is an easier way to pass a generic function the port and bit you want it to operate on with like a prebuilt library or maybe a label that already exists.

Any help would be very very appreciated,

Tay :)


Ryan K

Sat, 03 Mar 2012 01:06:36 +0000

Hello,

You could try this:

pulsein((unsigned int *) &PORTB, 0, timeout);

int pulsein(unsigned int * pPort, uint8_t bnPin, int timeout)
{
if((*pPort) & (1 < < bnPin))
//do something cool
}

Best Regards, Ryan K


Taygan

Sat, 03 Mar 2012 17:38:15 +0000

Thanks for the reply, this is what i ended up with:

uint32_t pulseIn(volatile uint32_t *port, uint16_t pin,uint8_t state, uint32_t timeout)
{
    unsigned long   width;
    unsigned long   numloops;
    unsigned long   maxloops;
    uint16_t stateMask;
    stateMask	=	(state ? pin : 0);
    width		=	0;
    numloops	=	0;
    maxloops	=	(timeout/7)*CL_TICKS_PER_US() + 10;

    // wait for any previous pulse to end
    while ((*port & pin) == stateMask)
    {
            if (numloops++ == maxloops)
                    return(0);
    }
    // wait for the pulse to start
    while ((*port & pin) != stateMask)
    {
            if (numloops++ == maxloops)
                    return(0);
    }
    width	=	micros();
    // wait for the pulse to stop
    while ((*port & pin) == stateMask)
    {
            if (numloops++ == maxloops)
                    return(0);
    }
    width	=	micros()-width;
    return (width+4);
}

borrowing code from the mpide and passing the port address. It could use a bit of clean up like removal of longs but for future use you get the driff.

Thanks again for the help, Tay