1+ #include < DHTesp.h>
2+ #include " LoRaWan_APP.h"
3+ #include " Arduino.h"
4+
5+ // DHT11 Configuration
6+ #define DHT_PIN 1 // GPIO1 connected to DHT11 (avoid using GPIO1)
7+ DHTesp dht;
8+
9+ // LoRa Configuration
10+ #define RF_FREQUENCY 915000000 // Hz (adjust according to your region)
11+ #define TX_OUTPUT_POWER 14 // dBm (increase power to extend transmission range)
12+ #define LORA_BANDWIDTH 0 // 125 kHz
13+ #define LORA_SPREADING_FACTOR 7 // SF7
14+ #define LORA_CODINGRATE 1 // 4/5
15+ #define LORA_PREAMBLE_LENGTH 8 // Preamble length
16+ #define LORA_FIX_LENGTH_PAYLOAD_ON false
17+ #define LORA_IQ_INVERSION_ON false
18+
19+ #define BUFFER_SIZE 50 // Data buffer size
20+ char txpacket[BUFFER_SIZE]; // Transmission buffer
21+ bool lora_idle = true ; // LoRa idle state flag
22+
23+ // LoRa event callbacks
24+ static RadioEvents_t RadioEvents;
25+ void OnTxDone (void );
26+ void OnTxTimeout (void );
27+
28+ void setup () {
29+ Serial.begin (115200 );
30+
31+ // Initialize DHT11
32+ dht.setup (DHT_PIN, DHTesp::DHT11);
33+ Serial.println (" DHT11 Initialized" );
34+
35+ // Initialize LoRa
36+ Mcu.begin (HELTEC_BOARD, SLOW_CLK_TPYE); // Adjust parameters according to your board
37+ RadioEvents.TxDone = OnTxDone;
38+ RadioEvents.TxTimeout = OnTxTimeout;
39+
40+ Radio.Init (&RadioEvents);
41+ Radio.SetChannel (RF_FREQUENCY);
42+ Radio.SetTxConfig (MODEM_LORA, TX_OUTPUT_POWER, 0 , LORA_BANDWIDTH,
43+ LORA_SPREADING_FACTOR, LORA_CODINGRATE,
44+ LORA_PREAMBLE_LENGTH, LORA_FIX_LENGTH_PAYLOAD_ON,
45+ true , 0 , 0 , LORA_IQ_INVERSION_ON, 3000 );
46+ }
47+
48+ void loop () {
49+ if (lora_idle) {
50+ delay (2000 ); // DHT11 requires at least 1-second sampling interval
51+
52+ // Read temperature and humidity data
53+ TempAndHumidity data = dht.getTempAndHumidity ();
54+ if (dht.getStatus () != DHTesp::ERROR_NONE) {
55+ Serial.println (" DHT11 read failed: " + String (dht.getStatusString ()));
56+ return ;
57+ }
58+
59+ // Format data as JSON string (example: {"t":25.5,"h":50.0})
60+ snprintf (txpacket, BUFFER_SIZE,
61+ " {\" t\" :%.1f,\" h\" :%.1f}" ,
62+ data.temperature ,
63+ data.humidity );
64+
65+ Serial.printf (" Sending data: %s\n " , txpacket);
66+
67+ // Transmit data via LoRa
68+ Radio.Send ((uint8_t *)txpacket, strlen (txpacket));
69+ lora_idle = false ;
70+ }
71+ Radio.IrqProcess (); // Process LoRa events
72+ }
73+
74+ // LoRa transmission complete callback
75+ void OnTxDone (void ) {
76+ Serial.println (" LoRa transmission successful" );
77+ lora_idle = true ;
78+ }
79+
80+ // LoRa transmission timeout callback
81+ void OnTxTimeout (void ) {
82+ Radio.Sleep ();
83+ Serial.println (" LoRa transmission timeout" );
84+ lora_idle = true ;
85+ }
0 commit comments