Nrf24l01+ не понятненько работают
- Войдите на сайт для отправки комментариев
Всем доброго времени суток! Код рабочий, но работает раз, через раз
Вообщем у меня тип умный дом.
Пока что побеждаю радио, пока что имеем рабочую регистрацию, и получение инфы от сенсоров.
Алгоритм получения инфы: База проходиться по массиву, открывает трубу(персональную для каждого сенсора) на отправку туда шлет некий байт "запрос", а сенсор отвечает на общую трубу для информации.
Сенсор у меня Arduino nano, База NodeMCU 1.0;
"Проблема" а точнее не правильную работу заметно начиная с двух устройств в схеме.
Вот так выглядит лог с одним сенсором(черная консоль это сенсор, а порт ардуино иде это база).
Но вот с подключением в сети второго сенсора, начинаются проблемы(первый сенсор с керамикой и електролитом на nrf24l01+, второй просто керамика на nrf'ке) частичные недолеты пакетов то у одного то у друго-го, то все ок, причем все (увидите на логе) повторяется циклично !
База
#include <SPI.h> #include "nRF24L01.h" #include "RF24.h" #define v_kef 100 uint8_t id_sensor = 0; uint8_t type_sensor = 1; RF24 radio(D4, D8); struct message { uint8_t id; uint8_t type; uint8_t data; }; struct info_ { uint8_t id_sensor; uint8_t type_sensor; int16_t v_bat; uint8_t status_sensor; uint8_t signal_lvl; uint8_t person_pipe[1][6]; }; message rx_data; info_ reg_pack; //uint8_t v_kef = 100; uint8_t pipe = 0; //uint8_t address[][6] = {0xAABBCCDD11LL, 0xAABBCCDD22LL, 0xAABBCCDD33LL, 0xAABBCCDD44LL, 0xAABBCCDD55LL}; uint8_t address[20][6] = {"0Node", "1Node", "2Node", "3Node"}; //0-Заглушка;1-Alarms;2-Reg; 3-Get_data; Another sesors! uint8_t pipes_elems() { uint8_t memory = sizeof(address) / sizeof(address[0]); uint8_t elems = 0; if (memory <= 254) { for (uint8_t i = 0; i < memory; i++) { if (address[i][0] != 0) { elems++; } } } else { Serial.println("ERROR! Size of array more 255 elements!"); } return elems; } boolean get_info(uint8_t elem) { } boolean get_data(uint8_t elem) { Serial.print("Elem:"); Serial.print(elem); radio.stopListening(); radio.openWritingPipe(address[elem]); boolean tx = false; uint8_t data = 101; for (uint8_t i = 0; i < 20; i++) { tx = radio.write(&data, sizeof(data)); if (tx) { break; } delay(200); } radio.startListening(); if (!tx) { Serial.println(" Sensor not talk with me!"); return false; } Serial.print(" Sended! "); uint8_t i = 0; uint8_t pipe = 0; while (i < 20) { if (radio.available(&pipe)) { Serial.print(pipe); if (pipe == 3) { break; } } i++; delay(150); } if (i < 15) { radio.read(&rx_data, sizeof(rx_data)); Serial.print(" Id: "); Serial.print(rx_data.id); Serial.print(" Data:"); Serial.println(rx_data.data); return true; } else { Serial.println("Responce not recived!"); return false; } } void get_data_all() { Serial.println("Start polling sensors!"); if (pipes_elems() > 4) { for (uint8_t i = 4; i <= pipes_elems() - 1; i++) { get_data(i); delay(20); } } else { Serial.println("Not found sensors!"); } } boolean register_() { radio.stopListening(); Serial.print("Scaning:"); radio.openWritingPipe(address[2]); boolean tx = false; uint8_t status_ = 200; //200 - granted! for (uint8_t i = 0; i < 15; i++) { tx = radio.write(&status_, sizeof(status_)); if (tx) { break; } } radio.startListening(); if (!tx) { Serial.println("not found!"); return false; } Serial.println("found!"); uint8_t pipe_r = 0; for (uint8_t i = 0; i < 20; i++) { if (radio.available(&pipe_r)) { if (pipe_r == 2) { break; } } delay(200); } if (pipe_r != 2) { Serial.println("REG cansel, respocne not recived!"); return false; } radio.read(®_pack, sizeof(reg_pack)); if (reg_pack.id_sensor != 0 or reg_pack.signal_lvl < 100) {//Verifying.. Serial.println("Reg cansel, sensor not verifyed!"); return false; } Serial.println("Sensor OK! Continue reg him!"); reg_pack.id_sensor = random(1, 230); Serial.print("Him new id is:"); Serial.println(reg_pack.id_sensor); radio.stopListening(); boolean tx_second = false; for (uint8_t i = 0; i < 20; i++) { tx_second = radio.write(®_pack, sizeof(reg_pack)); if (tx_second) { break; } delay(10); } if (!tx_second) { Serial.println("Reg error, packet not recived!"); radio.startListening(); return false; } Serial.println("Reg OK!"); radio.startListening(); memcpy(address[pipes_elems()], reg_pack.person_pipe[0], sizeof(address[0])); return true; } void setup() { Serial.begin(115200); radio.begin(); radio.setAutoAck(true); radio.setChannel(120); radio.openReadingPipe(1, address[1]);//Alarm pipe radio.setAutoAck(1, true); radio.openReadingPipe(2, address[2]);//Reg pipe radio.setAutoAck(2, true); radio.openReadingPipe(3, address[3]);//Data-info pipe radio.setAutoAck(3, true); radio.openWritingPipe(address[0]);//Trash pipe radio.setPALevel (RF24_PA_MAX); radio.setDataRate(RF24_1MBPS); radio.startListening(); radio.powerUp(); delay(100); Serial.println(); Serial.print("Pipes:"); Serial.println(pipes_elems()); } void loop() { if (Serial.available() > 0) { String buffer_ = Serial.readString(); if (buffer_ == "tx") { Serial.println("Start sending..."); get_data_all(); } else if (buffer_ == "reg") { Serial.println("Start registering..."); register_(); } } }
Сенсор:
#include <SPI.h> #include "nRF24L01.h" #include "RF24.h" #include <EEPROM.h> #define key 131 uint8_t id_sensor = 0; uint8_t type_sensor = 1; RF24 radio(9, 10); struct message { uint8_t id; uint8_t type; uint8_t data; }; struct info { uint8_t id_sensor; uint8_t type_sensor; int16_t v_bat; uint8_t status_sensor; uint8_t signal_lvl; uint8_t person_pipe[1][6]; }; message send_data; info info_data; const uint8_t v_kef = 100; uint8_t pipe = 0; //uint8_t address[][6] = {0xAABBCCDD11LL, 0xAABBCCDD22LL, 0xAABBCCDD33LL, 0xAABBCCDD44LL, 0xAABBCCDD55LL}; uint8_t address[4][6] = {"5Node", "1Node", "2Node", "3Node"}; //0-person pipe; 1-alarms; 2-reg; 3-Info; void setup() { Serial.begin(115200); randomSeed(analogRead(0)); radio.begin(); radio.setAutoAck(true); radio.setChannel(120); radio.setRetries(1, 7); radio.openReadingPipe(1, address[0]); radio.setAutoAck(1, true); radio.openWritingPipe(address[3]); radio.setDataRate(RF24_1MBPS ); radio.setPALevel (RF24_PA_MAX); //radio.powerUp(); delay(100); if (id_sensor == 0) { Serial.println("Sysetm not reg!"); Serial.println("Starting register..."); radio.startListening(); radio.closeReadingPipe(1); radio.openReadingPipe(1, address[2]); radio.setAutoAck(1, true); while (true) { Serial.println("Waiting a reg packet!"); while (true) { if (radio.available(&pipe)) { if (pipe == 1) { Serial.println("Packet resived!"); break; } } delay(100); } uint8_t incoming_data = 0; radio.read(&incoming_data, sizeof(incoming_data)); if (incoming_data != 200) { Serial.println("Reg not granted!"); continue; } Serial.println("Register granted!"); Serial.println("Configuring packet..."); float v_batt = 5.5; info_data.id_sensor = 0; info_data.type_sensor = type_sensor; info_data.v_bat = int(v_batt * v_kef); info_data.status_sensor = 1; info_data.signal_lvl = 250; memcpy(info_data.person_pipe[0], address[0], sizeof(info_data.person_pipe[0])); Serial.println("Start sending..."); radio.stopListening(); radio.openWritingPipe(address[2]); boolean send_status = false; for (byte i = 0; i < 10; i++) { send_status = radio.write(&info_data, sizeof(info_data)); delay(10); if (send_status == true) { break; } } radio.startListening(); if (send_status == false) { Serial.println("Send err!"); continue; } Serial.println("Responce wait...."); boolean is_reciv = false; for (uint8_t i = 0; i < 20; i++) { if (radio.available(&pipe)) { if (pipe == 1) { is_reciv = true; break; } } delay(200); } if (!is_reciv) { Serial.println("Reg ERR, responce not recived!"); continue; } Serial.println("Reg OK!"); radio.read(&info_data, sizeof(info_data)); id_sensor = info_data.id_sensor; Serial.print("My new id:"); Serial.println(id_sensor); radio.closeReadingPipe(1); radio.openReadingPipe(1, address[0]); radio.setAutoAck(1, true); radio.stopListening(); radio.openWritingPipe(address[3]); radio.startListening(); break; } } radio.powerUp(); } void loop() { if (radio.available()) { Serial.println("Data recived!"); uint8_t incoming_data = 0; radio.read(&incoming_data, sizeof(incoming_data)); if (incoming_data == 101) { Serial.println("Request on data get!"); radio.stopListening(); boolean status_s = false; uint8_t i = 0; send_data.id = id_sensor; send_data.type = type_sensor; send_data.data = random(1, 45); while (!status_s && i < 20) { delay(10); status_s = radio.write(&send_data, sizeof(send_data)); i++; } if (status_s) { Serial.println("Success! Data sended!"); } else { Serial.println("Error! Data not sended!"); } radio.startListening(); } else if (incoming_data == 102) { Serial.println("Request on info get!"); radio.stopListening(); boolean status_s = false; uint8_t i = 0; float v_batt = 5.5; info_data.id_sensor = id_sensor; info_data.type_sensor = type_sensor; info_data.v_bat = int(v_batt * v_kef); info_data.status_sensor = 1; info_data.signal_lvl = 250; while (!status_s && i < 20) { delay(10); status_s = radio.write(&info_data, sizeof(info_data)); i++; } if (status_s) { Serial.println("Success! Data sended!"); } else { Serial.println("Error! Data not sended!"); } radio.startListening(); } } }
Поскольку второй сенсор сидит на розетке то его лога по выше указанным причинам нету
Помогите пожалуйста! Ибо хочется верить в проблемы с питанием, но верится с трудом !
Из-за чего могут быть такие циклические сбои, на что мне обратить внимание или что исправить ?
Совершенно типичная гениальная идея делать умный дом на китайских подделках под передатчик разработанный для беспроводных клавиатур.
А потом тупить и просить, почему нарытое в нете гавно + своё гавно нехера не дюжат. ЕГ, не?
Ну недолеты... подумаешь. Никогда нельзя расчитывать, что по радио вся инфа долетит. Скорости не хватает или реакция прям так критична ?
Совершенно типичная гениальная идея делать умный дом на китайских подделках под передатчик разработанный для беспроводных клавиатур.
Именно так, только вы это также скажите всем кого на гуглите по запросу проекты на NRF24L01+, многим проектам Алекса Гайвера и тд.
А потом тупить и просить, почему нарытое в нете гавно + своё гавно нехера не дюжат. ЕГ, не?
Если вы считаете что код из документации это говно, тогда это печально. Как вы выразились "своё гавно" как раз таки работает. И если у вас нету каких-то адекватных советов, прошу вас как и "rkit" отдалиться от этой темы. Спасибо за понимание!
В Принципе и так оставить можно, но хотелось бы все таки выяснить, ведь оно "ломается" не на абум, а по порядку причем это не зависит от того с какой периодичностью слать запрос.
Дак принесите свои проблемы гайверу и потом нам поведайте - действительно ли он специалист или просто копипастер с импортного интернета в русскоязычный.
Обязательно, у вас будут какие-то советы по коду ?