digital level

#define REDPIN 10
#define YPIN   8
#define XPIN   9
#define LEFT   4800
#define RIGHT  5200
#define RANGE  (RIGHT-LEFT)

void setup()                    
{
  pinMode( REDPIN, OUTPUT );     
  pinMode( XPIN, INPUT ); 
  DDRD = 0xFF;
  PORTD = 0;
}

void loop()                     
{
  // read the x-axis value from the accelerometer
  int xval = (int)pulseIn( XPIN, HIGH );
  byte bubble;

  // the middle value for the memsic 2125 is 5000
  // if the x value is within 10 of the middle then
  // we'll call that "level"
  if( xval > 4990 && xval < 5010 )
  {
    digitalWrite( REDPIN, HIGH );
    PORTD = 0;
  }
  else
  {
    // we're not "level"
    if( xval < LEFT )
    {
      // the bubble is all the way to the left
      bubble = 0x80;
    }
    else if( xval > RIGHT )
    {
      // the bubble is all the way to the right
      bubble = 0x01;
    }
    else
    {
      // the bubble is somewhere inbetween 
      bubble = 0x80 >> ((xval-LEFT)/(1+(RANGE/8)));
    }
    PORTD = bubble;
    digitalWrite( REDPIN, LOW );
  }  
  delay( 100 );
}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: