I Have An Ultrasonic Sensor (4pins)
I Have an Arduino Mega 2560
#include <Servo.h> // Including Servo Library To Use Servo
int echo = 51; // Ultrasonic Sensor Echo Pin
int pingPin = 51; // Ultrasonic Sensor Trigger Pin
int inPin = 53;
int motorA = 12; //Motor A Direction Control
int motorB = 13; // Motor B Direction Control
int motorAS = 3; //PWM Speed Control
int motorBS = 11; //PWM Speed Control
int motorAB = 9; //PWM Speed Control
int motorBB = 8;
int mspeed = 200; // Defines Normal Speed
long microseconds;
int dangerdist = 1;
Servo myservo;
void setup() {
pinMode(echo, INPUT);
//pinMode(trigger, OUTPUT);
pinMode(motorA, OUTPUT);
pinMode(motorB, OUTPUT);
pinMode(motorAS, OUTPUT);
pinMode(motorBS, OUTPUT);
pinMode(motorAB, OUTPUT);
pinMode(motorBB, OUTPUT);
Serial.begin(9600);
myservo.attach(22);
}
void loop() {
check();
}
/*
Chasis Direction Controls
_________________________
*/
void forwards() {
digitalWrite(motorA, HIGH);
digitalWrite(motorB, LOW);
digitalWrite(motorAS, HIGH);
digitalWrite(motorBS, HIGH);
}
void backwards() {
digitalWrite(motorA, LOW);
digitalWrite(motorB, HIGH);
analogWrite(motorAS, mspeed);
analogWrite(motorBS, mspeed);
}
void right() {
digitalWrite(motorA, HIGH);
digitalWrite(motorB, LOW);
analogWrite(motorAS, 0);
digitalWrite(motorBS, HIGH);
}
void left() {
digitalWrite(motorA, HIGH);
digitalWrite(motorB, LOW);
analogWrite(motorAS, mspeed);
analogWrite(motorBS, 0);
}
/*
Servo Controls
_______________
*/
void servo_left(){
myservo.write(75);
}
void servo_center(){
myservo.write(110);
}
void servo_right(){
myservo.write(145);
}
/*
Ultrasonic Sensor Controls
__________________________
*/
void check(){
// Check Surroundings
long duration, inches;
servo_center();
delay(1000);
digitalWrite(pingPin, LOW);
delayMicroseconds(2);
digitalWrite(pingPin, HIGH);
delayMicroseconds(10);
digitalWrite(pingPin, LOW);
delayMicroseconds(2);
pinMode(pingPin, OUTPUT);
pinMode(inPin, INPUT);
duration = pulseIn(inPin, HIGH);
delay(100);
inches = microsecondsToInches(duration);
if (inches <= 40 )
{
right();
}
else{
forwards();
}
}
long microsecondsToInches(long microseconds){
// Accroding To Parrallax's Data Shate There Are 73.746 nicroseconds Per Inch
return microseconds / 74 / 2;
}