Advertisement
Guest User

Untitled

a guest
Oct 17th, 2019
98
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1.   #include <SPI.h>
  2. #include "RF24.h"
  3.  
  4. char radioNumber = '*';
  5. char clients[3] = {'b','0','e'};
  6.  
  7. RF24 radio(7,8);
  8.  
  9. #define PIPE_RX 0xF0F0F0F0D2LL
  10. #define PIPE_TX 0xF0F0F0F0E1LL
  11. char PROTOCOL_ID = 'H';
  12.  
  13. char response[32];
  14.  
  15. String encapsulate(String message, char destiny)
  16. {
  17.   String response;
  18.   response += PROTOCOL_ID;
  19.   response += destiny;
  20.   response += radioNumber;
  21.   response += message;
  22.   return response;
  23. }
  24.  
  25. void send(String package)
  26. {
  27.   radio.stopListening();
  28.   delay(50);
  29.   radio.startWrite(package.c_str(), package.length(), false);
  30.   delay(50);
  31.   radio.startListening();
  32. }
  33.  
  34. void route()
  35. {
  36.   String package;
  37.   Serial.println("Recebendo para rotear");
  38.   while(radio.available())
  39.   {
  40.     radio.read(&response, sizeof(response));
  41.   }
  42.   if (response[0] != '\0'){
  43.     Serial.println(response);
  44.     package = response;
  45.     if(response[0] == PROTOCOL_ID){
  46.       send(package);
  47.       Serial.print("Roteei: ");
  48.       Serial.println(package);
  49.     }else{
  50.       Serial.println("pacote de outra rede");
  51.     }
  52.     response[0] = '\0';  
  53.   }
  54. }
  55.  
  56. bool received(){
  57.   radio.startListening();
  58.   unsigned long startListenTime = millis();
  59.   while(!radio.available()){
  60.     if((millis() - startListenTime) > 3000){
  61.       Serial.println("Timeout");
  62.       return false;
  63.     }
  64.   }
  65.   return true;
  66. }
  67.  
  68. void testCarrier(){
  69.   do {
  70.       radio.startListening();
  71.       delay(128);
  72.       radio.stopListening();
  73.     } while(radio.testCarrier());
  74. }
  75.  
  76.  
  77. void tokenRing(){
  78.   for(int i = 0; i < 3; i++){
  79.     String package = encapsulate("a", clients[i]);
  80.     Serial.println(package);
  81.     for(int tries = 0; tries < 3; tries++){
  82.       testCarrier();
  83.       send(package);
  84.       if(received()){
  85.         route();
  86.         break;
  87.       }
  88.     }
  89.   }
  90.   Serial.println("---------------------------------------------------------");
  91. }
  92.  
  93. void setup() {
  94.   Serial.begin(115200);
  95.   radio.begin();
  96.  
  97.   radio.setPALevel(RF24_PA_HIGH);
  98.   radio.setAutoAck(false);
  99.  
  100.   radio.openWritingPipe(PIPE_TX);
  101.   radio.openReadingPipe(1, PIPE_RX);
  102.  
  103. }
  104.  
  105. void loop() {
  106.   tokenRing();
  107.   delay(5000);
  108. }//loop
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement