Making a musical Robot Santa ornament using an ATtiny 85

December 29th, 2012

William tests robot santa

In what is threatening to become a tradition, I made a Christmas ornament again this year. Last year I just made simple tree ornaments using sculpey and fimo.

This year things got a bit more involved, as I decided to make a musical model of the Robot Santa from Futurama. It was a good thing I started working on it in November, as it took quite a few evenings to get it all finished.

The first seeds were planted when I read about using an ATtiny 85 to make a musical greeting card. What got me thinking was that so few parts were involved and it could all run quite happily off a three volt coin/watch battery. Farnell had ATtiny 85′s available for 89p each (when you ordered 10 or more). So the chips with a few parts wouldn’t cost too much at all.

The next step was figuring out how to program the ATtinys. There’s a really good series of tutorials on using an Arduino to program the ATtiny chips on the MIT high-low tech blog. I was using an older Arduino (Duemilanove) so the circuit was a little different – no capacitor on the reset pin. Instead there’s a 100 Ohm pullup resistor on the reset pin to stop the Arduino resetting when it’s used as a programmer for the ATtinys.

The MIT tutorial specified a fairly basic set of “cores” for the ATtinys. These are the extra files need to make the Arduino environment work (to a greater or lesser extent) on the ATtiny. The cores in the tutorial provided some of the basic functionality, but in the end I opted for Arduino Tiny cores. These added quite a lot of the functions from the Arduino environment. In particular they added the tone function, which would be very helpful when it came to playing music.

To just check that I could program the ATtiny chips I setup the programming circuit on a breadboard at first:

Programming Attiny85 using Arduino

Setting up the circuit each time quickly became boring though, so I got a proto shield and soldered up the circuit (plus headers) to make it easier to quickly get going:

Shield soldered for easy Attiny85 programming

At this point I went through a few blind turns with the code on the ATtiny, but as I was using the Arduino environment I could use the Arduino itself for writing the code. In particular I could then use the serial port to aid my debugging of what was going on. This helped a lot, as it turned out I’d not been allowing for the fact that int on the ATtiny/Arduino is only 16 bits in size – rather than the 32 bit you’d expect on most desktop computers. This meant I was accidentally going past the maximum size of the int (about 32,000) and getting odd (usually negative) numbers in the wrong place.

I found a great Instructable on making a working set of traffic lights out of an ATtiny and Duplo. This had a very simple interface, that just required pressing a momentary push button to turn on the lights, that would then put the ATtiny to sleep after a while. It was powered by a watch battery and when asleep would use a minuscule amount of power (a few micro-amps), so would still carry on running after several months asleep. This was great as the code showed me how to disable the analog to digital converter and the analog comparator, which really cut down on the power used. It also showed me how to enable an interrupt on pin 0 to wake the ATtiny from sleep when the button is pressed.

For the music I went for the simple approach of having a function that would simply loop through an array, calling tone, noTone and delay to play the relevant notes. It also turned on the LED whenever tone was called, so that it would light up in time to the music.

The note frequencies and beats were specified in an array stored in the PROGMEM section of the ATtiny chip. This is an 8Kb section of read-only storage, which means you can store more data in there than can fit on the 512 bytes of RAM of the chip itself. The only tricky part is you then have to read values out the PROGMEM section using functions like pgm_read_word_near – you can’t treat it like regular RAM. With a few C-macros the transcribed music looked this this:

#define BPM 100l
#define NOTES_LEN 46

prog_uint16_t notes[2*NOTES_LEN] PROGMEM = {
  /* bar 1 */
  NOTE_E3, BEAT,
  NOTE_E3, BEAT,
  NOTE_REST, HALF_BEAT,
  NOTE_A3, HALF_BEAT,
  NOTE_A3, HALF_BEAT,
  NOTE_REST, HALF_BEAT,
  ...

Each note used one 16bit value for the frequency and one 16bit number for the the beat length. The beat length could probably have been encoded in less space, but this just kept the code simple. Also I only used either whole beats (crochet) or half-beats (quaver), so there could have been further optimisation there. In fact the total transcribed music only use 92 bytes of space anyway, which would have easily fitted in the RAM of the chip, but it seemed like a good practice to store the data in this way.

With the code figured out I then went back to the hardware side of things. I took the top of a washing liquid bottle and made a small wooden frame to mount the electronics on. I then tested that a piezo buzzer could still be heard when placed inside the container, when it was being run off of a 3 volt watch battery (rather than the usual 5 volts provided by the Arduino):

Testing piezo in container

The circuit consists of:

Circuit diagram for xmas ornament

Next I cut out some perfboard to mount the components, soldered them in place and stuck the board using hot glue to the wooden frame:

Checking rough layout of circuit

Decoration soldered up

At this point the electronics side of the things was done. I finished transcribing the music for the ornament (the theme from Futurama), which you can just about hear:

At this point I have some electronics components stuck to a piece of wood shoved into a plastic container – not yet resembling Robot Santa. At this point it was time to break out the milliput and start adding some recognisable features:

Robot Santa takes shape

Robot Santa halves

Robot Santa assembled

The milliput took quite a while to add, as I added a part then had to allow it to dry before applying the next part. I probably ended up spending more on the milliput I used, than on the electronics.

After all the milliput was complete I painted Robot Santa using acrylic paint and added a coat of varnish.

Robot Santa painted and varnish drying

Robot santa deployed in front of the xmas tree

I had to drill some extra holes in the case so the Futurama theme was audible, though it’s still on the quiet side:

The code I wrote is available on github in my arduino sketches repo.

A quick Halloween Cylon Pumpkin using an Arduino and a few LEDs

November 1st, 2012

Back in 2006 the new Battlestar Galactica series was going strong (and was still rather good). So it was almost inevitable (in hindsight) that someone would make a Cylon pumpkin for Halloween. That pumpkin was featured in a Halloween copy of Make magazine I bought and then held on to for the next five years. Finally, five years later, I have made my own Cylon pumpkin:


The original used a 555 timer, 4017 counter, several capacitors, transistors etc. Which would mean a fair bit of soldering.

Seeing as I had an Arduino lying around and an Arduino can control six LEDs with PWM (pulse width modulation) in code this was something I could whip up quickly with a small child running around. So the first job was breaking out the breadboard, resistors, LEDs and Arduino to test the circuit out and write some code:

Arduino Larson scanner


That went pretty well and I then surprised myself by managing to solder the LEDs etc to make a simple “shield” for the Arduino. The LEDs were on a strip so they could be attached easily to the inside of the pumpkin.

Larson scanner soldered up and ready for pumpkin

Later in the week I carved the pumpkin:

Carving cylon pumpkin

Sadly though I didn’t take out enough of the flesh, so a couple of days later it “melted” and I had to throw it out. Luckily I’d been leaving it to dry out and so hadn’t installed the Arduino.

So I acquired another pumpkin and started again:

Extracting the pumpkin contents

This time I really made sure I removed as much flesh as I could (which contains a surprising amount of water) and it didn’t go squishy.

Finished mk 2 cylon pumpkin

I made sure I placed the Arduino inside a plastic tub to keep it off the inside of the pumpkin. Some bamboo skewers were used to hold the eyes/LEDs in place and stop the lid falling down:

Inside of cylon pumpkin

I also made a small hole at the rear of the pumpkin to feed the power supply for the Arduino in:

Back of cylon pumpkin

I’ve put the code and Fritzing diagram on github for anyone who wants to do something similar.

Arduino powered, temperature sensing, RGB LED nightlight

September 4th, 2012

About a year ago I started on a project to make a temperature controlled nightlight. I was inspired by seeing these lovely LED lamps styled as mushrooms growing out of pieces of wood. Those mushrooms were made out of glass, which was somewhat beyond my skills. However I then saw some had used translucent sculpey to make mushroom nightlights on instructables. So with that discovery it seemed like it would be rather simple to do…

The first job was to solder up a three colour (RGB) LED (a super bright one from oomlout):


Wires + RGB LED ready for coating in Fimo

I then covered the LED in translucent Fimo:


RGB LED and wires covered in Fimo

As Fimo only needs to be heated to about 100C to set it’s ok to do this, as it won’t hurt the LED. Also LEDs don’t normally give out much heat, so covering them is ok. Of course this is a relatively low power (though quite bright) LED as well which helps.

I found a branch on the way home from work, which I cut up and sanded down. This formed the base for the mushroom:


Testing fit of fimo covered RGB LED

As you can see I also opted for a chunky on/off button, in the style of the original mushroom lamps.

Next I put a small electronics project box into the bottom of the piece of wood and made space for a slide switch and power socket:


Power socket, slide switch and latch switch soldered

At the time I decided to try to use a Picaxe 08m chip to control the LED and read from a temperature sensor. The Picaxe 08m has a native function to read the temperature from a DS18B20 One Wire digital temperature sensor. It also had just about enough inputs and outputs to handle controller the three colors of the LED and reading from a slide switch (to make it switch between temperature display and plain nightlight). The individual chips were also pretty cheap, so it seemed like a good plan at the time.

However the size of the circuit and number of components I needed to solder was all a bit too much for me:


Red means fail

Eventually after much debugging I was able to get some things working – e.g. controlling the colour of the LED, but the temperature sensor just wouldn’t cooperate and always gave a high reading. I also managed to get through a few sensors due to mis-wiring them!

So I decided it was time to start again with the circuit. I bought a better soldering iron (a not too expensive digital temperature controlled one) and started on a new circuit:


Nightlight circuit take 2
Lots of jumper wires on nightlight circuit attempt 2

And before I could finish everything I lost impetus (an active toddler and a lack of sleep may have played a part) and the project sat on a shelf for nearly a year.

Then after discussing a friend’s Arduino experiments I realised that maybe I could use an Arduino Pro Mini to finish the job.


Comparing size of Arduino pro mini to original nightlight circuit

The Arduino was a lot more powerful than the Picaxe chip, with several K of RAM (vs. the 512 bytes for the 08m). Though it was overkill and cost more than the Picaxe chip it would make my life a lot easier. The Arduino gave me a 5V regulated power supply, so I could use the slightly simpler to read from TMP36 temperature sensor. I could also use internal an pullup resistor for the slide button. The other advantage to all that processing power was that I could use PWM (Pulse Width Modulation) when controlling the LED to produce a full range of colours. With the Picaxe I could only really have seven colours, with no smoothing between them. As this was intended to be used in the aforementioned toddlers bedroom having nice smooth transitions between colours was very appealing.

I soldered together the LED, switch, sensor etc to a small piece of perf-board with some female headers for mounting the Arduino too. I had to do a bit of work with a dremel to create more space, as the new setup was a bit taller too.

At this point I could then start programming the nightlight by hooking it up to a regular sized Arduino.


Nightlight working when wired to regular Arduino

This was great as it proved that everything was working fine and I could just focus on the code. It also meant I could do things like temporarily wire in a potentiometer instead of the temperature sensor, to make debugging the code simpler:



It was at this point that I then discovered what could have been a disastrous miscalculation – I spaced the headers for the Arduino Pro Mini too close together! Bit too much haste and perhaps a bit too little sleep, meant that I nearly had to start all over again for the fourth time! Luckily I found that as the headers were only 0.1″ closer together than they should be I could use some extra long male headers soldered on to the Arduino and bent to compensate:


Creating slightly offset headers for Arduino pro mini

Then it was a case of programming the Arduino Pro Mini using a serial adapter (carefully balanced so as to make contact correctly). I found I had to reset the Pro Mini and un-plug and re-plug the USB cable to get it work properly, but once the connection was good I could reprogram the board easily enough.


Programming Arduino pro mini with code for nightlight

All was good, so I decided to try out the nightlight by testing in different temperatures. The fridge seemed like a good starting point:


Testing nightlight in fridge

Luckily the weather was fairly warm that day too:


The nearly finished nightlight

I recorded a timelapse of the LED’s colour change as the temperature warmed up:


Changing color of nightlight after warming up from being put in fridge for a while

Sadly although the nightlight was responding to the change in temperature, it appeared that left to it’s own devices it would tend to warm up over a few minutes and then read a couple of degrees higher than it should. Without the bottom cover on it too longer to do this, so it was clearly some sort of a cooling issue, as it still read higher again if I turned the nightlight off then on again. I think I should have placed the sensor much further away from the rest of the electronics and made sure it was well ventilated.

So to help stop provide a little cooling/ventilation I ended up carving a wooden base our of pine, that I could drill a hole at an angle for cooling with an exit hole in towards the top of the main section. The base also gave the nightlight a bit more heft and made it easier to turn on/off as well as to operate the switch to change it from temperature to simple nightlight.


Wooden base for nightlight Nightlight on stand (rear view)

Despite the slight disappointment that the temperature reading wasn’t going to stay constantly useful, I am quite happy with the nightlight. It looks nice and will does work well as an actual nightlight. The temperature reading facility has been proving useful to see what the temperature of William’s room is like and therefore what sort of nightclothes would work best. Given how protracted it’s development has been I’m rather happy really. It’s also rekindled my respect for the Arduino platform. The Mini Pro in particular is great. It’s very small, but extremely powerful and as it’s a bit cheaper than a full size Arduino makes it more appealing for embedding it into a project permanently. I guess the only downside would be the lack of integrated USB connection (for serial IO), but that’s not needed for every project.


Nightlight on stand Nightlight on stand

As usual source code is available in my Arduino Sketches github repo (plus a Fritzing wiring diagram of the circuit).

“Ultimate” Arduino Doorbell – part 2 (Software)

October 16th, 2010

As mentioned in the previous post about my arduino doorbell I wanted to get the doorbell and my Chumby talking.

As the Chumby runs Linux, is on the network and is able to run a recent version of Python (2.6) it seemed like it would be pretty easy to get it to send Growl notifications to the local network.

This did indeed prove fairly easy and involved three main activities:

  • Listening to the serial port for the doorbell to ring
  • Using Bonjour (formally Rendezvous)/Zeroconf to find computers on the network
  • Sending network Growl notifications to those computers

Getting Python and PySerial running on the Chumby is pretty easy. The Chumby simply listens for the doorbell to send the string ‘DING DONG’ and can then react as needed.


def listen_on_serial_port(port, network):
    ser = serial.Serial(port, 9600, timeout=1)
    try:
        while True:
            line = ser.readline()
            if line is not None:
                line = line.strip()
            if line == 'DING DONG':
                network.send_notification()
    finally:
        if ser:
            ser.close()

port is the string representing the serial port (e.g. /dev/ttyUSB0). network is an object that handles the network notifications (see below).

The network object (an instance of Network) has two jobs. Firstly to find computers on the network (using PicoRendezvous – now called PicoBonjour) and secondly to send network growl notifications to those computers.

A background thread periodically calls Network.find, which uses multicast DNS (Bonjour/Zeroconf) to find the IP addresses of computers to notify:


class Network(object):
    title = 'Ding-Dong'
    description = 'Someone is at the door'
    password = None
    
    def __init__(self):
        self.growl_ips = []
        self.gntp_ips = []

    def _rendezvous(self, service):
        pr = PicoRendezvous()
        pr.replies = []
        return pr.query(service)
    
    def find(self):
        self.growl_ips = self._rendezvous('_growl._tcp.local.')
        self.gntp_ips  = self._rendezvous('_gntp._tcp.local.')
        def start(self):
        import threading
        t = threading.Thread(target=self._run)
        t.setDaemon(True)
        t.start()
    
    def _run(self):
        while True:
            self.find()
            time.sleep(30.0)

_growl._tcp.local. are computers that can handle Growl UDP packets and _gntp._tcp.local. those that can handle the newer GNTP protocol. Currently the former will be Mac OS X computers (running Growl) and the latter Windows computers (running Growl for Windows).

I had to tweak PicoRendezvous slightly to work round a bug on the Chumby version of Python, where socket.gethostname was returning the string '(None)', but otherwise this worked ok.

When the doorbell activates netgrowl is used to send Growl UDP packets to the IP addresses in growl_ips and the Python gntp library to notify those IP addresses in gntp_ips (but not those duplicated in growl_ips). For some reason my Macbook was appearing in both lists of IP addresses, so I made sure that the growl_ips took precedence.


    def send_growl_notification(self):
        growl_ips = self.growl_ips
        
        reg = GrowlRegistrationPacket(password=self.password)
        reg.addNotification()
    
        notify = GrowlNotificationPacket(title=self.title,
                    description=self.description,
                    sticky=True, password=self.password)
        for ip in growl_ips:
            addr = (ip, GROWL_UDP_PORT)
            s = socket(AF_INET, SOCK_DGRAM)
            s.sendto(reg.payload(), addr)
            s.sendto(notify.payload(), addr)

    def send_gntp_notification(self):
        growl_ips = self.growl_ips
        gntp_ips  = self.gntp_ips
        
        # don't send to gntp if we can use growl
        gntp_ips = [ip for ip in gntp_ips if (ip not in growl_ips)]
        
        for ip in gntp_ips:
            growl = GrowlNotifier(
                applicationName = 'Doorbell',
                notifications = ['doorbell'],
                defaultNotifications = ['doorbell'],
                hostname = ip,
                password = self.password,
            )
            result = growl.register()
            if not result:
                continue
            result = growl.notify(
                noteType = 'doorbell',
                title = self.title,
                description = self.description,
                sticky = True,
            )

    def send_notification(self):
        '''
        send notification over the network
        '''
        self.send_growl_notification()
        self.send_gntp_notification()

The code is pretty simple and will need some more tweaking. The notification has failed for some reason a couple of times, but does usually seem to work. I’ll need to start logging the doorbell activity to see what’s going on, but I suspect the Bonjour/Zeroconf is sometimes finding no computers. If so I’ll want to keep the previous found addresses hanging around for a little longer – just in case it’s a temporary glitch.

You can see the full code in my doorbell repository.

“Ultimate” Arduino Doorbell – part 1 (Hardware)

September 6th, 2010

After a first couple of small Arduino projects I felt the need to make something a bit more useful and permanent.

I had seen Roo Reynolds talking about hacking his doorbell to get it onto Twitter and as our doorbell is a bit rubbish I thought this seemed like a good project. His hack only updated Twitter, so there was no direct physical sign that the doorbell had been rung. Given that our current doorbell is pretty rubbish anyway (it should ring, but just makes a rattling sound), I decided to start off with the physical/audible side of things and then later move on to pushing notifications out to laptops on the local network or beyond…

I’ve been documenting my progress on Flickr now for a while.

Take apart wireless doorbell

Following Roo’s approach, I picked up a cheap wireless doorbell from Tesco for about £9 and took it apart:

I was able to verify that I could turn an LED on/off with the doorbell at this stage, so I knew I could use that as a signal in the Arduino. Using a multimeter also let me figure out some more details about the voltage and current used to power the speaker:

Testing wireless doorbell with multi-meter

This was about 3.1 V and 75mA output. That’s a few milliamps more than the Arduino can tolerate, so I knew I had to make sure I put a resistor (22KOhm) in between the doorbell and the Arduino. The doorbell would also need to draw power from the Arduino, but luckily the Arduino has a separate 3V output, so that wasn’t an issue.

Testing connecting Arduino to doorbell

From there I verified that when the doorbell was activated I could read a drop in voltage from the wire on the doorbell labelled “SPI”. At this point I had the input for my Arduino.

Servos and prototypes

The next step was to provide some sort of audible output. Originally I had thought about just adding a buzzer, but fancied something a bit more old-fashioned. I figured it’d be good fun if the nice 21st century tech of the Arduino used some rather more ancient technology to create sound – a bell.

Using a micro servo from Oomlout I created a couple of prototypes.

I made a pretty simple circuit to hook up the servo, doorbell and arduino:

The first prototype used some lego and a bell from a Christmas ornament:

This worked, but the servo was probably louder than the bell!

Next I got hold of a small brass bell from a music shop. Luckily the top unscrewed and would let me easily attached it to a piece of lego. So another prototype was created using the small brass bell:

Prototype doorbell with brass bell

This worked much better!

The bell is about 100g in weight, which isn’t massive, but when it’s flung around the lego prototype would tend to move too. Not so good when this will live on the kitchen window sill. So I’d need something sturdier for the finished version.

A little soldering

As well as trying out a better bell I also made the circuit for the bell and servo more permanent, by soldering everything up on a piece of stripboard. I also used a few headers, so most of the circuit would plug into the Arduino – like a rudimentary shield. The wire to the pin controlling the servo, was left to be plugged in separately. I hadn’t soldered anything since school, so I ended up swearing quite a bit trying to do this. For me it was probably the trickiest part of the whole exercise, but it did work in the end. Just glad I had a multi-meter with a continuity mode to find the short-circuits – a knife worked well to clear up some of those.

Stripboard soldering

Full soldered doorbell + arduino

Woodwork

I next turned to my (t)rusty woodwork skills to create a sturdier version. First off some pieces of wood to mount the Arduino, doorbell circuit and servo:

Arduino and doorbell mounted on wood block

Servo mounted in wooden block

Next came the base and first part of the bell moving arm:

Then I added the top piece of the arm as well as the picture wire to make the bell swing properly:

Closeup of bell innards

At this point everything worked as expected:

Tidying up

After the sawing and sanding was finished there was still some general tidying up to do.

Once I’d taped down the servo wire and antena wire with electrical tape I needed to deal with the movement of the whole piece when the arm swings out. First I got hold of some Sugru and made some small rubberised feet to prevent the bell sliding around:

Sugru rubber feet on bell

The next task was to add a counter weight so the bell wouldn’t tip over. For this I made two piles of fifteen pennies, which I wrapped in electrical tape and taped to the ledge on the reverse side from the Arduino:

Counter weights on back/front of doorbell

Eventually these will be covered up and will probably actually make up part of the internal structure of the outer decoration. This should also mean they’ll end up being attached better. For now though electrical tape has proved sufficient.

One final tweak involved inserting some small nylon washers either side of the arm:

Washer and tidier wire

This was done to help make the movement of the arm more consistent and slightly smoother. Previously I was finding that the arm would shift position slightly, which sometimes caused problems for the servo.

Deployment

With the hardware finished I then set about actually getting it all up and running as our real doorbell. So imagine my horror when upon placing the doorbell on our kitchen window sill and connecting the power everything went haywire and the arm just constantly moved! After some tweaking of the code and kitchen-side debugging I realised that I really should make use of the Arduino’s internal pullup resistors for the doorbell pin. Up until that point I had left it “floating”. When powered by the USB this rarely drifted to zero, so I thought it was working fine. However on mains power it regularly dropped quite low, making the Arduino think the button had been pressed, triggering the servo. Configured the pullup resistor and tweaking the activation threshold (as it was now higher than zero) sorted out this problem perfectly:

Conclusion

So we now have a slightly Heath Robinson doorbell. It works better that our old one. There’s also plenty of scope for making it do more too. In fact phase two will be mostly about connecting the doorbell to my Chumby to get it communicating with the local network.

Check out my doorbell git repository on github for the code, as well as a fritzing circuit file.

Chumby to Arduino communication using PySerial

June 26th, 2010

So here are a few notes on getting a Chumby to talk to an Arduino using PySerial (and Python). It’s pretty easy, but I’ll document it to make it obvious. As the Chumby is sometimes a bit slow with a few of these steps, it’s good to know it will work in the end.

First you’ll want Python on the Chumby. At the time the latest version already compiled for the Chumby is Python 2.6, so it’s pretty up-to-date.

Once you’ve got Python installed and on a USB stick you’ll also want to download PySerial – I picked the latest version PySerial-2.5-rc2.

With PySerial expanded and on the USB stick (alongside Python) you’ll want to put the USB stick in the Chumby and connect to it via SSH.

Change to the directory for the USB stick (e.g. cd /mnt/usb).

You should see (at least) two directories, one for Python and one for PySerial:


chumby:/mnt/usb-EC5C-3D0A# ls -l
drwxr-xr-x    6 root     root         4096 Jun 26 21:15 pyserial-2.5-rc2
drwxrwxrwx    4 root     root         4096 Jan 10 13:51 python2.6-chumby

You’re first instinct may be to try and install PySerial via the usual call to python setup.py install. However this appears not to work.

All is not lost though – just manually copy the relevant directory (serial) from PySerial to the python site-packages directory, e.g.:


cp -r pyserial-2.5-rc2/serial python2.6-chumby/lib/python2.6/site-packages/

Know to check that’s worked open a python prompt and try to import the serial library:


chumby:/mnt/usb-EC5C-3D0A# python2.6-chumby/bin/python
Python 2.6.2 (r262:71600, May 23 2009, 22:28:43) 
[GCC 4.3.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import serial
>>> 

If you don’t see any errors (as above) then everything has installed ok.

Next step is to try out connecting an Arduino.

So first off you’ll want to ensure the Arduino has a program that can read from the serial port – to show that everything is working ok. In my case I picked my Morse Code program. This will read bytes from the serial port and toggle the built-in LED (on pin 13), so it’s handy for verifying the serial port is working.

So now you have a program loaded on the Arduino, connect it to the Chumby. The Arduino should get enough power from the Chumby to start up ok.

You need to work out which serial port the Arduino is using on the Chumby. List the tty’s in /dev and pick the most likely looking one (should have USB in it’s name):


chumby:/mnt/usb-EC5C-3D0A# ls /dev/tty*
/dev/tty      /dev/ttyS00   /dev/ttyS02   /dev/ttyS1    /dev/ttyS3
/dev/ttyS0    /dev/ttyS01   /dev/ttyS03   /dev/ttyS2    /dev/ttyUSB0

On my Chumby the serial port was /dev/ttyUSB0.

Now open up a python prompt again and try talking to the Arduino. You’ll need to configure the baud-rate of the serial port to match the program on the Chumby. In my case this was 9600.



chumby:/mnt/usb-EC5C-3D0A# python2.6-chumby/bin/python
Python 2.6.2 (r262:71600, May 23 2009, 22:28:43) 
[GCC 4.3.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import serial
>>> ser = serial.Serial('/dev/ttyUSB0', 9600, timeout=1)   
>>> ser.write('sos')
3

If you are using the same morse code program you should see the LED blink out ‘DOT-DOT-DOT DASH-DASH-DASH DOT-DOT-DOT’ – confirming that the serial port works.

This is really quite handy, as the Chumby is a small low-power Linux server. Coupled with Python this means it’s really easy to get any Arduino based project online, without needing a “normal” computer constantly running. Not quite as self-contained as using an Ethernet Shield, but the Chumby is fairly small, so it and an Arduino will easily sit on a window ledge (for example).

Arduino Tone Generator/”Theremin”

June 13th, 2010

So here’s another quick Arduino project. It is a “theremin” of sorts, but whereas a real theremin uses antennas to control pitch and volume this on uses a potentiometer for pitch and a push button for volume. The tone is output via a piezo buzzer (as used for generating morse tones in the previous project).


Arduino "Theremin"

The voltage from the potentiometer is read via analogRead, then is mapped to a freqency to output on the buzzer. To make things sound nicer the frequencies are limited to the twelve “well tempered” notes. As the potentiometer is turned the note played changes. There’s a little bit of smoothing (legato) in between note transitions too (so it sounds a bit more theremin-like).

All code for this Arduino “theremin” is available on github, as part of my Arduino Sketches project.

Here’s a demo of the tone generator in action:



My First Arduino Project (Morse Code)

May 26th, 2010

So I finally have an Arduino. I’ve been hankering after one for a while now, after seeing what Build Brighton and others have been able to do with them. So I was very happy when my better half paid attention to the hints I’d been dropping and got me an Arduino starter kit for my birthday. That was only a few days ago and thanks to how wonderfully easy the Arduino IDE is, it hasn’t taken long for me to get things working. The simplicity of writing the code, hitting upload and seeing the effect on the Arduino within seconds makes it really quick to try out different ideas. The only bit that’s tricky (for me at least) is the electronics side of things. Due to a slight fear of accidentally burning out the 8bit AVR chip at the core of the Arduino I’m being super cautious. Though this is due to my at best high school knowledge of electronics. That and the fact that I’m pretty much a software boy.

So what to make first? Well morse code seemed like a good starting point. I’d written an app to output morse on the capslock LED before and the starter kit had LEDs, so it seeded like a good starting point. On closer inspection there was also a piezoelectric buzzer – so even better it was possible to generate a tone too!

Getting the LED to turn on and off was pretty easy and it forms the standard “hello world” program for the Arduino. Getting the buzzer to generate a tone was marginally trickier, but not that hard and basically just consisted of turning it on and off quick enough to cause a vibration and therefore make a sound. With the help of this guide to making the Arduino play the Can-Can I also had details of how to wire the circuit correctly (in particular adding in a suitable resistor to avoid overloading the AVR chip).

Using the starter kits breadboard, jumper wires, a 330 Ohm resistor, an LED and the piezoelectric buzzer I put together this:


Arduino Morse Code Circuit

The buzzer had it’s positive pin wired in to pin 4 on the Arduino and the LED was in turn wired in to pin 13. In the picture above, I arbitrarily used yellow jumper leads for “ground” and green for positive. So one green lead goes to each pin (4 and 13) and only one yellow lead goes to the “ground” on the Arduino.

Initially I hard-coded the message the Arduino was going to output, but having to re-compile each time to change the message seemed a little tedious. So I decided to get the Arduino to read from the serial port, store the characters it read in, then output the relevant morse. To achieve this the program has a 512 byte buffer that it fills up with data read from the serial port. If the buffer is full it signals this by writing back a -1 down the serial port – otherwise it echos back what it has read in. As it plays the morse it moves along the buffer looking for the next character. Once all characters are output it resets the buffer. The program is actually able to read from the serial port whilst it is turning the LED on/off and generating tones. It’s only limited by the size of the buffer it is using and the fact that it can read faster from the serial port than it can output morse code.

Most of the work in the code revolved around trying to both read from the serial port and generate tones. If the morse was known ahead of time, it would be pretty easy to right several for-loops to run through each character generating tones until we were finished. However the program would not start reading from the serial port until it had finished outputting the morse. So apart from using some basic state-machine style antics to keep track of which character we were on and whether we were currently during a dot, dash or silent period the major a-ha moment for me was realizing how to easily generate a consistent tones without using delays in the code. In previous code I’d seen for generating tones, the code looked like:


for (long i=0; i < numCycles; i++){
    digitalWrite(targetPin,HIGH); // write the buzzer pin high to push out the diaphram
    delayMicroseconds(delayValue); // wait for the calculated delay value
    digitalWrite(targetPin,LOW); // write the buzzer pin low to pull back the diaphram
    delayMicroseconds(delayValue); // wait againf or the calculated delay value
}

This is nice and easy to follow, but all those calls to delayMicroseconds mean you are hanging around waiting for the air to move to make a sound.

As I wasn't too concerned with the particular fidelity of the sound from the buzzer I opted for the following instead:


void morse_pulse_on() {
  digitalWrite(LED_PIN, HIGH);
  unsigned long period = micros() % buzzer_delay;
  digitalWrite(BUZZER_PIN, period < (buzzer_delay>>1)? HIGH : LOW);
}

This was called every time through the loop() function if a sound needed to be played. As there is no delay in calling it, one could then immediately perform other tasks, such as checking for new serial data or turning the LED on and off. It's quite simple real - the modulus operator (%) is used to get the sub-divide the current time in microseconds into a number between 0 and buzzer_delay (a value pre-calculated to let us generate the right frequency) representing the current "period". If we are halfway through this period then we set the buzzer to HIGH, otherwise we set it to LOW. By repeatedly calling morse_pulse_on we end up with (in this case) a glorious 700Hz tone.

All code for this Arduino morse code program is available on github, as part of my Arduino Sketches project. Hopefully I'll add more code to that project as I get a chance to delve deeper into what the Arduino can do.

Here's a demo of the whole thing in action:



UPDATE: not long after finishing this, I discovered the tone and noTone functions. These produce a better tone than the technique outlined above. Though they do involve use of one of the interrupts on the arduino, that's normally used for PWM on pins 3 and 11 - not that it's a problem for this project.