#include <asm/MC68EZ328.h> 
#include <stdio.h>
#include <mathf.h>
/* reading distance from a sharp GP2D02 sensor.
    GNU license implied
    matthias schoeldgen <m.schoeldgen@b-cool.de> Mar 2002
    For initialising the CPU hardware, refer to inithard.c.
    measuring is initiated by a low on the output pin (PD 1).
    a rising edge on PD0 signals end of measuring cycle and begin of transfer
    clocking is done by PD1, where a falling edge requests the next bit. 
    read at rising edge then, MSB first. leaving PD1
     high then brings the sensor in powerdown mode 
     The sensor delivers 8 bit of data 
Closer distances than 10 cm and beyond 60 cm are unreliable. 
Here are some typical return values:
    10 cm : (203)  	15 cm : (157)
    20 cm : (134)  	25 cm : (118)
    30 cm : (109)	35 cm : (101)
    40 cm : (96)	45 cm : (91)
    50 cm : (88)	55 cm : (85)
*/

unsigned short getdist(void)
{
unsigned short val = 0;
short j;
    PDDATA &= 0xfd;		/* clock low */
    usleep(2000);	 	/* time delay */
    while ((PDDATA & 0x01) < 1)	/* wait for sensor */
	{}
    PDDATA |= 0x02;		/* clk high */
    for (j = 0; j < 8; j++) {
	PDDATA &= 0xfd;		/*clk lo */
	usleep(60); 		/* time delay */
	val = val << 1;		/* roll */
	val |= (PDDATA & 0x01); 	/* get bit */
	PDDATA |= 0x02;			/* clock high */
        }
    val = val - 60; /* remove basic sensor offset */
    if (val < 1) val = 1 ;  /* avoid divide by zero */
    return 1500 / val;  /* hyperbolic conversion to (rough) centimeters*/
}

int main(int argc, char *argv[])
{
switch (argc) {
    case 1:	
		printf("%d\n",getdist());
		break;
    default : 	printf("Measures distances with Sharp Sensor\n usage: getdist\n");
		break;
	}
exit(0);
}        
