arduino无线遥控解码           

arduino无线遥控解码

01 Feb 2021


//使用超外差模块,因为超再生模块容易受单片机高频干扰造成距离只有两米
//注意电源纹波,有条件使用信号隔离和独立电源
#include <EEPROM.h>
//#include "SoftwareSerial.h"
#include <RCSwitch.h>

RCSwitch mySwitch = RCSwitch();

char val;  //存储接收的变量
static byte g_len = 0;//第1个字节表示数组的数量
struct _SerialN
{
  unsigned int value;
  byte btn;
  unsigned int  dt;//延时
};

union data
{
  _SerialN btn;
  byte b[5];
};


_SerialN read_btn(int addr)
{
  data d;
  for(int i=0;i<5;i++)
  {
    d.b[i] = EEPROM.read(addr + i);
  }
  return d.btn;
}
void push_btn(_SerialN btn)
{
  int addr = 1+g_len*5;
  data d;
  d.btn = btn;
  Serial.println(d.btn.value);
  Serial.println(d.btn.btn);
  for(int i=0;i<5;i++)
  {
     EEPROM.write(addr + i,d.b[i]);
  }
  
 
   g_len = g_len+1;
  //写入eeprom
  EEPROM.write(0,g_len);
}


void HandleSwitch(RCSwitch& sw)
{
  
    int value = sw.getReceivedValue();
    
    if (value == 0) 
    {
      Serial.print("Unknown encoding");
    } 
    else 
    {
      long nRet = sw.getReceivedValue();
      long mRet = nRet;
      unsigned int n = nRet>>8;//右移8位,去掉按钮的值
      byte m = (byte)mRet;
      Serial.print(n);//16位值
      Serial.print(",");
      Serial.println(m);


      char buf[100];
      itoa(n, buf, 2); /*3个参数,第一个是待转换的数,第二个是存放转换后的字符串的指针,第三个是需要转换的进制*/
      Serial.print(buf);
      Serial.print("  ");
      itoa(m, buf, 2);
      Serial.println(buf);
     
      Serial.print(sw.getReceivedBitlength() );
      Serial.print("位,");
      Serial.print("Proto:");
      Serial.print(sw.getReceivedProtocol() );
      Serial.print("Delay:");
      Serial.println(sw.getReceivedDelay());    

    _SerialN newone;
    newone.value = n;
    newone.btn = m;
    newone.dt = sw.getReceivedDelay();

        int has = 0;
        int addr = 1+g_len*5;
        for(int i=1;i<addr;i=i+5)
       {
          _SerialN btn = read_btn(i);
          if(newone.value == btn.value && newone.btn == btn.btn)
          {
            Serial.println("已经存在");
            has = 1;
            break;
          }
  
     }
     if(has==0)
     {
      push_btn(newone);
     }  
    }

    sw.resetAvailable();

}



void setup() {

  Serial.begin(9600);  //设置波特率
  mySwitch.enableReceive(0);  // Receiver on interrupt 0 => that is pin #2
  g_len = EEPROM.read(0);
 // EEPROM.write(0,0);

pinMode(5, INPUT);
pinMode(6, INPUT); 
pinMode(13, OUTPUT);


Serial.println("315m接收器");
  Serial.print("count:");
  Serial.println(g_len);
   int addr = 1+g_len*5;
        for(int i=1;i<addr;i=i+5)
       {
        _SerialN btn = read_btn(i);

        Serial.println("-----------------------");
        Serial.print(i);
        Serial.print(",");
        Serial.print(btn.value);
        Serial.print(",");
        Serial.print(btn.btn);  
        Serial.print(",");
        Serial.println(btn.dt);     
       } 
     
}


 
void loop() {

   if(mySwitch.available())
   {
      
      HandleSwitch(mySwitch);
      
   }
   
}