/* The three input ports of RCX 
   Last updated 14.4.00
 */

#include "H8.h"
#include "AD.h"
#include "IOPorts.h"

#ifndef   InputPorts_H_DEFINED
#define   InputPorts_H_DEFINED

/* The three input ports are connected to three AD channels as follows
   
   Port 1 to AN2
   Port 2 to AN1
   Port 3 to AN0

   Furthermore, an active sensor connected to a port need a power 
   supply. This is accomplished by setting a bit in I/O port 6:

   bit2 for Port 1
   bit1 for Port 2
   bit0 for Port 3
 
 */ 

#define TurnOnPort1   P6DR |=  bit2
#define TurnOffPort1  P6DR &= ~bit2
#define TurnOnPort2   P6DR |=  bit1
#define TurnOffPort2  P6DR &= ~bit1
#define TurnOnPort3   P6DR |=  bit0
#define TurnOffPort3  P6DR &= ~bit0

static byte Port1Active = FALSE;
static byte Port2Active = FALSE;
static byte Port3Active = FALSE;

void Port1SetActive( void )
{
  Port1Active = TRUE;
  P6DDR_ROM |= bit2; P6DDR = P6DDR_ROM; 
  TurnOnPort1;
}

void Port1SetPassive( void )
{
  Port1Active = FALSE;
  TurnOffPort1;
}

int16 Port1Raw( void )
{ 
  int16 value;

  if ( Port1Active ) TurnOffPort1;
  value = ConvertADChannel( AN2 );
  if ( Port1Active ) TurnOnPort1; 
  
  return ( value  );
}

void Port2SetActive( void )
{
  Port2Active = TRUE;
  P6DDR_ROM |= bit1; P6DDR = P6DDR_ROM; 
  TurnOnPort2;
}

void Port2SetPassive( void )
{
  Port2Active = FALSE;
  TurnOffPort2;
}

int16 Port2Raw( void )
{ 
  int16 value;

  if ( Port2Active ) TurnOffPort2;
  value = ConvertADChannel( AN1 );
  if ( Port2Active ) TurnOnPort2; 
  
  return ( value  );
}
void Port3SetActive( void )
{
  Port3Active = TRUE;
  P6DDR_ROM |= bit0; P6DDR = P6DDR_ROM; 
  TurnOnPort3;
}

void Port3SetPassive( void )
{
  Port1Active = FALSE;
  TurnOffPort3;
}

int16 Port3Raw( void )
{ 
  int16 value;

  if ( Port3Active ) TurnOffPort3;
  value = ConvertADChannel( AN0 );
  if ( Port3Active ) TurnOnPort3; 
  
  return ( value  );
}




#endif /* InputPorts_H_DEFINED */
