Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //First Device (nano)
- #include <SPI.h>
- #include <RH_RF95.h>
- #define RFM95_CS 10
- #define RFM95_RST 9
- #define RFM95_INT 2
- #define BUTTON_PIN 5
- #define LED_PIN 6
- #define RF95_FREQ 433.0
- RH_RF95 rf95(RFM95_CS, RFM95_INT);
- bool ledState = false;
- void setup() {
- Serial.begin(9600);
- while (!Serial);
- pinMode(RFM95_RST, OUTPUT);
- pinMode(BUTTON_PIN, INPUT_PULLUP);
- pinMode(LED_PIN, OUTPUT);
- digitalWrite(RFM95_RST, HIGH);
- Serial.println("Initializing LoRa...");
- digitalWrite(RFM95_RST, LOW);
- delay(10);
- digitalWrite(RFM95_RST, HIGH);
- delay(100);
- if (!rf95.init()) {
- Serial.println("LoRa init failed. Check your connections.");
- while (1);
- }
- Serial.println("LoRa radio init OK!");
- if (!rf95.setFrequency(RF95_FREQ)) {
- Serial.println("setFrequency failed");
- while (1);
- }
- Serial.print("Set Freq to: "); Serial.println(RF95_FREQ);
- rf95.setTxPower(13, false);
- }
- void loop() {
- static bool lastButtonState = HIGH;
- bool buttonState = digitalRead(BUTTON_PIN);
- if (buttonState == LOW && lastButtonState == HIGH) {
- Serial.println("Button pressed, sending message to toggle LED on second device");
- sendMessage("TOGGLE_LED");
- }
- lastButtonState = buttonState;
- if (rf95.available()) {
- uint8_t buf[RH_RF95_MAX_MESSAGE_LEN];
- uint8_t len = sizeof(buf);
- if (rf95.recv(buf, &len)) {
- Serial.print("Received: ");
- Serial.println((char*)buf);
- checkRSSI();
- if (strncmp((char*)buf, "TOGGLE_LED", len) == 0) {
- ledState = !ledState;
- digitalWrite(LED_PIN, ledState ? HIGH : LOW);
- Serial.print("LED state: ");
- Serial.println(ledState ? "ON" : "OFF");
- }
- }
- }
- delay(10); // Small delay to debounce button
- }
- void sendMessage(const char* message) {
- uint8_t retries = 5;
- while (retries--) {
- rf95.send((uint8_t*)message, strlen(message));
- rf95.waitPacketSent();
- Serial.println("Message sent");
- checkRSSI(); // Print RSSI after sending message
- delay(1000); // Wait for response
- }
- }
- void checkRSSI() {
- int8_t rssi = rf95.lastRssi();
- Serial.print("RSSI: ");
- Serial.println(rssi);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement