Jonathan Thomson's web journal

Getting Started with the STM32F4DISCOVERY in Linux November 17, 2011

Filed under: Electronics — jethomson @ 8:58 pm

Building an ARM toolchain
To compile code for the STM32F4DISCOVERY you’ll need an ARM toolchain that supports the Cortex-M3. I used the build script summon-arm-toolchain to build one. Before running the script you need to install several dependencies:

$ su -c "apt-get install flex bison libgmp3-dev libmpfr-dev libncurses5-dev libmpc-dev autoconf texinfo build-essential libftdi-dev"

You might also need to run:

$ su -c "apt-get build-dep gcc-4.5"

Now make a directory to hold the files you’ll need to work with the STM32F4DISCOVERY:

$ mkdir ~/stm32f4discovery_root
$ cd ~/stm32f4discovery_root

Next clone the summon-arm-toolchain, read the README, and begin the build:

$ git clone https://github.com/esden/summon-arm-toolchain.git
$ cd summon-arm-toolchain
$ ./summon-arm-toolchain

 

Setting up the software to communicate with the STLINK
While the toolchain is compiling you can set up the software required to communicate with the STLINK, which is the on-board JTAG programmer/debugger on the lefthand side of the board. From a new shell run:

$ su -c "apt-get install libusb-1.0-0-dev"
$ cd ~/stm32f4discovery_root
$ git clone git://github.com/texane/stlink.git stlink_texane
$ cd ~/stm32f4discovery_root/stlink_texane
$ make

Now you should install the udev rules 49-stm32l-discovery.rules and restart udev. These steps will create a symbolic link called /dev/stm32l_stlinkN and give a normal user permission to access it.

$ su
# cp 49-stm32l-discovery.rules /etc/udev/rules.d/
# /etc/init.d/udev restart
# exit

 

Example projects and makefiles
Next, download the STM32F4DISCOVERY firmware package and an archive of makefiles for building some of the example projects found in the firmware package.

$ cd ~/stm32f4discovery_root
$ wget http://www.st.com/internet/com/SOFTWARE_RESOURCES/SW_COMPONENT/FIRMWARE/stm32f4discovery_fw.zip
$ unzip stm32f4discovery_fw.zip
$ wget http://jthomson.towhee.org/stm32f4discovery_files/STM32F4DISCOVERY_Makefiles.zip
$ unzip STM32F4DISCOVERY_Makefiles.zip
$ cd ~/stm32f4discovery_root/STM32F4DISCOVERY_Makefiles
$ cp Makefile.IO_Toggle ~/stm32f4discovery_root/STM32F4-Discovery_FW_V1.1.0/Project/Peripheral_Examples/IO_Toggle/
$ cd ~/stm32f4discovery_root/STM32F4-Discovery_FW_V1.1.0/Project/Peripheral_Examples/IO_Toggle

If the toolchain installation still hasn’t finished, then familiarize yourself with the example code and makefiles or take a break.

 

Compiling and Flashing
Once summon-arm-toolchain has finished building your ARM toolchain you can try it out on the IO_Toggle example by using the following commands.

$ cd ~/stm32f4discovery_root/STM32F4-Discovery_FW_V1.1.0/Project/Peripheral_Examples/IO_Toggle
$ make -f Makefile.IO_Toggle

If the build finished without error, then you’re ready to try downloading it to the board. Plug in the board and use stlink to write the blinking LED example, IO_Toggle.bin, to the STM32F4DISCOVERY’s flash memory.

$ PATH=~/stm32f4discovery_root/stlink_texane/flash:$PATH
$ flash write IO_Toggle.bin 0x8000000

Power cycle the board by removing then reinserting the USB plug. If the download was successful, the LEDs should light up in a clockwise pattern and pressing the pushbutton will not result in the board entering test mode.

You can easily modify one of the sample makefiles to work with another example by examining the .uvproj file (found in the example’s MDK-ARM directory) to determine which defines (-D), includes (-I), source files, etc. to add to the new makefile. Just open the .uvproj file in a text editor and look for lines like these:

<Define>USE_STDPERIPH_DRIVER,STM32F4XX</Define>
<IncludePath>
..\;
..\..\..\..\Libraries\CMSIS\Include;
..\..\..\..\Libraries\CMSIS\ST\STM32F4xx\Include;
..\..\..\..\Libraries\STM32F4xx_StdPeriph_Driver\inc;
..\..\..\..\Utilities\STM32F4-Discovery
</IncludePath>

<FilePath>..\main.c</FilePath>
<FilePath>..\..\..\..\Utilities\STM32F4-Discovery\stm32f4_discovery.c</FilePath>
<FilePath>..\..\..\..\Libraries\STM32F4xx_StdPeriph_Driver\src\stm32f4xx_rcc.c</FilePath>
etc.

 

Final Notes
There is a lot I don’t understand about compiling for the STM32F4DISCOVERY and I’m certain that the Makefiles I’ve provided could be improved. For example, I don’t know which -m options (see the Makefile’s MCUFLAGS variable) to set, when to set them, and why. If you have any corrections or improvements to share, please leave a comment.

 

Links
The STM32F4 high-performance discovery board (STM32F4DISCOVERY) and a range of of STMicroelectronics products are available at Newark
Alternate method of programming the STM32F4DISCOVERY using the Bus Blaster and OpenOCD
A fork of the summon-arm-toolchain that builds gcc for the Cortex-M4F
A comment discussing this fork

Advertisements
 

Getting Started with the STM32VLDISCOVERY in Linux

Filed under: Electronics — jethomson @ 8:16 pm

Building an ARM toolchain
To compile code for the STM32VLDISCOVERY you’ll need an ARM toolchain that supports the Cortex-M3. I used the build script summon-arm-toolchain to build one. Before running the script you need to install several dependencies:

$ su -c "apt-get install flex bison libgmp3-dev libmpfr-dev libncurses5-dev libmpc-dev autoconf texinfo build-essential libftdi-dev"

You might also need to run:

$ su -c "apt-get build-dep gcc-4.5"

Now make a directory to hold the files you’ll need to work with the STM32VLDISCOVERY:

$ mkdir ~/stm32vldiscovery_root
$ cd ~/stm32vldiscovery_root

Next clone the summon-arm-toolchain, read the README, and begin the build:

$ git clone https://github.com/esden/summon-arm-toolchain.git
$ cd summon-arm-toolchain
$ ./summon-arm-toolchain

 

Setting up the software to communicate with the STLINK
While the toolchain is compiling you can set up the software required to communicate with the STLINK, which is the on-board JTAG programmer/debugger on the lefthand side of the board. From a new shell run:

$ cd ~/stm32vldiscovery_root
$ su -c "apt-get install libusb-1.0-0-dev"
$ wget http://arm-utilities.googlecode.com/files/arm-utilities-2011-6-28.tgz
$ tar xvzf arm-utilities-2011-6-28.tgz
$ cd ~/stm32vldiscovery_root/arm-utilities/stlink-download
$ gcc -o stlink-download stlink-download.c

Now you should install the udev rules 10-stlink.rules, add your username to the group tape, and restart udev. These steps will create a convenient symbolic link called /dev/stlink to the board’s actual /dev entry (e.g. /dev/sg2)

$ su
# cp 10-stlink.rules /etc/udev/rules.d/
# usermod -aG tape your_username_here
# /etc/init.d/udev restart
# exit

 

Example projects and makefiles
Next, download the STM32VLDISCOVERY firmware package (AN3268) and an archive of makefiles for building some of the example projects found in the firmware package.

$ cd ~/stm32vldiscovery_root
$ wget http://www.st.com/internet/com/SOFTWARE_RESOURCES/SW_COMPONENT/FIRMWARE/stm32vldiscovery_package.zip
$ unzip stm32vldiscovery_package.zip
$ wget http://jthomson.towhee.org/stm32vldiscovery_files/STM32VLDISCOVERY_Makefiles.zip
$ unzip STM32VLDISCOVERY_Makefiles.zip
$ cd ~/stm32vldiscovery_root/STM32VLDISCOVERY_Makefiles
$ cp Makefile.GPIOToggle ~/stm32vldiscovery_root/an3268/stm32vldiscovery_package/Project/Examples/GPIOToggle/
$ cd ~/stm32vldiscovery_root/an3268/stm32vldiscovery_package/Project/Examples/GPIOToggle
$ cp ../../Demo/TrueSTUDIO/DISCOVER/STM32F100RB_FLASH.ld ./

As described in README.TXT, you’ll need to edit Utilities/STM32vldiscovery.h to change the line: #include "STM32f10x.h" to lowercase: #include "stm32f10x.h". If the toolchain installation still hasn’t finished, then familiarize yourself with the example code and makefiles or take a break.

 

Compiling and Flashing
Once summon-arm-toolchain has finished building your ARM toolchain you can try it out on the AN3268 GPIOToggle example by using the following commands.

$ cd ~/stm32vldiscovery_root/an3268/stm32vldiscovery_package/Project/Examples/GPIOToggle
$ make -f Makefile.GPIOToggle

If the build finished without error, then you’re ready to try downloading it to the STM32VLDISCOVERY. Before plugging in the STM32VLDISCOVERY run the following command:

$ su -c "modprobe -r usb-storage && modprobe usb-storage quirks=483:3744:lrwsro"

Plug in the board and wait for Linux to finish mounting it. Although the udev 10-stlink.rules are written to prevent the board from being auto-mounted it happens on my system regardless. Once the board is mounted, you should be able to see three URL files. In my experience, you must wait for the board to be mounted before attempting to flash a program; otherwise, you will crash Linux. Finally, use stlink-download to write the blinking LED example, GPIOToggle.bin, to the STM32VLDISCOVERY’s flash memory.

$ PATH=~/stm32vldiscovery_root/arm-utilities/stlink-download:$PATH
$ stlink-download /dev/stlink program=GPIOToggle.bin
$ stlink-download /dev/stlink reset
$ stlink-download /dev/stlink run

You can easily modify one of the sample makefiles to work with another example by examining the .uvproj file (found in the example’s MDK-ARM directory) to determine which defines (-D), includes (-I), source files, etc. to add to the new makefile. Just open the .uvproj file in a text editor and look for lines like these:

<Define>STM32F10X_MD_VL, USE_STDPERIPH_DRIVER</Define>
<IncludePath>
..\;
..\..\..\..\Libraries\CMSIS\CM3\CoreSupport;
..\..\..\..\Libraries\CMSIS\CM3\DeviceSupport\ST\STM32F10x;
..\..\..\..\Libraries\STM32F10x_StdPeriph_Driver\inc;
..\..\..\..\Utilities\
</IncludePath>

<FilePath>..\..\..\..\Libraries\STM32F10x_StdPeriph_Driver\src\misc.c</FilePath>
<FilePath>..\..\..\..\Libraries\STM32F10x_StdPeriph_Driver\src\stm32f10x_exti.c</FilePath>
<FilePath>..\..\..\..\Libraries\STM32F10x_StdPeriph_Driver\src\stm32f10x_gpio.c</FilePath>
etc.

 

I originally started working with a package that builds all the examples at once, but this requires compiling and linking code that isn’t needed by every example so it is best to create a tailored makefile for each individual project. However, it’s an easy way to create all the .bin file examples so that you can quickly try them out on your board. The STM32VLDISCOVERY_firmware_build_all package is based on Geoffrey Brown’s project “to enable building for the STM32VLDISCOVERY board in a Unix environment.” I modified his project slightly to fix some case sensitivity errors, a missing syscall _exit() function, and to prevent from redistributing code in possible violation of the code’s license.

$ cd ~/stm32vldiscovery_root
$ wget http://jthomson.towhee.org/stm32vldiscovery_files/STM32VLDISCOVERY_firmware_build_all.zip
$ unzip STM32VLDISCOVERY_firmware_build_all.zip
$ cd ~/stm32vldiscovery_root/STM32VLDISCOVERY_firmware_build_all
$ make

 

Final Notes
There is another open source software project that supports downloading and debugging via the STLINK hardware known as stlink. It allows JTAG debugging with gdb and OpenOCD. Unfortunately I wasn’t able to use stlink because it crashes my computer. I believe this may be caused by a bug in libsgutils2-dev. Here’s a link to the open source stlink project.

 

Links
The STM32 Value Line Discovery Kit (STM32VLDISCOVERY) and a range of of STMicroelectronics products are available at Newark

A great site on developing for the STM32 using open source tools
Geoffrey Brown’s makefiles to build for the STM32VLDISCOVERY board in a Unix environment
stlink-download wiki page
Another guide that shows how to build the STM32VLDISCOVERY firmware package’s examples using Eclipse and CodeSourcery
A good list of the various toolchains and utilities for the STM32
Programming STM32F10x I/O port pins
Cortex M3 For Dummies – STM32 Discovery Board
A fork of stlink that may work for the STM32VLDISCOVERY

 

7400 Competition — Flickering Jack-o’-lantern October 21, 2011

Filed under: Electronics — jethomson @ 12:43 am

The dollar store sells some cool, toy jack-o’-lanterns that have a small incandescent bulb with a bimetallic strip which causes it to blink and a removable battery holder with an on/off switch. They are very easy to disassemble. They’re a great deal for just a $1! Here’s a picture of it’s insides before I added my custom board.

 

Any or all of the six inverters in a 74HC14 can be used as a relaxation oscillator by adding a feedback resistor and a capacitor from the input to ground. The board below produces four square waves with frequencies somewhere around 2.5, 6.25, 9.19, and 15.24 Hz. Combining them together with a simple resistor mixer results in a seemingly random, non-periodic waveform, which when used to drive an LED causes a fast, eerie flickering effect. I placed one blue and one red LED in circuit such that when one was lit the other would be dark and vice versa. The red LED has a lower turn-on voltage so it’s the dominant color seen. The LEDs are covered in hot glue to diffuse their light.

 

 

Using a resistor mixer like this wastes power because whenever two inverter outputs are high and the other two are low then both LEDs are off and the only load is 1 kohm. However, the mixer has the advantage of allowing the square waves to both add to and subtract from one another meaning that an LED will put out different levels of brightness as well as being on and off for different durations. The red LED has three levels, bright, dim, and off, but the blue LED with it’s higher turn on voltage only turns on and off. This mixer also makes it very easy to control two LEDs by sourcing current to one and sinking current from the other. If you don’t want dueling LEDs you can use the outputs to drive transistors in an open-drain arrangement to save power and get a wider range of lighting levels. It’s also possible to make a simple persistence of vision device by connecting different colored LEDs to separate oscillators. For a more candle-like flicker effect I suggest using resistors in the 1 to 10 Megaohm range. Ultimately I settled on the values I used through trial and error until I found an flickering effect I liked.

 

Watch closely and every once in a while you’ll see the jack-o’-lantern turn completely blue with no red for a brief instant. It looks like a creepy after image. The blue flash happens so fast that you’re not quite sure what you saw which gives this jack-o’-lantern a very spooky quality. Unfortunately the flickering is a bit too quick for my camera so you will see some screen tearing in the video.

 

 

Here’s a link to the RGB pumpkin I did last year.

 

7400 Competition — Illogical Dickson Doubler October 19, 2011

Filed under: Electronics — jethomson @ 4:59 am

Update: This entry took 2nd place in the 7400 Competition. I won a Parallax Boe-Bot Robot Kit. Thanks Parallax! Thanks Ian!

Don’t listen to goatee Spock. He’s evil! This entry for Dangerous Prototypes’ Open 7400 Logic Competition is most illogical and at least somewhat fascinating. In this article I’ll demonstrate how you can use the internal protection diodes and back powering to power a 74HC14 at a voltage “double” (minus diode drops) that of the primary power supply. I call this circuit an illogical doubler mostly as a pun because the 74HC14 is a logic chip but also because of the quirky way it works. Perhaps “ill-understood” (by me) is a more apt description for the latter case.

 

 

 

Introductory Concepts
Most HCMOS devices have input and output protection circuitry to prevent ESD damage to the MOSFETs which make up the integrated circuit. How the protection circuitry is implemented varies among the devices and semiconductor manufacturers, but the usual way is to use clamping diodes to keep over/undervoltages away from the MOSFETs’ sensitive gates. The protection diode from an I/O pin to VDD can be a bother to hardware tinkerers because it will conduct if the IC’s power pin is disconnected and the I/O pin has a voltage on it resulting in the IC being powered by the I/O pin. This is known as back powering.

 

The Dickson doubler is a clever little circuit. It’s a type of charge pump voltage multiplier. When Clock goes low the input capacitor is charged via Vin and when Clock goes high it pushes the charge on the input capacitor onto the output cap. The diodes are necessary to make the charge flow in the desired direction. The output voltage of the Dickson doubler is only twice the input when the voltage drop caused by the diodes is negligible compared to 2*Vin.

 

Notice that the protected pins on a HCMOS IC have incoming and outgoing diodes just like the first capacitor in a Dickson doubler. Therefore if we connect Vin to the ground pin (i.e. VSS), the positive leg of a capacitor to a diode protected I/O pin and the negative leg to a clock source, then connect the positive leg of a second capacitor to the IC’s power pin (i.e. VDD) and the negative leg to ground, we’ll should be able to use the protection diodes to back power the IC at double the voltage Vin minus the voltage drop caused by the diodes. That’s the idea at least, but there are a few quirks that I’ll explain as we go along. To test the illogical Dickson doubler I used two SN74HC14N ICs. The one on the left generated the clock source and the right one served as the victim back powered doubler.

 

 

Output Pin Illogical Doubler
Oddly, the illogical doubler only works when the input capacitor is connected to an output pin. Even stranger, the doubler still works, better in fact, if Vin is connected to another output pin instead of ground; in this case, I don’t know what path the charging current takes to get from Vin to the input capacitor.

 

 

This video demonstrates using the protection diodes of a 74HC14 as part of a Dickson doubler. The UV LED (3.6V @ 20 mA) is only dimly lit by the voltage supplied by the batteries. The doubler increases the voltage from 2.68 V to 4.35 V which is 1.01 volts less than twice the input voltage. Although it is difficult to see in this video, when the LED is connected to the higher voltage it outputs more light. Next the input voltage wire is moved from ground to an output pin to show that the doubler still functions when an output is used. Finally the effects of lowering the clock frequency are shown by inserting a 0.1 uF capacitor in the clock circuitry.

 

 

Input Pin Illogical Doubler
Unfortunately the “output pin illogical doubler” doesn’t function properly when the ground pin is grounded even if Vin is fed into an output pin instead of the ground pin. Without a ground all the circuit can do is provide a higher voltage. However, by moving the input capacitor to an input pin and providing Vin through a separate diode connected to the same pin we’re able to sneak power through the protection diode, get a higher voltage, and use the 74HC14 normally.

 

 

In this video the illogical doubler increases the voltage from 2.68 V to 3.90 V which is 1.46 volts less than twice the input voltage. When the LED is connected to the higher voltage it outputs more light compared to when it was powered by the batteries alone. Next a 10 Megohm resistor is connected from the output pin to the input pin which forms an RC circuit with the 0.1 uF cap that is connected to the input pin and ground. The RC circuit causes the output to oscillate thereby demonstrating that the 74HC14 still functions normally.

 

 

Final Thoughts
Because the illogical doubler only uses the internal protection diodes it should work with ICs other than the 74HC14. I was able to get 4.6 V from 2.68 V using an SN74HC595N configured as an output illogical doubler. I didn’t blow a single pin while playing with any of my chips. They didn’t even get hot, but TI’s datasheets say the input/output clamp current is only ±20 mA, so don’t overload them. You may be wondering if it is possible for the back powered 74HC14 to provide it’s own Clock signal; I tried it and it doesn’t work. When Clock is pulling the input capacitor charges as expected; however, when Clock goes high a path is created for the input capacitor to discharge itself that doesn’t go through the output capacitor. For best results with a charge pump, you should optimize the frequency and capacitor values. I didn’t see the point in doing this because I thought it insane to use one of these circuits for anything but a laugh. For the frequency, I ran the 74HC14 Clock as fast as it would go. In general a faster frequency worked better, but I’ve read that there is a point where you lose more from parasitic capacitive losses than you gain by going faster. For the capacitor values I simply used two 100 uF, 50 V electrolytics. I’m not an expert in charge pumps. I simply used trial and error to find values that worked. If you can shed light on how the output pin illogical doubler with Vin supplied through an output pin instead of ground works, have a correction, or anything at all to share, then please leave a comment!

 

 

Links
AN-248 Electrostatic Discharge Prevention-Input Protection
Circuits and Handling Guide for CMOS Devices

Electrostatic Discharge: Understand, Simulate, and Fix ESD Problems. Appendix A

see page 8 of HCMOS Design Considerations

 

Project Ouroboros — Reflashing a betemcu USBasp Programmer August 18, 2011

Filed under: Electronics — jethomson @ 11:40 pm

Introduction
USBasp is a free, open source firmware and reference design for implementing a USB AVR programmer. It uses simple circuitry and an ATmega8 or ATmega*8 for interfacing with the USB host. A variety of inexpensive boards ($6 US) based on the USBasp project can be purchased from many eBay sellers. Re-programming one of these boards can often be an effective solution for a one-off project where the cost of a full development board or the time consumed designing and assembling a custom board is prohibitive. They can even be made to work with Arduino. This article focuses on the betemcu.cn board pictured here. Note that there are at least two versions of this board.

 

Terminology
V-USB — a firmware-only implementation of a low-speed USB device for Atmel AVR microcontrollers.
in-circuit programmer — a device for burning code and changing fuse settings on a microcontroller which remains in its application circuit.
USBasp – a USB in-circuit programmer for Atmel AVR microcontrollers that utilizes V-USB.
boot loader — a bit of firmware capable of burning code onto the same microcontroller on which it resides. A boot loader allows new code to be uploaded to a microcontroller without an external programmer.
USBaspLoader – a USB boot loader that follows the USBasp protocol.

It’s possible to erase the USBasp firmware and load a new program onto the betemcu.cn board via the 10 pin header. First insert a jumper wire into the two holes circled in yellow in the picture above. Doing this connects RST on the 10 pin header to PC6 (RESET). Now you can use a second programmer to burn the code. However if you put USBaspLoader onto the betemcu.cn board you can use AVRDUDE or Arduino to upload programs directly over USB without having to use an external programmer. Once you have the USBaspLoader on the board there is still enough room left to re-upload the USBasp firmware so that the betemcu.cn board can function as an external programmer again. I call this Project Ouroboros because it’s a play on the word asp and seeming recursiveness of using USBaspLoader to put USBasp onto a USBasp programmer.

 

Getting started
First you’ll need a betemcu.cn USBasp programmer (hereafter betemcu board) and a second, external programmer (hereafter primary programmer) capable of programming AVR microcontrollers over SPI. Next you should test out your betemcu board to make sure it’s not defective. Before you load new code onto your betemcu board you should use the primary programmer and AVRDUDE to save the betemcu board’s factory installed firmware to your computer and discover its original fuse settings. Doing this will allow you test whether the device is still functional by attempting to restore it to a known good state by writing back the original firmware and fuse settings. The following command will save the betemcu board’s firmware and display its fuse settings. The -c programmer-id option is the ID of the primary programmer.


avrdude -p atmega8 -c programmer-id -v -U flash:r:betemcu_factory_firmware.hex

 

Fuse settings for burning code to the betemcu board with an external programmer
If you are unfamiliar with microcontroller configuration fuses, then please visit the relevant articles in the Links section to learn more about them. You should also use a fuse calculator to double check fuse settings before applying them. The original settings for my betemcu board were hfuse = 0xD9 and lfuse = 0xFF but these leave CKOPT unprogrammed which should be set for crystals faster than 8 MHz. The makefile for USBasp uses hfuse = 0xC9 and lfuse = 0xEF but these settings don’t work because the start-up delay isn’t long enough, in fact they (recoverably) brick the betemcu board. Setting the fuses to hfuse = 0xC9 and lfuse = 0xBF sets a proper start-up delay and enables CKOPT. These also set a brown-out detection level of 2.7 V which is necessary if you want to use the onboard 3.3 V regulator for power. Here’s an example hex file that blinks the LEDs on a betemcu board. (mirror)


high fuse: 0xC9
low fuse: 0xBF


avrdude -p atmega8 -c programmer-id -U hfuse:w:0xC9:m -U lfuse:w:0xBF:m
avrdude -p atmega8 -c programmer-id -U lock:w:0x3F:m
avrdude -p atmega8 -c programmer-id -v -U flash:w:betemcu_blink.cpp.hex

 

To restore the boot loader:

avrdude -p atmega8 -c programmer-id -v -U flash:w:betemcu_factory_firmware.hex

 

If you’ve downloaded the USBasp package, you can also restore the boot loader with a precompiled hex file:

avrdude -p atmega8 -c programmer-id -v -U flash:w:usbasp.atmega8.2011-05-28.hex

 

Modifications required to run USBaspLoader on the betemcu board
The unmodified version of USBaspLoader connects PD2 and PD4 to the USB data plus and data minus lines. However the betemcu board connects PB1 and PD2 to USB data plus and PB0 to USB data minus. Therefore the USBaspLoader code needs to be changed to use the same pins. Here’s a snippet of bootloaderconfig.h with the changes already made.


#define USB_CFG_IOPORTNAME B
/* This is the port where the USB bus is connected. When you configure it to
* "B", the registers PORTB, PINB and DDRB will be used.
*/
#define USB_CFG_DMINUS_BIT 0
/* This is the bit number in USB_CFG_IOPORT where the USB D- line is connected.
* This may be any bit in the port.
*/
#define USB_CFG_DPLUS_BIT 1
/* This is the bit number in USB_CFG_IOPORT where the USB D+ line is connected.
* This may be any bit in the port. Please note that D+ must also be connected
* to interrupt pin INT0!
*/

Vanilla USBaspLoader is set up so that it will only enter self-programming mode (i.e. listen for a program being uploaded and write it to the flash) if PD7 is held low after pulling the reset pin low (i.e. an external reset) occurs. Therefore you will have to make a couple of modifications to the betemcu board. First you’ll want to add a normally open pushbutton connected to the reset pin and ground for producing an external reset. Soldering the pushbutton connection at the reset pin’s pull-up resistor is easier than soldering it directly to the pin.

 

For the second modification you’ll have to determine how you want to signal the boot loader to wait for a program. The typical method is to use a jumper to connect PD7 to ground. The NC (not connected) pin of the 10 pin header is conveniently located 0.1″ from one of the header’s ground pins so running a mod wire from PD7 to NC is a simple way to add a jumper header. However, if you plan on interfacing the betemcu board with another circuit through the 10 pin header by using a 10 pin IDC you will want to add the jumper header somewhere else on the board because of the difficulty of inserting and removing the 10 pin IDC while the USB connector is plugged in. Using a pushbutton connected to PD7 and ground instead of a jumper is also an option, but you’ll have to keep the pushbutton pressed until AVRDUDE has finished.

Here’s a picture of my modified board. At first I was using a jumper to connect PC2 (orange wire to NC) to ground, but later I decided to add a second pushbutton to signal the boot loader to wait for a program to be uploaded. The brown and blue wires are for I2C and not a necessary modification.

 

The pin used to signal the boot loader can be easily changed by modifying bootloaderconfig.h. If you want to use a different pin make certain it’s not already being used for another function by consulting USBasp schematic and by carefully examining the betemcu board. Keep in mind that pins at the corners of the ATmega8’s package are easier to solder to.

Compiling a new hex file from the USBaspLoader source also requires a few changes to the Makefile. I’ve created a package of the vanilla version of USBaspLoader preconfigured to work with the betemcu board. I’ve also included a pre-compiled hex in case you have difficulty compiling. Here’s a link to the preconfigured vanilla USBaspLoader package. (mirror)

 

Alternate version of USBaspLoader
I wasn’t happy with using a jumper (or pressing and holding a pushbutton) to signal the boot loader to enter self-programming mode (SPM). So I’ve made some changes to the vanilla version and packaged them as an alternate version of USBaspLoader. The alternate version allows you to enter and stay in self-programming mode by pressing and releasing a pushbutton, which is a more typical method used by other USB development boards with microcontrollers that have a HWB pin. I’ve also added an option that compiles the boot loader so that it always enters SPM after every reset and uses a timeout to exit the boot loader, which makes adding a jumper (or a second pushbutton) unnecessary. This is the method that should be most familiar to Arduino users. For the betemcu board I made a few more modifications to utilize the board’s LEDs. Click here to download the alternate version of USBaspLoader configured for the betemcu board. (mirror) Here’s a sample of some of the changes I made:


#define TIMEOUT_ENABLED 1
/* If TIMEOUT_ENABLED is defined to 1 then the boot loader will always load
* and stay active until the programmer closes the connection or the time
* out period has elapsed. Since the boot loader always loads there is no
* need for a jumper on the bootLoaderCondition() pin. Costs ~108 bytes.
*/
#define TIMEOUT_DURATION 5
/* The number of seconds the boot loader waits before exiting if no activity
* has occurred during the timeout interval. If TIMEOUT_ENABLED is defined
* to 0 this define will be ignored. Maximum value is 255 seconds.
*/
#define USING_PUSHBUTTON 1
/* If USING_PUSHBUTTON is defined to 1, then a press and release of a
* pushbutton on the bootLoaderCondition() pin can be used to signal that
* you wish to enter the boot loader. If USING_PUSHBUTTON is defined to 0,
* then you must use a jumper or the pushbutton must be pressed and held
* for the duration of the programming (failing to do so will result in
* the boot loader exiting prematurely).
*/

 

Fuse settings for burning USBaspLoader to the betemcu board with an external programmer
The USBaspLoader hex file for an ATmega8 at 12 MHz is around 1900 bytes so the 2 kB boot loader section is required. After flashing a boot loader, the proper lock bits should be set so that the boot loader isn’t overwritten when you use it to upload a program. These fuses set a boot flash section size of 1024 words (2048 bytes) and a start-up delay of 64 ms.


high fuse: 0xC8
low fuse: 0xBF
lock bits (unlock): 0x3F (AVRDUDE)
lock bits (lock): 0x0F (AVRDUDE)

lock bits (unlock): 0xFF (AVR studio)
lock bits (lock): 0xCF (AVR studio)


avrdude -p atmega8 -c programmer-id -U hfuse:w:0xC8:m -U lfuse:w:0xBF:m
avrdude -p atmega8 -c programmer-id -v -U flash:w:alternate_USBaspLoader_betemcu_pushbutton.hex
avrdude -p atmega8 -c programmer-id -U lock:w:0x0F:m

 

If you don’t want to add a SPM jumper or button, you can use the timeout boot loader.

avrdude -p atmega8 -c programmer-id -U hfuse:w:0xC8:m -U lfuse:w:0xBF:m
avrdude -p atmega8 -c programmer-id -v -U flash:w:alternate_USBaspLoader_betemcu_timeout.hex
avrdude -p atmega8 -c programmer-id -U lock:w:0x0F:m

 

Flashing a program with USBaspLoader
Now that you have USBaspLoader on your betemcu board you can flash new programs to it directly over USB. Here’s a link to a program from the V-USB project that emulates a mouse. (mirror) To instruct your board to enter self-programming mode, start by pressing and holding the program button, next press and release the reset button, then release the program button. The green LED should turn on indicating the board is ready for a program upload. Upload the hex file using the following command. If the upload is successful you should see the mouse cursor move in a circle.


avrdude -p atmega8 -c usbasp -v -U flash:w:vusb_mouse_example.hex

 

You can also upload the USBasp firmware onto the board to restore its ability to program other AVR microcontrollers.


avrdude -p atmega8 -c usbasp -v -U flash:w:usbasp.atmega8.2011-05-28.hex

 

Arduino
With USBaspLoader on the board it is now compatible with the Arduino programming environment. You must add some entries to boards.txt to be able to upload a sketch within the Arduino IDE. Follow this link for an explanation of the variables used in boards.txt. Put the following at the top of boards.txt:


##############################################################
usbasploader_board.name=USBaspLoader w/ ATmega8 at 12MHz
usbasploader_board.upload.protocol=usbasp
usbasploader_board.upload.maximum_size=6144
usbasploader_board.upload.speed=115200
usbasploader_board.upload.disable_flushing=true
usbasploader_board.bootloader.low_fuses=0xBF
usbasploader_board.bootloader.high_fuses=0xC8
#usbasploader_board.bootloader.path=
#usbasploader_board.bootloader.file=
usbasploader_board.bootloader.unlock_bits=0x3F
usbasploader_board.bootloader.lock_bits=0x0F
usbasploader_board.build.mcu=atmega8
usbasploader_board.build.f_cpu=12000000L
usbasploader_board.build.core=arduino

(Update: I didn’t have to but you may also need to add a few lines to programmers.txt and one more line to boards.txt to get things working. See John Bäckstrand’s comments below.)

Then under Tools->Board select "USBaspLoader w/ ATmega8 at 12MHz". It is normal to get this message: "avrdude: warning: cannot set sck period. please check for usbasp firmware update." Note that you’ll need to connect a USB to serial adapter to RX and TX if you want to send data over the UART (i.e. Serial.print()). Also note that the ATmega8 is missing some of the features the ATmega*8 series of chips have. For example, the ATmega8 doesn’t have PWM capability on Timer0. Therefore, this board won’t work with some Arduino sketches.

 

You can also upload the sketch from the command line with the following command. Notice that you don’t need to set any fuses, in fact the boot loader is incapable of changing fuses.


avrdude -p atmega8 -c usbasp -v -U flash:w:betemcu_blink.cpp.hex

 

Mischief
Here are a couple of source packages of concentrated evil.
haunted-usb-1.1-atmega8.zip (mirror)– This is a modified version of the firmware used in the Haunted USB cable. It was changed slightly so that it works on the ATmega8. For some reason it doesn’t work in X windows.
jack.zip (mirror)– Jack prints out “All work and no play makes Jack a dull boy.” 13 times while randomly pressing space and backspace. It is based on the USB Business Card firmware.

 

Links
AVR Fuses HOWTO Guide
LadyAda’s AVR Tutorial — Fuses
A very helpful fuse calculator
If you’d like a full V-USB development board check out USnooBie.

 

Super Mario Bros. Warp Pipe Sound Effect Toilet Touch Sensor May 27, 2011

Filed under: Electronics — jethomson @ 11:58 pm

I read a comment from a redditor, who had just decorated her bathroom in a Super Mario Bros. theme, a few months back saying she wanted to make her toilet play the warp pipe sound effect. I thought this would be funny, plus I had just recently noticed something on eBay called a sound drop key chain that played Mario sound effects, so I put it on my project list. Some three months later after prototyping the touch circuit I’ve finally gotten around to finishing the project. This document is my build log.

Here’s a couple shots of what the pipe sound drop key chain looks like on the inside. I added the red (power), black (ground), and green (S4) wires to aid in prototyping. The sound effect IC is underneath the epoxy blob and plays the pipe sound effect when the S4 pin is brought high. Although this key chain only plays the pipe sound effect when the play button is pressed, if pins S1, S2, or S3 are brought high the sound effect IC will output the jump, coin, or death sound effects respectively.

 

So how can the key chain be made to play the sound effect when the toilet is flushed? My first idea was to affix the key chain to the underside of the reservoir cover and have the trip lever press the play button when the flush handle is pushed down. However, after a bit of experimentation I decided the trip lever was too weak for this and that the sound effect would be difficult to hear over the noise of the flushing if it was inside the reservoir. I was also worried the key chain would come unstuck and clog the toilet; this is after all the place where “Shit happens.”

Therefore I decided to use a simple circuit that would bring pin S4 high when I touched the metal toilet handle. There are many ways to sense touch but to keep it simple I used a sort of Sziklai pair circuit to detect the static electric field that is present on our skin almost all the time. If you are familiar with triboelectric series you’ll know that human skin picks up a positive charge when rubbed by some of the materials used to make clothing. This positive charge is used to switch on an NPN transistor which turns on a PNP transistor which switches the key chain’s battery voltage onto the sound effect IC’s pin. The capacitor prevents the circuit from bouncing so that the sound effect IC is only triggered once. The 100k resistor limits the current through the base of the PNP transistor and the quiescent current should the NPN transistor be partially on. The 1k resistor is suppose to limit the base current of the NPN transistor and keep the high voltages from the static electricity off of the base but I’m not certain how necessary it really is. I think high voltage should leap across the 1k resistor as if it wasn’t even therefore, but I seem to recall that the circuit works better with it in. I prototyped this circuit months ago and have forgotten some of the results of my experimentation. A schematic for the touch sensor follows; comments on how to improve it are very welcome.

 

Here is a picture of the sensor circuit wired up to the key chain.

 

I made an enclosure for the circuit that resembles the warp pipes in Super Mario Bros out of cardboard tubes. The larger tube is from a roll of toilet paper and I think the smaller one came from a roll of sheet plastic. To decorate the enclosure I scaled, printed out, and pasted an image of the pipe taken from the game. To scale the image properly I first split it into two separate images. Then I scaled, while preserving the aspect ratio, the image of the bottom part of the pipe to be 2.5 inches wide because that is half of the circumference of the smaller cardboard tube. Next, I performed the same scaling to the upper part of the pipe, then horizontally stretched it to a width of 2.75 inches which is half of the circumference of the larger cardboard tube. After that, I put both scaled images into a single image to make it easier to print. I left some whitespace in between them to make cutting the pieces out easier. Finally, I printed out two copies of the image, one per side of a single sheet of paper; then cut and pasted them onto cardboard tubes cut to the proper length.

 

Now that I had my enclosure finished I was almost ready to put the circuit inside it. Before I did that I added some long lengths of solid core 24 AWG wire to the circuit. One of which acts as a grounding wire and goes to the water intake valve. The other is the sensor wire which attaches to the 1k resistor and the metal part of the toilet handle inside the reservoir. I also cut out a couple plastic circles from a lid and used them to seal up the ends of the pipe. Please note that although the grounding wire and the S4 wire are both green they are not connected.

 

Once I had the circuit all sealed up all I had to do was connect the wires to ground and the handle. Sorry the picture of the handle connection is out of focus, but you get the idea. Finally a picture of the warp pipe all hooked up and sitting pretty on the toilet.

 

 

Videos
Here’s a video of the Super Mario Bros. Toilet Warp Pipe in action. Notice that I don’t have to flush the toilet to activate it. This way you can amaze your friends without wasting water.

 

Even germaphobes can enjoy the fun!

 

 

Extra Notes
Finally, please be aware that this sort of touch sensor can be unreliable because of the vagaries of static electricity. Sometimes it will trigger before you touch it, other times it will trigger as you move away from it. Sometimes it won’t trigger and other times it will trigger multiple times. Actually flushing the toilet usually activates the circuit more than once. I’m assuming this somehow caused by the water flowing through the grounding pipe. If you can’t make a connection to a metal water pipe, that’s not a big problem because the “grounding wire” for this circuit doesn’t actually have to be at earth potential. As long as your electrostatic field is strong enough to induce charge to move then the circuit will work, just not as well; also there will be a period where re-touching the handle won’t reactivate the circuit because the induced charge hasn’t dissipated yet. If the sensor doesn’t trigger try rubbing your pants on your leg a little bit to generate some static or touching the grounding wire to balance the charge. Sealing up both ends of the pipe with the plastic disks cut down on the loudness of the sound effect and also makes it difficult to replace the batteries; on the other hand, not sealing the pipe could leave the circuit vulnerable to the high humidity in a bathroom.

 

Comments
Constructive comments on how to improve the circuit and my fuzzy understanding (mis-understanding?) of static electricity circuits are greatly appreciated; book titles and article links would be most helpful.

 

5-by-555 February 28, 2011

Filed under: Electronics — jethomson @ 9:53 am

This is my entry for the 555 contest in the minimalistic category. I believe it might actually be an original use of the 555, if such a thing is even possible anymore. I call it the 5-by-555 because it can perform five (or more!) different functions all based on nearly the same topology. Plus, the name is a play on the phrase five by five.

 

The 5-by-555 can be used in many different ways. To explain how it works it’s easiest to first view it as a toggle flip-flop. When a toggle flip-flop is triggered (e.g. it detects a positive edge) it’s output becomes the inverted value of it’s previous output. Assuming the 555’s output is low, then when a pulse of a sufficiently short duration is input to the circuit the transistor will pull the trigger pin low and the 555 will switch it’s output to high. The threshold pin does not see the first input pulse because the discharged capacitor holds it low. While the output is high the capacitor charges at a rate determined by R1*C1. Once Vc reaches a certain voltage, a second input pulse will be missed by the trigger pin because the transistor is unable to pull it low and detected by the threshold pin because the capacitor is no longer acting as a sink; as a result the 555 will switch it’s output to low. While the output is low the discharge pin is grounded. This will cause the capacitor to discharge through R2 so that the trigger pin maybe pulled low again when the next pulse occurs. Diode D1 prevents the capacitor from discharging through R5 when the input is low. D1 also keeps the charged capacitor from activating the threshold pin. Diode D2 allows the charge time of C1 to be independent from R2 and prevents a voltage divider between R1 and R2 allowing C1 to hold the threshold pin low. The oscilloscope capture below demonstrates this behavior, but it also shows oscillation when the input is held high for too long (see nota bene).

 



N.B.
It’s important to understand that because the 5-by-555 uses the charge stored on a capacitor to remember its previous state it is sensitive to the duration and frequency of the input pulses. For pulses having a t_on that is longer than the charge time of the capacitor or occur before the capacitor has sufficiently discharged the circuit will not behave as expected. Therefore you must determine the maximum t_on and minimum t_off of a pulse train when picking resistor and capacitor values for your circuit. Most of the circuits shown in this article use pulses that have a fixed t_on; the remainder assume a worst case t_on.

When this article mentions charge and discharge time it is not referring to tau = R*C, but instead to the amount of time it takes for Vc to reach a voltage such that a new pulse will result in the output of the 555 changing states.


 

Toggle Flip-Flop and Oscillator
This circuit demonstrates the use of a 5-by-555 as a toggle flip-flop and as an oscillator. When the input pulse is the correct duration it will toggle the 555’s output. However, if the input is high for longer than the charge time of the capacitor the threshold pin will see the pulse and the 555’s output will begin to oscillate at a frequency determined by R1, R2 and and C1 as long as the input pulse is applied. Normally this ability to oscillate would be undesirable but with the right problem it could be useful. For instance, this circuit can be used to turn a light on or off when a momentary switch is pressed and released and flash when the switch is pressed and held.

 

 

 

 

Divide-by-n
A toggle flip-flop can be used to divide the frequency of a pulse train by two. The 5-by-555 circuit can divide-by-2 but it can also be made to divide-by-n if the charge and discharge times of the capacitor are adjusted such that the period of one cycle of the output is equal to the duration of n pulses [n*(t_on+t_off)]. The following images show the 5-by-555 used as a divide-by-7. The extra 555 is used to generate the input pulse train which is shown as the blue waveform in the oscilloscope capture.

 

You may have noticed that the capacitor on the control pin of the pulse generating 555 goes to Vcc and not ground. While this is an error it did not affect the operation of the circuit. The breadboard picture for the timer has the same error.

 

 

Timer
The 5-by-555 can act as timer where the output remains high for n-1 pulses and then goes low at the beginning of the nth pulse. This is accomplished by choosing an R1 value such that C1 charges slowly holding the threshold pin below (2/3)*Vcc until the beginning of the nth pulse. Then R2 quickly discharges C1 during one pulse cycle making the timer ready to respond to the next pulse so a new timing cycle may begin. The images below show the 5-by-555 setup as a timer that asserts a positive edge after ~7.20 ms (10*720 us) has elapsed; notice that the oscilloscope measured a period of 7.04 ms.

 

 

Counter
The frequency divider and the timer circuits are excited by input pulses with a fixed t_on and t_off. If pulses with a fixed t_on but a variable t_off (i.e. the arrival time of the next pulse is unknown) are used to charge C1 instead of Vcc through R1, then the 5-by-555 can be used as a counter. The images below show a modulo-5 counter. The Schmitt inverter circuit simply transforms button presses (simulated by V2) into pulses with a fixed t_on. Unfortunately the simulation doesn’t agree with the oscilloscope capture of the breadboard circuit. I’m not sure why. This may be a transient effect; for some reason the simulation slows to a snails pace at 80%. Using the 5-by-555 as a counter doesn’t work particularly well. It will miss pulses and sometimes go low prematurely. This is a result of pulses arriving before the capacitor has sufficiently discharged.

 

 

One-shot
Finally, the 5-by-555 can be used as a one-shot that can generate an output pulse shorter than the input. This is accomplished by allowing the capacitor to fully charge while the input is still high resulting in the output turning off. The larger R2 resistor increases the discharge time blocking the remainder of the input pulse from retriggering the 555.

 

 

Edge Triggering
If the t_on of a pulse is long and the charge time of the capacitor is short then the same pulse that triggered the 555 may also be seen by the threshold pin causing the output to go low prematurely. Sometimes this behaviour is desirable, but usually not. For pulses that are on for very long the resistor and capacitor values become prohibitively large. However, with some slight additions to the circuit it is possible to make it respond to only the positive edge of a pulse removing these problems. The following schematic was only simulated. It turns any pulse with a t_on longer than 1 microsecond into a 1 microsecond pulse. It appears from the simulation results that the maximum input frequency is approximately 200 kHz. This means that the fastest square wave the 5-by-555 can output is around 100 kHz. Notice that the input resistors were lowered to 100 kOhms. This is because the input capacitance of the threshold pin does not charge quickly enough with a 1 microsecond pulse when the input resistance is 10 Megohm.

 

Schematics
All of the schematics shown in this article were created in LTspice and are available in the.asc format for circuit simulation. They are packaged into a single zip archive and may be downloaded using this link.

If you like Falstad’s circuit simulator applet, here are a few links to 5-by-555 circuits implemented in it:
Toggle flip-flop (modified to better match the simulator’s speed)

Timer

Count to 7

 

Pitfalls
When the 5-by-555 is in steady state it will have a minimum voltage that it will store on C1. If this minimum voltage is not zero a transient output will result the first time the 5-by-555 is activated because the voltage across C1 is zero at t0.

The counter is extremely buggy. When a pulse arrives during the discharge period, one of three things can happen: 1) the pulse is ignored because the capacitor has not sufficiently discharged. 2) a new count begins with residual charge still remaining on the capacitor resulting in a shorter count that desired. 3) the capacitor has discharged (almost) completely resulting in the proper number of pulses being counted. Number 3 is the desired result. However, since it is assumed that the pulses occur at random intervals it is not possible to always discharge the capacitor before a new pulse arrives.

Keep in mind that electrolytics leak charge so they are likely unfit for use in counting pulses that have a long t_off.

 

Update
The 555 contest winners were announced April 21st by Chris Gammell and Jeri Ellsworth live on Jeri’s ustream. Unfortunately, I did not place in the final round. While I feel my entry was technically interesting it was not very exciting and just couldn’t hold up against the winners. However, I had the great fortune of winning a door prize! I was randomly selected to receive a XuLa-200 board courtesy of XESS. I could not be happier with my luck! The board arrived on the 4th of May with a little extra surprise. The padded envelope contained two items rolled up separately in bubble wrap. One was obviously the board because I could see through the bubble wrap; the second was a mystery. At first I assumed it was a USB cable or header pins, but as I peeled away the layers I could tell by the feel of it I had no idea what it was. Finally, I removed all the bubble wrap to reveal the grotesque face seen below. It’s a magnet and I love it. I put it on my old, indestructible, metal power strip with the hopes that it will keep the electrons with bad juju away.

 

A very big Thank You! to Chris Gammell, Jeri Ellsworth, all of the judges, and the sponsors (especially XESS!) for making the 555 contest a great success.