Update – Upcoming Electronics Industry Documentary
Hello readers
Today I am going to introduce something quite different, yet hopefully interesting to you out there. The renowned director and cinematographer Karl von Muller has just released the roll-call trailer for his upcoming documentary titled “State of Electronics” – a discussion on the Electronics Industry in Australia. Although the focus is on the Australian electronics scene, much of the content and discourse within the documentary can be related to by those from many other countries.
However, Karl can explain it better:
After several months of researching, interviewing and filming, I’m excited to present the first public Trailer to my new Documentary “State of Electronics” – A discussion on the Electronics Industry in Australia. Even though the documentary is focused on Australian Electronics Design and Manufacture, much of it applies to all countries from around the world.
The discussion is focused initially on the world of Hobby Electronics and how it’s decline could affect the Electronics Industry in the future. The Documentary then discusses many issues that face industry including the issue of “Repair and Recycle”, “Education”, “Surface Mount Technology”, “Globalisation”, “Opportunities” and many many more off the cuff & candid comments from Industry professionals.
The Documentary features interviews with famous Australians and Industry professionals including Dick Smith, Dave L Jones, Doug Ford, Leo Simpson, Grant Petty, Matthew Pryor, Jonathan Oxer, Andy Gelme, Andrew Griffiths, Eugene Ruffolo & Bill Petreski. In the future, I am planning to interview just a few more before the final release of the Documentary soon.
Shot completely on the Canon 5DMK2, using the Zoom H4N Audio recorder. Directed, Edited and shot by Karl von Moller, this version of the trailer is largely ungraded and only has an FCP sound mix applied. Music track is composed by Karl von Moller also. Enjoy!
Please visit karlvonmoller.com for more on the progress and information on “State of Electronics”
Here is the new roll-call trailer:
… and the original trailer for those unfamiliar with the project:
This will surely be a fascinating and insightful documentary that we are all looking forward to. Nice one Karl!
Tutorial: Arduino and Infra-red control
Learn how to use Arduino and infra-red remote controls in chapter thirty-two of a series originally titled “Getting Started/Moving Forward with Arduino!” by John Boxall – A tutorial on the Arduino universe. The first chapter is here, the complete series is detailed here.
Updated 05/02/2013
In this article we will look at something different to the usual, and hopefully very interesting and useful – interfacing our Arduino systems with infra-red receivers. Why would we want to do this? To have another method to control our Ardiuno-based systems, using simple infra-red remote controls.
A goal of this article is to make things as easy as possible, so we will not look into the base detail of how things work - instead we will examine how to get things done. If you would like a full explanation of infra-red, perhaps see the page on Wikipedia. The remote controls you use for televisions and so on transmit infra-red beam which is turned on and off at a very high speed – usually 38 kHz, to create bits of serial data which are then interpreted by the receiving unit. As the wavelength of infra-red light is too high for human eyes, we cannot see it. However using a digital camera – we can. Here is a demonstration video of IR codes being sent via a particularly fun kit – the adafruit TV-B-Gone:
Now to get started. You will need a remote control, and a matching IR receiver device. The hardware and library used in this tutorial only supports NEC, Sony SIRC, Philips RC5, Philips RC6, and raw IR protocols. Or you can purchase a matching set for a good price, such as this example:
Or you may already have a spare remote laying around somewhere. I kept this example from my old Sony Trinitron CRT TV after it passed away:
It will more than suffice for a test remote. Now for a receiver – if you have purchased the remote/receiver set, you have a nice unit that is ready to be wired into your Arduino, and also a great remote that is compact and easy to carry about. To connect your receiver module – as per the PCB labels, connect Vcc to Arduino 5V, GND to Arduino GND, and D (the data line) to Arduino digital pin 11.
Our examples use pin 11, however you can alter that later on. If you are using your own remote control, you will just need a receiver module. These are very cheap, and an ideal unit is the Vishay TSOP4138 (data sheet .pdf). These are available from element-14 and the other usual retail suspects. They are also dead-simple to use. Looking at the following example:
From left to right the pins are data, GND and Vcc (to Arduino +5V). So it can be easily wired into a small breadboard for testing purposes. Once you have your remote and receiver module connected, you need to take care of the software side of things. There is a new library to download and install, download it from here. Extract the IRremote folder and place into the ..\arduino-002x\libraries folder. Then restart your Arduino IDE if it was already open.
Using Arduino v1.0? Open the file “IRRemoteInt.h” in the library folder, and change the line
#include <WProgram.h>
to
#include <Arduino.h>
Then save and close the file, restart the Arduino IDE and you’re set.
With our first example, we will receive the commands from our remote control and display them on the serial monitor. Download and run the following sketch:
// example 32.1 - IR receiver code repeater
// http://tronixstuff.com/tutorials > chapter 32
// based on code by Ken Shirriff - http://arcfn.com
#include <IRremote.h> // use the library
int receiver = 11; // pin 1 of IR receiver to Arduino digital pin 11
IRrecv irrecv(receiver); // create instance of 'irrecv'
decode_results results;
void setup()
{
Serial.begin(9600); // for serial monitor output
irrecv.enableIRIn(); // Start the receiver
}
void loop()
{
if (irrecv.decode(&results)) // have we received an IR signal?
{
Serial.println(results.value, HEX); // display it on serial monitor in hexadecimal
irrecv.resume(); // receive the next value
} // Your loop can do other things while waiting for an IR command
}
Open the serial monitor box, point your remote control to the receiver and start pressing away. You should see something like this:
What have we here? Lots of hexadecimal numbers. Did you notice that each button on your remote control resulted in an individual hexadecimal number? I hope so. The number FFFFFFFF means that the button was held down. The remote used was from a yum-cha discount TV. Now I will try again with the Sony remote:
This time, each button press resulted in the same code three times. This is peculiar to Sony IR systems. However nothing to worry about. Looking back at the sketch for example 32.1, the
if (irrecv.decode(&results))
section is critical – if a code has been received, the code within the if statement is executed. The hexadecimal code is stored in the variable
results.value
with which we can treat as any normal hexadecimal number. At this point, press a few buttons on your remote control, and take a note of the matching hexadecimal codes that relate to each button. We will need these codes for the next example…
Now we know how to convert the infra-red magic into numbers, we can create sketches to have our Arduino act on particular commands. As the IR library returns hexadecimal numbers, we can use simple decision functions to take action. In the following example, we use switch…case to examine each inbound code, then execute a function. In this case we have an LCD module connected via I2C, and the sketch is programmed to understand fifteen Sony IR codes. If you don’t have an LCD you could always send the output to the serial monitor. If you are using the DFRobot I2C LCD display, you need to use Arduino v23.
Furthermore you can substitute your own values if not using Sony remote controls. Finally, this sketch has a short loop after the translateIR(); function call which ignores the following two codes – we do this as Sony remotes send the same code three times. Again. you can remove this if necessary. Note that when using hexadecimal numbers in our sketch we preced them with 0x.
Download the sketch below from here:
// example 32.2 - IR receiver code translator
// for Sony IR codes (ignores 2nd and 3rd signal repeat)
// http://tronixstuff.com/tutorials > chapter 32
// based on code by Ken Shirriff - http://arcfn.com
#include "Wire.h" // for I2C bus
#include "LiquidCrystal_I2C.h" // for I2C bus LCD module http://bit.ly/eNf7jM
LiquidCrystal_I2C lcd(0x27,16,2); // set the LCD address to 0x27 for a 16 chars and 2 line display
#include <IRremote.h> // use the library for IR
int receiver = 11; // pin 1 of IR receiver to Arduino digital pin 11
IRrecv irrecv(receiver); // create instance of 'irrecv'
decode_results results;
void setup()
{
lcd.init(); // initialize the lcd
lcd.backlight(); // turn on LCD backlight
irrecv.enableIRIn(); // Start the receiver
}
void translateIR() // takes action based on IR code received
// describing Sony IR codes on LCD module
{
switch(results.value)
{
case 0x37EE: lcd.println(" Favourite "); break;
case 0xA90: lcd.println(" Power button "); break;
case 0x290: lcd.println(" mute "); break;
case 0x10: lcd.println(" one "); break;
case 0x810: lcd.println(" two "); break;
case 0x410: lcd.println(" three "); break;
case 0xC10: lcd.println(" four "); break;
case 0x210: lcd.println(" five "); break;
case 0xA10: lcd.println(" six "); break;
case 0x610: lcd.println(" seven "); break;
case 0xE10: lcd.println(" eight "); break;
case 0x110: lcd.println(" nine "); break;
case 0x910: lcd.println(" zero "); break;
case 0x490: lcd.println(" volume up "); break;
case 0xC90: lcd.println(" volume down "); break;
case 0x90: lcd.println(" channel up "); break;
case 0x890: lcd.println(" channel down "); break;
default: lcd.println(" other button ");
}
delay(500);
lcd.clear();
}
void loop()
{
if (irrecv.decode(&results)) // have we received an IR signal?
{
translateIR();
for (int z=0; z<2; z++) // ignore 2nd and 3rd signal repeat
{
irrecv.resume(); // receive the next value
}
}
}
And here it is in action:
You might be thinking “why would I want to make things appear on the LCD like that?”. The purpose of the example is to show how to react to various IR commands. You can replace the LCD display functions with other functions of your choosing.
At the start working with infra-red may have seemed to be complex, but with the previous two examples it should be quite simple by now. So there you have it, another useful way to control our Arduino systems. Hopefully you have some ideas on how to make use of this technology. In future articles we will examine creating and sending IR codes from our Arduino. So stay tuned for upcoming Arduino tutorials by subscribing to the blog, RSS feed (top-right), twitter or joining our Google Group. Furthermore, a big thanks to Ken Shirriff for his Arduino library.
Have fun and keep checking into tronixstuff.com. Why not follow things on twitter, Google+, subscribe for email updates or RSS using the links on the right-hand column, or join our Google Group – dedicated to the projects and related items on this website. Sign up – it’s free, helpful to each other – and we can all learn something.
Arduino Game: Tic-Tac-Toe
[Updated 19/02/2013]
Let’s recreate the game of Tic-tac-toe with our Arduino systems. This game is also known as Noughts and Crosses or Three-in-a-row. Whatever we call it, I’m sure you will be familiar with the game from your childhood or general messing about. For the uninitiated, there is an excellent explanation of the game over at Wikipedia.
In the following examples, a human will play against the machine (Arduino). The demonstration sketches are almost identical except for one function – machineMove();. This function contains the method of deciding a move for the machine. By localising the machine’s decision making into that function we can experiment with levels of intelligence without worrying about the rest of the sketch. In writing this article it is assumed the reader has some basic Arduino or programming experience. If not, perhaps read some of my Arduino tutorials indexed here.
However first we will examine the hardware. I have used my well-worn Freetronics Eleven board, which is equivalent to the Arduino Uno. For a display, the Sparkfun LCD shield is used. For user input we have two buttons connected to digital pins 6 and 7, using 10k pull-down resistors as normal. The buttons are wired via a ScrewShield set. To save time I have used my generic button-board, whose schematic is below: 
If you were to construct a more permanent example, this could be easily done. One could possibly use a DS touch-screen over their LCD. Perhaps for mark II? Nevertheless, time to move on. Now to explain how the sketch works – please download a copy from here so you can follow along with the explanation.
I have tried to make the sketch as modular as possible to make it easy to follow and modify. The sketch itself is relatively simple. We use an array board[] to map the pieces of the game board in memory – board[0] being the top-left and board[8] being the bottom-right position. We create a graphical representation of the board by drawing rectangles for the horizontal and vertical lines, lines to form crosses, and circles for … circles. The function drawBoard(); takes care of the board lines and calls drawPiece(); to place the players’ pieces. drawBoard(); reads the board[] array to determine if a position is blank (zero), a nought (1) or a cross (2).
The flow of the sketch is easy to follow. First the function introScreen() is called – it displays the introductory screen. Then drawBoard() is called to draw the initially-blank game board. Then the main function playGame(); is called. We have a global variable winner, whose value determine the winner of the game (0 – game still in play, 1 – human, 2 – machine, 3 – draw). playGame(); and other functions will refer to winner throughout the sketch. Within playGame();, the human and machine take turns placing their pieces. The function humanMove(); accepts the human’s choice in piece position, storing it into board[], and not allowing false moves. The function machineMove(); controls the decision-making process for the machine’s moves. In the first example, the machine moves by randomly selecting a board position. If the position is taken, another random position is selected (and so on) until a valid move can be made.
After each instance of humanMove(); and machineMove();, the function checkWinner(); is called. This function compares the contents of the array board[] against all possible scenarios for a win by either player, and calls the function drawTest(); – which checks for a draw – and stores the result in the variable winner as described earlier. Checking for a win is simple, however checking for a draw was a little more complex. This involves counting the number of 1s and 2s in the board[] array. If there are five 1s and four 2s or four 1s and five 2s ( in other words, the board is full) there is a draw. Easy!
If, after the function checkWinner(); is called, the varible winner >0 – then something to end the game has happened – either a win or a draw. This is determined using the switch…case function at the end of checkWinner();. At this point a function relative to the game status is called, each of which display the outcome and wait for the user to press button A to start a new game. At the end of each of these functions, we call the function clearBoard(); – which resets the array board[] and winner back to zero, ready for the next battle of wits.
Now for our first example in action. The function machineMove() is an example of the simplest form of play – the machine randomly selects blank positions on the board until the game ends. In the following video clip you can see this in action:
For the forthcoming examples, we will allow the choice of who moves first. This is accomplished with the function moveFirst(); which sets the variable whofirst to 1 for human first, or 2 for machine first. This is read by playGame() to determine the first move. Now let’s inject some strategy into our machineMove(); function to give the machine a slight edge above sheer randomness.
In the following example, the machine will first only use the centre or corners until those positions have been taken. This is accomplished by placing the position numbers into another array strategy1[]={0,2,4,6,8} which the machine will randomly select from until those positions are used. Once all those positions have been filled, the machine will revert to random positioning to attempt a win. You can download this example sketch from here. Do you think the machine can win if allowed to move first? Let’s see what happens in the following video clip:
In the second example the player who moves first will generally have the advantage. From this point, how could we strengthen the machine’s level of intelligence to improve its strategy? If you have a better method, and can integrate it into the example sketch, and are happy to publish it under Creative Commons – email the sketch to john at tronixstuff dot com.
So there you have it, some variations on a classic game translated for our Arduino systems. I hope you found it interesting… or at least something different to read about.
In the meanwhile have fun and keep checking into tronixstuff.com. Why not follow things on twitter, Google+, subscribe for email updates or RSS using the links on the right-hand column? And join our friendly Google Group – dedicated to the projects and related items on this website. Sign up – it’s free, helpful to each other – and we can all learn something.
Happy Birthday
Hello everyone
Well it has been twelve months since my very first post – banging on about replacing the battery in my cordless telephones. The last year has certainly zoomed by very quickly, and with it has seen 135 original posts about all sorts of things. Funnily enough, I had never planned on creating a “blog” at the time… instead a few books of notes were being used to record my thoughts and ideas.
It all started while looking for an electronic kit to build… I thought it would be great to have a website where you could read about others’ experiences in building the kit – in order to decide whether or not you would like to build it yourself. Whilst waiting for the kit to arrive some other ideas evolved into posts, mundane things such as replacing calculator batteries, sourcing cheap electronics books, and the start of a power supply saga.
After writing about the JYE Capacitor meter kit, Madeleine and Marcus from Little Bird Electronics asked me to write about this Arduino thingy that they had, and sent one over to play with. Thanks guys! Things picked up a bit after that – now hundreds of thousands of people regularly visit my Arduino tutorials for fun, guidance, and to rip them apart (the tutorials, not the Arduino). And along the way I have had loads of fun writing about more kits, reviewing various parts and items, sharing my projects with the world and learning the basics.
One of the best things that has resulted from this blog is the opportunity to come into contact with some very interesting and inspirational people such as Jon Oxer from Freetronics, Andy Gelme, Dave Jones, Tim Carr from Mindkits, and many others too numerous to mention. Furthermore, it has been great conversing with the many members of the tronixstuff Google Group, answering the thousands of random email questions (well, answering most of them has been great), interacting with my twitter followers, and giving away things with the regular competitions. Speaking of which:
Finally, a lot of the content in this blog would not be possible without the generosity of various people and organisations. So a huge thank you to Little Bird Electronics, Freetronics, element-14, RS Designspark, Alan Parekh, Ogi Lumen and Gabotronics. And especially to those who were kind enough to make a donation.
The year ahead shall see a few (or more?) more Arduino tutorials, the start of another series concerning a different type of microcontroller, more interesting and inane projects, more reviews, and possibly a book. So stay tuned, and thanks for coming along for the ride.
In the meanwhile, be good to each other and make something
Tutorial: Your Arduino’s inbuilt EEPROM
This is chapter thirty-one of a series originally titled “Getting Started/Moving Forward with Arduino!” by John Boxall – A tutorial on the Arduino universe. The first chapter is here, the complete series is detailed here.
[Updated 09/01/2013]
Today we are going to examine the internal EEPROM in our Arduino boards. What is an EEPROM some of you may be saying? An EEPROM is an Electrically Erasable Programmable Read-Only Memory. It is a form of non-volatile memory that can remember things with the power being turned off, or after resetting the Arduino. The beauty of this kind of memory is that we can store data generated within a sketch on a more permanent basis.
Why would you use the internal EEPROM? For situations where data that is unique to a situation needs a more permanent home. For example, storing the unique serial number and manufacturing date of a commercial Arduino-based project – a function of the sketch could display the serial number on an LCD, or the data could be read by uploading a ‘service sketch’. Or you may need to count certain events and not allow the user to reset them – such as an odometer or operation cycle-counter.
What sort of data can be stored? Anything that can be represented as bytes of data. One byte of data is made up of eight bits of data. A bit can be either on (value 1) or off (value 0), and are perfect for representing numbers in binary form. In other words, a binary number can only uses zeros and ones to represent a value. Thus binary is also known as “base-2″, as it can only use two digits.
How can a binary number with only the use of two digits represent a larger number? It uses a lot of ones and zeros. Let’s examine a binary number, say 10101010. As this is a base-2 number, each digit represents 2 to the power of x, from x=0 onwards:
See how each digit of the binary number can represent a base-10 number. So the binary number above represents 85 in base-10 – the value 85 is the sum of the base-10 values. Another example – 11111111 in binary equals 255 in base 10.
Now each digit in that binary number uses one ‘bit’ of memory, and eight bits make a byte. Due to internal limitations of the microcontrollers in our Arduino boards, we can only store 8-bit numbers (one byte) in the EEPROM. This limits the decimal value of the number to fall between zero and 255. It is then up to you to decide how your data can be represented with that number range. Don’t let that put you off – numbers arranged in the correct way can represent almost anything!
There is one limitation to take heed of – the number of times we can read or write to the EEPROM. According to the manufacturer Atmel, the EEPROM is good for 100,000 read/write cycles (see the data sheet). One would suspect this to be a conservative estimate, however you should plan accordingly. *Update* After some experimentation, the life proved to be a lot longer…
Now we know our bits and and bytes, how many bytes can be store in our Arduino’s microcontroller? The answer varies depending on the model of microcontroller. For example:
- Boards with an Atmel ATmega328, such as Arduino Duemilanove, Uno, Uno SMD, Lilypad or the Freetronics KitTen/Eleven - 1024 bytes (1 kilobyte)
- Boards with an Atmel ATmega1280 or 2560, such as the Arduino Mega series – 4096 bytes (4 kilobytes)
- Boards with an Atmel ATmega168, such as the original Arduino Lilypad, old Nano, Diecimila etc – 512 bytes.
If y0u are unsure have a look at the Arduino hardware index or ask your board supplier.
If you need more EEPROM storage than what is available with your microcontroller, consider using an external I2C EEPROM as described in the Arduino and I2C tutorial part two.
At this point we now understand what sort of data and how much can be stored in our Arduino’s EEPROM. Now it is time to put this into action. As discussed earlier, there is a finite amount of space for our data. In the following examples, we will use a typical Arduino board with the ATmega328 with 1024 bytes of EEPROM storage.
To use the EEPROM, a library is required, so use the following library in your sketches:
#include <EEPROM.h>
The rest is very simple. To store a piece of data, we use the following function:
EEPROM.write(a,b);
The parameter a is the position in the EEPROM to store the integer (0~255) of data b. In this example, we have 1024 bytes of memory storage, so the value of a is between 0 and 1023. To retrieve a piece of data is equally as simple, use:
z = EEPROM.read(a);
Where z is an integer to store the data from the EEPROM position a. Now to see an example:
Example 31.1
This sketch (download) will create random numbers between 0 and 255, store them in the EEPROM, then retrieve and display them on the serial monitor. The variable EEsize is the upper limit of your EEPROM size, so (for example) this would be 1024 for an Arduino Uno, or 4096 for a Mega.
/* Example 31.1 - Arduino internal EEPROM demonstration
http://tronixstuff.com/tutorials > chapter 31 | CC by-sa-nc */
#include <EEPROM.h>
int zz;
int EEsize = 1024; // size in bytes of your board's EEPROM
void setup()
{
Serial.begin(9600);
randomSeed(analogRead(0));
}
void loop()
{
Serial.println("Writing random numbers...");
for (int i = 0; i < EEsize; i++)
{
zz=random(255);
EEPROM.write(i, zz);
}
Serial.println();
for (int a=0; a<EEsize; a++)
{
zz = EEPROM.read(a);
Serial.print("EEPROM position: ");
Serial.print(a);
Serial.print(" contains ");
Serial.println(zz);
delay(25);
}
}
The output from the serial monitor will appear as such:
So there you have it, another useful way to store data with our Arduino systems. Although not the most exciting tutorial, it is certainly a useful.
Have fun and keep checking into tronixstuff.com. Why not follow things on twitter, Google+, subscribe for email updates or RSS using the links on the right-hand column, or join our Google Group – dedicated to the projects and related items on this website. Sign up – it’s free, helpful to each other – and we can all learn something.
March 2011 Competition
Hello readers
The March competition has now closed and the winners have been notified. The April competition will be announced shortly!
Another month has passed, so time for another competition!
To enter, find the five questions that will be spread across the articles published in tronixstuff.com between the first and last day of March. When you have answers to all five questions, email your answers to competition at tronixstuff dot com with “March″ in the subject line. Then in the first week of April, I will compile a list of people with the correct answers, and randomly select two winners…
Each winner will receive an Au$40 gift voucher to spend with Little Bird Electronics – Australia’s leading online retailer of fun stuff, including competitive prices on merchandise from Sparkfun, Seeed Studio, DF Robot and more!
As with any other competition, there needs to be some rules:
- Prizes will be emailed upon confirmation of email address;
- Winners outside of Australia will be responsible for any taxes, fees or levies imposed by your local Governments (such as import levies, excise, VAT, etc.) upon importation of purchased goods;
- If you have won a previous competition you cannot enter;
- If you know me in real life you cannot enter;
- The Judge’s decision is final with regards to any dispute;
- Entries will be accepted until 2359h GMT on 31st March 2011.
So have fun and keep checking into tronixstuff.com. Why not follow things on twitter, subscribe for email updates or RSS using the links on the right-hand column, or join our Google Group – dedicated to the projects and related items on this website. Sign up – it’s free, helpful to each other – and we can all learn something.
Once again, thank you to our generous competition sponsor Little Bird Electronics!
Otherwise, have fun, stay safe, be good to each other – and make something!
Moving Forward with Arduino – Chapter 30 – twitter
This is chapter thirty of a series originally titled “Getting Started/Moving Forward with Arduino!” by John Boxall – A tutorial on the Arduino universe.
The first chapter is here, the complete series is detailed here.
[Updated 09/01/2013]
In this article we will learn how to send messages from our Arduino to twitter. For the uninitiated who may be thinking “what is all this twitter nonsense about?”, twitter is a form of microblogging. You can create a message with a maximum length of 140 characters, and broadcast this on the twitter service. For people to receive your messages (or tweets) they also need to be a member of twitter and choose to subscribe to your tweets.
Generally people will use the twitter service using one of three methods: using a web browser on a personal computer or internet device, on a mobile phone, or using a specific application such as TweetDeck on one of the aforementioned devices. For example, here is a typical web browser view:
And here is an example of a twitter application running on an Android OS smartphone:
So as you can see, it is easy enough to read peoples’ tweets. Therein lies the reason for this article – we can harness twitter as an output device for our Arduino systems. We can broadcast various messages, so systems can be created to monitor specific parameters and report on their status at regular intervals, upon an event occurring, and so on.
In some areas, you can set twitter to send tweets from a certain user to your mobile phone via SMS – however if doing so be careful to confirm possible charges to your mobile phone account. Finally, if you are worried about privacy with regards to your tweets, you can set your account to private and only allow certain people to follow your tweets.
So let’s get started. First of all – you will need a twitter account. If you do not have one, you can sign up for one here. If you already have a twitter account, you can always open more for other uses – such as an Arduino. For example, my twitter account is @tronixstuff, but my demonstration machine twitter account is @tronixstuff2. Then I have set my primary account to follow my machine’s twitter account. Once you have logged into twitter with your machine account, visit this page and get yourself a token by following the Step One link. Save your token somewhere safe, you’ll need to insert it into your Arduino sketch.
Next, you will need some hardware. Apart from your usual Arduino board, you will need an Ethernet shield. However to save space and money I’ll be using the Freetronics EtherTen:
If you are unfamiliar with using Arduino and Ethernet, please review chapter sixteen before continuing forward with this article.
From a software perspective, we will need another library for our Arduino IDE. Download and install the twitter library from here.
Now, at this point – please run the Webserver example described in chapter sixteen and ensure it is working before moving forward from this point. While you do that, we’ll have a break…
Now it is time to send our first tweet. The following sketch is a modification of the demonstration version, in which we have isolated the tweet-sending into a separate function called (strangely enough) tweet();. It is not complex at all:
// Example 30.1 - simple twitter interface
#include <SPI.h> #include <Ethernet.h> #include <Twitter.h>
// Alter IP address to suit your own network!
byte mac[] = {0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED }; // create MAC address for ethernet shield
byte ip[] = {10,1,1,69}; // choose your own IP for ethernet shield
Twitter twitter("aaaaaaa"); // replace aaaaaaa with your token
void setup()
{
delay(5000);
Ethernet.begin(mac, ip);
Serial.begin(9600);
}
void tweet(char msg[])
{
Serial.println("connecting ...");
if (twitter.post(msg))
{
// Specify &Serial to output received response to Serial.
// If no output is required, you can just omit the argument, e.g.
// int status = twitter.wait();
int status = twitter.wait(&Serial);
if (status == 200)
{
Serial.println("OK.");
}
else
{
Serial.print("failed : code ");
Serial.println(status);
}
}
else
{
Serial.println("connection failed.");
}
}
void loop()
{
delay(1000);
tweet("bazinga!");
do{
}
while(1>0); // endless loop
}
So after uploading the above sketch, running a network cable from your access point to the Ethernet shield, and powering up the Arduino board – your tweet should appear as such:
Excellent – it works. And I hope yours did as well. If it did not, open the serial monitor box to get some feedback from the sketch. From experimentation the most amount of errors are caused by incorrect IP and trying to send multiple tweets too quickly. If you get excited and try to run the sketch again by hitting reset, twitter will reply back with an error – it does not allow duplicate tweets to be sent (over a short period of time). Twitter will reply to your tweet with a code which describes the result of your tweet. This code is stored in an integer variable using the function
int status = twitter.wait(&Serial);
For example, 200 means the tweet was sent successfully, and 403 means you have attempted a duplicate tweet. However you can omit the code-checking if you are not fussed about your tweet’s status.
Although it was fun tweeting Hello world, let’s create an example that reacts to various events and tweets about them. To simulate some events I have connected four buttons to digital inputs (using the button board from chapter twelve). Pressing a button sends of the matching message. However you can use any form of digital output or decision-making in your sketch. For now, here is the example sketch:
// Example 30.2 - tweeting digital event status
#include <SPI.h> #include <Ethernet.h> #include <Twitter.h>
// our event messages char b1[]="one"; char b2[]="two"; char b3[]="three"; char b4[]="four";
byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED }; // create MAC address for ethernet shield
byte ip[] = { 10,0,0,69}; // choose your own IP for ethernet shield
Twitter twitter("aaaaaaa"); // replace aaaaaaa with your token
void setup()
{
delay(5000);
Ethernet.begin(mac, ip);
Serial.begin(9600);
pinMode(2, INPUT);
pinMode(3, INPUT);
pinMode(4, INPUT);
pinMode(5, INPUT);
}
void tweet(char msg[])
{
Serial.println("connecting ...");
if (twitter.post(msg))
{
int status = twitter.wait(&Serial);
if (status == 200)
{
Serial.println("OK.");
} else
{
Serial.print("failed : code ");
Serial.println(status);
}
} else
{
Serial.println("connection failed.");
}
}
void loop()
{
if (digitalRead(2)==HIGH)
{ tweet(b1); delay(2000); }
if (digitalRead(3)==HIGH)
{ tweet(b2); delay(2000); }
if (digitalRead(4)==HIGH)
{ tweet(b3); delay(2000); }
if (digitalRead(5)==HIGH)
{ tweet(b4); delay(2000); }
}
And here is a screen shot of the results after pressing buttons one, four, two then three:
So there you have it, another useful way to send information from your Arduino to the outside world. Stay tuned for upcoming Arduino tutorials by subscribing to the blog, RSS feed (top-right), twitter or joining our Google Group. Big thanks to @neocat for their work with the twitter Arduino libraries.
Have fun and keep checking into tronixstuff.com. Why not follow things on twitter, Google+, subscribe for email updates or RSS using the links on the right-hand column, or join our Google Group – dedicated to the projects and related items on this website. Sign up – it’s free, helpful to each other – and we can all learn something.
February 2011 Competition Results
Hello readers!
As it is now March we can announce the winners of the tronixstuff February 2011 competition. The five questions and answers for February were:
- What does the acronym RFID stand for? – Radio frequency identification
- How many pixels in the LCD on the Sparkfun LCD shield? - 16384
- What is the maximum supply voltage for a Fairchild CD4047B IC? - 18 volts DC (page four of data sheet)
- How many capacitors are used in the Freetronics KitTen Arduino Duemilanove-compatible board kit? – Eleven
- Name the company that first manufactured the 555 timer IC – Signetics
It was great to see all the entrants had correct answers for every question, nice work everyone. However there can only be two winners…
First Prize: Congratulations to Mike R, USA
One brand-new, hot off the pick-and-place Freetronics “Eleven” 100% Arduino Uno-compatible board

Second Prize: Congratulations to Cary D, Australia
One brand-new, Freetronics “KitTen” 100% Arduino Duemilanove-compatible board kit

So as you can see you can win great prizes just for checking into tronixstuff.com on a regular basis. If you missed out this month, stay tuned as it all starts again in the next few days. Why not follow things on twitter, subscribe for email updates or RSS using the links on the right-hand column, or join our Google Group – dedicated to the projects and related items on this website. Sign up – it’s free, helpful to each other – and we can all learn something.
Once again, thank you to our generous competition sponsor Freetronics!






























