Motor with sonar
So this week’s challenge was to build something that involved motors and sensors. I decided to make mine out of a servo and a sonar sensor. Here is the code...
#include <Servo.h>
#include <Servo.h>
Servo servo1;
long distance;
long duration;
int trigPin = 10;
int echoPin = 9;
void setup() {
servo1.attach(8);
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
}
void loop() {
ultra();
servo1.write(0);
if(distance <= 10){
servo1.write(90);
}
}
void ultra(){
digitalWrite(trigPin, LOW);
delay(2);
digitalWrite(trigPin, HIGH);
delay(10);
digitalWrite(trigPin, LOW);
duration = pulseIn(echoPin, HIGH);
distance = duration*0.034/2;
}
This challenge didn't seem to hard to program but I was swamped with other work that I had to do for my job so I was unable to build the circuit this week to actually test to see if it worked. I think it should have but I will try it next week but since this is due today I thought that I would just publish this now and finish it later. So stay tuned for an update when I actually get the chance to play with it and see if it will work. I know that is where the real learning happens but I still did learn quite a bit. I had to read up on how the sonar thing works and how to program it. I hope I got it right but I guess we will see if that is correct. I also learned the difference between the long and integer numbers. I had to use a long number for the distance to the object and the duration variables. Well anyway stay tuned so see if the code and circuit actually work.
Comments
Post a Comment