Hi experts,
Need help with following.
This line: myservo.attach(SERV0_PIN); gives me output
either Ping: 0cmAngle: 0 degrees or Ping: 1149cmAngle: 4136 degrees.
When I write myservo.attach(10); or //myservo.attach(SERV0_PIN);
output reading are fine. Very strange. Don't know what I am missing.
Here is the code
include <NewPing.h>
#define TRIGGER_PIN 12 // Arduino pin tied to trigger pin on the ultrasonic sensor.
#define ECHO_PIN 11 // Arduino pin tied to echo pin on the ultrasonic sensor.
#define MAX_DISTANCE 50 // Maximum distance we want to ping for (in centimeters). Maximum sensor distance is rated at 400-500cm.
NewPing sonar(TRIGGER_PIN, ECHO_PIN, MAX_DISTANCE); // NewPing setup of pins and maximum distance.
#include <Servo.h>
Servo myservo; // create servo object to control a servo
#define SERV0_PIN 8 //
int val; // variable to read the value from the analog pin
void setup() {
Serial.begin(9600); // Open serial monitor at 115200 baud to see ping results.
pinMode(TRIGGER_PIN, OUTPUT);
pinMode(ECHO_PIN, INPUT);
myservo.attach(SERV0_PIN); // attaches the servo
pinMode(SERV0_PIN, OUTPUT);
}
void loop() {
delayMicroseconds(10); // Wait 50ms between pings (about 20 pings/sec). 29ms should be the shortest delay between pings.
unsigned int uS = sonar.ping(); // Send ping, get ping time in microseconds (uS).
val= (uS / US_ROUNDTRIP_CM); // Convert ping time to distance in cm and print result (0 = outside set distance range)
int valmap = map(val, 0, 50, 0, 180); // scale it to use it with the servo (value between 0 and 180)
Serial.print("Ping: ");Serial.print(val);Serial.print("cm");Serial.print( "Angle: ");Serial.print(valmap);Serial.println(" degrees ");
delay(100);
pinMode(SERV0_PIN, OUTPUT);
delay(10);
/this line/ myservo.write(valmap); // sets the servo position according to the scaled value
delay(10);
pinMode(SERV0_PIN, OUTPUT);
delay(100); // waits for the servo to get there defualt 15
}