New Software for Analyzing IR Signals

It was my pleasure to be an Indigogo supporter and beta tester of the new software solution for analyzing infrared signals using Arduino, Raspberry Pi and other controllers. It is a Windows application called AnalysIR. Software is now available for the general public here http://www.analysir.com/blog/

One of the nicest features of this system is that it allows you to use and IR learner chip to directly decode raw IR signals rather than using a decoder bandpass filter and AGC style chip that I normally recommend for my projects. This is essential if you do not know the base frequency of an unknown protocol.

The Arduino portion of their software is freely distributable at some point I will be adding something to my IRLib library for Arduino that will allow you to do frequency analysis. But no matter what I come up with it’s not going to be as useful as this full-featured package which is now available at a reasonable price considering the effort they’ve put into it.

I’ve had many requests for output of IR signals in different formats such as ProntoHEX that I’ve not yet been able to implement in my code. However this software easily outputs that format.

I highly recommend you check out the software.

Resetting an Adafruit Trinket using an Arduino Uno

satb100Sometimes when you’re designing electronic circuit boards especially on a budget it’s easy to cut corners and only put the very bare essentials into the board. But the folks at Adafruit Industries make quality inexpensive products and they never cut corners. Case in point is there new ATtiny85 development boards the Adafruit Trinket and Adafruit Gemma. Other boards using the ATtiny85 require you to physically unplug and re-plug their boards every time you want to load a new sketch. On the other hand Adafruit included a reset button and they broke out the reset line on one of the breakout pins. For most people that’s probably not a big deal but for someone with a disability with myself, the inability to physically plug and unplug the board is a dealbreaker. Thanks to Adafruit including this reset breakout I was able to use another microcontroller namely an Arduino Uno to toggle the reset for me and allow me to use the board despite my disability. Here is a demo video I created for the weekly Adafruit Show-and-Tell.

Here is a code used on the Arduino Uno to toggle the pin 5 low for 1/10 of a second
//Sends reset signal from Arduino to
//Adafruit trinket by pulsing the reset line
//low for 1/10 of a second
int reset_pin = 5;
void setup() {
pinMode(reset_pin, OUTPUT);
digitalWrite(reset_pin, HIGH);
delay(100);
digitalWrite(reset_pin, LOW);
delay(100);
digitalWrite(reset_pin, HIGH);
}
void loop() {
}

Here is the code that you load onto the trinket so that it will blink a particular pattern. That verifies that you successfully uploaded.
//Modified trinket blink sketch
int led = 1; // blink pin 1 the built in red LED
void setup() {
pinMode(led, OUTPUT);
}
void Signal (char N,int T) {
for(int i=0;i

Here is the Adafruit Show-and-Tell from September 21, 2013 where I demonstrated this project.

IRLib Tutorial part 4: IR Remote Mouse

Click this logo to see my Adafruit Show-and-Tell presentation June 22, 2013

Click this logo to see my Adafruit Show-and-Tell presentation June 22, 2013

The reason I got into working with Arduino and IR remotes was to create adaptive technology for disabled people like myself. After building a specialized TV remote, the next project I tackled was to create an IR remote controlled mouse and keyboard emulator that allows me to use my IR remote to move the mouse, the arrow keys, and even type complete messages using a full keyboard.

First I would like to share with you some background as to why I created this device and then we will show you how to make a simplified version of this IR remote mouse that would be useful to anyone who uses a computer… not just someone with a disability.

My Dragon Isn’t Draggin’ Very Well

Normally I control my computer using dictation software known as Dragon NaturallySpeaking however there are some things which Dragon does not do well. Ironically a program called “Dragon” isn’t very good at draggin’ the mouse. There are mouse control commands but they are sometimes difficult to use. Also it is very difficult to use control click, shift click and (although I’ve never had to) alt click. I also have a graphics program which occasionally requires you to drag the mouse holding the right button. To my knowledge there’s no way to do that with Dragon. I also have an app on my iPod touch which allows me to wirelessly control the mouse. However it has even fewer dragging capabilities than Dragon. And there are just times when Dragon gets locked up for some reason and doesn’t work. I needed an alternative way to access my computer when something goes wrong with my usual methods. So creating an Arduino-based IR controlled mouse has been a real godsend.

Okay you’re thinking “Come on Chris isn’t it a little bit egotistical to call a device you designed a godsend?” But it really has been a blessing that such technology is available for me to create this device. When I first came up with the idea for it I was going to have to use a Arduino Uno. But it isn’t very well suited to doing mouse and keyboard emulation. You have to use an ISP to reprogram the USB controller and then you have to use an ISP to upload sketches. I had done Google searches to learn how to do it and it wasn’t going to be fun. There were some libraries available but I thought it was going to be a pretty steep learning curve about USB protocols in order to write the code to make this happen. I was still very new working with Arduino and I wasn’t looking forward to getting into something that complicated.

Arduino Leonardo

Arduino Leonardo

Leonardo to the Rescue

Finally one day I did one last Google search on “how to emulate a mouse using an Arduino” and up popped something new! A new kind of Arduino called “Arduino Leonardo“. It was designed specifically for this purpose to be able to do mouse and keyboard commands. It has all of the necessary libraries built in. I could use the device as a mouse or keyboard and I could still upload sketches directly through the USB port using the traditional Arduino IDE. It literally brought tears to my eyes when I realized that what I feared was going to be unbelievably difficult was now going to be almost trivially easy. I immediately went to the Adafruit website and ordered a brand-new Arduino Leonardo and other necessary parts to build the device shown below. Inside the box is a Leonardo, and IR receiver, and a 20 character by 4 line LCD text display and then I2C backpack for controlling the display. Here is an image of what I built and use every day.

My Leonardo-based Mouse and Keyboard Emulator

My Leonardo-based Mouse and Keyboard Emulator

Mouse Mode Display

Mouse Mode Display

The device had three modes of operation. In mouse mode you could move the mouse up, down, left, right and all 4 diagonal directions. You could left click, right-click, scroll wheel and you can also left drag or right drag. You can also toggle the control, shift, or alt keys by pushing a particular button. The display on mouse mode really didn’t tell you much except for the status of the control, shift, or alt keys and the speed at which you move the mouse. The “lr” changes to “Lr” or “lR” if you are dragging with the left or right buttons respectively. The “sca” change to uppercase if you are toggling the Shift, Control, or Alt keys respectively. The other strings of text shown on the screen are some universal keyboard commands that work in mouse or arrow modes. They are only on the screen to remind me which buttons do which functions. For example the text “Pl=^V” reminds me that the “Play” button on the remote sends a “ctrl-v” which is the same as a “Paste” function.

Arrow Mode Display

Arrow Mode Display

In arrow key mode the arrows on the TV remote don’t move the mouse, they move the arrow keys. This has been an especially useful feature for me when selecting large numbers of files in Windows Explorer. To do it with voice control I would select the first file an attempt to say the phrase “press shift down” dozens of times to select a bunch of files. If you accidentally mispronounce that phrase or if it misunderstands you it can do something completely different and you have to start over. This image shows arrow mode which again doesn’t really show you much except the status of the control, shift, alt keys and the reminders of other program keys.

Finally there is a full keyboard mode and that is the reason we needed the 20×4 character LCD display. In this mode there is a blinking cursor that you move around on the screen and when you get to the key that you wish to press you hit the select button on the remote and it types that key. It can type any key that is normally available from a standard PC keyboard including function keys and any combination of control, shift, and alt keys. This was really more of a proof-of-concept than a practical application but there have been times when everything else on my PC was locked up and I could type commands using this mode. I even plugged this device into my Raspberry Pi when doing the initial configuration although it was a bit tricky to type in the passwords before the session timed out. Here is an image of keyboard mode.

Keyboard Mode Display

Keyboard Mode Display

satb100Here is a YouTube video that I created for the weekly Adafruit Google+ Hangout Show-and-Tell where I demonstrate the various uses of my device. Unfortunately technical difficulties prevented me from showing this video on the live chat however you can see the video below and you can also click on the Show-and-Tell icon on the left to see the actual Google+ Hangout where I attempted unsuccessfully to show the video.

Sometimes Smaller is Better

Recently I purchased a new Windows 8 laptop from Dell. I knew I needed to make another IR mouse but I didn’t want something as big and bulky as a full-size Leonardo and a 20×4 character display. I really didn’t need the keyboard mode. It was more just a proof-of-concept. I really only needed mouse and arrow key mode. I thought perhaps I could get by with just a few indicator LEDs to let me know if I was dragging the mouse or if the control, alt, or shift toggles were on.

Fortunately the technology has improved yet again since I built my first mouse and keyboard emulator. There is an even smaller Arduino available known as the Arduino Micro. It was designed by our friends at Adafruit Industries. It uses the same ATmega32u4 chip that the Arduino Leonardo uses. It is essentially a miniature Leonardo and it can also be used as a mouse and keyboard emulator. Here’s what it looks like…

Arduino Micro: a mini Leonardo

Arduino Micro: a mini Leonardo

Adafruit RGB LED NeoPixels

Adafruit RGB LED NeoPixels

I still needed some sort of indicators to show me if I was holding down the shift, control, or alt and if I was dragging with the left or right mouse button. I would also need an indication if I was in mouse mode or arrow mode. This was a total of six indicators. Rather than wire up six individual multicolored LEDs complete with current limiting resistors and to take up six output pins, I decided to use two of these tiny Adafruit NeoPixel RGB LEDs. You can string dozens of them together and control them all with a single control wire. Add the +5v and ground wires and thus you only need three wires for an entire strand. The driver chip in each pixel controls the current so you don’t need to add resistors or anything. Since they are RGB I decided I can get by with just two of them. The wiring diagram below shows two of the pixels and an IR receiver wired into the back side of the Arduino Micro.

Wiring Diagram for IR Mouse

Wiring Diagram for IR Mouse

I placed a piece of double stick tape on the backside of the Micro and stuck the IR receiver and pixels onto the back of it. Arranging the parts in this particular way made it very easy to wire up the circuit. Here is an image of the completed device.

Completed Project

Completed Project

At some point I will probably cover the exposed wires with some hot glue or perhaps encase the entire device in some Sugru putty. I will need to maintain access to the six pins on the front side in case I ever want to rewrite the boot loader and access to the reset button might be necessary.

This new miniaturized person of my IR mouse not only helps me with my computer in light of my disability but it could be a useful gadget for anyone to use. Although you can purchase IR mouse controllers from a variety of sources, it’s always more fun to build your own and you can custom program in additional features not available in the commercially available products. For example if you are controlling a PowerPoint presentation on a projection monitor you might want to be free to move around the room while talking and using a small IR remote to click on the next image or do various other functions.

You can use any IR remote control such as a TV, DVD etc. to control the mouse as long as it uses a protocol that IRLib can understand. For this tutorial we are going to use a mini remote from Adafruit. It has 21 buttons and uses the NEC protocol. It’s small pocket-sized would make it ideal for controlling a PowerPoint presentation. Here is what the remote looks like

Adafruit Mini Remote

Adafruit Mini Remote

Programming the Commands

That takes care of the hardware. Now we need to write some software. We have 21 buttons available on this remote. Obviously we want to assign the mouse directions to the four arrow buttons. The four buttons diagonally from these arrows are an obvious choice for moving the mouse diagonally. And in arrow mode those corner buttons are obviously a good choice to assign the Home, End, Page Up, and Page Down functions. Among the other mouse functions are left and right click, left and right drag, faster or slower mouse movements, and scroll wheel up and down. Other arrow mode functions will include Backspace, Space, Escape, Tab, and a GUI key such as the Windows key. You can modify the program to put any command in any of these slots. This is just a suggestion.

Several of the buttons operate identically in either mouse or arrow mode. The top row of buttons toggle the Alt, Control, and Shift keys. The “Mode” button toggles between mouse mode and arrow mode. The “Release” button releases all held mouse buttons and toggle keys. Here is a graphic which shows which of the buttons on the remote performed which functions in either mouse mode or arrow mode.

Assigning Commands to Buttons

Assigning Commands to Buttons

One of the RGB pixels will show red, green, or blue if the Alt, Control, or Shift toggles are on. The other pixel shows blue when the left mouse button is dragging and read when the right mouse button is dragging. It shows green when you are in arrow mode.

The NEC protocol we are using sends a special code of 0xffffffff as a repeat code whenever you hold down a button. In order to process this we will always store any received codes so when we receive the repeat code we know what function to repeat. However the toggle keys should not be repeated without lifting off of the button so we have zeroed out the previous code when pressing one of those toggles.

Here is a complete listing of the code.
/* Example program for from IRLib – an Arduino library for infrared encoding and decoding
* Version 1.1 April 2013 by Chris Young http://tech.cyborg5.com
* "IRmouse" Control a PCs mouse or arrow keys using an IR remote
*/
#include
#include
#include
//The IR codes shown below are for the Adafruit mini remote
//which uses an easy protocol. The comments after each code refer to the buttons
//on that remote and not to their actual function on this device.

//Codes used by both mouse and arrow modes
#define CodeAlt 0xfd00ff //Vol-
#define CodeCtrl 0xfd807f //Play/Pause
#define CodeShift 0xfd40bf //Vol+
#define CodeRls 0xfda857 //5
#define CodeMode 0xfd9867 //8

//Used by mouse and arrow but have different meanings
#define CodeUp 0xfda05f //Up arrow
#define CodeDown 0xfdb04f //Down arrow
#define CodeLeft 0xfd10ef //Left arrow
#define CodeRight 0xfd50af //Right arrow

//Used only in mouse mode
#define CodeUpLf 0xfd20df //Set up
#define CodeUpRt 0xfd609f //Stop/mode
#define CodeLfClk 0xfd906f //Enter/save
#define CodeDnLf 0xfd30cf //0 10+
#define CodeDnRt 0xfd708f //Repeat
#define CodeLfDrag 0xfd08f7 //1
#define CodeRtDrag 0xfd8877 //2
#define CodeRtClk 0xfd48b7 //3
#define CodeFaster 0xfd28d7 //4
#define CodeScrUp 0xfd6897 //6
#define CodeSlower 0xfd18e7 //7
#define CodeScrDn 0xfd58a7 //9

//Arrow mode only
#define CodeHome 0xfd20df //Set up
#define CodePgUp 0xfd609f //Stop/mode
#define CodeEnter 0xfd906f //Enter/save
#define CodeEnd 0xfd30cf //0 10+
#define CodePgDn 0xfd708f //Repeat
#define CodeGUI 0xfd08f7 //1
#define CodeInsert 0xfd8877 //2
#define CodeDelete 0xfd48b7 //3
#define CodeBkSp 0xfd28d7 //4
#define CodeSpace 0xfd6897 //6
#define CodeEsc 0xfd18e7 //7
#define CodeTab 0xfd58a7 //9

#define Bright 16 //brightness of pixels

#define MOUSE_MODE 0
#define ARROW_MODE 1
#define MAX_MODE (ARROW_MODE+1)

#define MOUSE_LED 0
#define SHIFT_LED 1

Adafruit_NeoPixel strip = Adafruit_NeoPixel(2, 6, NEO_GRB + NEO_KHZ800);//Output pin 6
IRrecv My_Receiver(11); //Input pin 11
IRdecodeNEC My_Decoder;

int Speed;
int Current_Mode;
char Control_State;
char Shift_State;
char Alt_State;
long Previous;
uint32_t Shift_Status, Mouse_Status;

void UpdateStatus () {
Mouse_Status=0;
Shift_Status=0;
strip.setPixelColor(MOUSE_LED,Bright*Mouse.isPressed(MOUSE_LEFT),Bright*Current_Mode,Bright*Mouse.isPressed(MOUSE_RIGHT));
strip.setPixelColor(SHIFT_LED,Bright*Alt_State,Bright*Control_State,Bright*Shift_State);
strip.show();
};
//This Change_Mode routine is overly complex but it's a holdover from earlier code
//where I had three modes instead of two. Note we do not want to repeat feature
//on this function or on the toggle functions so we set Previous=0
void Change_Mode () {
Current_Mode=(++Current_Mode) % MAX_MODE;
Previous=0; UpdateStatus(); delay(500);
};

void setup() {
strip.begin(); strip.show();
Shift_Status=0; Mouse_Status=0;
My_Receiver.enableIRIn(); // Start the receiver
Current_Mode=0;
Control_State=0; Shift_State=0; Alt_State=0;
Speed=8; Previous=0; UpdateStatus();
Mouse.begin();
}

void Toggle_Mouse(int Button) {
if(Mouse.isPressed(Button)) Mouse.release(Button);
else Mouse.press(Button);
Previous=0; UpdateStatus(); delay(500);
}

void Mouse_Mode() {
switch (My_Decoder.value) {
case CodeLeft: Mouse.move(-Speed,0,0); break;
case CodeRight: Mouse.move( Speed,0,0); break;
case CodeUp: Mouse.move(0,-Speed,0); break;
case CodeDown: Mouse.move(0, Speed,0); break;
case CodeUpRt: Mouse.move( Speed,-Speed,0); break;
case CodeUpLf: Mouse.move(-Speed,-Speed,0); break;
case CodeDnLf: Mouse.move(-Speed, Speed,0); break;
case CodeDnRt: Mouse.move( Speed, Speed,0); break;
case CodeLfClk: Mouse.release(MOUSE_LEFT); Mouse.click(MOUSE_LEFT); delay(400);break;
case CodeRtClk: Mouse.release(MOUSE_RIGHT); Mouse.click(MOUSE_RIGHT); delay(400);break;
case CodeLfDrag: Toggle_Mouse(MOUSE_LEFT); break;
case CodeRtDrag: Toggle_Mouse(MOUSE_RIGHT); break;
case CodeFaster: Speed=min(30,++Speed); delay(100); break;
case CodeSlower: Speed=max(1,--Speed); delay(100); break;
case CodeScrUp: Mouse.move(0,0,1); delay(100); break;
case CodeScrDn: Mouse.move(0,0,-1); delay(100); break;
};
};

void Toggle_Key(char *Toggle,char Key) {
if(*Toggle){
Keyboard.release(Key); *Toggle=0;
}
else{
Keyboard.press(Key); *Toggle=1;
};
Previous=0; UpdateStatus(); delay(500);
};
//Releases all held mouse buttons and toggle keys
void Release_All() {
Keyboard.releaseAll();
Mouse.release(MOUSE_LEFT); Mouse.release(MOUSE_RIGHT); Mouse.release(MOUSE_MIDDLE);
Alt_State=0; Control_State=0; Shift_State=0;
UpdateStatus();
};
//In my experience some keys work better if you put a little extra delay.
void Key_Press (char Key,int D) {
Keyboard.write(Key); delay(150+D);
}

void Arrow_Mode() {
switch (My_Decoder.value) {
case CodeLeft: Key_Press(KEY_LEFT_ARROW,0); break;
case CodeRight: Key_Press(KEY_RIGHT_ARROW,0); break;
case CodeUp: Key_Press(KEY_UP_ARROW,0); break;
case CodeDown: Key_Press(KEY_DOWN_ARROW,0); break;
case CodeInsert: Key_Press(KEY_INSERT,0); break;
case CodeEnter: Key_Press(KEY_RETURN,100); break;
case CodeBkSp: Key_Press(KEY_BACKSPACE,100); break;
case CodePgUp: Key_Press(KEY_PAGE_UP,200); break;
case CodePgDn: Key_Press(KEY_PAGE_DOWN,200); break;
case CodeHome: Key_Press(KEY_HOME,0); break;
case CodeEnd: Key_Press(KEY_END,0); break;
case CodeGUI: Key_Press(KEY_LEFT_GUI, 100); break;
case CodeSpace: Key_Press(32, 100); break;//ASCII space
case CodeEsc: Key_Press(KEY_ESC, 100); break;
case CodeTab: Key_Press(KEY_TAB, 100); break;
};
};
/*
//You can uncomment and use this routine to send control characters such as
//control-z for an undo button or control-c for copy etc.
void Send_Control(char Key,int D) {
Release_All(); Keyboard.press(KEY_LEFT_CTRL);
Keyboard.write(Key); Release_All();delay(150+D); Update ();
}
*/
void loop() {
if (My_Receiver.GetResults(&My_Decoder)) {
My_Decoder.decode();
//Adafruit remote uses NEC protocol which sends a special repeat code
//if you are holding down the same button. We store each received code
//in "Previous" so that we can properly handle repeat codes.
if(My_Decoder.value==0xffffffff)
My_Decoder.value=Previous;
else
Previous=My_Decoder.value;
switch(Current_Mode) {
case MOUSE_MODE: Mouse_Mode(); break;
case ARROW_MODE: Arrow_Mode(); break;
}
switch (My_Decoder.value) {
case CodeMode: Change_Mode(); break;
case CodeAlt: Toggle_Key(&Alt_State,KEY_LEFT_ALT); break;
case CodeShift: Toggle_Key(&Shift_State,KEY_LEFT_SHIFT); break;
case CodeCtrl: Toggle_Key(&Control_State,KEY_LEFT_CTRL); break;
case CodeRls: Release_All(); break;
};
My_Receiver.resume();
}
}

For reference purposes here’s a link to the documentation on the keyboard and mouse libraries for use with Leonardo or other comparable Arduinos.
http://arduino.cc/en/Reference/MouseKeyboard

You will also need the special library for Adafruit RGB NeoPixels which can be downloaded from GitHub.
https://github.com/adafruit/Adafruit_NeoPixel

Simply download and unzip the library into your library folder.

Note that the latest Arduino IDE (version 1.0.5 as I write this) lists the Arduino Micro as one of the boards it supports. When using either the Leonardo or Micro you will need a special driver for Windows computers. This driver is available in the driver’s library of the latest Arduino IDE. The latest drivers combine drivers for all of the supported boards into a single Windows 8 compatible signs package.

Simply plug the Arduino Micro into the USB port, upload the sketch, and then point your remote at the receiver. The device initializes into mouse mode so you should be able to move the mouse around using the arrow keys. Try switching to arrow mode using the “Mode” button. Go back to mouse mode and try pressing the faster or slower buttons. You won’t notice anything while pressing them however subsequent mouse movements will be faster or slower.

Here are links to the hardware mentioned in this tutorial:

Here are links to hardware used in the original IR mouse and keyboard emulator. At some point I will clean up the code on that project and publish it. If you have an immediate use for such a device, feel free to contact me and I will give you what I have but for now it’s not really fit for public consumption.

IRLib Tutorial part 3: Overview Sending IR Codes

Part 3 of this tutorial is so big we have spread it over 4 installments. This blog post is just to pull all of those post together in a single location.

Part 3a: Sending IR Codes
In this segment we create a small Arduino sketch that allows you to type IR codes into the serial monitor and have them transmitted by your IR LED.

satb100Part 3b: Creating a Virtual Remote Using Python
In the segment we use a Python script on a PC or Raspberry Pi to communicate over the serial port with the Arduino. By clicking on the virtual buttons on the PC, the Python script transmits the codes to the Arduino which in turn translates into your device by your IR LED.

Part 3c: Python, PySerial and PyGame Installation on Windows
Because Python and the other tools for creating the Virtual Remote may not be on your system, we have included this extra tutorial on how to install the necessary software on a Windows PC. While it isn’t technically connected to IRLib, we thought it would be useful to a variety of people not just users of our library.

Part 3d: Installing the Arduino IDE on a Raspberry Pi
Again this is not strictly related to IRLib but if you want to run the Part 3b example on a Raspberry Pi you will need to install the Arduino IDE. General users of Arduino and Raspberry Pi might be interested in this even if they do not use our libraries. If you do not use a Raspberry Pi then you do not need this part of the tutorial.

IRLib Tutorial part 3d: Installing the Arduino IDE on a Raspberry Pi

As we mentioned in part 3c, this section of the tutorial doesn’t have anything to do with IRLib specifically, however if you have not already installed the software necessary to run the tutorial part 3b then you will have to follow these instructions. In this section we will install the Arduino IDE on a Raspberry Pi. If you’re not using Raspberry Pi as a host machine but are using Windows like we did in part 3c then you do not need this tutorial at all.

Note: This article has only been tested with Arduino IDE version 1.0.x and not with the beta version 1.5.x. We cannot guarantee these procedures will work with the new version which may have a totally different structure since it is a fairly big upgrade.

We are assuming that you are using a plain vanilla Raspbian Wheezy OS on your Raspberry Pi. We cannot guarantee any of these instructions will work on other versions of the operating system. We are also assuming that your Raspberry Pi has Internet access for downloading updates. If your Raspberry Pi is not connected to the Internet you’ll have to figure out how to get the necessary files onto your system by an alternate means.

Raspbian Wheezy is actually a version of Debian Linux and according to the following reference http://playground.arduino.cc/Linux/Debian the Arduino IDE has already been prepackaged for easy installation. Go to a command prompt and type the following command
sudo apt-get install arduino
Breaking this command down for those of you who may not be familiar with Linux commands… The “sudo” stands for “Super User Do”. Access to the root directory and installation on your machine requires superuser privileges. This command temporarily gives you those privileges. And what are you going to do with them? You’re going to run the “apt-get” command. This is a system already set up in most Linux distributions to get various programs from a central repository. And the command that we passed this program is “install arduino”. I take the time to explain all of that because when I was new to Linux and didn’t know what I was doing, I would ask a question on the support forum and they would give me some obscure line of text type and I had absolutely no idea what I was doing or why.

This process not only installs the necessary Arduino components it also installs and/or updates various Java components necessary to run the Arduino IDE. If you do not have Internet access and did not use the “apt-get” command to install the package but simply copied the programs over to your Raspberry Pi, then you do not have the full package. The process of getting those additional Java packages is beyond the scope of this tutorial.

When the installation is completed most of the software is installed in the folder “/usr/share/arduino” and the folders inside that include “hardware”, “lib”, “libraries”, and “tools”. There is also an alias for the “examples” and “reference” folders however these folders are actually stored in “/usr/share/doc/arduino-core/”.

Also upon completion you will discover that your GUI start menu now has a new folder and it called “Electronics” which contains a link to the Arduino IDE as seen here.
startmenu
If you would like a shortstop on your desktop, the easiest way to do it is to collect up on the start but do not actually click on it. Instead do a right-click and there will be an opportunity to “Add to desktop” as seen here.
add2desktop
You now have an Arduino IDE shortcut on your desktop. For future reference your desktop icon is at /usr/share/pixmaps/arduino.xpm
icon
If you double-click on the desktop icon on select it from the start menu the Arduino IDE the first thing you will want to check is the version number. As of this writing the pre-packaged version of Arduino was only at version 1.0.1 however the most recent version was 1.0.4 which among other things added support for other Arduino boards such as the Arduino Esplora and Arduino Micro. If the above installation process did not get you the latest version then you will have to manually updated yourself. We successfully used the procedure below to update from 1.0.1 up to 1.0.4 and a week or so later ran the process again to get up to 1.0.5.

We’re going to assume you are starting out in a directory called “/home/pi” where “pi” is your username. If you’re logged in under a different username that will be different naturally. We recommend that you create a directory for downloading programs. At the command prompt type
mkdir downloads
Which obviously makes a directory called “downloads”. Then type…
cd downloads
Which changes your current directory to the downloads directory or folder. Then you should type the following command
wget http://arduino.googlecode.com/files/arduino-1.0.5-linux32.tgz
The “wget” command gets a file from the web. If you are installing something newer than 1.0.5 you will have to change the filename. If you are uncertain of the filename, call up a web browser in your computer and go to http://arduino.cc/en/Main/Software and then right-click on the 32-bit Linux link and copy shortcut. Then paste that text somewhere so that you can see the proper filename for the most recent version.

We will now use the “tar” utility to unzip the archive that we have downloaded. Issue the following command.
tar zxvf arduino-1.0.5-linux32.tgz
This will create a folder under your downloads folder called “arduino-1.0.5”. Then change to that folder with this command.
cd arduino-1.0.5
We now want to get rid of the “hardware/tools” folder inside the unzipped distribution. That is because the version that we have downloaded is compiled for an Intel x86 or AMD x86 processor and not the ARM chip that is in your Raspberry Pi. We will use the “rm” command to “remove” that folder.
rm -rf hardware/tools
Now we will copy using “cp” to copy the other files into their proper locations. We will go through the subfolders and overwrite any existing files.
cp -ru lib /usr/share/arduino
cp -ru libraries /usr/share/arduino
cp -ru tools /usr/share/arduino
cp -ru hardware /usr/share/arduino
cp -ru examples /usr/share/doc/arduino-core
cp -ru reference /usr/share/doc/arduino-core

Note some readers of this blog have reported that they needed to pre-append “sudo” to these commands above. If you are having difficulty with these commands you should try using “sudo cp -ru… etc.” instead.
Now if you launch the Arduino IDE you will see that the version has been updated. In this image we had only updated it to 1.0.4 but you can see it does have the additional boards that were missing from the 1.0.1 installation.
boards
One last item… If you were doing this in order to run the IRLib tutorial part 3b on your Raspberry Pi then you will also need Python, PySerial, and Pygame. Fortunately Python and Pygame are already installed on your system. Be sure to use the Python 2 and not Python 3. You will however have to install the PySerial module with the following command.
sudo apt-get install python-serial
That should be all you need.

IRLib Tutorial part 3c: Python, PySerial and PyGame Installation on Windows

Although technically this installment of our tutorial isn’t directly related to IRLib, we are including it here as part 3c because it may be necessary to do these steps if you want to use the example in part 3b of our tutorials.

We’re going to take you step-by-step through installing Python and other necessary modules on a Windows system. We used this method on a Windows 7 64-bit home premium PC. Other versions of Windows will have extremely similar installations.

In order to use the previous examples, we highly recommend that you use Python 2 rather than Python 3 and we recommend that you use the 32-bit version even if you are on a 64-bit Windows machine. You might be able to get our examples to work under 64 bits or Python 3 but we were warned there might be problems and we did encounter them and chose not to try to come up with workarounds.

 Installing the Python Interpreter

Python is an interpreted language rather than a compiled language. The Python interpreter is a program that runs on your PC, reads the text script of your Python program and executes the script rather than compiling it into native machine language for your type of hardware. You can download the Windows version of Python 2 or 3 at…

http://www.python.org/download/releases/

As of this writing the most recent version of Python 2 is 2.7.5 dated May 15, 2013. Download the file named “Windows x86 MSI Installer (2.7.5) (sig)” you can save the program and run it from the same location or run it immediately.

01 downloadInstall the program for all users.

02 all usersChoose your directory. The default will work.03 directory

The default for customization is install everything. That will work fine.

04 customize

And complete the installation

04 finishWhen you completed the installation the following items will be in your start menu.

06 start menuThere is a command line version that can run scripts directly or there is an IDE called “IDLE”. In our previous installment of the tutorial we use the IDE.

There is one more item we need to do to complete this installation. We need to add the Python interpreter to the default system path so that when you try to execute a Python script it will know where to find the interpreter. The process is slightly different on Windows XP versus Windows Vista, 7, or 8.

 Adjusting the path on Windows Vista, 7, or 8…

Go to your Control Panel and click on “System”. If you are in icon view you can click on “System” directly. If you are in category view you should click on “System and Security” and then click on “System”. You should next click on “Change Settings” as shown here

07 change settingsYou will get a system properties dialog that looks like this. You should click on the “Advanced” tab.

08 system propertiesNext click on environment variables.

09 advancedYou’ll get the Environment Variables dialog which looks like this.

In the upper section look for the item “Path”. Select it and click on “Edit” just below it.

11 pathThen very carefully go to the end of the variable value and add a semicolon followed by the path where you installed Python. Make sure do not erase any other text that was previously there. On my system I added “;C:\Python22” to the end of the value. Then click on okay and continue out of all of the open dialogues. You can now proceed to the next section where we will install pySerial.

Adjusting the path on Windows XP

Go to your Control Panel and click on “System”. If you are in classic icon view you can click on “System” directly. If you are in category view you should click on “Performance and Maintenance” and then click on “System”. Unlike later versions of Windows, this will take you directly to the “System Properties” dialog. You do not need to click on any “Change Settings” link. It will look like this…

08 system properties XPClick on the tab labeled “Advanced” and it will look like this

09 advanced XPClick on the “Environment Variables” button and you will see the following dialogue.

10 environment variables XPIn the lower section look for the item “Path”. Select it and click on “Edit” just below it.

11 path XPThen very carefully go to the end of the variable value and add a semicolon followed by the path where you installed Python. Make sure you do not erase any other text that was previously there. On my system I added “;C:\Python22” to the end of the value. Then click on okay and continue out of all of the open dialogues. You can now proceed to the next section where we will install pySerial.

Installing PySerial

Next we will install the PySerial module which will allow us to do serial communication through Python. The main page for the PySerial code is…

http://pyserial.sourceforge.net/

Click on the “Download Page” link as shown here
20 pySerialAt click on the big green download button. Save the file to a convenient location. Note that the version “2.6” refers to the pySerial version and not to the version of Python which you are running.

21 downloadUnzip the file. If you do not have a utility that can handle .tar.gz compressed files we recommend using “7 Zip” which can be downloaded here…

http://www.7-zip.org/

Now we will have to do something that Windows users rarely do. We need to type some command lines to install the package. Click on your start button and choose the “run” command and then type “cmd”.
22 run command
23 run dialog cmd

Or alternatively you may have a command prompt shortcut in your start menu under accessories as shown here.
24 command prompt

When the command line window comes up you need to change directories to where you unzipped the pySerial package. In my case it was in the c:\downloads\pyserial-2.6 so the command was…

cd c:\downloads\pyserial- 2.6

Then type the following command…

python setup.py install

25 set up install

When the installation is complete type “exit”
26 exit

 Instructions for Installing Pygame

Our final step is to install the Pygame package. You can download it at

http://www.pygame.org/

Click on the download link in the upper left menu

30 pygame

Scroll down to the section for windows and click on the link labeled “pygame-1.9.1.win32-py2.7.msi”
31 download

Or whatever the most recent 32-bit Windows installer link is. Simply run the installer and use all of the default settings to complete installation.

That’s everything you need to know to install Python, PySerial and Pygame on a Windows machine.

If you are using a Raspberry Pi you will already have Python and Pygame installed with the standard version of Raspbian. To install PySerial simply go to a command prompt and type

sudo apt-get install python-serial

This tells it to issue a superuser command to get the package and install it. In the next installment of this tutorial we will talk about how to install the Arduino IDE on a Raspberry Pi.

IRLib Tutorial part 3b: Creating a Virtual Remote Using Python

satb100In the previous lesson we demonstrated how to send IR codes to a TV, DVD, DVR/cable box or any other device that uses an infrared remote. In order to tell the Arduino what code to send, we typed codes into the serial monitor of the Arduino IDE. While that’s great for demonstration purposes, it’s not very practical. In this continuation of the lesson, we will create a small program using Python which will create a “virtual remote”. This Python script will run on your PC, laptop or even Raspberry Pi which is connected to the Arduino. As you click on the buttons on the app, the script will send the proper codes over the serial link to the Arduino. The Arduino in turn will send the IR signals to your device. In addition to the items listed in part 3a will also need…

  • a PC, laptop or even a Raspberry Pi with the Arduino connected to a USB port.
  • Python 2.x programming environment installed
  • PySerial add-on for Python that enables serial communication
  • PyGame add-on for Python that makes it easy to use graphics, mouse, keyboard
  • IRLib version 1.1 or later which includes the sample code

  • At the end of this tutorial we will post links to the Python, PySerial and PyGame packages. In part 3c of this tutorial we will give detailed instructions on how to install these passages on a Windows PC and a Raspberry Pi. When using Raspberry Pi it will probably already have Python and probably PyGame installed or you can find instructions on how to install them elsewhere online. We will include instructions on installing PySerial, the Arduino IDE and the IRLib packages on Raspberry Pi.

    This example assumes you are using Python 2.7.x or later. Python 3 has some problems with serial communication especially in the Windows version. We also highly recommend installing the 32-bit version even if you have a 64-bit computer. We cannot guarantee this will run on 64 bits. Similarly when installing PySerial we recommend the 32-bit version.

    Presuming you already have these packages installed we can proceed to customize a Python script to create virtual remote. In the previous installment we had you use the dump routine on your Arduino to capture the protocols, codes and number of bits for the functions you want to use. Our Python app can handle up to 40 functions however you can leave some of the buttons empty if you wish. But if you’re not yet done so, go back to the previous lesson and write down a whole bunch of codes you want to put in this new remote.

    The Python script we will use is available in IRLib/examples/IRserial_remote/IRserial_remote.py. You also need the files “click.wav” and “remotebg.png” in the same folder. You will have to edit several lines of the script to customize it for your purposes.

    A few lines into the script we will have to edit the serial port that the script we use to communicate to the Arduino. Look for these lines…


    # You will have to edit this to the proper port and speed
    ser = serial.Serial('COM4', 9600)

    As distributed it is set to “COM4” but on a PC it might be some other COM port or on a Linux machine such as a Raspberry Pi it would be something like

    ser = serial.Serial('/dev/ttyACM0', 9600)

    We also need to specify what font will be used to put the labels on the buttons a few lines down like this…


    # Specify a font. I'm using Arial narrow bold from my Windows
    # font folder. However the default font shown below also works.
    myfont =pygame.font.Font ("c:/windows/fonts/ARIALNB.TTF",30)
    #myfont=pygame.font.Font(None,36)

    By the way if you are not familiar with the Python language it uses a hash tag at the beginning of the line to specify it is a comment. The default is a Windows font that is Arial narrow bold that you can specify your own font of choice or used default font by substituting the word “None” as shown above. Look for the section where we define the label text each button. Here are the values as distributed.

    # These are the text labels that will appear on each button
    label_text=("TVp", "CBp", "P^", "Pv",
    "<<", ">", ">>", "->",
    "Rec", "=", "s", "<-", "Gd", "^", "Fav", "Inf", "<", "sel", ">", "Lis",
    "ret", "v", "Prv", "Mnu",
    "1", "2", "3", "Ch+",

    "4", "5", "6", "Ch-",
    "7", "8", "9", "Vol+",
    "Pip", "0", "Mut", "Vol-",
    )

    These correspond to TV power, cable box power, Page Up, Page Down, rewind, play, fast-forward, jump to live, record, pause stop, jump back, Up Arrow, favorites, info, Left Arrow, Select, Right Arrow, Lists Recordings, Return, Down Arrow, Previous Channel, Menu, numbers 1 through 9 and 0, Channel up, Channel down, Volume up, Volume Down, Mute, and PIP. However you can make them say anything you want.

    Below that we insert the actual codes. We will use the same format we used in the previous lesson when we type codes into the serial monitor. First is a single digit that describes the protocol number, followed by a hex value, followed by the number of bits. Note that when some protocols the number of bits is optional. Here are the codes I used for a Magnavox TV using the “RC5” protocol and 13 bids And a Scientific Atlantic SA 8300 DVR using the PANASONIC_OLD protocols.


    IR_Codes= ("3,180c,13","5,37c107","5,36d924","5,37d904",
    "5,37291a","5,37990c","5,36293a","5,36b129",
    "5,375914","5,374117","5,365934","5,37c906",
    "5,36c127","5,36812f","5,37f101","5,36213b",

    "5,37810f","5,366133","5,364137","5,36c926",
    "5,366932","5,37a10b","5,36e123","5,373918",
    "5,36113d","5,37111d","5,36912d","5,377111",

    "5,37910d","5,365135","5,375115","5,36f121",
    "5,36d125","5,37d105","5,363139","3,1810,13",
    "5,37b908","5,373119","3,180d,13","3,1811,13",
    )

    Once you have everything edited using your codes you should then load the IRserial_remote sketch into your Arduino. You can try typing a few codes into the serial monitor to make sure it’s working but once you are sure the sketch is running properly you need to close the serial monitor and the Arduino IDE so that they do not tie up the serial port. If you do not close at least the serial monitor, your Python script may not be able to connect to the Arduino properly.

    Then run the Python script IRserial_remote.py script. A window should pop up showing a virtual remote control with 40 buttons on it looking something like this…

    Virtual TV Remote using Python

    Virtual TV Remote using Python


    Notice as you hover your mouse over each button, the text will turn red. If you click on the button with the mouse it will make a clicking noise and it will instruct the Arduino send the proper IR codes. If everything works properly you should be able to control your device. Here is a YouTube video demonstrating how it works.

    It’s not our intent to make this a Python tutorial so we will not go through the Python script line by line to explain how it works. Also included in the examples folder under IRserial_remote is a folder called “povray” which contains the source file for the Persistence of Vision Ray Tracer POV-Ray which is a freeware rendering program which was used to create the background image for the buttons on the remote.

    Here is a video which demonstrates this application. This video was shown on the weekly Adafruit Show and Tell video chat on Google+ You can click on the “As seen on Show-and-Tell” logo at the top of this post to see it on the show and tell.

    As promised here are links to various downloads you may need for this tutorial

    In the next installment we will show you how to install these packages in case you haven’t already done so.

IRLib Tutorial part 3a: Sending IR Codes

In this lesson we will demonstrate how to send IR codes to a TV, DVD, DVR/cable box or any other device that uses an infrared remote. You will need…

  • a 38 kHz IR receiver module,
  • an IR LED and driver circuit such as described in part 1 of this tutorial,
  • a TV, DVD, DVR or whatever device to control,
  • an IR remote control for that device so we can obtain the proper codes.

Begin the process by wiring an IR receiver to pin number 11 on your Arduino as described in part 1 of this tutorial. Hook up an IR LED and a driver circuit also described in part 1 of this tutorial. If you are using Arduino Uno it will connect to pin 3. On the Arduino Leonardo you should use pin 9

Now you should load the IRrecvDump sketch from the examples folder of the IRLib library. We will use this sketch to determine what codes your infrared remote is transmitting. Run the sketch and open the serial monitor. This is the same process described in part 2 of this tutorial. Write down the received codes for all of the major functions of your device such as power on, channel up and down, volume up and down, rewind, fast-forward, play, stop etc. Also make note of the protocol and the number of bits. Here is what the dump for the power on function looks like on my Magnavox TV
Decoded RC5: Value:180C (13 bits)
Raw samples(24): Gap:30014
Head: m850 s900
0:m900 s900 1:m1700 s900 2:m900 s900 3:m850 s900
4:m850 s900 5:m850 s900 6:m900 s850 7:m900 s1750
8:m900 s850 9:m1750 s900 10:m900
Mark min:850 max:1750
Space min:850 max:1750

As before, you only need to concern yourself with the first line of text. The protocol is “RC5” the code is “180C” and it uses 13 bits.

We are going to presume that you are using a remote that has a protocol that this library understands. If the top line of the dump says “Decoded Unknown” then you will have to skip ahead to section on how to program your own protocol in a future lesson of this tutorial.

Now load the following sketch named “IR_serial_remote” which is shown here. It is also available in the latest update to IRLib version 1.1 which was uploaded to GitHub on April 21, 2013 or later. This upgrade to the library also contains some other minor enhancements and a copy of the “IRservo” example used in part 2 of this tutorial.
#include

IRsend My_Sender;

int protocol;
long code;
int bits;
void setup() {
Serial.begin(9600);
}

long parseHex (void) {
long Value=0; char C;delay(100);
while (Serial.available()>0) {
C= tolower(Serial.read());
if ((C>='0')&&(C<='9')) C=C-'0'; else if ((C>='a') && (C<='f')) C=C-'a'+10; else return Value; Value= C+(Value<<4); }; return Value; } void parseDelimiter () { char C; while(Serial.available()>0) {
C=tolower(Serial.peek());
if( (C>='0') && (C<='9') )return; if( (C>='a') && (C<='f') )return; C=Serial.read();//throwaway delimiters delay (5); } } // enum IRTYPES {UNKNOWN, NEC, SONY, RC5, RC6, PANASONIC_OLD, JVC, NECX, HASH_CODE, LAST_PROTOCOL=HASH_CODE}; void loop() { if (Serial.available ()>0) {
protocol = Serial.parseInt (); parseDelimiter();
code = parseHex (); parseDelimiter();
bits = Serial.parseInt (); parseDelimiter();
/* Serial.print("Prot:"); Serial.print(protocol);
Serial.print(" Code:"); Serial.print(code,HEX);
Serial.print(" Bits:"); Serial.println(bits);
*/
My_Sender.send(IRTYPES(protocol), code, bits);
}
}

Upload the sketch and open the serial monitor. We will type in the protocol number, function code, and the number of bits for one of the functions that you wrote down. For example to turn on my TV I would type in

3,180c,13

The “3” is the number of the protocol that I’m using. If you look in “IRLib.h” at about line 50 you will see the following enum definition.

enum IRTYPES {UNKNOWN, NEC, SONY, RC5, RC6,
PANASONIC_OLD, JVC, NECX, HASH_CODE,
LAST_PROTOCOL=HASH_CODE};

You can send that “RC5” is the third protocol. In my examples I will also be using protocol 5 which is “PANASONIC_OLD” which is the protocol used by my Scientific Atlantic SA 8300 HD cable box/DVR.

After typing in the protocol number, code, and number of bits in the serial monitor you should press enter or click on the “send” button. The Arduino should decode this information and send the proper signals from your IR LED. If you want to make sure that what you are typing is getting parsed you can uncomment the “Serial.print…” statements near the end of the sketch.

Here are the details on how the sketch works…

We start by including the IRLib.h file for the library. We create the sender object and create some integers to store the protocol number, code, and number of bits. The setup routine simply initializes the serial port.

The standard Serial objects include routines for parsing integers in decimal format coming across the serial line but it does not include parsing hexadecimal values so we’ve written a little routine called

long parseHex (void)

Which accepts characters “0” through “9” and “A” through “F” either upper or lower case and converts it into an integer value. We also have a routine called

void parseDelimiter ()

It skips over any commas, blanks or other extraneous characters which you use as a separator.

The main loop simply looks for serial characters available, parses them, and then sends them using the send method as follows

My_Sender.send(IRTYPES(protocol), code, bits);

Note that because the protocol is actually an enum rather than an integer we have to typecast it when passing it to the send method.

Of course it would be quite tedious to have to look up the protocol number, hex codes, and number of bits every time you wanted to send a function. So we’re going to write a program which will send that serial data from your PC to the Arduino. We will create a “virtual remote control” in which you can click on buttons on it will send that serial data to the Arduino which will in turn control your device.

In part 3b we will show you how to use a Python script to create just such a virtual remote and send the codes from your PC or laptop to the Arduino.

IRLib Tutorial part 2: Controlling a Servo Using an IR Remote

As seen on Show-and-TellIn this lesson we will demonstrate how to receive IR codes and to use that information to do something useful. In this case we’re going to position a servo. You will need

  • a 38 kHz IR receiver module
  • a servo motor that uses PWM for positioning
  • an IR remote control for a TV or VCR or any such device

At the end of this blog we will link to some sources for these items. If you do not have a servo available you should be able to follow the code given here to control relays or turn on and off LEDs or any other function you might control with an Arduino microcontroller.
Begin the process by wiring an IR receiver to pin number 11 on your Arduino as described in Lesson 1 of this tutorial. For this example you do not need to hook up an IR LED. We’re going to be receiving only. Also hook up a servo motor to power and ground and to pin number 9 on your Arduino. This diagram shows the complete set up.

Hardware set up for IR servo control demo

Hardware set up for IR servo control demo


Now you should load the IRrecvDump sketch from the examples folder of the IRLib library. We will use this sketch to determine what codes your infrared remote is transmitting. Run the sketch and open the serial monitor. Point your remote at the receiver and press the right arrow button. In this example I’m using a remote from my Sony DVD/VCR. The output on the serial monitor looks like this…

Decoded Sony: Value:86BCA (20 bits)
Raw samples(42): Gap:12550
  Head: m2300  s650
0:m1200 s600 1:m550 s650  2:m550 s650 3:m500 s650
4:m550 s650 5:m1150 s650  6:m1150 s600 7:m600 s600
8:m1150 s650 9:m550 s650  10:m1100 s650 11:m1200 s600
12:m1150 s650 13:m1150 s600  14:m550 s650 15:m550 s650
16:m1150 s650 17:m550 s600  18:m1200 s600 19:m550
Mark  min:500  max:1200
Space min:600  max:650 

We really only need to concern ourselves with the first line of text of this dump. It says that the protocol that was decoded was “Sony” and that the value was 86BCA which is a number in hexadecimal code. The remainder of the information is unimportant to us. You need to write down the value received for each of the following buttons: right arrow, left arrow, up arrow, down arrow, select, and the number buttons 0 through 9.
We are going to presume that you are using a remote that has a protocol that this library understands. If the top line of the dump says “Decoded Unknown” then you either need to use a different remote or skip ahead to section on how to program your own protocol in a future lesson of this tutorial.
Now load the following sketch named “IR_Servo” and we will modify it with the codes you have obtained. You can click on the little orange pair of scissors to copy the code into your clipboard.

/* Example program for from IRLib – an Arduino library for infrared encoding and decoding
 * Version 1.0  April 2013 by Chris Young http://cyborg5.com
 * "IR_Servo" Control a servo using an IR remote
 */
#include <IRLib.h>
#include <Servo.h> 
// You will have to set these values depending on the protocol
// and remote codes that you are using. These are from my Sony DVD/VCR
#define MY_PROTOCOL SONY
#define RIGHT_ARROW   0x86bca //Move several clockwise
#define LEFT_ARROW    0x46bca //Move servo counterclockwise
#define SELECT_BUTTON 0xd0bca //Center the servo
#define UP_ARROW      0x42bca //Increased number of degrees servo moves
#define DOWN_ARROW    0xc2bca //Decrease number of degrees servo moves
#define BUTTON_0 0x90bca  //Pushing buttons 0-9 moves to fix positions
#define BUTTON_1 0x00bca  // each 20 degrees greater
#define BUTTON_2 0x80bca
#define BUTTON_3 0x40bca
#define BUTTON_4 0xc0bca
#define BUTTON_5 0x20bca
#define BUTTON_6 0xa0bca
#define BUTTON_7 0x60bca
#define BUTTON_8 0xe0bca
#define BUTTON_9 0x10bca
IRrecv My_Receiver(11);//Receive on pin 11
IRdecode My_Decoder; 
Servo My_Servo;  // create servo object to control a servo 
int pos;         // variable to store the servo position 
int Speed;       // Number of degrees to move each time a left/right button is pressed
 
void setup() 
{ 
  My_Servo.attach(9);  // attaches the servo on pin 9 to the servo object 
  pos = 90;            // start at midpoint 90 degrees
  Speed = 3;           //servo moves 3 degrees each time left/right is pushed
  My_Servo.write(pos); // Set initial position
  My_Receiver.enableIRIn(); // Start the receiver
} 
 
void loop() 
{ 
    if (My_Receiver.GetResults(&My_Decoder)) {
       My_Decoder.decode();
       if(My_Decoder.decode_type==MY_PROTOCOL) {
          switch(My_Decoder.value) {
            case LEFT_ARROW:    pos=min(180,pos+Speed); break;
            case RIGHT_ARROW:   pos=max(0,pos-Speed); break;
            case SELECT_BUTTON: pos=90; break;
            case UP_ARROW:      Speed=min(10, Speed+1); break;
            case DOWN_ARROW:    Speed=max(1, Speed-1); break;
            case BUTTON_0:      pos=0*20; break;
            case BUTTON_1:      pos=1*20; break;
            case BUTTON_2:      pos=2*20; break;
            case BUTTON_3:      pos=3*20; break;
            case BUTTON_4:      pos=4*20; break;
            case BUTTON_5:      pos=5*20; break;
            case BUTTON_6:      pos=6*20; break;
            case BUTTON_7:      pos=7*20; break;
            case BUTTON_8:      pos=8*20; break;
            case BUTTON_9:      pos=9*20; break;
          }
        My_Servo.write(pos); // tell servo to go to position in variable 'pos' 
       }
     My_Receiver.resume();
    }
}

First you need to tell it what protocol you have received. Edit it into the line which reads

#define MY_PROTOCOL SONY

In general want to use the protocol name that was shown in the dump routine but it must be in all capital letters. If you want to get technical about it, legal values for this item are shown in the file “IRLib.h” at approximately line 53 which looks like this.

enum IRTYPES {UNKNOWN, NEC, SONY, RC5, RC6, 
  PANASONIC_OLD, JVC, NECX, HASH_CODE, 
  LAST_PROTOCOL=HASH_CODE};

Now back to the sketch… You need to edit into the sketch the values which you copied down for each of your buttons on your remote. Note that since these are hexadecimal numbers you should precede each one with “0x”. So in our example for the right arrow which produced a value of “86BCA” the line should look like this…

#define RIGHT_ARROW   0x86BCA

Note that in hexadecimal numbers when the letters “A” through “F” are used you may use either upper or lower case letters.
Once you have all of the values edited into the sketch, you should upload it. The servo will automatically center itself when the sketch has been uploaded and runs. Point your remote at the IR receiver and press the right or left arrow on your remote. The servo should rotate right or left as you push the buttons. If you push the select button on your remote it should center of the servo again. Pressing the numbers 0 through 9 will position the servo to fixed points 20 degrees apart.
By default, when using the left and right arrow buttons, the servo will rotate left or right by 3 degrees for each push of the button. By using the up arrow or down arrow buttons you can change how far the servo rotates. If you press and hold the down arrow for a couple of seconds it will change the default rotation to 1 degree. Pressing the up arrow button increases it to a maximum of 10 degrees. You won’t see anything happen when you push up or down but subsequent presses of left or right will be faster or slower. Here is a YouTube video demonstrating the project.

Now let’s look at the sketch line by line to see how it works. Just below the section which you edited we define several variables and objects

IRrecv My_Receiver(11);//Receive on pin 11
IRdecode My_Decoder; 
Servo My_Servo;  // create servo object to control a servo 
int pos;         // variable to store the servo position 
int Speed;       // Number of degrees to move each time a left/right button is pressed

We create a receiver object and tell it to look for codes on pin 11. IR codes consist of a series of on and off signals called marks and spaces. The receiver object is an interrupt driven routine that looks for a signal every 50µs. It then stores in a buffer of integers the length of each mark or space in 50µs intervals. The buffer is located in the decoder object so we pass the address of the decoder to the receiver. There are technical reasons why we have separated these processes into receiver and decoder unlike other IR libraries. We will get into that in a future must. As mentioned we also have to create a decoder object. The decoder object looks at the values and attempts to determine which protocol was used and what the data values are that were encoded in the signal. We also create a servo object. Details on the servo library can be found here in the standard Arduino documentation. And we need integers to hold the position and the speed of the servo.
In the “Setup” function we initialize the servo on pin 9 set some default values and give it the command to move the servo into the default position. You then have to use this line

  My_Receiver.enableIRIn(); // Start the receiver

To initialize the IR receiver. In the “Loop” routine we have a single if statement that is constantly looking for an IR code.

    if (My_Receiver.GetResults(&My_Decoder)) {
       My_Decoder.decode();

The “GetResults(address)” function returns true if a code has been received. It puts it into the decoder object whose address you passed to it. You then call the “decode()” method of your decoder.
We next check to see if the results received were from the proper protocol. No need to go through a bunch of testing if you picked up a signal from a different remote. We check to see if the “decode_type” is the right one using this if statement. The variable “My_Decoder.decode_type” is an enum which was shown earlier in this lesson and can be found in “IRLib.h”.

       if(My_Decoder.decode_type==MY_PROTOCOL) {

Finally we check the “My_Decoder.value” in a switch statement to see if any of our defined codes are what was sent. If none of the case statements are activated, the code just falls through and updates the servo at its previous position.
It is important that we restart the IR receiver after any signal has been received even if it’s not one that we were interested in. This is done with the following statement

     My_Receiver.resume();

You could easily modify the sketch to handle multiple servos doing all sorts of things such as positioning a robot arm or steering a remote-controlled car or doing any other function. You could hook up LEDs that would turn off on depending on which button to press on the remote. You could hook up relays to turn lights on motors off and on.
As promised here are some links to the hardware mentioned in this post

In the next lesson we will focus on transmitting IR signals.