To Build a Robot part 3

March 26, 2010

Encouraged by my quick work with the H-Bridge I decided to add in the accelerometer. Below is the wiring diagram and sketch I am using. The sketch just spins the motor forward or backward based on the X tilt / accel.

Arduino DC Motor and Accelerometer with L293B and 2125

Arduino DC Motor and Accelerometer with L293B and 2125



int enablePin = 9; //Motor's enable pin
int dPin_1 = 6;// Digital Pin to turn the motor on/off
int dPin_2 = 10;

int xPin = 2;
int yPin = 3;

int ledPin = 13; //LED pin

void setup()
{
Serial.begin(9600);

//latch_state = 0;

//latch_tx(); // "reset"

pinMode(enablePin, OUTPUT);
pinMode(dPin_1, OUTPUT);
pinMode(dPin_2, OUTPUT);

pinMode(xPin, INPUT);
pinMode(yPin, INPUT);

pinMode(ledPin, OUTPUT);
}

void loop()
{
// variables to read the pulse widths:
int pulseX, pulseY;
// variables to contain the resulting accelerations
int accelerationX, accelerationY;

pulseX = pulseIn(xPin,HIGH);
pulseY = pulseIn(yPin,HIGH);
Serial.println(pulseX);
Serial.print("\t");
// convert the pulse width into acceleration
// accelerationX and accelerationY are in milli-g's:
// earth's gravity is 1000 milli-g's, or 1g.
accelerationX = ((pulseX / 10) - 500) * 8;
accelerationY = ((pulseY / 10) - 500) * 8;
if (accelerationX > 255) {
accelerationX = 255;
}
if (accelerationY > 255) {
accelerationY = 255;
}
if (accelerationX < -255) {
accelerationX = -255;
}
if (accelerationY 40) {
// digitalWrite(enablePin, 1);
digitalWrite(dPin_1, HIGH); //turn on the motor
digitalWrite(dPin_2, LOW);

analogWrite(enablePin, accelerationX);
Serial.print(accelerationX);
} else if (accelerationX < -40) {
// digitalWrite(enablePin, 2);
digitalWrite(dPin_1, HIGH); //turn on the motor
digitalWrite(dPin_2, HIGH);

analogWrite(enablePin, accelerationX);
Serial.print(accelerationX);
} else {
digitalWrite(dPin_1, LOW); //turn on the motor
digitalWrite(dPin_2, LOW);
analogWrite(enablePin, 0);
}
// print a tab character:
Serial.print("\t");
Serial.print(accelerationY);
Serial.println();

}

Advertisements

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 )

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s

%d bloggers like this: