0

I have been struggling with arduino and ultrasonic sensor HC-SR04 and PWM. I am using arduino pro mini. Also using NewPing library.

the newping library example works perfectly if I have just the sonar attached and I get about 170cm when pointing upwards towards the ceiling.

However if I add a pwm call on a different pin(pin 3 in this case) the sonar outputs maximum of 41cm, everything below that works, albeit bit noisily.

I have almost nothing connected to the pwm pin, there is only a capasitor and a resistor. I had a motor as well but removed it for debugging.

Illustration of my wiring:enter image description here

code:

#include <NewPing.h>

#define TRIGGER_PIN  8  // Arduino pin tied to trigger pin on the ultrasonic sensor.
#define ECHO_PIN     7  // Arduino pin tied to echo pin on the ultrasonic sensor.
#define MAX_DISTANCE 200
NewPing sonar(TRIGGER_PIN, ECHO_PIN, MAX_DISTANCE);
int p = 3;
void setup() {
  // put your setup code here, to run once:
  pinMode(p,OUTPUT);
  Serial.begin(115200);
}

void loop() {
  delay(50);                     // Wait 50ms between pings (about 20 pings/sec). 29ms should be the shortest delay between pings.
  Serial.print("Ping: ");
  int d = sonar.ping_cm();
  Serial.print(d); // Send ping, get distance in cm and print result (0 = outside set distance range)
  Serial.println("cm");
  analogWrite(p,d);
  
}

The problem does disappear if I remove everything from the pin 3, but I don't see how this wiring can have any effect, especially with the motor missing.

Any ideas how to get the sonar and pwm working at the same time.

Community
  • 1
  • 1
Ou Tsei
  • 470
  • 7
  • 24
  • Also it seems that after powerup the first reading is correct, and the rest are wrong, showing 41 – Ou Tsei Mar 13 '17 at 13:10

1 Answers1

0

Check the pin color of your HC-SR04. Models with "brass" colored pins have a defect. They might and will return false readings. Models with "silver-y-ish" pins are more precise. The defect isn't there.

Also, try using pins 2 & 3 for the distance sensor and something else for the PWM.

Dat Ha
  • 562
  • 1
  • 9
  • 16