C4DI Arduino tutorial 4 Things beginning with the letter i



Similar documents
IR Communication a learn.sparkfun.com tutorial

An Introduction to MPLAB Integrated Development Environment

Animated Lighting Software Overview

cs281: Introduction to Computer Systems Lab08 Interrupt Handling and Stepper Motor Controller

FREQUENCY RESPONSE OF AN AUDIO AMPLIFIER

DS1307 Real Time Clock Breakout Board Kit

Surveillance System Using Wireless Sensor Networks

Using your LED Plus keypad

Inwall 4 Input / 4 Output Module

TUTORIAL FOR INITIALIZING BLUETOOTH COMMUNICATION BETWEEN ANDROID AND ARDUINO

ON-GUARD. Guard Management System. Table of contents : Introduction Page 2. Programming Guide Page 5. Frequently asked questions Page

-Helping to make your life betterwww.person-to-person.net

Building a Basic Communication Network using XBee DigiMesh. Keywords: XBee, Networking, Zigbee, Digimesh, Mesh, Python, Smart Home

AN141 SMBUS COMMUNICATION FOR SMALL FORM FACTOR DEVICE FAMILIES. 1. Introduction. 2. Overview of the SMBus Specification. 2.1.

Your Multimeter. The Arduino Uno 10/1/2012. Using Your Arduino, Breadboard and Multimeter. EAS 199A Fall Work in teams of two!

CONTENTS 4. HOW TO UNSET THE PANEL...7

Eric Mitchell April 2, 2012 Application Note: Control of a 180 Servo Motor with Arduino UNO Development Board

Theory and Practice of Tangible User Interfaces. Thursday Week 2: Digital Input and Output. week. Digital Input and Output. RGB LEDs fade with PWM

CHAPTER 11: Flip Flops

Arduino Lesson 16. Stepper Motors

Using Arduino Microcontrollers to Sense DC Motor Speed and Position

WA Manager Alarming System Management Software Windows 98, NT, XP, 2000 User Guide

Pop-up Surveillance Camera On Your TV

Chord Limited. Mojo Dac Headphone Amplifier OPERATING INSTRUCTIONS

Welcome to life on. Get started with this easy Self-Installation Guide.

The $25 Son of a cheap timer This is not suitable for a beginner. You must have soldering skills in order to build this kit.

Build The Universal Alarm System

INSTRUCTION MANUAL All-In-One GSM Home Alarm System SB-SP7200-GSM

IDS X-Series User Manual D Issued July 2012

Develop a Dallas 1-Wire Master Using the Z8F1680 Series of MCUs

truecall Ltd 2012 Call Recorder and Message Centre guide

CAN-Bus Shield Hookup Guide

2-Line CapTel User Guide

EDA-Z5008 & Z5020. Radio Fire Alarm System. User Manual

500r+ Installation and User Guide

MANUAL FOR RX700 LR and NR

User User Manual Manual Harmony 900

Touch Tone Controller. Model TR16A. Owner s Manual

Introduction to Arduino

Bright House Networks Home Security and Automation Mobile Application. Quick Start Guide

1. Learn about the 555 timer integrated circuit and applications 2. Apply the 555 timer to build an infrared (IR) transmitter and receiver

2 0 Help S Back to the previous instruction 2

Basic Pulse Width Modulation

Personal Assistance System Owner's Guide

Bright House Networks Home Security and Control Mobile Application

Quick Start Guide. Installing. Setting up the equipment

2.0 System Description

Roomie Remote Version 3

Car Alarm Series 2 B 2 Buttons

GSM Home Alarm System User Manual.

Interfacing the Yaesu DR 1X

A REST API for Arduino & the CC3000 WiFi Chip

Breathe. Relax. Here Are the Most Commonly Asked Questions and Concerns About Setting Up and Programming the SurroundBar 3000.

SMS Alarm Messenger. Setup Software Guide. SMSPro_Setup. Revision [Version 2.2]

Using Lync on a Mac. Before you start. Which version of Lync? Using Lync for impromptu calls. Starting Lync 2011

Arduino Lesson 4. Eight LEDs and a Shift Register

INTERFACING SECURITY SYSTEMS TO HOMEVISION

Table of Contents Function Keys of Your RF Remote Control Quick Setup Guide Advanced Features Setup Troubleshooting

Let s Get Connected. Getting started with your Wireless Modem.

Your EdVenture into Robotics You re a Programmer

Lab 6 Introduction to Serial and Wireless Communication

Firmware version: 1.10 Issue: 7 AUTODIALER GD30.2. Instruction Manual

How To Control A Car Alarm On A Car With A Remote Control System

PHYS 2P32 Project: MIDI for Arduino/ 8 Note Keyboard

How to Use Motion Detection in ACTi Cameras

Arduino Lesson 17. Sending Movement Detector

User Manual GSM Alarm System. All rights reserved by Delta Security Co., Ltd

oxigen system Slot.it oxigen timing RMS installation Dongle driver installation 1/ 11 Race Management Software

Business/Home GSM Alarm System. Installation and User Manual

No more nuisance phone calls! Call Recorder and Message Centre Guide

Chapter I Model801, Model802 Functions and Features

An Introduction To Simple Scheduling (Primarily targeted at Arduino Platform)

Wireless Communication With Arduino

DEPARTMENT OF ELECTRONICS ENGINEERING

Adafruit MCP9808 Precision I2C Temperature Sensor Guide

HANDLING SUSPEND MODE ON A USB MOUSE

Controlling a Dot Matrix LED Display with a Microcontroller

Vanderbilt University School of Nursing. Running Scopia Videoconferencing from Windows

The 104 Duke_ACC Machine

Arduino Wifi shield And reciever. 5V adapter. Connecting wifi module on shield: Make sure the wifi unit is connected the following way on the shield:

Your Optus Local Access Telephony User Guide.

GROUPTALK FOR ANDROID VERSION for Android

MONITOR ISM / AFx Multi-Tenant Security System User Guide V1.3

SwannEye HD Plug & Play Wi-Fi Security Camera Quick Start Guide Welcome! Lets get started.

Getting Started Guide

Snow Inventory. Installing and Evaluating

FIRST ALERT INSTRUCTION MANUAL FOR FA 270 KEYPADS SECURITY SYSTEM

Taurus Super-S3 LCM. Dual-Bay RAID Storage Enclosure for two 3.5-inch Serial ATA Hard Drives. User Manual March 31, 2014 v1.2

MeshBee Open Source ZigBee RF Module CookBook

ImagineWorldClient Client Management Software. User s Manual. (Revision-2)

ABUS WIRELESS ALARM SYSTEM

Original brief explanation

Final Design Report 19 April Project Name: utouch

This Document Contains:

MAGICAR M871A. Car alarm with two-way remote User s guide

ADVANCED USER S GUIDE

Home Security System for Automatic Doors

By: John W. Raffensperger, Jr. Revision: 0.1 Date: March 14, 2008

LOCKSS on LINUX. CentOS6 Installation Manual 08/22/2013

Transcription:

C4DI Arduino tutorial 4 Things beginning with the letter i If you haven t completed the first three tutorials, it might be wise to do that before attempting this one. This tutorial assumes you are using the Sparkfun RedBoard Arduino clone. It will work with others (I have tested it on a Leonardo), but it s possible there may be slight differences (e.g. onboard LEDs may be different colours). You can download this tutorial (including any source code) and others from my blog at http://www.robinsonia.com/wp Part 1 Interrupts In a standard Arduino program, there is a main loop, which runs as long as the hardware is switched on. In this loop, all the control processing takes place. Lights are flashed, relays and motors turned on or off, and the states of switches are regularly checked. It s that last item and its associated possible problem which is addressed by this tutorial. Here s a simple loop, which shows what the problem is: boolean LEDstate = false; int buttonpin = 11; void loop() // Do some task that takes a bit of time RepeatedTask(); // Check the button and flip the LED if necessary if (digitalread(buttonpin)==low) LEDstate = ~LEDstate; digitalwrite(13,ledstate); In the code (which you don t need to put on to your Arduino, it s just to look at) some arbitrary task is executed as frequently as possible. After each time the task is executed, a button is checked; if it s pressed, then an LED is lit or extinguished. This is a common and simple way of monitoring a button (it s called polling), and it works very well providing the call to RepeatedTask() does not take very long. Suppose RepeatedTask() takes half a second, however. Half a second doesn t sound long, but you could easily push a button in that time, and the loop would not detect it. You could hold the button down of course. But what if the input were not a button, but a coin sensor, detecting customers putting money into your vending machine? Or a sensor in an intruder alarm? It would be much better if the trigger, whatever it was, could interrupt the RepeatedTask(), do what it needed to do and then carry on where it left off. You ve probably guessed that it is possible to do this with Arduino. The simplest way to do it is with the attachinterrupt(interruptid, ISR, mode) method. Using this, you specify a pin you want to use for the trigger signal (related to interruptid), the method you want to be called when the trigger happens (ISR), and a trigger condition (mode). Not all pins can be used. Depending on the model of Arduino you have, you may have as few as two or as many as five pins which can be used as interrupt triggers. On the Uno (or the RedBoard), you can use pins 2 and 3, which have the interrupt IDs 0 and 1 respectively. The method called when an interrupt happens is known as an Interrupt Service Routine (ISR), and is just a standard Arduino code method of your own. The mode parameter tells the system when you want an interrupt triggered. Because interrupts are generally used to check for things that happen rather than continuing states, you Dr Peter A Robinson http://www.robinsonia.com/wp 1

usually want to check for a change in an input: it s more useful to know that the button has just been pressed (or released) than it is to know that it is down (or up). So you can specify the mode as CHANGE, RISING, FALLING or LOW. RISING will trigger an interrupt if the pin goes from low to high, FALLING if it goes from high to low, and CHANGE will trigger in either case. LOW is a little odd, because it s not a transition, and it will trigger continuously while the pin is held low. It s generally used to wake the Arduino from sleep. Perhaps we ll come back to it later. Here s some code using an interrupt: #define LED_R 9 #define LED_G 10 #define LED_B 5 int led = LED_R; int fadevalue=0; int fadeincrement=1; void setup() // configure pin 2 to be the interrupt trigger pin // and call the changecolour() function when it changes from // high to low attachinterrupt(0,changecolour,falling); // Step the LED colour through red, green and blue each time // the function is called void changecolour() analogwrite(led, 0); switch(led) case LED_R: led = LED_G; break; case LED_G: led = LED_B; break; case LED_B: led = LED_R; break; // In the main body of the program, fade the LED in and out void loop() while (true) fadevalue+=fadeincrement; analogwrite(led, fadevalue); if (fadevalue==255) fadeincrement=-1; delay(500); if (fadevalue==0) fadeincrement=1; delay(500); delay(3); Dr Peter A Robinson http://www.robinsonia.com/wp 2

To make it work, you will need to wire up a button (held high until pressed) to pin 2, and the red, green and blue connections of the RGB LED via resistors to pins 9, 10 and 5. I haven t included a diagram, because you know how to make those connections now. When you run the program, you should see the LED slowly glowing red then fading out, over and over again. That s what the main loop of the program does. When you press the button, however, the interrupt service routine (changecolour()) is called, which cycles the LED to the next colour then continues fading it in and out. It s as simple as that. The important part is that the state of the button is not being checked in the main loop. The interrupt service routine is doing its job. Some relatively wise words about interrupts, which you need to know 1) ISRs should be short. Everything else stops while your ISR runs. Perhaps the best thing to do is to use the ISR to set a flag, or change a variable value which the main loop can check for as part of its regular cycle once control has been returned to it 1. 2) ISRs can t be interrupted. This is another reason to keep them short, of course. What s not obvious, however is that your code is not the only user of interrupts. Many of the Arduino libraries use them too. Serial communications, analog output (which is actually pulse width modulation) and even the system timer rely on interrupts. While your ISR is running, these other processes stop. 3) Inside an ISR, you can t use Arduino functions which use interrupts internally to their operation. For example, the delay() function will not work. Sometimes, it makes sense in your application to turn interrupts off (usually temporarily). You can call detachinterrupt() to remove one you have set up, or you can call nointerrupts() if you want to stop all interrupts from whatever source (and then call interrupts() to turn them back on again). Just remember if you do this that it will stop all interrupt based functionality, as discussed above. 1 But, I hear you say, isn t this the same as just checking the state of the button in the main loop? Good question. It s not the same, because using an interrupt will always catch a short event, whether or not it was happening at the time the main loop was able to check. Setting a flag means that such an event will not be missed, regardless of when it happens. Dr Peter A Robinson http://www.robinsonia.com/wp 3

Part 2 Infra-red remote control Hull University Department of Computer Science This part has nothing to do with interrupts (except that the libraries you will be using need them). This is about making your Arduino respond to an infrared remote control, such as one used for a TV. The remote control used in this example is one from Poundland (guess how much it cost), but you could use almost any other. Infra red remote controls work by flashing a bright LED at a light-sensitive chip. Because the light is infra-red, our eyes can t see it. Mobile phone cameras often can, so if you want to check a remote is working, try that. For a really simple remote control, you could simply switch the IR LED on when you wanted to switch a device on. That would work for one device and one function. To control more, you need to send codes. You could send the codes simply as sequences of regular on/off pulses. This would work, but it would be very susceptible to pulses from other sources of light such as the sun, a television, room lights This noise would interfere with your carefully constructed data, because the receiver could not tell the difference. Imagine sending Morse code using sound, by just sending single clicks with variable length gaps between them. This works fine (think of the old telegraph systems) providing you can hear no other clicking. Other clicky noises from all sorts of sources could easily mess up your signal, especially if they were louder than your real clicks. To get over this problem with Morse code, signals are sent as beeps of varying length. A beep sound is much easier to separate from other noise than a click is, especially if you know what pitch it s supposed to be. Infra red remote controls use the same principle. When they transmit an on pulse it s actually a series of pulses, usually at 38kHz. This is a frequency which is unlikely to occur from any other source (except another remote control). The receiver looks out for signals at this frequency, just as the Morse code receiver listens for the particular pitch of sound, and times how long it lasts. This is known as Amplitude Modulation (AM); a constant frequency signal is switched on or off, and it s the relative lengths and timings of the ons and offs which carry the data. You can do this on an Arduino, of course. Using timers and interrupts, you can send AM signals and listen for them, decoding the pulses into meaningful data. Alternatively, you can use a library that someone else has written, and you can use an infra red detector which filters the raw 38kHz signal back into the original pulses. Guess which we re going to use? The sensor we will use is the VS1838B. This is not included in the Sparkfun RedBoard kit, but it is very cheap, and we have some to lend out. This sensor is used in millions of televisions, DVD players, and other devices which use remotes. It s a cheap, simple (to use, at least I wouldn t want to design one) device which does the 38kHz demodulating for you and has a simple output which goes high when there is a 38kHz infra red signal present, and stays low when there is not. In the picture on the right, the output pin is at the top, ground is the middle pin and the +5V pin is at the bottom. You don t need any resistors to connect it directly to the Arduino. It doesn t decode the signal pulses for you; this requires a code library. Getting the decoding library The infra red library is not part of the standard Arduino install, so you will have to download it from github at https://github.com/shirriff/arduino-irremote. The direct link to a zip file with everything in is https://github.com/shirriff/arduino-irremote/archive/master.zip. It s written by Ken Shirriff, Dr Peter A Robinson http://www.robinsonia.com/wp 4

whose blog at http://www.righto.com/2009/08/multi-protocol-infrared-remote-library.html gives a lot of good information about it and about the coding schemes used for data transmission by infrared remote controls. Download the file and unzip it. In the unzipped results, find the folder which contains IRRemote.cpp. All these files in the s folder (and in the examples folder beneath) should be copied to a folder called IRremote (which you will have to create) in the libraries folder of your Arduino installation. If you are running Windows, this will probably be at C:\Program Files (x86)\arduino\libraries or C:\Program Files\Arduino\libraries. If you are running the Mac or Linux versions, you ll have to find it yourself. Note that the Arduino software may not find the new library until the next time you start it. This library is quite comprehensive. It needs to be, because there are many different data encoding schemes used by the manufacturers of electronic equipment. We will just be using the listening part, which will make available to us the numeric code being sent by the remote control. Because every control uses different codes, you may need to edit the program to use the ones your remote provides. If you are using the Poundland control described earlier, you have lots of options. Because it is a universal one you can program it to send a specific set of commands. The program below expects the TV function to be set for Panasonic televisions (programing code 2027). For any other control, you can use the serial monitor to see what codes your remote control is sending, then modify the code to use them. The hardware setup is fairly straightforward. Here s how to wire it up on the breadboard. Note that the infra red sensor you have does not look like exactly like the one in the diagram, but it should plug directly into the breadboard where the wires are shown in the picture. Don t forget to correct the deliberate mistake in the diagram. Yes, there really is one. Dr Peter A Robinson http://www.robinsonia.com/wp 5

Here s the software to operate it the circuit. There are no deliberate mistakes in this, but I don t guarantee there are no accidental ones. #define LED_R 9 #define LED_G 10 #define LED_B 5 int led = LED_R; int fadevalues[] = 0,0,0; int fadepins[] = 9,10,5; // R,G,B int RGB=0; int RGBchange=0; int fadeincrement=5; int sensorvalue=0; // Set up the Shirriff Infra red receiver library #include <IRremote.h> // select the analog input pin the IR sensor is connected to int RECV_PIN = A3; // Create an IR receiver object, based on the selected pin IRrecv irrecv(recv_pin); // Create an IR code decoder object, for processing the data rom the sensor decode_results results; long myir = 0; void setup() // Open a serial connection to your PC. Needed to print results on the monitor. // Useful for debugging and usng new remotes Serial.begin(9600); irrecv.enableirin(); // Start the IR receiver void loop() // Read the remote code, and store it in the variable results.value if (irrecv.decode(&results)) myir = results.value; // store the value from the IR Remote in variable myir myir = abs(myir); // use the abs command, to ensure we only get +ve values myir = myir % 10000; // IR codes have large values; only the last few digits are interesting Serial.print("IR code received: "); Serial.println(myIR); //Print the IR code to the serial monitor for debug purposes // If the IR code matches volume up or down, change the selected colour's brightness if (myir==7865) fadevalues[rgb]+=fadeincrement; if (myir==3113) fadevalues[rgb]-=fadeincrement; // keep the brightness in the valid range 0-255 if (fadevalues[rgb]<0) fadevalues[rgb] = 0; if (fadevalues[rgb]>255) fadevalues[rgb] = 255; // If the code matches button 1, 2 or 3, change the selected colour if (myir==8449) RGB = 0; RGBchange = 1; if (myir==5753) RGB = 1; RGBchange = 1; if (myir==721) RGB = 2; RGBchange = 1; Dr Peter A Robinson http://www.robinsonia.com/wp 6

// If the selected colour is changed, show the new colour at full brightness // briefly so the user knows what's going to be adjusted if (RGBchange == 1) analogwrite(fadepins[0], 0); analogwrite(fadepins[1], 0); analogwrite(fadepins[2], 0); analogwrite(fadepins[rgb], 255); delay(1000); RGBchange = 0; // Now set all three channels to their desired brightnesses analogwrite(fadepins[0], fadevalues[0]); analogwrite(fadepins[1], fadevalues[1]); analogwrite(fadepins[2], fadevalues[2]); delay(10); // a delay to provide time before resume. irrecv.resume(); // Receive the next value from the IR receiver Assuming that your wiring is correct, when you run the program (don t forget to start the serial monitor once the program is running on the Arduino) you should see output from showing the value received from the infra red sensor. When you press buttons 1, 2 or 3 on the remote, you should see a brief flash of red, green or blue light. The indicates which channel you are selecting. The volume up and volume down buttons then control the brightness of the red, green or blue component of the LED as appropriate. Congratulations! You have a fully controllable colour dimmer. What next? The infra-red library can be used to send signals as well as receiving them. You can wire up an infrared LED in the same way as you would a visible one. Look at the documentation for the library, and see if you can write a program to send data to somebody else s receiver. If you can do that, then modify it to turn your television (or, more entertainingly, somebody else s) off at random intervals Dr Peter A Robinson http://www.robinsonia.com/wp 7