We are trying to make an intrusion detection system using ultrasonic sensor, arduino UNO and nodemcu v1. The basic idea is to connect ultrasonic sensor to arduino(because the sensors output voltage is 0-5 v and esp's ADC doesnt support it ) and send it's readings to a platform like blynk via ESP8266. For now we have just tried serial communication (UART) between arduino uno and esp and display the results on serial monitor. However, while the sensor is working fine, the readings are not displayed on the serial monitor of esp code. What to do? We have to show in 3 days.
This is code for arduino and ultrasonic sensor:
#include <SoftwareSerial.h>
#define TRIG_PIN 9 // Trigger pin for HC-SR04
#define ECHO_PIN 8 // Echo pin for HC-SR04
SoftwareSerial mySerial(2, 3); // RX, TX (for communication with ESP8266)
void setup() {
Serial.begin(9600); // Serial monitor for debugging
mySerial.begin(115200); // Communication with ESP8266
pinMode(TRIG_PIN, OUTPUT);
pinMode(ECHO_PIN, INPUT);
}
void loop() {
// Trigger ultrasonic pulse
digitalWrite(TRIG_PIN, LOW);
delayMicroseconds(2);
digitalWrite(TRIG_PIN, HIGH);
delayMicroseconds(10);
digitalWrite(TRIG_PIN, LOW);
// Measure echo pulse duration
long duration = pulseIn(ECHO_PIN, HIGH);
float distance = duration * 0.034 / 2; // Convert to cm
// Send data to ESP8266
mySerial.print(distance);
mySerial.println(" cm");
Serial.print("Sent: "); // Debugging message
Serial.print(distance);
Serial.println(" cm");
delay(1000); // 1-second delay between readings
}
Here serial monitor baud rate is 9600
This is code for esp:
void setup() {
Serial.begin(115200); // Start Serial Monitor for debugging
}
void loop() {
if (Serial.available()) {
String data = Serial.readStringUntil('\n'); // Read data from Arduino
Serial.print("Received Distance: ");
Serial.println(data);
}
}
Here baud rate for serial monitor is 115200.