WhiteboardEraser.ino

This is the Arduino code to run the motor in synchronization with the ultrasonic sensor and the touchpad. It includes sensor based feedback control between the ultrasonic sensor and the motor.


#include <Wire.h>
#include <mpr121.h>
int X ; // X-coordinate
int Y ; // Y-coordinate
int E1 = 5;
int M1 = 4;
int E2 = 6;
int M2 = 7;
int pot = A0;
const int trigPin = 9;
const int echoPin = 10;
// defines variables
long duration;
int distance;
// Y-coordinate
//6in/sec
//HIGH is left
//LOW is right
//21 in total= 3.5 secs @100
//15 columns total

void setup()
{
Serial.begin(19200);
pinMode(trigPin, OUTPUT); // Sets the trigPin as an Output
pinMode(echoPin, INPUT); // Sets the echoPin as an Input
Wire.begin();
CapaTouch.begin();
delay(500);
Serial.println("START");
pinMode(M2, OUTPUT);
}

void loop()
{
X = CapaTouch.getX(); // Get X position.
Y = CapaTouch.getY(); // Get Y position.
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
duration = pulseIn(echoPin, HIGH);
distance = duration * 0.034 / 2;
int pos = map(Y, 0, 16, 5, 30);
Serial.print(distance);
Serial.print(" ");
Serial.println(pos);
while (distance < 34 && distance > 9) {
digitalWrite(M2, HIGH);
analogWrite(E2, 100);
Serial.print(distance);
Serial.print(" ");
Serial.println(pos);
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
duration = pulseIn(echoPin, HIGH);
distance = duration * 0.034 / 2;
if ((distance == pos || distance < pos)) {
while (distance < 35) {
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
duration = pulseIn(echoPin, HIGH);
distance = duration * 0.034 / 2;
digitalWrite(M2, LOW);
analogWrite(E2, 80);
Serial.print(distance);
Serial.print(" ");
Serial.println(pos);
}
}
}
analogWrite(E2, 0);
Serial.println("STOP");
}