Archive for the 'my projects' Category

Arduino tweeting back and forth via USB

Sunday, May 29th, 2011

Following on from last night writing up how to get the Arduino to tweet via USB using a Python script running on the local computer that monitors the serial port to act as a gateway to twitter, I explored python-twitter further to look at then monitoring twitter for @fouldsy_arduino mentions that would then pass data back over the serial connection to the Arduino. This would basically allow you to send a status update to the Arduino twitter account that would be read by the Python script, passing some data to the Arduino to then carry out some code. My basic example involved simply writing the status update “lights on” or “lights off” to then have the Arduino call the appropriate lightsTurnOn() or lightsTurnOff()

Again, all this is done via the USB connection. I don’t have an Ethernet shield which would have made this somewhat easier, as removes the need for Python to do most of the lifting. But, for those without an Ethernet shield and wanting to be able to control their Arduino via twitter, this method works pretty good and is a lot cheaper given you have a USB cable and computer already ;-)

The Python script and Arduino sketch is available under twittering-arduino on my Github. The Python script uses the same twitter API as previously, so assumes you have all the required Python dependencies and application registered at dev.twitter.comcheck the blog post I wrote outlining getting all that going if you need to set all that fun stuff up.

All we’re doing is calling api.GetMentions(), grabbing the most recent tweet sent to our Arduino twitter account, and then parsing out so we end up with just the status message sent to us. We then do an if: elif: to do an arduino.write(x) where x is the integer we determined in our if logic dependent on the twitter status sent to us, and arduino is our initiated serial connection via USB. You’ll need to edit the Python script to include your own twitter API tokens, as well as adjust what you want your if statements to process. I wanted to watch for ‘lights on’ or ‘lights off’ and send a ’1′ or ’2′ respectively:

if message == "lights on":
arduino.write("1")
elif message == "lights off":
arduino.write("2")

As shown below, tweeting @fouldsy_arduino lights off causes our Python script to read in the ‘lights off’ part, convert that to the integer ’2′ and send it via the serial port to the Arduino, which is monitoring it’s serial port for incoming data and then calls turnLightsOff();. I was running a Python script that was monitoring both ways and so the Arduino then tweeted back out “turned lights off” via the same mechanism outlined in my earlier blog post:

Tweeting to control an Arduino

My Python isn’t quite up to speed to figure out how to constantly monitor the serial port for the Arduino sending data that then needs tweeting out, whilst being nice to twitter and only making an API call every 5 minutes to see if any tweets have been sent to it that need passing back to the Arduino, so I’ve made the code to read from twitter to the Arduino available on Github, and hope someone else might be able to figure out that niceity and contribute back ;-)

Also note that the Python script passes back ASCII code data, so you’d need to some converting based on an ASCII table like this if you wanted to pass something other than a single integer. You can pass entire strings back and forth, but to me that seemed inefficient and required a lot more processing when the Arduino receives the serial data, so the method I used in this code, at least to me, made more sense.

a’twittering Arduino without an Ethernet shield

Saturday, May 28th, 2011

The Arduino Ethernet shield is pretty awesome and can, for example, allow a mini webserver to run off the board displaying sensor data. Although not outrageously expensive, at $45, it’s still $15 more than an Arduino Uno itself. There does seem to be quite a bit of functionality that you can do with it, especially as the official Arduino Ethernet shield includes a micro SD slot allowing to read + write data to card, but for my tinkering right now, it’s a little too much money.

But, it would be cool to at least look at how to push data from the Arduino out the Internet, and so I started looking around at ways to utilize the USB connection and have the computer the Arduino is connected to act as a go-between. Cue some fun python libraries. The setup entails using pySerial to monitor the USB port and read in data printed to the Arduino serial port, and then python-twitter to push that data out as a status update to twitter. This was all based off an awesome post from Brad Wells on using Arduino to Twitter over USB.

To get the python libraries installed and ready to roll:

  • Download pySerial – unpack the archive and then from the command line within that directory run
    python setup.py install
  • python-twitter has three dependencies that need installing first:
    • simplejson – download and unpack the archive, and then from the directory run
      python setup.py install
    • httplib2 – download and unpack the archive, and then from the directory run
      python setup.py install
    • python-oauth2 – download and unpack the archive, and then from the directory run
      python setup.py install
  • Now you can download python-twitter – unpack the archive, and then from the directory run:
    python setup.ph build
    python setup.ph intall

Now we need to get twitter ready. The python script uses the twitter API, so it requires you to register your own application in order to get the access tokens needed to function. Most people create a separate twitter account specifically for the Arduino to tweet to (the entry in the Arduino playground for tweeting using the Ethernet shield has you running through an external service to pass the tweet, so you probably shouldn’t use your primary account), and when registering your application at dev.twitter.com, make sure you’re signed in to twitter using this dedicated Arduino account. After registering, your consumer key and consumer secret key are immediately provided – click on ‘My Access Token’ to gain the access token and access token secret.

The python script, broken down and detailed in Brad’s blog post, requires you to copy and paste those four twitter tokens in to the script. On the Arduino side, the sketch can be as simple as:

Serial.begin(9600);
Serial.println("Tweeting arduino!");

within setup(). All you need to do is initialize a 9600 baud serial instance and then print out a line. Whatever your print out to the serial port is what the python script will read in and tweet. Make sure you compile and upload the sketch to your Arduino before you run the python script – as you have python monitoring your USB port to watch for the serial output, you can’t then upload via USB to the Arduino. Once you sketch is uploaded, you can fire up the python script and then hit the reset button on your Arduino.

Tweeting Arduino

The python script will just sit at the command line, watching for messages sent out to the Arduino’s serial port. If you check your twitter feed, you should see your tweet :-) You can easily expand beyond simply printing a line of text to reading in data from sensors and have that included. It would definitely make it more useful, and within the python-twitter library, there are functions to also monitor twitter updates and send data back to the Arduino. That’s something I haven’t quite figured out yet, but is definitely an appealing feature!

Arduino RTC timer sketch

Thursday, May 26th, 2011

Something somewhat useful, and the main reason I started playing the the DS1307 real time clock, was to be able to accurately control events based on the current time. In the same way you can get a simple plug-in timer to turn on or off an appliance depending on the time, I wanted to be able to do the same with the Arduino.

I wrote a fairly wide-ranging RTC timer sketch that I posted to Github that will allow you to execute a given block of code or function based on a start and end time that you specify. Although the default sketch is simply turning on and off an LED connected to digital pin 2, there’s probably a lot of situations beyond just turning a light on or off that this could be used for.

Hopefully it’s useful, and it’s definitely something I’ll be incorporating in to other programs I’ll be writing :)

Ardunio RTC, temp sensor, and LCD

Wednesday, May 25th, 2011

I figured that if I was going to end up building some kind of aquarium controller / monitoring system based around the Arduino, I’d need a way of keeping track of time. Either to automate certain events like turning lights and off, or simply to log the time temperature readings we taken, I’d like something more advanced that milli() built in to the Arduino to track time since it was last turned on. Plus, if the power goes out (we lost power for a few hours on Monday after a big storm came through…), then I’d have to tell the Arduino to reset it’s time and calculate afresh when it needed to carry out certain events.

There’s a few basic little circuits built around the DS1307 chip that act as a real time clock – I went with this little kit from Adafruit. It only took 5-10 minutes to assemble and solder, and then I had fun playing with outputting various time formats to the serial monitor and calculating dates in the past and future. Ultimately, I wanted to hook it up to the LCD screen though.

I also got a tiny TMP36 temperature sensor, with the plan being to craft a waterproof housing so it could sit in the aquarium to record water temperature. It only uses one analog pin (in it’s most basic form of connecting), which is great since I’m basing things of the Arduino Uno so don’t have a massive number of pins available. But, with the LCD backpack reducing the numbers of pins required, it’s not too bad. I discovered to output the degrees symbol (°) is written to the LCD using lcd.print((char)223); or to the serial monitor with Serial.print(176, BYTE);

Arduino with LCD, RTC, and temp sensor

Anyway, after figuring out running both the LCD backpack and the RTC off analog pins 4 + 5, I managed to get the LCD displaying the current time and temperature in both degrees celsius and fahrenheit as shown above. Here’s the actual diagram of the circuit (Fritzing file available via Github below):

Circuit schematic

It was a pretty cool set up, though it was kinda annoying that there’s nothing built in to Arduino or the RTC library that allows for a leading zero on the time if only a single digit is present, such as 7 seconds when on a clock it should ideally display 07 seconds. A simple if (now.second() < 10) lcd.print("0"); checks if the value returned from the RTC requires this leading zero and outputs it to the LCD before the actual time value.

The code and circuit schematic for this little project is available on Github at Arduino-LCD-time-temp, and I guess is the first little program beyond basically copying and pasting example code that I've written. It was largely based on the DS1307 RTC tutorial by Ladyada along with her TMP36 temperature sensor tutorial. The Ardiuno forums also had a good few little snippets on how to write out the degrees symbol both to the LCD and to serial when I was testing, and different methods to write out the leading zeros when dealing with time.

Playing with Ardunio

Monday, May 23rd, 2011

With college classes done for the summer, I’ve gotten back in tinkering with electronics a little. I had trouble with my Basic Stamp 2 after bouncing around Alaska and being boxed up for a couple of years, so I decided to try tinkering with an Ardunio, something I’ve looked at for a while but never had time. I’m currently in the process of cycling a 55 gallon freshwater aquarium (something else I’m very excited about!), and have some cool ideas for building a basic monitoring system that can keep track of water temperatures, control lights, and provide a status report and XML feed or something for use elsewhere. So, I picked up a cool Arduino Uno.

I bought a 16×2 LCD from Adafruit which helpfully included the header pins, along with an i2c/SPI backpack which allows easier connection to the Arduino and uses less pins. After remembering which end of the soldering iron to hold, I got the header connected and the backpack attached (though I really need to clean up my soldering job…):

i2c LCD backpack

Using a modified LiquidCrystal library for using the i2c connection made it pretty straightforward to write out to the LCD. Using two analog input pins along with the 5V and GND made it really quick to hook up the board too. The basic code for displaying two lines of text is:


#include < Wire.h >
#include < LiquidCrystal.h >

LiquidCrystal lcd (0); // Initialize a single i2c LCD

void setup() {
lcd.begin(16, 2); //Set up our 16x2 LCD
lcd.print("Line 1 text");
lcd.setCursor(0,1); // Set our cursor to character 0, line 1
lcd.print("Line 2 text");
}

void loop() {
}

Which should display something a little like this:

Arduino and 16x2 LCD

This was all based on the awesome tutorials from Ladyada on connecting the i2c backpack and writing characters to an LCD. There’s a wealth of awesome info and tutorials, and a great starting place for components and code ideas :D I’m looking forward to playing around with the temperature sensors and battery powered real time clock over the next week or so.

Boe-Bot infrared eyes

Monday, June 30th, 2008

The internet was off all weekend, made even more annoying by a) their customer service lines were also closed all weekend and b) it came back online first thing this morning meaning when they got into the office and saw the problem, a simple remote equipment reset or similar fixed it in a matter of seconds :( Still, least it’s working now. It gave me a chance to play with using IR detectors on the Boe-Bot to act as eyes for navigating which was pretty cool:

Boe-Bot IR

As opposed to using the wire ‘whiskers’ which have to physically touch an object before then backing up and moving away, and the light-sensitive photoresistors which weren’t really useful for navigating around objects at any great speed, using the IR sensors allowed it to continually send out pulses to detect objects and then react to them before they became an obstacle. This allowed much faster movement through a small maze (another USPS-sponsored event!):


Alt video for blocked YouTube access

I also set it up using basic code for a sumobot where it would lock onto an object and try to follow. Mia was not impressed! I was though, as it was able to successfully track a very fast moving dog :-D

Light sensitive navigation with the Boe-Bot

Sunday, June 22nd, 2008

A little more difficult working with the photoresistors rather than the whiskers as there’s so many windows in this house, it’s very bright at the best of times :) But, I played around making the Boe-Bot act like a scaredy-cat by backing away from a flashlight:


Alt video for blocked YouTube access

More useful was programing it to move towards light sources, such as exiting a dark area or room and moving towards the light – of course, Mia decided to come stick her nose in again! Think I need a subroutine called “DogAvoidance” (maybe use the piezospeaker to emit a high frequency tone!), but it seemed to do pretty well on this one anyways:


Alt video for blocked YouTube access

And one more project to have the Boe-Bot detect changes in the colour surface and avoid black areas.


Alt video for blocked YouTube access

One common robotics challenge is following a black line, so I’m guessing this is something the textbook will move onto using the same principles of detecting the colour changes and making adjustments as to the direction of travel. Next up though is using the infrared sensors for navigation and object detection.

Tactile navigation with the Boe-Bot

Saturday, June 21st, 2008

This afternoon I worked through using ‘whiskers’ on my Boe-Bot so that it can detect when it’s touched an object and so backup and try again in a different direction:

Boe-Bot with whiskers

It was a little more interesting than the first few chapters of programming it to move in certain directions, turn at a particular angle, etc. although probably worthwhile in the long run to be able to calculate what speed and durations of turn produce various distances and directions. After setting up a minor obstacle course (sponsored by the US Postal Service…), Mia decided to come and see whether anything good was happening:


Alt video for blocked YouTube access

Inquisitive little bugger…

Note: I’m switching some videos to YouTube as the media plugin I use for WordPress automatically starts downloading all videos displayed which is getting boring if there’s more than one video to load. For those at work, school, college, etc. where YouTube may be blocked, I’ll be including an alternative video link here on the blog below each YouTube clip, ‘cos I’m nice :-)

Playing with Boe-Bot

Friday, June 20th, 2008

Robotics is something I’ve wanted to get into for years, pretty much since Robotwars appeared on TV and the idea of creating big machines with flames coming out the top that were designed to smash other machines sounded like fun :D I raced various forms of remote controlled cars on + off for a number of years, but that was mainly build the cars, then set them up from race to race. But, programming a microchip and building a robot to figure it’s way through an obstacle course or similar seems like a good challenge, and then there’s stuff like the RoboGames each year (along with smaller regional gatherings) which includes events for small sumo-bots or robosoccer (check the videos!).

Boe-BotAnyway, Parallax caught my attention a while ago with their Boe-Bot robotics kit based off a BASIC Stamp 2 microcontroller and mine arrived today. It seems a pretty good introduction to robotics, and the BS2 chip can be used for a bunch of other things too. Parallax make all their books available on-line in PDF format, so also I’ve worked through some basics with using the BS2 chip outside of controlling the Boe-Bot. With a number of projects included with the kit and components to allow the robot to make it’s own decisions based on position, speed, contact with objects, etc. it should keep me entertained for a while. When I have the rest of the circuitry built up and programmed for something slightly more advanced than moving backwards, forwards, and rotating around itself I’ll post some photos or videos :)

Using it within OS X was a little harder than inserting the CD and installing the software as Parallex don’t produce their programming suite for OS X or Linux, but others have written apps available for free online which work great. For anyone trying to use the USB version under OS X, download the FTDI VCP drivers here and then install MacBS2 by Murat Konar which is the equivalent of the Parallex programming tool for Windows. For code requiring user input using DEBUGIN, goSerial from Furrysoft works great for displaying the output the same as Debug Terminal does, but also capturing your inputs and sending them to the BS2 chip which MacBS2 can’t do yet. Simply select your USB connection under the ‘Serial Port’ option in goSerial, and then choose ’9600 bps’ for the connection speed and it should work just fine so long as you close down MacBS2 first otherwise you have both apps trying to connect to the same port concurrently.

Flight simulator avionics panels

Tuesday, June 17th, 2008

Now that I can steal Kat’s camera (she’s asleep, will never know ;-) ), I can put together some shots of a ‘little’ project I’ve been working the past month or so…

As I spend quite a bit of time playing flight simulator on the PC, using the mouse to click buttons to change radio frequencies, control the GPS, or even just flick switches to turn on or off navigation lights doesn’t quite cut it compared to sitting in the cockpit of a real airplane. This realisation materialised long before I actually took the intro flight in the Cessna 152 last month :-) There are people who literally spend thousands of dollars and hundreds (if not thousands) of hours rebuilding complete Boeing 737 or Airbus A319 flight decks which look amazing, though a little difficult to accomplish out here. Plus, you’re pretty much pigeon-ed into flying that one particular type of aircraft. The in-between are companies like GoFlight or SimKits which build + sell individual panel components to connect together allowing to utilise them as you see fit and for controlling any aircraft you wish to load up in flight simulator. Again, fantastic units, but still more than a little pricey at $110 plus shipping for a basic 8-button or switch panel.

Since I can’t complain about not having time to build something similar myself and being able to pick + choose the various electrical components myself from various suppliers online, I er, did:

Flight sim avionics panel

It still needs a couple of sheets of balsa wood for the top parts of each panel which I’ll get in Anchorage next month, but everything is functional and otherwise complete. Some of the labels aren’t perfectly straight and I could do with adjusting some of the push buttons on the autopilot panel so they are all aligned, but it wasn’t built to score any style points! It runs off four USB to 20 button interface modules produced by Desktop Aviator which provide the core controls. These were a great find, even if the articles on flightsim.com which explain how to use toggle switches, push buttons and rocker switches were slightly biased in recommending them given the author of the articles is the founder of the Desktop Aviator ;-) But, I liked the way I could buy just one or two and add in functionality over time (which is exactly what I did to make sure I could do what I wanted to do with them in the first place before).

The first completed section was based just off rocker switches and push buttons. The rotary switches for the autopilot panel were added later:

Avionics panel

The electronics behind were not all that complicated – the push buttons connect straight to the input pins on the USB interface controller, whereas the toggle or rocker switches require a simple circuit built around an optoisolator to generate a ‘pulse’ as the switch is flicked to allow the computer to recognise the input. The flightsim.com article and instructions on the Desktop Aviator website explain it all in detail and isn’t hard, just time consuming, as this part of the panel required 20 of these small circuits to be soldered. But, figuring on about a $1 for a rocker/toggle switch, $1 for the optoislator, and maybe another $1 total for a capacitor, two resistors and diode, factoring in the USB controller being $29 for 20 inputs, you’re still looking at less than $5 per input. The fantastic plastic panels at 75c each also from Steve at Desktop Aviator were great too as it meant I could drill them however I wanted to group the buttons and switches to my liking.

Com panel

The radio panel was the main section I wanted to build, as all available solutions are either complicated, expensive, or both. Dual rotary push button switches aren’t easy to find and pricey when you can, and also require either a separate interface controller (usually the more expensive kind used in high-end simulators where you have 80+ inputs per controller) or meant you have to program your own microcontroller to interpret rotating clockwise or anti-clockwise. For the hardcore who won’t accept anything less, they’ll pay quite a price for these kind of inputs, but me, I’ll take a little less!

Taking a basic single-pole 12-position rotary switch (one of the most commonly available at about $2.50) and wiring up pins 1-5-9 and then 3-7-11, it creates the equivalent of a standard toggle switch. To switch between Mhz and Khz when adjusting radio frequencies, after connecting the output of the rotary switch to the standard pulse circuit, the output of this pulse circuit normally going straight to the USB interface controller instead connects to what would be the output of a SPDT toggle switch. The upper terminal can then connect to an input pin on the controller, and the lower terminal to another input pin. Now, when you flip the toggle switch, the rotary controller’s output is sends a different event to the PC. Here’s the circuit to explain a bit better (yes, pretty much just what’s on the Desktop Aviator site):

Circuit diagram

With the way the rotary switch is wired, you only get a pulse sent on every second ‘click’ as we have a break between our contacts. In practice, this actually works nicely, as with FSUPIC which is used to pass the controls to flight sim, it needs a 1/4 second pause (I believe) between inputs otherwise it won’t recognise it, so if you were rotating very quickly, it wouldn’t register anyways. If you had a rotary switch that had a slightly smoother contact point on the rear (as oppose to mine which has quite a large ball which makes a definitive click and clunk), you probably wouldn’t notice it really. Still, our drawback (for the moment…) is that rotating either clockwise or counter-clockwise, we can’t make a difference in whether we’re increasing or decreasing our radio frequency. This is where the more complicated solutions involving a dedicated microcontroller would read in a binary output from the rotary switch (if we wired up our other contacts in the same manner) to calculate what position the switch is being moved to/from and thus whether it’s going up or down. In contact with Desktop Aviator, they are actually producing a pre-programmed chip to do just this, but no word on pricing. Anyway, my simple solution is to use a modifier key within FSUIPC.

In FSUIPC, I mapped each rotary switch to send a key command rather than an action in flight simulator. For example, rotating the rotary switch for COM 1 will map to Ctrl-C by FSUIPC, and then you can set Ctrl-C to represent COM RADIO WHOLE INC. Fairly straightfoward. Then, add another key mapping for Ctrl-Shift-C to represent COM RADIO WHOLE DEC. Hold down shift whilst rotating the rotary switch and now the frequency will decrease. Technically, you can continue rotating the rotary switch clockwise and it will decrease so long as you’re holding down the Shift key but that’s no fun :-) As I use the CH Yoke, the left rear button on the yoke is set as the Shift key, so I simply hold my finger down on the button whilst rotating the rotary switch counter-clockwise to decrease the frequency; release the button and turn clockwise to increase the frequency. Repeat this key-mapping process where Shift acts as the modifier key to decrease the frequency for the other COM and NAV functions, and with the toggle switch on both Mhz and Khz.

Sounds like a clunky process, but in practice it’s all pretty natural. When leaning over to adjust the radios, you’d keep your left hand on the yoke anyway, so it’s no problem to press you finger on the button at the rear of the yoke. Flicking between the Mhz and Khz positions is no harder than moving your fingers between the inner and outer knobs on a dual-rotary switch. I also put in two push buttons for each control – one to enable the COM or NAV channel and another to switch standby frequency. Really, the only thing missing is an LED screen showing the frequency and your adjustments, but that’s getting back into substantially increasing cost + complexity. With this setup, each rotary switch requires 2 inputs on the USB interface controller, plus one each for selecting the channel and standby frequency. To do both COM 1 + 2 and NAV 1 + 2, it works out to about $50 including the cost of the USB interface controller. A 3rd of the price of the GoFlight unit, though admitedly requiring a little more work to get going and not providing exact functionality of those in a real airplane by having. Still, for those on budget and with the time and patience to build the controls themselves, very worthwhile.

Other cool features I included was a GPS panel which happily recreates the Garmin GNS 430′s found in the EagleSoft Cirrus SR-22 and the default Garmin 500 model within FS2004. The rotary controls work in the same way as the radio controls. I also used another rotary switch to represent the ignition switch of a GA aircraft, and then a selection of buttons and a toggle switch for sending the transponder code and going between standby + on. There’s no direct controls available for FSUIPC to do things like IDENT but you won’t get that unless you fly online with something like VATSIM, with clients providing that functionality anyways.

Shoot voice recognitionWhilst building these avionics panels, I also came a lightweight, quick, and free voice recognition utility called Shoot which allows you to speak commands and have the computer respond. This is my way of ‘talking’ to ATC without $50 on VoxATC or similar. Again, it’s not going to perfectly replicate talking to ATC with the correct phrases, but in conjunction with Peter Wilding’s control set and adding in a bunch of other commands, I can say “Ready for taxi for north departure” even though all Shoot sends to flight sim is ’4′ (or whatever) to select from the text-based prompt in the ATC window. Makes things a lot more realistic, and after a few flights of adding in commands on the fly (no pun intended!) as I came across a new ATC command to set, I very fairly have to just say the numbers to move through menus.

All in all, pretty happy with the setup now, as it certainly gives me a lot more to do when flying, and kept me entertained for a good while figuring out how to do it all and then building up the circuits and wiring the controls. An awful lot cheaper than buying pre-built modules, and let me build it exactly how I wanted, such as for the GPS panel. If you have no interest in flight sim, all this has probably made no sense, but will at least give you something to read to help you sleep! And if anyone is trying to do something similar, let me know in the comments to share your ideas + suggestions or if you have any problems.