irtest2.c

#include "ticker.h"
#include "lcd.h"
#include "3052.h"
#include <stdio.h>

#define GETIRPULSE_TIMEOUT 5000 /* msec */
#define MAXONPULSEWIDTH    20000 /* usec */
#define MAXOFFPULSEWIDTH   10000 /* usec */
#define MAXPULSE 128

typedef unsigned char  uchar;
typedef unsigned short ushort;
typedef unsigned long  ulong;

typedef struct {
  ushort onwidth;
  ushort offwidth;
} PulseWidth;

PulseWidth pw[MAXPULSE];
uchar npw; /* assuming MAXPULSE is less than 256 */

#define isIRSensorOn() (PA.DR.BYTE&0x20)
#define FUNCTIONLED    PB.DR.BIT.B3
#define getSWStatus()  (PA.DR.BYTE^0x0f)
#define STARTSW        0x08
#define PREVSW         0x02
#define NEXTSW         0x01


uchar getIRPulse()
{
  ulong tm0,tm1;
  ulong timeout;

  FUNCTIONLED = 0;
  timeout = tick+(GETIRPULSE_TIMEOUT*1000/TICK);
  npw = 0;

  /* Wait for begin */
  while(!isIRSensorOn()){
    if(tick == timeout){
      FUNCTIONLED = 1;
      return 0;
    }
  }
  tm0 = tick;

  FUNCTIONLED = 1;
  while(npw < MAXPULSE){
    /* Wait for off */
    timeout = tm0+(MAXONPULSEWIDTH/TICK);
    while(isIRSensorOn()){
      if(tick == timeout)
        return npw;
    }
    tm1 = tick;
    pw[npw].onwidth = tm1-tm0;
    FUNCTIONLED = 0;
    /* Wait for on */
    timeout = tm1+(MAXOFFPULSEWIDTH/TICK);
    while(!isIRSensorOn()){
      if(tick == timeout){
        pw[npw++].offwidth = 0;
        FUNCTIONLED = 1;
        return npw;
      }
    }
    tm0 = tick;
    pw[npw++].offwidth = tm0-tm1;
    FUNCTIONLED = 1;
  }
  return npw;
}

void displayPulse(uchar cpw)
{
  char msg[32];
  if(cpw >= npw){
    LCDDisplay("",1);
    return;
  }
  sprintf(msg,"%2d:%6d/%6d",cpw+1,pw[cpw].onwidth*TICK,pw[cpw].offwidth*TICK);
  LCDDisplay(msg,1);
}

int main()
{
  uchar swstatus;
  uchar cpw;
  char msg[32];

  PA.DDR = 0x00;
  PB.DDR = 0xff;
  PB.DR.BYTE = 0xff;

  TickerInit();
  LCDInit();
  LCDDisplay("iR TEST",0);
  cpw = 0;
  while(1){
    swstatus = getSWStatus();
    if(swstatus&STARTSW){
      LCDDisplay("Waiting...",0);
      LCDDisplay("",1);
      cpw = 0;
      if(!getIRPulse()){
        LCDDisplay("Timeout",0);
      }else{
        sprintf(msg,"Got %d pulses",npw);
        LCDDisplay(msg,0);
        displayPulse(cpw);
      }
      while(getSWStatus()&STARTSW)
        ;
    }else if(swstatus&PREVSW){
      if(cpw > 0)
        cpw--;
      displayPulse(cpw);
      while(getSWStatus()&PREVSW)
        ;
    }else if(swstatus&NEXTSW){
      if(cpw < npw-1)
        cpw++;
      displayPulse(cpw);
      while(getSWStatus()&NEXTSW)
        ;
    }
  }
  return 0;
}

This page was generated at 2005/3/19 15:4:13