RF Sniffer на 433 МГц с Arduino
В наши дни радиочастотные передатчики / приемники с частотой 433 МГц очень популярны среди любителей электроники и возиться с электроникой. Эти дешевые радиомодули ближнего радиуса действия могут использоваться практически для всех микроконтроллеро в для широкого спектра приложений, для которых требуется беспроволочное радиоуправление, хотя в этом случае мы будем использовать его как радиочастотный снифер.
Удивительно, но широко не отмечалось, что полоса ISM (промышленная, научная и медицинская), сосредоточенная на 433,92 МГц, на самом деле охватывает колоссальную 1,7 МГц между 433,05 МГц и 434,79 МГц. Еще одна неприятная вещь заключается в том, что когда отсутствует доступность сигнала, схема AGC приемника растет, и все, что вы получаете, — это нежелательный шум на выводе данных. Это затрудняет фактическое захват «слишком быстрых» данных от шума с помощью самодельного логического анализатора звуковых карт или обычного осциллографа для целей аналитического обзора / обратного проектирования. На самом деле, около 100 миллисекунд радиомолчания после приема данных до того, как АРУ возобновит резервное копирование, позволяет вам искать радиомолчание, а затем мгновенно ищет данные, чтобы вынюхать сигнал. Это действительно неуклюжий процесс проб и ошибок!
Настройка
Позвольте мне показать вам, как вы можете легко обрабатывать упакованные данные радиосигналов без использования дорогостоящих тестовых устройств (эта идея на самом деле более удобна, чем использование чего-то чрезвычайно дорогого). Ниже представлен простой и дешевый 433-Mz RF Sniffer, идеально подходящий для тестирования / реконструирования большинства беспроводных устройств с частотой 433 МГц. Как вы можете видеть, установка находится на земле Arduino с приемным модулем 433 МГц и интерфейсом USB.
Код для захвата радиочастотных сигналов 433 МГц на самом деле является слегка измененной частью известной библиотеки «RCSwitch» ( https://github.com/sui77/rc-switch ). Ниже приведены снимки моей начальной настройки эксперимента и окна последовательного монитора моего ноутбука. В дополнение к Arduino Serial Monitor, я попробовал такую же настройку позже с PuTTY.
Я использовал простой двухканальный пульт дистанционного управления 433 МГц для отправки кодов снифферу для выполнения большинства экспериментов, выполненных в моей лаборатории. Здесь вы можете увидеть слежение за тем же пультом дистанционного управления:
-Arduino 433MHz RF Sniffer
-Based on an example from the RCSwitch Library
-Hardware: Arduino Nano & Generic 433MHz RF Receiver
RCSwitch mySwitch = RCSwitch();
mySwitch.enableReceive(0); // Receiver input on interrupt 0 (D2)
pinMode(13, OUTPUT); // D13 as output- Optional
digitalWrite(13, HIGH); // Toggle the onboard LED if serial is available — Optional
Если у вас есть телефон Android / планшет с USB-OTG, вы можете играть с сниффером без рабочего стола / портативного компьютера. Просто установите «DroidTerm (v7.2)» и запустите его «USB-виртуальный последовательный порт» (Baud Rate 9600). Смотрите снимок экрана с моего телефона. Процедура проста: откройте «Serial Monitor» и установите скорость передачи в бодах до 9600. Когда вы нажимаете кнопки на пульте дистанционного управления с частотой 433 МГц, принятые 433 МГц радиочастотные коды затем должны быть напечатаны в «Десятичное число / бит / Протокол «. Первый результат — от кнопки «А» моего пульта дистанционного управления — «Десятичный (24 бит): 2220642 и протокол 1.« Примечание: десятичный (24 бит) 2220642 = двоичный: 001000011110001001100010.
Кстати, протокол радиочастотных устройств с частотой 433 МГц довольно интересен. Ниже приведен снимок формы сигнала радиосигнала, захваченного моим надежным DSO. В основном, когда вы нажимаете кнопку, одна и та же последовательность передается несколько раз, и перед повторением одной и той же последовательности происходит небольшая задержка (в миллисекундах). Каждая последовательность состоит из двух типов прямоугольных волн: длинный, затем короткий, который представляет собой «1», а короткий, за которым следует длинный, который представляет «0.». Я понял, что длинный или длинная длина примерно в три раза превышает ширину короткого замыкания или короткого замыкания. Имея это в виду, я удержал полную последовательность включения-выключения (OOK), соответствующую кнопке «А», как и ожидалось. Конечно, кнопка «A» моей пульта дистанционного управления выводит 24-битный код «001000011110001001100010» (2220642 в десятичной форме), как это было показано в точности по установке Arduino, но с ложным «0» в конце (что может быть незначительным Значение «конец сообщения»).
Там у вас есть — вот как я захватил и проанализировал сигналы радиочастотного пульта 433 МГц. Я планирую продолжить эту статью с помощью нескольких руководств по обратному проектированию в будущем. Отсюда вы можете начать эксперименты, чтобы сделать ваши собственные радиопередатчики с помощью частей, расположенных вокруг, для передачи «реплицированных» кодов, чтобы возиться с вашими (или вашими соседями — хаха!) Существующими 433-МГц радиочастотными бытовыми приборами или аналогичные вещицы. Конечно, сложная часть — это выяснить, как кодируются данные. Если вы можете захватывать и декодировать сигналы с устройства, вы можете воспроизвести его с помощью микроконтроллера и передатчика с частотой 433 МГц и взять его под контроль (радиочастотный передатчик имеет один вывод данных, который может быть подключен к любому выводу микроконтроллера ввода / вывода) ,
В каждой стране есть регулирующий орган, ответственный за радиосвязь. Крайне важно, чтобы вы знали о законах, касающихся использования нелицензированных радиопередатчиков. Если вы не соблюдаете эти правила, вы можете столкнуться с большими неприятностями.
Decode and Send 433 MHz RF Signals with Arduino
This guide shows how to use an Arduino to decode 433 MHz signals from RF remotes, and send them with an Arduino and a 433 MHz transmitter to remotely control mains switches outlets.
Why Decoding RF Signals?
I’ve tried different methods of controlling the mains voltage, but some of the methods require:
- Experience dealing with AC voltage
- Opening holes in your wall/ceiling/switches
- Modifying the electrical panel
- Knowing the electrical rules for each country
It’s difficult to come up with a solution that is safe and works for everyone. One of the easiest and safest ways to remotely control appliances connected to mains voltage is using radio frequency (RF) controlled outlets. Why? Using remote controlled outlets have 5 benefits:
- Fairly inexpensive
- Easy to get
- Works with ESP8266 and Arduino
- Safe to use
- Works in any country
Parts Required
For this tutorial, you need the following parts:
Note: you need to buy remote controlled outlets that operate at a RF of 433MHz. They should say the operating RF either in the product page or in the label.
You can use the preceding links or go directly to MakerAdvisor.com/tools to find all the parts for your projects at the best price!
Example
Here’s how they look:
Setting the RF Channels
I’ve set my remote control to the I position.
The outlets must be both on the I position. I’ve selected channels 3 and 4 for the outlets (you can use any channel you want).
If you plug them to an outlet, you should be able to control the remote controlled outlets with your remote control.
Installing the RC Switch Library
The RC Switch library provides an easy way of using your ESP8266, ESP32, or Arduino to operate remote radio controlled devices. This will most likely work with all popular low-cost power outlet sockets.
- Click here to download the RC Switch library. You should have a .zip folder in your Downloads folder
- Unzip the .zip folder and you should get rc-switch-master folder
- Rename your folder from rc-switch-master to rc_switch
- Move the rc_switch folder to your Arduino IDE installation libraries folder
- Then, re-open your Arduino IDE
Opening the Decoder Sketch
You need to decode the signals that your remote control sends, so that the Arduino or ESP8266 can reproduce those signals and ultimately control the outlets.
The library comes with several sketch examples. Within the Arduino IDE software, you need to go to File > Examples > RC_Switch > ReceiveDemo_Advanced . This next sketch opens:
You must open the example using File > Examples > RC_Switch > ReceiveDemo_Advanced, so it automatically also loads the output file.
Having an Arduino board connected to your computer follow these instructions:
- Go to the Tools tab
- Select Arduino UNO board
- Select the COM port
- Press the Upload button.
Decoder – Schematics
After uploading the sketch, connect an 433MHz RF receiver to Digital Pin 2 of your Arduino UNO board:
Decode RF Signals (codes)
Open the Arduino IDE serial monitor and start pressing the buttons. As shown in the video demonstration below:
After pressing each button one time, you can see the binary code for each button (it’s highlighted in red):
Save your binary codes for each button press (you can also use the Decimal or Tri-State codes):
- Button 3 ON = (24Bit) Binary: 000101010101000101010101
- Button 3 OFF = (24Bit) Binary: 000101010101000101010100
- Button 4 ON = (24Bit) Binary: 000101010101010001010101
- Button 4 OFF = (24Bit) Binary: 000101010101010001010100
Save your Pulse Length: 416 Microseconds and Protocol: 1.
Send the RF Signals (codes)
You’ll need to customize the next sketch with your binary codes, pulse length and protocol:
In my case, the pulse length and protocol looks like this:
Here’s a binary sender example (you have to replace with your own binary codes):
Sender Schematics
After uploading the sketch to your Arduino board, assemble this circuit:
Both of your outlets should be turning on and off continuously.
Wrapping Up
I hope you’ve found this guide useful. If you like this post probably you might like my next ones, so make sure you subscribe the RNT blog.
You can use the concepts learned in this tutorial with your ESP8266 or ESP32.
Thanks for reading.
[eBook] Build Web Servers with ESP32 and ESP8266 (2nd Edition)
Build Web Server projects with the ESP32 and ESP8266 boards to control outputs and monitor sensors remotely. Learn HTML, CSS, JavaScript and client-server communication protocols DOWNLOAD »
Recommended Resources
Build a Home Automation System from Scratch » With Raspberry Pi, ESP8266, Arduino, and Node-RED.
Home Automation using ESP8266 eBook and video course » Build IoT and home automation projects.
Arduino Step-by-Step Projects » Build 25 Arduino projects with our course, even with no prior experience!
What to Read Next…
ESP8266 Controlled with Android App (MIT App Inventor)
Guide for TCA9548A I2C Multiplexer: ESP32, ESP8266, Arduino
Build an All-in-One ESP32 Weather Station Shield
Enjoyed this project? Stay updated by subscribing our newsletter!
42 thoughts on “Decode and Send 433 MHz RF Signals with Arduino”
Thanks for doing all of this work both for this project and all of the other projects you do. It helps the rest of us who don’t know how to do this,but want to learn.
Again thanks
I’ve designed a same circuit and uploaded the program in Arduino UNO which is mentioned above. I am not seeing any output in serial monitor. Could you please tell me the type of receiver you’ve used and what other rf receivers I can use. Thank you… Hope to see your reply soon…
Hello Ruturaj, some of those inexpensive RF transmitter/receivers don’t work or come defective. Can you try it with a new receiver? If it still doesn’t work, it means that your remote controlled sockets might not be operating at 433MHz or that they aren’t compatible with the RC Switch library…
I have compilation Problems. The Compiler says: ” ‘output’ was not declared in this scope”.
Hi Frank.
Did you installed the RC_Switch library?
First, i thought it’s the wrong library. But all ok. I used copy/paste to copy the sourcecode from this Internet site to my arduino. That was the Problem! I think, that i copied some “undisplayed signs”. Now it works. 🙂
Great! I’m glad it works! 🙂
Same problem here. I just can’t get it running 🙁
Hi Sara. Thanks for sharing this
I got the same problem as Frank : “undisplayed signs”?
Im getting this error: exit status 1
‘output’ was not declared in this scope
Any ideas? Thanks 🙂
Hi.
Have you copied the code from here: https://raw.githubusercontent.com/RuiSantosdotme/Random-Nerd-Tutorials/master/Projects/decode-rf-arduino/ReceiveDemo_Advanced.ino ?
Try to get the code by going to File > Examples > RC_Switch > ReceiveDemo_Advanced
Also make sure you have Arduino IDE up to date and the RC Switch library installed.
Regards,
Sara
Ciao e buon anno!
Articolo interessante, grazie a voi per averlo condiviso. Chiedevo se è possibile copiare anche radiocomandi per apertura garage a 433mhz. Inoltre, chiedevo se questo codice di può usare con nodemcu. Grazie.
Hello and happy new year!
Interesting article, thanks to you for sharing it. I asked if you can also copy radio controls for the garage opening at 433mhz. Also, I was wondering if this code can use with nodemcu. Thank you.
Hi, im a complete noob at this, but im trying to build a system that works kind of like a garage door, just that instead of opening the garage it just powers a LED light. It’ll work as a visual notification to my deaf grandma, that someone has arrived to visit. Will this work for me? or there is another tutorial more in line with my situation? Also what range is this 433 Mhz functional?
Thanks, sorry for my long message.
Sara, sos brillante. … Felicitaciones..
Thank you so much for your support! 😀
Just tested it with a generic module bought from Jaycar in Australia. I had to set the setPulseLength value to 10 and it was immediately picked up my my Sonoff RF Bridge running Tasmota. This is great. Thank you so much for making your code available to the world!
Hi, thanks for this tutorial. I am trying to capture 433MHz codes from remotes that control window blinds. The receiver/transmitter components I have look like the ones in your pictures. I’m pretty sure the receiver is connected correctly, and the sketch is uploading correctly to my Uno device. But nothing registers when I press the buttons on the remote.
I have been able to grab codes successfully using the exact same receiver connected to a Raspberry Pi (using pigpiod/piscope). But the Arduino sketch isn’t picking anything up.
As a test I added an “else” to the if statement in the loop to spit out a character on serial every 32760 iterations. It appears continuously.
Which suggests the board isn’t seeing any output from the receiver. I’ve tried both 5V and 3.3V power (3.3V worked OK on the Pi).
Any suggestions?
Hi Mark.
Without further information, it is very difficult to find out what might be wrong.
Are you really sure the module is wired correctly? And are you sure that your remotes are powered on and sending the controls?
Regards,
Sara
Sara, thanks for your reply. Yes, I am pretty sure the receiver module is wired correctly. I have tried with either +3.3v or +5V and ground connected to their respective pins on the module, and the signal wire going to pin 2 on the Uno,
The remotes are unbranded but labelled DC1600 – very similar to or identical to those you can see here: https://fccid.io/2AIDK-DC1600F/User-Manual/User-Manual-3024928 They are controlling blinds rather than remotely switchable sockets, but they definitely operate on 433MHz, so I’m guessing RCSwitch should be able to handle them – or is that an assumption too far?
I know the remotes are working because the blinds respond when I press the buttons, yet nothing appears on the IDE serial monitor. I know the sketch is loaded because some print statements that I added appear.
FWIW the signals I was seeing in piscope were like this: pressing each button results in a series of continuously repeated patterns for as long as a button is pressed. Each repetition lasts about 50ms, starting with a LOW of 8.825ms duration, then HIGH approximately 4.75ms, followed by LOW of 1.5ms, Subsequent transitions, which I took to be binary digits 0 and 1, were either short HIGHs of around 0.3ms followed by LOW of 0.78ms; or HIGH of 0.65ms followed by LOW of 0.44ms – I assume these were 0 and 1 respectively. In all there are 40 binary digits in each repetition. (NB my timings may be a bit off, I was using a very old, 1st gen Raspberry Pi.)
An example of one complete sequence with one of the remotes – an UP command – was 0111 0100 0100 0100 1011 1001 0111 0001 0001 0001. There seem to be 32 bits that characterise the remote, then 8 bits of command, consisting of the same four bits repeated. 0x11 for UP, 0x33 for DOWN, and 0x55 for STOP.
Mark. Did you manage to get the DOOYA DC1600 to work with this?
I am facing the exact same problem at the moment and cannot get these remotes to work.
Never did. In the end I bought a Broadlink RM4 Pro and was able to teach it the commands and get the blinds to work, more or less.
Hi and Thanks for sharing this. It is first time I do this and I am totaly new in this , but everething works as it is explained. But how to turn on/off the light with arduino?