Advertisement
luqman440

Untitled

Jul 9th, 2024
61
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. //First Device (nano)
  2.  
  3. #include <SPI.h>
  4. #include <RH_RF95.h>
  5.  
  6. #define RFM95_CS   10
  7. #define RFM95_RST  9
  8. #define RFM95_INT  2
  9. #define BUTTON_PIN 5
  10. #define LED_PIN    6
  11.  
  12. #define RF95_FREQ  433.0
  13.  
  14. RH_RF95 rf95(RFM95_CS, RFM95_INT);
  15.  
  16. bool ledState = false;
  17.  
  18. void setup() {
  19.   Serial.begin(9600);
  20.   while (!Serial);
  21.  
  22.   pinMode(RFM95_RST, OUTPUT);
  23.   pinMode(BUTTON_PIN, INPUT_PULLUP);
  24.   pinMode(LED_PIN, OUTPUT);
  25.   digitalWrite(RFM95_RST, HIGH);
  26.  
  27.   Serial.println("Initializing LoRa...");
  28.  
  29.   digitalWrite(RFM95_RST, LOW);
  30.   delay(10);
  31.   digitalWrite(RFM95_RST, HIGH);
  32.   delay(100);
  33.  
  34.   if (!rf95.init()) {
  35.     Serial.println("LoRa init failed. Check your connections.");
  36.     while (1);
  37.   }
  38.   Serial.println("LoRa radio init OK!");
  39.  
  40.   if (!rf95.setFrequency(RF95_FREQ)) {
  41.     Serial.println("setFrequency failed");
  42.     while (1);
  43.   }
  44.   Serial.print("Set Freq to: "); Serial.println(RF95_FREQ);
  45.  
  46.   rf95.setTxPower(13, false);
  47. }
  48.  
  49. void loop() {
  50.   static bool lastButtonState = HIGH;
  51.   bool buttonState = digitalRead(BUTTON_PIN);
  52.  
  53.   if (buttonState == LOW && lastButtonState == HIGH) {
  54.     Serial.println("Button pressed, sending message to toggle LED on second device");
  55.     sendMessage("TOGGLE_LED");
  56.   }
  57.  
  58.   lastButtonState = buttonState;
  59.  
  60.   if (rf95.available()) {
  61.     uint8_t buf[RH_RF95_MAX_MESSAGE_LEN];
  62.     uint8_t len = sizeof(buf);
  63.  
  64.     if (rf95.recv(buf, &len)) {
  65.       Serial.print("Received: ");
  66.       Serial.println((char*)buf);
  67.       checkRSSI();
  68.  
  69.       if (strncmp((char*)buf, "TOGGLE_LED", len) == 0) {
  70.         ledState = !ledState;
  71.         digitalWrite(LED_PIN, ledState ? HIGH : LOW);
  72.         Serial.print("LED state: ");
  73.         Serial.println(ledState ? "ON" : "OFF");
  74.       }
  75.     }
  76.   }
  77.  
  78.   delay(10);  // Small delay to debounce button
  79. }
  80.  
  81. void sendMessage(const char* message) {
  82.   uint8_t retries = 5;
  83.   while (retries--) {
  84.     rf95.send((uint8_t*)message, strlen(message));
  85.     rf95.waitPacketSent();
  86.     Serial.println("Message sent");
  87.     checkRSSI();  // Print RSSI after sending message
  88.     delay(1000);  // Wait for response
  89.   }
  90. }
  91.  
  92. void checkRSSI() {
  93.   int8_t rssi = rf95.lastRssi();
  94.   Serial.print("RSSI: ");
  95.   Serial.println(rssi);
  96. }
  97.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement