Hello, I have combined the BWD code from the arduino website with another code used for the HCSR04 Ultrasonic Sensor. My sensor always reads zero and my LED does not blink continuously, only once. Here is the code.
const int triggerPin = 12; //Trig pin
const int echoPin = 11; //Echo pin
const int ledPin = 5;
void setup() {
// put your setup code here, to run once:
Serial.begin(9600);
pinMode(triggerPin, OUTPUT);
pinMode(echoPin, INPUT);
pinMode(ledPin, OUTPUT);
}
void loop() {
// put your main code here, to run repeatedly:
int Duration, Distance;
digitalWrite(triggerPin, HIGH);
delayMicroseconds(1000);
digitalWrite(triggerPin, LOW);
Duration = pulseIn(echoPin, HIGH);
Distance = (Duration/2) / 29.1;
Serial.print(Distance);
Serial.print(" cm");
delay(500);
int ledState = LOW; //integer used to set LED Status
unsigned long previousMillis = 0;
unsigned long currentMillis = millis();
const long interval = 1000;
if (currentMillis - previousMillis >= interval) {
previousMillis = currentMillis;
if (ledState == LOW) {
ledState = HIGH;
} else {
ledState = LOW;
}
digitalWrite(ledPin, ledState);
}
}
Right sorry that was probably an issue on it's own, I meant to disable the delay.
Do you know why the sensor would be reading 0 continuously though? I saw many posts about the issue and I have tried both the NewPing library and my own attempts but I couldn't get it to work.
Is it the sensor or my programming?
Edit:
const int triggerPin = 12; //Trig pin
const int echoPin = 11; //Echo pin
const int ledPin = 5;
void setup() {
// put your setup code here, to run once:
Serial.begin(9600);
pinMode(triggerPin, OUTPUT);
pinMode(echoPin, INPUT);
pinMode(ledPin, OUTPUT);
}
void loop() {
// put your main code here, to run repeatedly:
int Duration, Distance;
digitalWrite(triggerPin, HIGH);
digitalWrite(triggerPin, LOW);
Duration = pulseIn(echoPin, HIGH);
Distance = (Duration/2) / 29.1;
Serial.print(Distance);
Serial.print(" cm");
int ledState = LOW; //integer used to set LED Status
unsigned long previousMillis = 0;
unsigned long currentMillis = millis();
const long interval = 1000;
if (currentMillis - previousMillis >= interval) {
previousMillis = currentMillis;
if (ledState == LOW) {
ledState = HIGH;
} else {
ledState = LOW;
}
digitalWrite(ledPin, ledState);
}
}
Still not blinking more than once. Maybe I'm doing something wrong in the loop?