LoRa(Long Range)是一种远距离低功耗无线通信技术,广泛应用于物联网(IoT)场景。它的特点是传输距离远、功耗低、穿透力强,适合需要长时间运行的电池供电设备。
#include <SPI.h>
#include <LoRa.h>
#define SOIL_SENSOR_PIN A0 // 土壤湿度传感器连接到 A0 引脚
#define LORA_SS 10 // LoRa 模块的 SS 引脚
#define LORA_RST 9 // LoRa 模块的 RESET 引脚
#define LORA_DIO0 2 // LoRa 模块的 DIO0 引脚
void setup() {
Serial.begin(9600);
while (!Serial);
pinMode(SOIL_SENSOR_PIN, INPUT);
// 初始化 LoRa 模块
LoRa.setPins(LORA_SS, LORA_RST, LORA_DIO0);
if (!LoRa.begin(433E6)) {
Serial.println("启动 LoRa 失败!");
while (1);
}
Serial.println("LoRa 发送端已启动");
}
void loop() {
// 读取土壤湿度
int soilMoistureValue = analogRead(SOIL_SENSOR_PIN);
// 发送数据
LoRa.beginPacket();
LoRa.print("Soil Moisture: ");
LoRa.print(soilMoistureValue);
LoRa.endPacket();
Serial.print("已发送: Soil Moisture = ");
Serial.println(soilMoistureValue);
delay(2000); // 每 2 秒发送一次数据
}
#include <SPI.h>
#include <LoRa.h>
#define LORA_SS 10 // LoRa 模块的 SS 引脚
#define LORA_RST 9 // LoRa 模块的 RESET 引脚
#define LORA_DIO0 2 // LoRa 模块的 DIO0 引脚
void setup() {
Serial.begin(9600);
while (!Serial);
// 初始化 LoRa 模块
LoRa.setPins(LORA_SS, LORA_RST, LORA_DIO0);
if (!LoRa.begin(433E6)) {
Serial.println("启动 LoRa 失败!");
while (1);
}
Serial.println("LoRa 接收端已启动");
}
void loop() {
// 检查是否有数据可用
int packetSize = LoRa.parsePacket();
if (packetSize) {
Serial.print("收到数据: ");
// 读取数据
while (LoRa.available()) {
String received = LoRa.readString();
Serial.print(received);
}
Serial.println();
}
}
433E6
(433 MHz)。
LoRa 是一种低功耗、长距离通信的优秀选择,非常适合对数据速率要求不高的应用场景。以上案例提供了从传感器数据采集到无线传输的完整实现方案。