I like messing with the ping sensors and have had lots of success. You had several problems that were difficult to relay over the forum I placed notes in the attached modified code to help you.
Move the echoout pin on the ping sensor to pin 2 on the arduino to take advantage of the interrupt feature available to you
The code compiles and should work as you expected. I removed the NewPing.h library because of "blocking code" it contains in favor of the interrupt method of capturing distance.
#include <Servo.h>
const int TriggerPin = 6;
const int EchoPin = 2; //<<<<<<<<<<<<<<<<<<<<<< Move to Pin 2
const int ServoPin = 9;
const int ledPin = 11;
const int ledPin2 = 13;
const int ledPin3 = 12;
Servo servo;
#define read2 bitRead(PIND,2)//faster than digitalRead() (((value) >> (bit)) & 0x01)
#define read3 bitRead(PIND,3)//faster than digitalRead() (((value) >> (bit)) & 0x01)
volatile unsigned long PingTime;
volatile unsigned long edgeTime;
void PingTimer(){
uint8_t pin;
static unsigned long cTime;
cTime = micros(); // micros() return a uint32_t
if (read2)edgeTime = cTime; //Pulse went HIGH store the start time
else { // Pulse Went low calculate the duratoin
PingTime = (cTime - edgeTime) ; // Calculate the change in time NOTE: the "% EchoInputCount" prevents the count from overflowing the array look up % remainder calculation
}
}
void PingTrigger(int Pin){
digitalWrite(Pin, LOW);
delayMicroseconds(1);
digitalWrite(Pin, HIGH); // Trigger another pulse
delayMicroseconds(10);
digitalWrite(Pin, LOW);
}
void setup() {
Serial.begin(9600);
servo.attach(ServoPin);
attachInterrupt(digitalPinToInterrupt(EchoPin), PingTimer, CHANGE );
}
void loop() {
int cm = PingTime / 29 / 2;// convert round trip time to cm
Serial.println(cm);
if (cm < 7 && cm !=0) {
digitalWrite(ledPin, HIGH);
digitalWrite(ledPin2, HIGH);
digitalWrite(ledPin3, HIGH);
servo.write (180);
delay (1000);
servo.write (110);
delay (2000);
}
else if (cm > 7 ) {
digitalWrite(ledPin, LOW);
digitalWrite(ledPin2, LOW);
digitalWrite(ledPin3, LOW);
}
PingTime = 0; // Clear old data
static unsigned long Timer;
if ((millis() - Timer) >= (100)) {// Trigger a pulse every 100 ms
Timer = millis();
PingTrigger(TriggerPin);
}
}
Enjoy ![]()
Z