This circuit integrates an Arduino Nano microcontroller with an HC-SR04 Ultrasonic Sensor, a LoRa Ra-02 SX1278 module, and an AM2302 Humidity and Temperature Sensor. The purpose of the circuit is to measure distance using the ultrasonic sensor, read humidity and temperature data, and transmit this information wirelessly using the LoRa module. The Arduino Nano serves as the central processing unit, interfacing with the sensors and handling data acquisition and communication.
#include <NewPing.h>
#include <Wire.h>
#include <SPI.h>
#include <LoRa.h>
#include <DHT.h>
#define trigPin 3
#define echoPin 4
#define MAX_DISTANCE 593
#define DHTPIN 8 // What pin we're connected to
#define DHTTYPE DHT21 // DHT 21 (AM2301)
DHT dht(DHTPIN, DHTTYPE); // Initialize DHT sensor for normal 16mhz Arduino
float hum; // Stores humidity value
float temp; // Stores temperature value
// Define variables:
long duration;
int distance;
void setup() {
// Define inputs and outputs
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
// Begin Serial communication at a baudrate of 9600:
Serial.begin(9600);
dht.begin();
while (!Serial);
Serial.println("LoRa Sender");
if (!LoRa.begin(433E6)) {
Serial.println("Starting LoRa failed!");
while (1);
}
LoRa.setTxPower(20);
LoRa.setSpreadingFactor(12);
LoRa.setSignalBandwidth(62.5E3);
}
void loop() {
// Read data and store it to variables hum and temp
hum = dht.readHumidity();
temp = dht.readTemperature();
int roundedHum = round(hum);
float roundedTemp = round(temp * 10) / 10.0;
// Clear the trigPin by setting it LOW:
digitalWrite(trigPin, LOW);
delayMicroseconds(5);
// Trigger the sensor by setting the trigPin high for 10 microseconds:
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
// Read the echoPin. pulseIn() returns the duration (length of the pulse) in microseconds:
duration = pulseIn(echoPin, HIGH);
// Calculate the distance:
distance = duration*0.034/2;
String line2 = "T:"+String(roundedTemp,1)+ "C"+" H: "+String(roundedHum)+"%";
// Combine messages with a separator
String message = "Dist. "+ String(distance) + " cm " + "\\n" + line2;
// Send data via LoRa
LoRa.beginPacket();
LoRa.print(message);
LoRa.endPacket();
// Print the distance on the Serial Monitor (Ctrl+Shift+M):
Serial.print("Dista. = ");
Serial.print(distance);
Serial.print(" cm");
Serial.println("");
Serial.print("Humidity: ");
Serial.print(hum);
Serial.print("%, Temperature: ");
Serial.print(temp);
Serial.println(" Celsius");
LoRa.endPacket();
delay(9000);
}
This code is designed to run on the Arduino Nano and handles the interfacing with the HC-SR04 Ultrasonic Sensor and AM2302 Humidity and Temperature Sensor, as well as the communication with the LoRa Ra-02 SX1278 module. It reads the distance from the ultrasonic sensor, the humidity and temperature from the AM2302 sensor, and sends this data wirelessly via LoRa.