I am using an Arduino Uno for these tests, then eventually once done I am going to make a PCB that can house an Arduino Nano.
But during my test the distance keeps reading 0cm on my ultrasonic sensor, and my servo just rotates about 10 degrees then back to 0 in under 0.5 seconds. I have the servo power connected to 5v, and the ultrasonic connected to 3.3v, this is the only problem I could think of that would be causing this.
What I am wanting it to do is when it can sense a distance closer then 20cm, it will rotate the servo 80 degrees and hold for 1 second.
//defining trig and echo pin
#define trigPin 2
#define echoPin 3
//defining servo pin
#define servoPin 9
//library implimintation
#include <Servo.h>
//defining servo name
Servo servo1;
//a variable to store the servo position
int angle = 0;
//defining the variables
long duration;
int distance;
void setup()
{
//defining inputs and outputs
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
//the servo is now attatched to pin 9 or the servo pin
servo1.attach(servoPin);
//Begining the serial communication at a rate of 9600
Serial.begin(9600);
}
void loop() {
//Clearing the trigPin by setting it to LOW
digitalWrite(trigPin, LOW);
delayMicroseconds(5);
//Triggering the sensor by setting the trigPin to high for 10 microseconds
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
// Read the echoPin, pulseIn() returns the duration (length of the pulse) in microseconds:
duration = pulseIn(echoPin, HIGH);
// Calculate the distance:
distance = duration * 0.034 / 2;
// Print the distance on the Serial Monitor (Ctrl+Shift+M):
Serial.print("Distance = ");
Serial.print(distance);
Serial.println(" cm");
delay(50);
if (distance >20);{ // if the distance read, is further then 20cm, then activate code below
servo1.write(80);
delay(1000);
servo1.write(0);
}
}
This is my code, if you want to ask any other questions feel free to ask in replys. Thanks.