编写代码实现:其中一个ESP32通过串口每隔3秒发送一个数字至LoRa模块,该数字初始值为1,随后每发送一次该数字增大1,另一个ESP32将LoRa模块接收的到的数字显示在OLED上,分别上传两个ESP32的代码。(LoRa模块出厂默认是透传模式,波特率是9600,无需进行AT配置即可直接进行通信)
时间: 2024-03-08 21:50:04 浏览: 129
ESP32发送端代码:
```c
#include <Wire.h>
#include <LoRa.h>
#define SCK 5 // GPIO5 -- SX1278's SCK
#define MISO 19 // GPIO19 -- SX1278's MISO
#define MOSI 27 // GPIO27 -- SX1278's MOSI
#define SS 18 // GPIO18 -- SX1278's CS
#define RST 14 // GPIO14 -- SX1278's RESET
#define DI0 26 // GPIO26 -- SX1278's IRQ(Interrupt Request)
int counter = 1;
unsigned long previousMillis = 0;
const long interval = 3000; // 每隔3秒发送一次数据
void setup() {
Serial.begin(9600);
while (!Serial);
SPI.begin(SCK, MISO, MOSI, SS);
LoRa.setPins(SS, RST, DI0);
if (!LoRa.begin(433E6)) {
Serial.println("LoRa init failed. Check your connections.");
while (true);
}
}
void loop() {
unsigned long currentMillis = millis();
if (currentMillis - previousMillis >= interval) {
previousMillis = currentMillis;
LoRa.beginPacket();
LoRa.print(counter);
LoRa.endPacket();
Serial.print("Sent: ");
Serial.println(counter);
counter++;
}
}
```
ESP32接收端代码:
```c
#include <Wire.h>
#include <LoRa.h>
#include <Adafruit_SSD1306.h>
#define SCK 5 // GPIO5 -- SX1278's SCK
#define MISO 19 // GPIO19 -- SX1278's MISO
#define MOSI 27 // GPIO27 -- SX1278's MOSI
#define SS 18 // GPIO18 -- SX1278's CS
#define RST 14 // GPIO14 -- SX1278's RESET
#define DI0 26 // GPIO26 -- SX1278's IRQ(Interrupt Request)
#define OLED_SDA 21
#define OLED_SCL 22
#define OLED_RST 16
Adafruit_SSD1306 display(128, 64, &Wire, OLED_RST);
void setup() {
Serial.begin(9600);
while (!Serial);
SPI.begin(SCK, MISO, MOSI, SS);
LoRa.setPins(SS, RST, DI0);
if (!LoRa.begin(433E6)) {
Serial.println("LoRa init failed. Check your connections.");
while (true);
}
display.begin(SSD1306_SWITCHCAPVCC, 0x3C);
display.clearDisplay();
display.display();
}
void loop() {
int packetSize = LoRa.parsePacket();
if (packetSize) {
String received = "";
while (LoRa.available()) {
received += (char)LoRa.read();
}
Serial.print("Received: ");
Serial.println(received);
display.clearDisplay();
display.setTextSize(2);
display.setTextColor(SSD1306_WHITE);
display.setCursor(0, 0);
display.print("Received:");
display.setCursor(0, 20);
display.print(received);
display.display();
}
}
```
阅读全文