hello. I'm trying to build a robot that picks up trash, but I have a few programming questions. The robot consists of two DC motors that are for the movement of the robot. The robot uses two servos to pick up trash, and the robot also uses a buzzer that is controlled by the ultrasonic sensor. The first question is how do I code the DC motors to travel a certain distance, such as ten feet. So far, this is the code I have (from Mert Arduino).
const int leftForward = 2;
const int leftBackward = 3;
const int rightForward = 4;
const int rightBackward = 5;
void setup()
{
pinMode(leftForward , OUTPUT);
pinMode(leftBackward , OUTPUT);
pinMode(rightForward , OUTPUT);
pinMode(rightBackward , OUTPUT);
}
void loop()
{
digitalWrite(leftForward , HIGH);
digitalWrite(leftBackward , LOW);
digitalWrite(rightForward , HIGH);
digitalWrite(rightBackward , LOW);
}
The second question is, how I would combine the individual codes?
This is the code for the ultrasonic sensor controlling the buzzer (from Arduino Hub and edited, and I'm not using the LED)
/* This simple project describes how to make an ultrasonic alarm system using
LED, Ultasonic Sensor(HC-SR04) and a buzzer.*/
//Firstly the connections of ultrasonic Sensor.Connect +5v and GND normally and trigger pin to 12 & echo pin to 13.
#define trigPin 12
#define echoPin 13
int Buzzer = 8; // Connect buzzer pin to 8
int ledPin= 6; //Connect LEd pin to 6
int duration, distance; //to measure the distance and time taken
void setup() {
Serial.begin (9600);
//Define the output and input objects(devices)
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
pinMode(Buzzer, OUTPUT);
pinMode(ledPin, OUTPUT);
}
void loop() {
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
duration = pulseIn(echoPin, HIGH);
distance = (duration/2) / 29.1;
//when distance is greater than or equal to 200 OR less than or equal to 0,the buzzer and LED are off
if (distance >= 200 || distance <= 0)
{
Serial.println("no object detected");
digitalWrite(Buzzer,LOW);
digitalWrite(ledPin,LOW);
}
else {
Serial.println("object detected \n");
Serial.print("distance= ");
Serial.print(distance); //prints the distance if it is between the range 0 to 200
tone(Buzzer,400); // play tone of 400Hz for 500 ms
digitalWrite(ledPin,HIGH);
}
}
This is the code for the servos moving
/*
#include <Servo.h>
Servo servoLeft; //Define left servo
Servo servoRight; //Define right servo
*/
void setup() {
servo.attach(10) //Set left servo to pin 10
servo.attach(9) //Set right servo to pin 9
}
My last question is, how would I program those things to work after another? I wanted the DC motors to move a certain distance, then for the sensor to detect the trash, and then, after ten seconds, for the servos to pick up the trash. i know I'm asking alot of questions here, and any help would be very much appreciated. Thank you.