Сеть беспроводных устройств на Arduino

Подключение исполнительных устройств, датчиков, контроллеров.

Модератор: immortal

Аватара пользователя
sergejey
Site Admin
Сообщения: 4284
Зарегистрирован: Пн сен 05, 2011 6:48 pm
Откуда: Минск, Беларусь
Благодарил (а): 75 раз
Поблагодарили: 1559 раз
Контактная информация:

Re: Сеть беспроводных устройств на Arduino

Сообщение sergejey » Пн июн 02, 2014 3:51 pm

Vip писал(а):Сергей, спасибо за ответ.
Моя проблема заключается в том, что на макетной плате работало достаточно хорошо, а когда запаял всё дело и установил в подрозетник, то при 5 вольтах и 15 см внешней антенны дальше чем на 2 метра прямой видимости не "бъёт". Ещё и приёмник "базы" должен стоять в определённом положении для того что бы на 2м расстоянии получать пакеты.
С вольтажом разобрался. Не мог "вкурить" как землю от бп 12В и ардуинные 5В правильно объединить, что б не спалить.
Хотел ещё уточнить 12 вольтами и приёмник и передатчик усиливаются, или только передатчик?
И можете тогда добавить объединённый скетч трансивера на страницу "Сеть беспроводных устройств на Arduino".
Честно говоря, у меня у самого сейчас проблема с правильным питанием этих модулей. Собрал себе устройство из Arduino Mega, 16 реле, 10 включателей, приёмник и передатчик. Подключил и вроде всё работает, но жутко ненадёжно -- через какое-то время просто перестают работать то приёмник, то передатчик (сам контроллер работает, т.к. отрабатывает корректно нажатие кнопок замыканием нужных реле). Есть подозрение, что дело как раз в питании (использую блок питания 9В и 800mA). Очень уж капризные эти модули в плане питания -- надо питать и приёмник и передатчик. Даже приёмник почему-то более критично, т.к. у меня несколько штук датчиков работают от обычных телефонных USB-зарядок и всё отлично пробивает в том числе через стены, а вот приёмникам подавай питание по-лучше.

Скетч от описанного устройства ниже:

Код: Выделить всё

#include <VirtualWire.h>
#include <EasyTransferVirtualWire.h>
#include <EEPROM.h> //Needed to access the eeprom read write functions

#define PIN_LED (13) // INDICATOR
#define PIN_RF_R (2) // Receiver pin
#define PIN_RF_T (3) // Transmitter pin
#define RF_SEND_COUNTER (3) // number of packets to send
#define CLASS_ON (20) // rf command ON
#define CLASS_OFF (21) // rf command OFF
#define CLASS_PULSE (22) //rf command pulse

unsigned int unique_device_id = 0;
unsigned int packet_received_id = 0;
   
long int uptime = 0;
long int old_uptime = 0;

String inData;

#define TOTAL_OUTPUTS (16)
#define TOTAL_INPUTS (10)
int outputPins[TOTAL_OUTPUTS] = {22, 24 , 26, 28, 30, 32, 34 ,36 , 23, 25, 27, 29, 31, 33, 35, 37};
int inputPins[TOTAL_INPUTS] = {38, 39, 40, 41, 43, 45, 47, 49, 51, 53};
int directLinkedPins[TOTAL_INPUTS] = {22,24,26,28,30,32,34,36,23,25};

int inputPinsStatus[TOTAL_OUTPUTS];

struct SEND_DATA_STRUCTURE {
  //put your variable definitions here for the data you want to send
  //THIS MUST BE EXACTLY THE SAME ON THE OTHER ARDUINO
  //Struct can'e be bigger then 26 bytes for VirtualWire version
  unsigned int device_id;
  unsigned int destination_id;  
  unsigned int packet_id;
  byte command;
  int data;
};

SEND_DATA_STRUCTURE mydata;
EasyTransferVirtualWire ET; 

//This function will write a 2 byte integer to the eeprom at the specified address and address + 1
void EEPROMWriteInt(int p_address, unsigned int p_value)
      {
      byte lowByte = ((p_value >> 0) & 0xFF);
      byte highByte = ((p_value >> 8) & 0xFF);

      EEPROM.write(p_address, lowByte);
      EEPROM.write(p_address + 1, highByte);
      }

//This function will read a 2 byte integer from the eeprom at the specified address and address + 1
unsigned int EEPROMReadInt(int p_address)
      {
      byte lowByte = EEPROM.read(p_address);
      byte highByte = EEPROM.read(p_address + 1);

      return ((lowByte << 0) & 0xFF) + ((highByte << 8) & 0xFF00);
      }


void setup()
{
    randomSeed(analogRead(0));
    pinMode(PIN_LED,OUTPUT);  
    Serial.begin(9600);

    ET.begin(details(mydata));
    // Initialise the IO and ISR
    pinMode(PIN_RF_T,OUTPUT);
    pinMode(PIN_RF_R,INPUT);
    vw_set_rx_pin(PIN_RF_R);
    vw_set_tx_pin(PIN_RF_T);
    //vw_set_ptt_pin(A2);         
    //vw_set_ptt_inverted(true); // Required for DR3100
    vw_setup(2000);      // Bits per sec
    vw_rx_start();       // Start the receiver PLL running  


 Serial.print("Initializing inputs ... ");
 int i;
 for (i = 0; i < TOTAL_INPUTS; i = i + 1) {
   pinMode(inputPins[i],INPUT);
   inputPinsStatus[i]=digitalRead(inputPins[i]);
 }
 Serial.println("DONE"); 
 
 Serial.print("Initializing outputs ... ");
 for (i = 0; i < TOTAL_OUTPUTS; i = i + 1) {
   turnOffPin(outputPins[i]);
   pinMode(outputPins[i],OUTPUT);
   turnOffPin(outputPins[i]);
 } 
 Serial.println("DONE");  

  // Device ID
  Serial.print("Getting Device ID... "); 
  unique_device_id=EEPROMReadInt(0);
  if (unique_device_id<10000 || unique_device_id>60000 || unique_device_id==26807) {
   Serial.print("N/A, updating... "); 
   unique_device_id=random(10000, 60000);
   EEPROMWriteInt(0, unique_device_id);
  }
  Serial.println(unique_device_id);    

}

void sendRFData() {
 //vw_rx_stop();
 Serial.print("Transmitting packets ... ");   
 for(int i=0;i<RF_SEND_COUNTER;i++) {
  if (i>0) {
   delay(200);    
  }
  digitalWrite(PIN_LED, HIGH); 
  ET.sendData();
  digitalWrite(PIN_LED, LOW);
 }  
 //vw_rx_start();
 Serial.println("DONE");   
}


void blinking(int count) {
 for(int i=0;i<count;i++) {
  digitalWrite(PIN_LED, HIGH); 
  delay(1000);
  digitalWrite(PIN_LED, LOW);
  delay(1000);
 }
}

void turnOnPin(int number) {
  Serial.print("OUTPIN");
  Serial.print(number);  
  Serial.println(" set to 1");
  digitalWrite(number, LOW);  
}

void turnOffPin(int number) {
  Serial.print("OUTPIN");
  Serial.print(number);  
  Serial.println(" set to 0");  
  digitalWrite(number, HIGH);  
}

void loop() {

  
  
 int i;
 for (i = 0; i < TOTAL_INPUTS; i = i + 1) {
   int currentStatus=digitalRead(inputPins[i]);
   if (currentStatus!=inputPinsStatus[i]) {
    delay(100); // de-bounce delay
    int currentStatusUpdated=digitalRead(inputPins[i]);
    if (currentStatusUpdated==currentStatus) {
     inputPinsStatus[i]=currentStatus;
     Serial.print("IN");
     Serial.print(i);
     Serial.print(" set to ");      
     Serial.println(currentStatus);
     if (directLinkedPins[i]!=0 && currentStatus==HIGH) {
      turnOnPin(directLinkedPins[i]);
     }
     if (directLinkedPins[i]!=0 && currentStatus==LOW) {
      turnOffPin(directLinkedPins[i]);      
     }    
    
     mydata.device_id = unique_device_id;
     mydata.destination_id = 0;  
     mydata.packet_id = random(65535);
     packet_received_id=mydata.packet_id;
     if (currentStatus==HIGH) {
       mydata.command=CLASS_ON;
     } else {
       mydata.command=CLASS_OFF;      
     }
     mydata.data = i;
     sendRFData();
    }
   }
 }  
  
  uptime=round(millis()/1000);
  if (uptime!=old_uptime) {
    Serial.print("Uptime: ");
    Serial.println(uptime);
    old_uptime=uptime;
  }
  
  //begin easy transfer
  if (ET.receiveData()) {
    Serial.print("Got packet for device ");
    Serial.print(mydata.destination_id);        
    Serial.print(" packet ");
    Serial.print(mydata.packet_id);
    Serial.print(" command ");    
    Serial.print(mydata.command);    
    Serial.print(" data ");    
    Serial.println(mydata.data);
  
    if ((mydata.destination_id==unique_device_id) && (mydata.packet_id!=packet_received_id)) {      
      Serial.print("Got RF command: ");
      Serial.print(mydata.command);
      Serial.print(" data: ");
      Serial.println(mydata.data);
      packet_received_id=(int)mydata.packet_id;    
      if (mydata.command==CLASS_ON) {
        turnOnPin(outputPins[mydata.data]);
      }
      if (mydata.command==CLASS_OFF) {
        turnOffPin(outputPins[mydata.data]);        
      }
      if (mydata.command==CLASS_PULSE) {
        turnOnPin(outputPins[mydata.data]);
        delay(1000);
        turnOffPin(outputPins[mydata.data]);        
      }      
   } else {
     Serial.println("Ignoring packet.");
   }
   
  } 
  
  
  if (Serial.available()) {
    char c=Serial.read();
    if (c == '\n' || c == ';')
        {
          Serial.println(inData);
          int commandProcessed=0;
          
          if (inData.equals("blink")) {
           commandProcessed=1;            
           Serial.println("BLINKING!");
           blinking(3);
          }
          
          if (inData.startsWith("turnon")) {
            commandProcessed=1;            
            inData.replace("turnon","");
            turnOnPin(outputPins[inData.toInt()]);
          }
          
          if (inData.startsWith("turnoff")) {
            commandProcessed=1;            
            inData.replace("turnoff","");          
            turnOffPin(outputPins[inData.toInt()]);            
          }          
          
          if (inData.startsWith("status")) {
            commandProcessed=1;
            inData.replace("status","");            
            int currentStatus=digitalRead(inData.toInt());     
            Serial.println(currentStatus);
          }
          
          if (commandProcessed==0) {
            Serial.print("Unknown command: ");
            Serial.println(inData);
          }
         
          inData="";
          Serial.flush();
        } else {
          inData += (c);
        }    
  }  
  //delay(100);
}
 

Сергей Джейгало, разработчик MajorDoMo
Идеи, ошибки -- за предложениями по исправлению и развитию слежу только здесь!
Профиль Connect -- информация, сотрудничество, услуги
Denilkor
Сообщения: 2
Зарегистрирован: Вс янв 29, 2017 7:03 am
Благодарил (а): 0
Поблагодарили: 0

Re: Сеть беспроводных устройств на Arduino

Сообщение Denilkor » Вс янв 29, 2017 7:16 am

Доброго дня форумчане. Буквально вчера вечером наткнулся на этот любопытный проект и решил изучить для последующей реализации . С помощью 2 UNO собрал макет . 1 UNO выступает в качестве удаленной погодной станции , собирает данные с сенсоров и плюется ими по средством NRF24 на вторую UNO . Та в свою очередь заполняет структуру (как в примере) данными и отправляет их через COM --> ArduinoGW-->MajorDoMo . Я добавил скрипт как указано в примере и дальше не могу разобраться как добавить датчики и поместить их на рабочий стол . Помогите пожалуйста разобраться с интеграцией.
Ответить