WiFi to IR interface

Last update: 2018-02-25 15:30 (See the note at end)

Once again a project realized in the B&B during my free time, far from home. The circuit described here will be capable to drive almost any device that currently uses an IR remote control, by means of WiFi connection, as to say: with your smartphone. This time I want to show all the route from the idea to the running device. I had the idea some years ago (look at my previous articles regarding IR and WiFi), but I completely forgot it until today.

When I start a new project, there is the first step that I call: “sofa time”. I spend such time lying down on the sofa, without any computer, pen, document or tool. I just think about how to realize the project with the minimal effort.

After this time, I take a block-notes and draw with a pencil (or a pen) a very minimal schematic. In practice, it’s just a brief list of essential connections for the various components that I’m going to use. Here is such minimal schematic:

I don’t need a full schematic, at this time. I will draw it “seriously” with a CAD in the final steps. Well, now I can start building the prototype. First of all I search in my “junk box” what components are available and eventually I change the schematic in order to make it possible to be realized with available components. Usually my laboratory is very complete, but currently I have only few parts, being far from home. This is the prototype, wired on a proto board :

If you are curious to see how this circuit is wired, look at the bottom part :

Note the presence of some SMD components. Sometimes I put such components mixed with the through-hole parts for space saving or just to substitute missing parts of the required value. It’s a simple circuit, but requires soldering skills to be built !

Did you noticed that I used a 16MHz crystal? Did you also noticed that I used a linear 3.3V regulator for powering the microcontroller ATmega88 and the WiFi module ESP-01? Well, there is a mistake ! A 16 MHz crystal is out of specs at 3.3V as you can see in the next picture:

The diagram is taken from the ATmega88 datasheet and says that the maximum crystal frequency at 3.3V is about 13.3MHz, evaluated with dF=(20-10)MHz and dV=(4.5-2.7)V. The nearest value that I have in my junk box is 12.288MHz, then I’m going to replace the component onto the circuit (it will be an easy job).

I plan to power my circuit with a 5V wall adapter, probably a phone charger, but during the tests I will use a Li-Ion battery, just to limit the number of cables on my unfair working place. Note that the LM1117-3.3 IC does NOT stabilize very well with the power supply taken from a Li-Ion battery. Look at this picture taken from the component’s datasheet :

A fully charged battery has 4.2V voltage, so it’s under the minimal dropout at 100mA to have a stable 3.3V output. Consider that the ESP-01 can have current peaks greater than 250mA, so the regulator output may be unstable. This situation will degrade more when the battery discharges to 3.7V (its nominal voltage) and the residual charge is about 10% of the nominal capacity. I used a 100uF capacitor connected to the ESP-01 power lines in order to absorb part of the current spikes in WiFi transmission and if necessary I will increase such capacity. In the “real life” the circuit, powered with a 5V-700mA wall adapter, will work fine ; for this test version I can accept some limitations.

Here is the first version of the circuit schematic (still subject to change):

For a better view, you can download the drawing in PDF format from this link. The pinout for the wifi module ESP-01 in the schematic diagram corresponds to this figure:

Note: if you want to replicate this project, you must program the ESP-01 module to use a 9600 BPS communication speed. There is an AT version created with such default speed on this website: http://wiki.aprbrother.com/wiki/Firmware_For_ESP8266 ; go there and look for ai-thinker-0.9.5.2-9600.bin. You can also alter (in a permanent way) the current communication speed of your ESP-01 module using AT commands. There are two, that works depending upon the version of firmware installed. Try both of them; the first that gives answer “OK” is the right one.

For additional information and useful SW tools, take a look at my previous articles here:
Interfacciare il modulo ESP-01 con una porta USB
http://ficara.altervista.org/?p=3041
AT-commands tool
http://ficara.altervista.org/?p=3158

The firmware – Part 1

At this moment I don’t want to write an App to test the device, so the first version of the firmware contains a very basic webserver, just to check if I can connect to the device with my smartphone using the default browser. The first release of the firmware (about 3 KBytes) is available at this link. The file is zipped with password. Use the program 7Z with password: eficara to expand it. The zip contains the .hex file to program the micro and the following image for the fuses map:

When the microcontroller has been programmed, you can try to check if it works. First of all, connect your smartphone to the AP that is presented by the Esp-01 module. You will be informed, obviously, that you are NOT connected to the Internet:

Note that the last 6 characters of the AP SSID will differ from the ones showed in the image, being the representation of last 3 bytes of the MAC address of the module and also the ESP_  part can differ if there is another release of the AT firmware in the module.

After connecting your smartphone to the Esp-01 AP, you can open the default browser and navigate to the single page available on this minimal webserver implementation. Here is an example:The page is always located at 192.168.4.1 (the Esp-01 IP) /cmd.htm (the single implemented web page) and the command ?k= followed by 4 hexadecimal digits. You will receive an html page with the same hex digits. This is just for test purposes. Please note that the hex digits that you will use in your requests must be in capital letters, or you will receive wrong answers:IR protocols – Tools

Now I must indagate the IR protocols that I want to use in this device. Many, many years ago, I realized an IR protocol analyzer under MS-DOS using Borland C and some subroutines in Asm 8086. It worked  with direct I/O control of the pins of a COM port. Here is the hardware I used for IR protocol analysis:

At the left, the “receiver” part ; in the middle, a more recent wired prototype used with a microcontroller and at the right the “transmitter” part, from  the same MS-DOS tools suite.

Well, I will NOT present here such old MS-DOS programs because I have found on the internet a great page published by Ondřej Staněk at this link: http://www.ostan.cz/IR_protocol_analyzer/ that has a freely downloadable tool that is much more complete and powerful than mine. It works under Windows and the involved hardware is very simple to build. Here is a screenshot of the program running on my PC:

The software uses the MIC (audio) input of your PC / Notebook to capture the IR signals from a remote controller. You can use a simple photodiode like this :

My interface, mounted on a 3.5 mm stereo jack

Or, if you can’t find the photodiode, you can try with a normal IR emitter (LED) using this circuit. I made it ‘cause I haven’t any photodiode in my “mobile laboratory”, but I have an IR emitter (LED) mounted on a small proto-board. I tested this unconventional circuit on my notebook and after a couple of tries it worked (the previous screenshot was taken with this interface).

Another detector that uses a normal IR LED as receiver. Don’t consider the other components on the board. Those parts are from another circuit !

Here are some audio settings I used on my notebook in order to make it work:

Here is a list of some articles on my website about the IR remote controls:

WM8650 tablet as remote control for Sony TV
http://ficara.altervista.org/?p=497
Using Android tablet as SIRC remote control (#2)
http://ficara.altervista.org/?p=859
General purpose infrared remote control receiver with RS232 output
http://ficara.altervista.org/?p=1221
Usare lo smartphone come telecomando TV
http://ficara.altervista.org/?p=2426
Un altro telecomando TV per smartphone Android
http://ficara.altervista.org/?p=2908

The firmware – Part 2

Well, I finished this project or, better, this “proof of concept”. It works, I can control my TV using the browser of my smartphone. The IR protocols used here are NEC and RC5. Due to the low power of IR led, driven directly by uC Port with a single resistor, the distance from the device to the TV (or other apparatus) will be 1 meter max. Add a transistor interface if you want long distance.

Note (Feb, 25 2018): I tested the circuit in the picture below and the distance now is over 3.5 meters. I can’t test if it works over 3.5 meters ‘cause my B&B room is very small !

One reader from Hackaday proposed to use multiple output pins in parallel to drive the IR LED with more power.  It’s a good idea, but the software needs to be modified ‘cause I used the SBI I/O,#bit and CBI I/O,#bit instructions respectively to turn OFF (remember, negative logic for LED) and ON the port bit.

Part of the C source (commented ASM listing) – Section: Nec protocol – Xtal: 12.288MHz – Interrupts: disabled

Controlling multiple port bits at the same time needs the OUT I/O,R instruction. Using the OUT instruction also involves to get the port status (in order to save other bits not used for IR led) and save it to 2 different registers, one to be used when you want low level on the IR outputs and the other when you want high level, without affecting the “non IR led” bits. Such approach changes the number of clock cycles needed to generate the 38KHz (Nec) and 36KHz (RC5) frequencies.  This is absolutely not difficult to realize, but at this moment I closed my test firmware, so the transistor solution is simpler.

At power-on (reset) the microcontroller automatically sends one command for testing the NEC and RC5 protocol as you can see in the Main procedure.

After sending the test commands, the main procedure loops in the wifi section (function: Parameters) waiting for commands from any browser. The same IR code used in the test procedure can be sent with the smartphone, with the same  effect.

The command 0x0408 (address, 0x04, cmd 0x08) turns on  or off the TV in my B&B room 🙂 This is the screenshot of the IR tester, splitted in two parts ‘cause is a bit long:

In the Main procedure there is also a transmission of one RC5 code. This is the screenshot of the actual code set (RC5 is smaller)

Note that in order to send RC5 protocol IR commands, you must use another string in the browser. In place of: cmd.htm?k= you must use: cmd.htm?r= . This informs the firmware that the following 4 characters (hex) must be used as address and command for RC5 protocol, not for NEC. Please, remember that the standard RC5 protocol has 5 bits address (0x00..0x1F) and 6 bits command (0x00..0x3F). Codes out of the limits will be cut out with a simple “and” operation.

Finally, the new release of the firmware. It’s only 3034 bytes long. In the zip file you can find the .hex to burn the micro and a picture of the fuses configuration. Download the file from here and use the program 7Z to expand it. The password is: eficara.

Have fun !

Note (Feb,21 2018): this article was linked by Hackaday and then I’ve seen many comments there about the “unuseful” ATmega88 micro used in my circuit. Someone assumed (wrongly) that I used the Arduino IDE to create this project ! Well, there is a big misunderstanding. May be that someone leaves his opinion before reading the article or simply thinks that reading the article is just an option. Ok, I just want to make clear that I wrote all the firmware in C language (some ASM code was optimized to C) and without using any “pre-cooked” library for ESP-01 or IR functions. All the webserver via AT commands and the IR RC5 and NEC protocols are mine, not copied from other people’s works. I know that the Esp8266 itself is a fully programmable device, but my target was to use a preprogrammed part (Ai-Thinker ESP-01 module with AT firmware) and just control that part how it comes “out-of-the-box”, without any modification, to create my “proof of concept”. I also know that there is a Lubuntu virtual machine (VirtualBox) with the complete environment to develop C language applications for the ESP8266. I have such VM enabled and working on my desktop computer, at home.

Un altro telecomando TV per smartphone Android

Sì, l’ho fatto ancora. In un mio precedente articolo descrivevo come costruire una interfaccia da collegare al telefonino per poterlo usare come telecomando per il TV. L’applicazione Android permetteva, in quel caso, di controllare un TV di modello Sony Bravia, che utilizza un protocollo a infrarossi di tipo NEC. Ora non ho più quel televisore ed ho un piccolo Telefunken, che però usa un protocollo a infrarossi di tipo RC5, che è completamente diverso. Allora ho scritto una nuova applicazione, mantenendo sempre la stessa interfaccia hardware. E’ da notare che la distanza di funzionamento di questa versione è inferiore alla precedente. Purtroppo, la frequenza generata col sistema descritto nella pagina citata a inizio articolo è sempre di 38.4 KHz che è molto vicina ai 38 KHz “standard” del protocollo NEC, ma purtroppo è un po’ distante dai 36 KHz canonici del protocollo Philips RC5. Comunque, funziona lo stesso, dato che il notch filter del ricevitore non è proprio così stretto in frequenza, ma ha una “campana” ampia a sufficienza per tollerare questo errore in frequenza… Per la corretta temporizzazione delle fasi di “pieno / vuoto” ho utilizzato i pattern che derivano da 11 bytes di valore 0x5B per il “pieno” (burst di frequenza) e 11 bytes di valore 0x00 per il “vuoto” (pausa). Durante la trasmissione di 11 bytes di valore 0x00 si avranno comunque dei “glitches” di 8.68 uS attivi alti, perché questi sono gli “stop bits” della trasmissione che non posso eliminare. Per fortuna, i circuiti di ricezione presenti nei TV hanno una funzione di “filtro” che elimina questi disturbi. I filtri sono indispensabili perché alcuni tipi di illuminazione domestica (specie i tubi al neon) emettono disturbi nello spettro dell’infrarosso con una potenza notevole (provare per credere). Senza una “ripulita” del segnale, i telecomandi sarebbero poco efficienti. Comunque, i prossimi controlli remoti per TV saranno via radio, con i soliti 2.4GHz che ci stanno rendendo le case simili a forni a microonde… 🙂

Perché il tutto funzioni, è necessario che la versione Android sia in grado di gestire le periferiche USB, naturalmente. Nella figura sottostante potete vedere lo screenshot del programma in funzione.

Il programma in funzione: iRemUSB-RC5

Il programma in funzione: iRemUSB-RC5

La App iRemUSB-RC5.apk è scaricabile gratuitamente dalla mia pagina di Google Play.

Usare lo smartphone come telecomando TV

Qualche tempo fa ho proposto in queste pagine un circuitino basato su un convertitore USB-RS232 da collegare ad un tablet Android per realizzare un telecomando a raggi infrarossi. In quell’occasione il convertitore USB veniva “visto” da Android come una porta seriale ttyUSB5, ma si trattava di una vecchia versione del sistema operativo (la 2.6 se ricordo bene). Nelle nuove versioni, le periferiche USB sono gestite in modo del tutto diverso e così la vecchia applicazione che avevo scritto un paio d’anni fa non funziona sui nuovi dispositivi. A questo punto, ho pensato di riscriverla perché possa funzionare sui nuovi smartphone (o tablets) basati su Android 4.0 e successivi. Nella foto sottostante potete vedere il mio smartphone con la periferica collegata e il programma in funzione.

IRemoteUSB-pic1A parte la gestione dell’interfaccia USB, il principio di funzionamento è lo stesso. Si sfrutta la porta seriale per inviare dati formattati in un modo particolare. Utilizzando la velocità di 115200 BPS, una lunghezza di 7 bits ed 1 stop bit, infatti, si ha la possibilità di generare dei “bursts” di 38.4 KHz che vengono ricevuti molto bene dal sensore IR contenuto nel TV. Nel disegno qui sotto si vede come questo sia possibile:

serial7bitIn questo esempio vediamo la trasmissione seriale di due caratteri di valore 0x5B (hex) ; se però guardiamo la forma d’onda da un punto di vista differente, scorgiamo un burst di 6 impulsi con una frequenza di 38.4 KHz ! Ogni bit, a 115200 BPS, dura infatti 8.68 uS ; noi usiamo 3 bits per definire un periodo della nostra onda rettangolare e così la durata totale è di 26.04 uS che corrisponde appunto alla frequenza di 38.4 KHz. Grazie a questa “fortunata coincidenza”, possiamo usare la porta seriale per emettere una serie di caratteri che formano bursts e pause rispettando il protocollo di trasmissione di un telecomando a raggi infrarossi. La mia applicazione per Android utilizza il protocollo SONY e funziona perfettamente con un televisore di modello “Bravia”. Si possono realizzare senza problemi anche altri protocolli, quali il NEC o il Philips (RC5) ; il programma sarà diverso, ma il principio resta lo stesso.

Ovviamente, non basta usare lo smartphone e scaricare l’applicazione, si deve avere una interfaccia USB-TTL e in più si deve costruire un piccolo circuitino. La figura seguente mostra lo schema elettrico ed il prototipo.

IRemoteUSB-schEsistono moltissimi modelli di interfaccia USB-TTL, io ho comprato quella mostrata in figura presso un “noto negozio on-line” ed ho speso (compresa la spedizione dalla Cina) meno di due Euro. Il circuitino con il transistor serve a dare un po’ di potenza al LED infrarosso ; con questa interfaccia e “mirando” bene verso il sensore del TV, ho raggiunto una distanza utile di oltre tre metri.

L’applicazione per Android è molto semplice: ha solo sei tasti che servono per le funzioni “classiche”, che sono il cambio di canale (CH+ e CH-), la modifica del volume (VOL+, VOL- e MUTE) e l’accensione / spegnimento del TV (POWER).

Screenshot_2014-11-27-13-46-43Se si lancia l’applicazione SENZA aver collegato l’interfaccia USB, si riceve una schermata di errore.

Screenshot_2014-11-27-13-26-26Se invece si lancia l’applicazione con l’interfaccia collegata, viene richiesta l’autorizzazione all’uso di tale periferica da parte del programma.

Screenshot_2014-11-27-13-46-30L’applicazione è disponibile gratuitamente su Google Play , mentre il circuito lo dovete costruire voi… 😉 Buon divertimento.

General purpose infrared remote control receiver with RS232 output

This circuit, based on popular micro ATtiny2313 from Atmel, can receive signals transmitted by an infrared remote control using the NEC protocol (or similar) with 32 bits of data. The received infrared stream is converted to ASCII string and transmitted on the RS232 port with format 19200,N,8,1. Power supply is taken directly from the PC serial port, if you activate the DTR or/and RTS lines. To test the circuit you can use the standard Windows HyperTerminal program.

148pic

The circuit transmits on RS232 three types of informations :
1) the character @ at micro reset and then every 5 seconds of inactivity (no signal received by the infrared sensor)
2) a string of 8 hexadecimal ASCII characters preceded by < and followed by >
3) the character # if you continue to hold down a button on the remote control, with a period given by the repetition rate of the remote control (100/200 mS approx.)

A typical string may be something like this : @@@@<00FF00FF>## where the first 4 characters @ means that there was no activity on the infrared sensor for about 20 seconds, <00FF00FF> is the key code received from remote and ## indicates that the key was pressed for 200/400 milliseconds.

Want to take a look at C source for this program ? Click here

To burn the micro, I used the freeware version of SP12 for WinXP or Win2K.
The batch files to program the micro and the fuses that are included in zip file, are tailored for this software (you can find it easily with a google search).

If you have other tools for micro programming, the fuses configuration for the application described is : Ext = 0xFF High = 0xCB Low = 0xEC

The downloadable file ef148.zip contains :
– schematic.pdf – the electric schematic in PDF format
– top.pdf – the PCB layout in 1:1 scale
– topprint.pdf – the components mounting map
– irrx.hex – the HEX file to burn the micro
– wrFuses.bat – the batch file for micro’s fuses programming
– wrProg.bat – the batch file for micro’s memory programming
– 148pic.jpg – the picture of the working circuit

This circuit was designed and programmed by me on 2008 Nov 08 ; it was published on my old sites, then removed when I closed that sites and now is here (to stay)  😉