Archive | November, 2016

Basic Blink example for dsPIC30F4013

20 Nov

Basic Blink example for dsPIC30F4013

With an Arduino, I can teach someone to blink a LED in 15 minutes. It will always work. In the world of PIC microcontrollers, there's nothing "that just works". To help others trying to make a dsPIC30 family microcontroller do just the simplest thing, I'm posting this mini tutorial including what they expect you to know and what you actually need to know.

The Arduino community has always been a place where newcomers could feel welcome. Even the simplest questions are answered politely and nobody looks down on someone just learning the ropes. In general, it's a very welcoming platform. You just download the IDE, plug the Arduino in via USB and you're already moving. I've now tought microcontrollers to students for 4 years and they really love using Arduino as their first hardware tool. So what's different with the microcontrollers from Microchip you may ask? The answer is simple - everything!

What they expect you to know

For a freelance project I'm working on, I have a piece of hardware designed in the US. It's using a dsPIC30f4013 and it has been doing it's job for many years without major problems. Now I've been tasked with adding new features into it and it's been very interesting to see how the culture around the product is extremely different.

In the Arduino world you are expected to be a beginner, but in the PIC-world you are expected to be an expert - even if you're just starting. Let me illustrate this with an example from this thread where a guy starts off by saying he is an absolute beginner and that he just wants to blink a LED.

Here are some of the comments he receives:

Refer to your  micro datasheet. bye!

Do you have access to a logic probe or an oscilloscope to check if your crystal is oscillating?

And anyway I cannot see your CONFIG settings…

you need a pullup on MCLR, and a small bypass capacitor (say 100nF) mounted as close as possible to each pair of power pins

The first of these comments is just terrible? The datasheet for a MCU (like the dsPIC30F4013 that I am using) is no less than 221 pages. The worst is - that is just the parts that are specific for that single MCU. To get the full picture, you also need the datashee for the family of CPUs. For the dsPIC30F family that is no less then 772 pages! To top this off - to use anything remotely advanced, you'll also need to study the dsPIC Language Tools Library. These 400+ pages detail how to use core features like UART, SPI and I2C - all features that an Arduino user will explore within the first few days of use. With a PIC, you should read almost 1400 pages of dense and highly technical documentation BEFORE even blinking a LED?

I can't even imagine how long it would take to read close to 1400 pages? These manuals are not written for a beginner. I would say that datasheets in general are written by engineers that want to impress other engineers. Its not light reading, but requires focus so it's quite tiresome for most to read.

Regarding comment #2 - how on earth can you expect someone that says he is a beginner and cannot blink a LED to have a logic probe or an oscilloscope? Regarding #3 - what CONFIG? Now - I know that config is important when it comes to PIC, but I have yet to find a good tutorial that explains how that is done correctly. I know it's in the datasheet, but the text here really isn't meant for beginners.

Comment #4 is actually quite good, but I'd guess it's somewhat confusing to a beginner? The pullup is essential, but the capacitors are not required to get this working. You would be wise to have them in a PCB design, but they are really just complicating things for beginners trying to blink a LED.

What you REALLY need to know

To get a bare bones dsPIC30F4013 up and running blinking a breadboard, you will need the following:

  • DIP version of the dsPIC30F4013
  • 10K ohm resistor
  • LED
  • 220-510 ohm resistor (for the LED)
  • PICKIT 3 programmer (or similar)
  • breadboard
  • Jumper cables

Locate the datasheet for the dsPIC30F4013 and find the page that explains the PINOUT.

Pin number 1 is marked with a dot on the chip. The text next to the pin shows that this is the pin with the MCLR function. We'll need that later. Place the chip so that pins 1-20 align with the numbering on the breadboard. Connect the 10k resistor from pin 1 (MCLR on the datasheet) to the 5V rail that runs along your breadboard. Connect all the pins marked as Vdd to the 5V rail and all the pins marked as Vss to the minus/ground rail. If you use the power rails on both sides of the breadboard, make sure you connect the minus on one side side with the other and the same for the 5V rail.

Next, connect the shorter PIN on the LED to Vss (minus/ground) and the longer to one end of the 220 ohm resistor. The other end of the resistor should go into the hole connected to Pin 19 (marked as OC4/RD3).

That's all that is needed for the Microcontroller itself. Now we need to connect it to the programmer.

On the PICKIT 3 programmer, there's 6 pins and one is marked with a small arrow. This is Pin 1. Here's how you connect the various pins:

PICKIT 3 dsPIC30F4013
Pin 1 (MCLR) Pin 1 (MCLR)
Pin 2 (Vdd) Vdd (5V power rail)
Pin 3 (Vss) Vss (Ground rail)
Pin 4 (PGD) Pin 9 (PGD)
Pin 5 (PGC) Pin 8 (PGC)

Note that these pin numbers will only be correct for the dsPIC30F4013. Other variants will need to use different pins, but you can locate these by looking at the correct datasheet.

With that connected, it's on to the code.

The code and the config

There are several things that are difficult to know that is required. The main reason for this is the absolute lack of good resources when it comes to tutorials and examples. MicroChip has examples in both the docs and online, but few of these are suited for beginners. The online examples are not publicly available in search engines. They are listed in a cumbersome tool that tries to be smarter than Google that allows you to filter. It's not smarter than Google and Google will never find and index these example files since they are ZIP archived.

Anyway - there's a few things you need to know before starting:

  • What to download
  • How to setup
  • How to set the frequency
  • How to configure
  • What to include

Start by downloading the MPLAB X IDE. This is modern IDE that has the features you'll need, but it's impossible to make it work on anything other than Windows. It comes with most, but not all the features you'll need. If you need to use Legacy libraries, you'll need to do some digging to find these. The normal download is sufficient for the LED example, but there's one confusing thing you must resolve - what compiler should you download? You've got to hand it to the people that named the microcontrollers from Microchip - they really did their best to confuse people! In my case I have a dsPIC30. Should I use XC8, XC16 or XC32?

For obvious reasons you would think that what compiler to use is mentioned in those almost 1000 pages of datasheets, right? Well, it isn't. You need to KNOW that the dsPIC30 is a 16 bit Microcontroller and that for any 16 bit microcontroller from Microchip you should use XC16. It amazes me that nobody thought of distributing all 3 compilers with the IDE and then just automatically select the correct compiler. The IDE will know what compiler to use when it's time to compile the projects since you have to tell what microcontroller it's working with. That brings us to the next part - setting up a new project.

Setting up a new project is fairly simple using the MPLAB X IDE. Select File -> New Project -> Microchip Embedded -> Standalone Project. Select your chip family and device and click through the dialogues. This only does the project setup. It doesn't even set up a single source file, so you'll need to right click the Source Files folder in the Projects window and then choose New -> mainXC16.c. You can rename this to anything you want (like main.c). This newly created file is more or less empty, but it does include the xc.h file that in turn includes the basic files for your microcontroller.

Next you need to know what frequency that your dsPIC30F will be running at. In most examples, this is referred to as FCY and the value of this is confusing. It varies across different microcontrollers, so you can't just use one you found in an example somewhere online. You'll need to search the datasheet for the "Oscillator Operating Modes". This is a long and confusing list of basic clock speeds that your microcontroller can run at. It is however easy to find the one needed for this example. Since we have no external clock signal attached, we need to use the internal oscillator built into the microcontroller. According to the datasheet, this is 7.37Mhz and you can find this set in the example below as SYS_FREQ.

Another important thing is to set the FCY variable. On this specific microcontroller this should be SYS_FREQ/4, but figuring this out is difficult. Reading the datasheet you can see that FCY =1/TCY. So what is TCY then? It's the "Instruction Cycle Time" dummy, don't you know? Well how on earth could I? Digging further I find that TCY = 1/MIPS and that MIPS = (FOSC*PLL)/4. So now you need to know what FOSC and PLL is then? Figuring that part out is difficult if you're not using either an external clock or crystal (if you're experienced enough to know what that is), but lets just leave it at that?

Next up is the CONFIG mentioned in one of the comments. Few beginners include this since ... it just looks insanely complicated I guess? It isn't all that hard, but it does require some former experience to get this right. What looks scary is all those FWPSB and WDT's. Luckily there's a tool built into the MPLAB X IDE that can set this up for you Window > PIC Memory Views > Configuration bits. In this dialogue, you tell the tool what oscillator you are using (hey, didn't you already do that?), prescaling,  watchdog and lots of other things that beginners really should not have to know… I understand that it's there for the advanced users, but to become an advanced user you just need to get a stupid LED blinking first, right?

Behold - now you're ALMOST there! The last thing you need to know (without anyone telling you) is that to just wait a little on a PIC you can't just use the builtin "delay" function. Why? It's not builtin… Include the libpic30.h file that includes the second most required utilities for the dsPIC30F family and your projects should compile. Phew!

// Useful advice!

// FCY must be defined before the includes or things go wrong.
// For some odd reason, the config tool does not set this based
// on the MCU + Oscillator selected
#define SYS_FREQ        7370000L
#define FCY             SYS_FREQ/4

// Device Config; generate using Window > PIC Memory Views > Configuration bits

#pragma config FOSFPR = FRC             // Oscillator (Internal Fast RC (No change to Primary Osc Mode bits))
#pragma config FCKSMEN = CSW_FSCM_OFF   // Clock Switching and Monitor (Sw Disabled, Mon Disabled)

#pragma config FWPSB = WDTPSB_16        // WDT Prescaler B (1:16)
#pragma config FWPSA = WDTPSA_512       // WDT Prescaler A (1:512)
#pragma config WDT = WDT_ON             // Watchdog Timer (Enabled)

#pragma config FPWRT = PWRT_64          // POR Timer Value (64ms)
#pragma config BODENV = BORV20          // Brown Out Voltage (Reserved)
#pragma config BOREN = PBOR_ON          // PBOR Enable (Enabled)
#pragma config MCLRE = MCLR_EN          // Master Clear Enable (Enabled)

// FGS
#pragma config GWRP = GWRP_OFF          // General Code Segment Write Protect (Disabled)
#pragma config GCP = CODE_PROT_OFF      // General Segment Code Protection (Disabled)

#pragma config ICS = ICS_PGD            // Comm Channel Select (Use PGC/EMUC and PGD/EMUD)

// Device Config /end (paste config between these two)

#include <xc.h>
#include <libpic30.h>

int main(void) {
    _TRISD3 = 0;
        _LATD3 = 1;
        _LATD3 = 0;
    return 0;

Oh? you don't know what those TRISD and LATD's are? Let me repeat that with comments so you have a remote idea:

int main(void) {
    _TRISD3 = 0; // set D3 to output
        _LATD3 = 1;       // turn D3 on
        __delay_ms(1000); // wait a second
        _LATD3 = 0;       // turn D3 off
        __delay_ms(1000); // wait a second
    return 0;

Yup. _TRISD is what Arduino calls pinMode, you know the method you use to set the mode of a pin? And yes - setting _LATD3 to 1 is similar (but not too similar or explanatory) as the Arduino digitalWrite method. Obvious once you know it, right?

You must be kidding, right?

No I'm not. It does sound like a joke, but it really is this convoluted to get a simple LED blinking. This is the exact reason that Arduino was founded - to be a counterweight to this elitist, top down world. I should note that I have seen similar things on the AVR Freaks forum also, but not this bad. I should also point out that the hardware itself works great, it's just incredibly hard for beginners to learn how to use it. One might argue that you can’t compare a chip manufacturer to a platform like Arduino that use many different chip’s in their designs. I’m not really comparing hardware here - I’m comparing the developer experience for beginners. As a teacher, that is a concern for me. If you start with an Arduino (like most do these days) you expect solutions to be that easy to work with in the future. If you come from Arduino, then you’ll instantly dismiss PIC as being unnecessary difficult. This is hardware, so you’ll loose slowly but you will eventually loose completely.

The forum thread mentioned above is not unique. After working with PIC the last months, I can tell that this top down view persists across the entire forum and unless you prove worthy you won’t get an answer. Developers from across the world are fleeing solutions based on PIC controllers. There is no reason you should have to pay the massive extra cost of poor documentation and a lack of examples. Even Chinese chip manufacturers such as Espressif (the makers of the popular ESP8266) managed to make better tooling and API within a year. Microchip should really look to companies like Particle and Electric Imp that sell advanced microcontrollers with builtin wifi and hardware encryption/decryption. Their APIs are super solid across multiple devices and they just work. If they want to be really impressed, they should study Paul Stoffregen's work on the Teensy. It's so much cool stuff happening in the microcontroller world, but Microchip isn't part of it.

PS: I know that Microchip makes lots of other things apart from Microcontrollers. It's just that this blog post is about just that and not the other things they do like sensors.

PPS: If you go to the Microchip website after reading this - they have an error in the website JS so no links will open normally in Chrome. Just right click and select "Open in new window" to view the pages. If you open the console, you can see that the error thrown is "Uncaught ReferenceError: ga is not defined" referring to the Google Analytics implementation that is broken.


Call me! (with Adafruit FONA)

09 Sep

Call me! (with Adafruit FONA)

About a year ago, Adafruit launched the FONA. It's a neat little breakout board that packs all the features you'd want in a phone such as Calling, SMS, Data and Lipo battery operation and charging. Add to that a good API that is easy to extend and we have a winner.

By itself, the module can't do much, so you'll need a microcontroller of some sort. My preference is using a Teensy 3.1 since these are just incredibly flexible, fast & cheap. They're also small and placement friendly. By now I've used the FONA for two commercial projects and I thought it'd be nice to collect my experiences in this post.

Call for pizza using the ad on a bus station

The first project had me build the FONA into an advertising board. Check this video to see it in action. The large timer was connected to a motor that pulled it slowly back to zero. At each end position of the timer, there was a manual switch that triggered the FONA in different ways. When the timer was set to 15 minutes, the Teensy set the FONA to call up the pizza delivery. If the person turning the timer wanted, they could get a free pizza within 15 minutes. When the timer was set back to Zero, the Teensy prepared the FONA for the next customer.

As can be seen in the video, it was a snowy morning and I got to do some extra troubleshooting in the bus shed since the timer motor accidentally burned out the evening before and the replacement motor made so much electrical noise that it messed up the sensing on the button pins. I solved this by moving the button pins to analog pins and using a different threshold than the normal digital I/O used.

The FONA used a normal headset-mic to pick up the sound. To play it back I used some more Adafruit components - a 3.7W amplifier and these neat transducers. Despite being only 5W, it was not a problem to hear the sound on a busy Bus-stop when attaching the transducer firmly to the board itself. While the person waited for their pizza, we also played them some cheezy elevator-music. This came from the Teensy using the Audio Adaptor board. I really dig this board. So many cool audio things you can do. Really powerful!

The installation stood there for a whole day and worked without any issues despite the moist weather.

Call anywhere in the world for free!

The second project had us set up a telephone booth that looked kind of like a 1.2 meter tall iPhone. It was to promote the mobile provider MyCall and the idea was to make a phone booth where you can call for free (3 minutes at a time). JCDecaux also made a nice video for this one that highlights that the campaign gave 30% boost in sales.

The interface to the user was a 47" touchscreen showing a multi-screen AIR app that communicated with a Teensy 3.1 via Serial. Before calling, the user was asked to input their existing phone number. After their free call was finished, we used their phone number to send them a polite SMS telling that MyCall offered great prices on calls abroad (their specialty). The project stood outside in a very public space (outside the Oslo central station) for 10 days and worked without a single error. I'm really happy with the stability of the FONA/Teensy combination!

Both projects were done for JCDecaux with MesseTjeneste making the enclosures and me doing the software + electronics.

Fona tips and tricks learned

Here's some things that are nice to know about FONA that you won't find on the (as always) solid tutorial pages on

A lipo battery is indeed Required
The FONA needs a battery to be able to source the required power upon connecting to the network. A 2.2A / 5V dedicated power supply was not enough, but a half-charged 150mA lipo in addition to the USB connection did the trick. The lipo battery is now added as a requirement on the FONA product page.

GSM calling produces serious EMP
Once a call was placed or the FONA connected to the network, the audio chip in the Teensy Audio board was completely messed up. It produced random and unpleasant audible noise. I solved by moving the FONA away from the Teensy, putting them in two separate boxes. I also tried shielding them from each other, but I got very varying results. Much easier to just move them away from each other.

Not all SIM cards will work
I initially picked up a dirt cheap SIM card at a kiosk and it worked right away. This was from MyCall, the company I later made the kiosk for. I then needed to make a copy of the installation, but when I tried to use a SIM card from Norway's largest telco Telenor, it didn't work.

The SIM worked like a charm when inserted into a phone, but on the FONA I was unable to connect to the network. The SIM unlocked successfully, but I was denied access to the network. I later learned that holding down the KEY button for 20 seconds can solve this.

Library only covers some
I needed to blink some lights while a call was in progress and play some audio when the call ended. There currently isn't a method in the default library to check this, but all I had to do was to look up the SIM800L datasheet to find the required AT command.  I then looked through the Adafruit code to see how they had implemented similar features and added this (gist). It's all just serial AT-commands that are wrapped nicely. Super simple!

Using Teensy
Since the Teensy has several Serial ports, you may need to make some minor changes to the default FONA sketches and lib. I've detailed these in this gist.

Ideas aplenty

My initial thought seeing the FONA was to build a phone, but I still haven't done that. Instead, I've used it for installations. Using a phone rather than wifi or bluetooth has advantages and drawbacks, but there are some pretty cool things you can do with this. As an example of something I'd love to do:

  • Imagine an interactive window display controlled via SMS?
  • Using it as a transparent network access point?
  • Click-this-big-button-to-talk-to-support/sales?
  • Circuits that allow you to check status or remote control vending machines or controls? It would be really simple to make a machine send an SMS if it fails to do it's task, so it can alert you that it needs service.
  • It could also be perfect for simple surveilance of hunting spots or beehives in rural areas where there's no phone coverage
  • Turning on the heat at the family cottage via SMS

It's so many cool things you can do with this when you don't need to think about having wifi available!

I really dig how easy it is to build connected installations with the FONA board and it looks like others also think so since Adafruit has now expanded the range to also include a board with a GPS and some convenient starter packs. I'm looking forward to play much more with FONA in the future!

ESP8266 and stability

24 Mar

ESP8266 and stability

Like many others in the Maker Community I've spent a lot of time playing with the dirt cheap ESP8266 wifi chip. It is the cheapest way to add wifi to your project and it's easy to get hold of. My hope was that it would be solid enough that I couldbuild permanent installations and fun Internet Of Things (IoT) devices with it, but the darn thing keeps crashing. I've been testing it since the 0.91 firmware and all the way up to the current 1.0 version and it's not possible to keep the device running for a prolonged period of time.

I've spent more than a weeks worth of time getting it to not crash at random intervals, so I thought I'd share what I've learned in case others find it useful.

Setting up for development

The best way to hook up these dev boards is to use the ESPlorer software (java) and getting a USB to Serial converter. If you have a version that offers 3.3V on both data and power lines (such as this one), it is the most convenient. If you can't find a 5V USB to Serial, you should know that the Serial pins (RX/TX) are supposedly 5V tolerant, but the power must be 3.3V or you will fry the chip. The ESP modules will pull a couple hundred mA, so powering it from a good 3.3V power source such as a LM1117 / LD33 can be a good idea.

There's many guides to hooking up the various development boards, so I won't detail that part, but lets look at the software side of things! When you buy the ESP-01 breakout boards from ebay, you never know what version of the firmware it comes with. Most likely it will be an old one so you'll probably want to update it. But - what firmware should you use?


NodeMCU is a firmware that adds a LUA layer on top of the (somewhat stable) official 0.95 Espressif SDK. This seems to be the most stable firmware you can currently use and it is also the one that is the easiest to get started with. It is well documented and offers good tools. Rui Santos has a great guide for hooking up an ESP-01, burn the NodeMCU firmware and setting it up as a webserver.

Briefly said, you hook up the ESP directly to a USB to Serial converter (3.3V!), download the NodeMCU Flasher tool, select the COM port and hit the Flash Button.

When that is done, download the ESPlorer software to talk to it. LUA is a very straightforward language to learn and if you're used to closures like in Javascript, you'll feel right at home. NodeMCU has a nice, documented API and several libraries that you can add for special hardware like LCD's, WS2812/2811 LEDs, sensors and more.

The NodeMCU firmware is based on the original Espressif SDK and thus inherits all the bugs it comes with. This means that the hardware will crash just as often, but since it always restarts after a crash, it will re-run your LUA script on startup. This makes NodeMCU good enough for devices that will just send some sensor data to a webservice such as Thingspeak. It will not work as an access point doubling as a webserver though. It'll crash and hang just as often as with the original firmware, so for me this is a showstopper. I want to make IoT gadgets that serve up a web interface as well as an open API.

Stock firmwares

Updating the firmware is quite easy if you use the NodeMCU Flasher. This has a nice, minimal GUI and everything is point and click. It's Windows only though, so if you like Python, check out the esptool. All the officially Espressif SDK's contain a "bin"-folder that has the precompiled files and a text description of what memory addresses to copy each .bin file into.

My initial idea was to use the UART in the ESP boards with a Microcontroller. Most my projects are based around the Teensy 3.1 and since it has 3 serial ports, so it's a breeze to do UART communications with. However, no matter how hard I tried, I couldn't make it 100% stable. After a few hours, it just crashed and restarted. It could run fine over night, but it would always crash after some usage. If there was a lot of traffic, it would crash more often and my intent was to basically bombard it with data continuously. I tried all the different versions of the firmware and even the official 1.0 version that was released this week is buggy beyond repair. It is actually so buggy that Espressif recently started an official bug-hunt...

That pretty much rules out using the official firmwares. How about making your own then? Espressif provides an SDK and the required code to compile your own version. Building it yourself is quite easy if you have a Ubuntu VM. Just follow the instructions outlined here. This will however not solve all your problems. Some of the codebase is Open Source, but other parts are provided as "binary blobs" so you can't really know what bugs are hiding inside. You can however exclude those parts of the Espressif SDK that you suspect to be causing the problems, so if want to program the ESP8266 directly check this neat guide on Hackaday.


This "Transparent Bridge" is the solution I'm currently experimenting with. It's a completely dumbed down firmware that can take a TCP connection on any port and relay it to the Serial port (RX/TX). Just apply power, connect to the WiFi access point that it sets up, Telnet to the default address and you can set it up to join your local network / access point. You can then up the BAUD rate to whatever you want/need and change the Port to for example 80 to make it work easily with browsers.

Anything sent to the ESP will then show up on the Serial connection. When you write back to a connection, you can serve data (like a webpage). Currently, this seems to be the most promising solution, but it requires some more testing. The basic idea is to use as little as possible of the buggy Espressif SDK as possible. To get the ESP Transparent Bridge firmware onto the device, just load the premade .bin files using the NodeMCU Flasher tool like this:

I'll post back here when I have more details & results on this setup.

But why care if it's buggy?

You might ask yourself - why on earth should one care about this chip if it is so buggy the creator has to host a competition to find all the bugs? The thing is - at $2 you can put wifi into ANYTHING! A typical wifi-shield for an Arduino will cost you from $30 and up to $90. Just a plain breakout board from Adafruit will cost you $35 and the CC3000 that it's based on isn't exactly stable either. A $2 chip that works would open up so many possibilities, so that's why I still care after fiddling this much with it.

A little about the hardware

I presume that you already know a bit about the hardware if you're reading this. If not, here's some details. The ESP8266 is a small powerhouse and this is a small 101 on the hardware. It's an ARM processor that runs at 80Mhz and can be overclocked to the double. It has up to 16 GPIO pins available and it does SPI, I2C, UART & more in hardware (fast!). It offers great range and you can get one for as low as $2 on ebay. Physically, it is a tiny 5 x 5 mm Integrated Circuit that needs a little supportive components around it to be useful. There is a series of dev-boards that offers this: ESP-1, ESP-2, ESP-3, ESP-4, ESP-5, ESP-6, ESP-7 and so on, all the way up to ESP-12. They differ with regards to pin spacing, internal/external antenna and the number of GPIO pins broken out. It was hard to locate all the pinout diagrams, so I've gathered them all in a github repository that I'll fill with useful code and resources. The original datasheets has some decent info, but check the ESP8266 wiki for more details.

The ESP-1 is typically the cheapest and most available. It only has 2 I/O pins broken out and uses 2.54mm headers. They are however clumsily combined into a 2x4 arrangement making them impossible to breadboard. It's not hard to make an adapter, but the ESP-2 is more practical for breadboard use. This also has a third I/O pin broken out, but requires an external antenna. The different versions all offer useful features, but the ones to avoid are ESP-5 and ESP-10. These do not have the pins required for updating the firmware exposed.

The version that seems to attract the community is ESP-12. It has FCC certification, RF-shielding, ADC and 9 GPIO's. It is included in the NodeMCU devkit that you can now get from TronixLabs and several other Open Hardware vendors. I'm looking forward to getting a couple of these to play around with. Other devboards that look interesting are the new one's from Olimex.


Project: wifi-enabled RGB LED displays

08 Jul

Project: wifi-enabled RGB LED displays

Every now and then there's a project you can't say no to and this was one of them. is sort of Norway's version of Craigslist, a big online market where you can sell just about anything. As a marketing stunt, they opened a physical store downtown Oslo. I was called in via some friends in the agency that handled the project and they needed lots of things quickly. Since I was fully booked, I couldn't say yes to all the projects suggested so I passed some of them to my friend Thomas Winther who did a great job making an in-store Selfie-app using Unity & LeapMotion.

In the store they needed a way to show information from the website and this was the job I couldn't say no to. Apparently it isn't very easy to get hold of a wifi-enabled LED display that can pull data from the web? Also - most commercially available displays are small, monochrome and use tiny LEDs so they're not that visible when mounted high up on a wall. The agency wanted 5 large displays, perferably with more than one color display. Having recently read about Teensy 3.1 and the OctoWS library I promptly said I'd do it!

The Teensy microcontroller is a great alternative to using Arduino's in installations. It has a really fast ARM processor and lots of RAM, but it is still 99% Arduino compatible. This means that pretty much all Arduino code will run on it, but at blazing speeds. After installing a little extra software, you can use the normal Arduino IDE to program it, so it's really an "Arduino compatible". It's so compatible (and affordable @ $20!) that I feel that this is really the path that the Arduino Team should have taken instead of making bigger and more complex boards. Here's how the Teensy 3.1 looks next to an Arduino Nano. It's soo tiny that the Nano looks big!

For the parts, I could have saved some money by picking it up from different places, but I didn't have much time. I picked up tons of Neopixels & Teensy's from Adafruit since they'd ship the parts so I had them within a week. Buying parts from Adafruit really makes a difference since the whole process is completely trouble free. It's a little more expensive, but worth every dollar.

This is how the test-display looked when running the rainbow sketch:

Lovely, isn't it? You can see the neopixel strips lying in front. I stuck these to the back plate using the same clear silicone that I used to fix the panel to the front. The first test showed that we'd have to compensate a little for every 50cm as the neopixels are put together of 50cm segments and loose a few mm in the overlap between these.

Thanks to Jens Dyvik at Bitraf, making the wooden parts was short. Jens is really good at Rhino and CAM software, so the process from sketch to finished product was really swift. His huge Shopbot CNC'd all the lattices and backplates in one go! Nice to have good tools, right? Two things to note about the CNC'd parts:

  • When using MDF as material, make sure each protuding part has a certain minimum size or they'll break off easily.
  • Research carefully what kinds of silicone that will remain fully transparent over time. Most clear silicones will get a yellowish tone over time. The ones that are made for aquariums appear to be the most suited ones.
  • When exposed to heat for a long time, MDF will want to "bend". Make sure you stick it down properly to avoid too much maintenance.

Soldering and gluing together the displays took quite some time, but it was made a lot easier by Paul Stoffergren releasing these neat adapter boards. I added a 2.4Ghz radio to each of these and tucked it away on the back of each display. Here's a photo showing 1920 pixels running at once. Note that the Mac to the left is on full brightness! The displays are so bright that they're visible in daylight as well.

Each sign requires quite a bit of cable and with the amount of current going through them, this was the first electronics project I've made where I've had to calculate the correct diameter of each cable. A good learning experience!

I could have built a Wifi adapter inside each of the displays and in hindsight, that would have been an easier choice if it wasn't for wifi issues. What I went for instead was a server-client solution where a single box would connect to the internet as well as serve up a webserver that could be used to control all the 5 signs. It has a Teensy 3.1 that holds a custom webserver, uses cable for internet access, has a display that shows status and the IP address of the webserver as well as a nrf24l01 radio (2.4Ghz) that sends data to the signs. This is put together in a nice 3D printed box that is wall mounted.

It's a pretty versatile solution and it works rather well. There's two drawbacks to this solution:

  • The NRF24L01 radio's are dirt cheap, but they have a limited range and are affected by other 2.4Ghz radios (bluetooth, wifi & more)
  • The Ethernet library for Arduino is a synchronous API. When the device fetches data from the internet, it'll freeze a short while until the data is received.

None of those issues are big problems, but they're worth noting if you are building something similar. Initially I planned to use a Raspberry Pi to be the webserver, but it turned out to be really hard to make the NRF24 radios work reliably with GPIO on the Pi. I've since noticed that the NRF24 dislikes fast CPUs, so if you're trying to make this readio work on the Pi, make sure to add a delay to your main loop. The Teensy 3.1 is also too fast for this radio.

The final result is that you can use any device such as your phone to control what is displayed on each of the signs. I've also built some remote admin to it as well. Every time the displays power up they'll await instructions from the server. The server fetches API data such as how many tractors are for sale or what are the latest boats available, and sends this to the displays. It's super flexible and a true IOT solution.

Disregarding some (serious) mounting issues beyond my control, I really loved solving this project and you can check it out if you're in Oslo. 


After making this, my wife said that I should start making and selling these commercially. It's probably a good idea, but I really can't see myself selling LED signage. However - if you have some weird project in the Internet of Things domain - feel free to contact me. I love a good challenge!



X/Y robot with MakeBlock (Part 4)

17 Feb

X/Y robot with MakeBlock (Part 4)

Have spent a couple evenings on getting GRBL up and running now. Here's my notes from setting it up.

Compiling GRBL on OSX

At Oslo Maker Faire, I finally met Simen Svale Skogsrud from the Oslo firm Bengler. One of their/his many cool side-projects is GRBL - a machine control software used for CNC, laser and 3D printers. As soon as I saw the Makeblock X/Y gantry, I knew that I had to make it run GRBL. Since most of the guides available seem to think that getting GRBL onto an Arduino is difficult, I thought that I'd write a small guide/tutorial for how I did this.

Start by copying / clone the source files from the Github repository to your machine. The precompiled versions could work, but I'll need access to the source later.

Download what we'll need

If you don't have the Arduino IDE installed, go get it from This contains all the command line tools we'll need, including avrdude (used for uploading code to the Arduino) and the avr-gcc compiler (converts source code to something the Arduino can use). The Terminal application is in the Utilities subfolder on your Mac /Applications/Utilities/Terminal. Open the app and type avrdude. If you get an error message along the lines of "command not found", we will need to setup the Mac to know where the AVR software are.

Adding the AVR tools to PATH

My original intent was to use LadyAda's tutorial ( for setting up AVR, but it's unfortunately quite outdated. Some of the external links are dead and I think it's possible to do this a little easier given that all the required tools are in the Arduino download.

Add your AVR-dude to the OSX path according to this tutorial. The AVR tool location on your machine will vary, but it will probably be somewhere inside your Arduino app folder like this:


After adding to the path, you'll need to close that terminal window and open a new one for the PATH to refresh. Typing "avrdude" in this new terminal window should now list all the options instead of "command not found". If not, go back to the tutorial above and try again.

Compiling the source

Now that we have the AVR tools in our path, we can go to the GRBL folder. I placed mine along with other Arduino code at /Users/jensa/Documents/Arduino/grbl/. Open open a terminal window and go to that folder:

cd /Users/jensa/Documents/Arduino/grbl/

To generate a .HEX file from the source code, simply type "make" and hit Enter.

If all goes well, you will now get a compiled program that you can upload to your Arduino. If something goes wrong, type "make clean" to remove the generated files. To see what other options are available, have a look at the "makefile" in the grbl folder. this is also where you'll adjust the compilation options if you're compiling for something other than an Arduino UNO (or other Atmega 328p-based devices).

AVR adjustments

To upload the hex file to the Arduino, you'll use "make flash". As long as the path has been set properly, that will compile just fine, but uploading it didn't go as planned. After figuring this one out, I found this official guide that could have helped me. To help others in the same situation, I'll leave how I got it working without this guide and the errors I got:

avrdude -c avrisp2 -P usb -p atmega328p -B 10 -F -U flash:w:grbl.hex:i
avrdude: can't open config file "/usr/local/etc/avrdude.conf": No such file or directory
avrdude: error reading system wide configuration file "/usr/local/etc/avrdude.conf"
make: *** [flash] Error 1

Looks like avrdude needs some custom configuration. Let's have a look at what's required. By typing "avrdude" on the command line, you'll get an overview of what's possible. From this, we can see that the "-C" flag allows us to set a custom configuration file. Since we are using the Arduino supplied version of AVR, we should probably use that config file as well. I found this file by using the find command in the terminal window:

sudo find / -name "avrdude.conf"

In my case, the path was:


so you're will probably be something similar. I added this to "makefile" after the other parameters for "PROGRAMMER" so that the line was now:

PROGRAMMER ?= -c avrisp2 -P usb -C /Applications/

Running "make flash" now returned a different error message:

avrdude: usbdev_open(): did not find any USB device "usb"

Right... That makes sense. In the Arduino IDE you're always specifying paths that start with /dev/ and such. You can find the correct port using the command

ls -l /dev/cu.*

This returns a list of possible devices and it's the same you'll find in the Arduino IDE. In my case it was /dev/cu.usbmodem411. Note: do not have the Arduino IDE open while doing this as it can cause trouble.

My "PROGRAMMER"-line in the makefile was now like this:

PROGRAMMER ?= -c avrisp2 -P /dev/cu.usbmodem411 -C /Applications/

I still got errors though:

avrdude: stk500v2_ReceiveMessage(): timeout

Ok. I've seen this one before. It basically means that your config is correct, but something is incorrect with the programmer. The programmer is set with the "-c" flag and here it's set to "avrisp2". That's the same as using "AVRISP mkII" in the Arduino IDE and that won't work with an Arduino UNO board. How about removing the number 2 so we get this:

PROGRAMMER ?= -c avrisp -P /dev/cu.usbmodem411 -C /Applications/ -carduino

Note the addition of -carduino at the end there? It helps with defining the right board. Ohhh! It's uploading! Now let's see if this works. We should be able to log onto the GRBL installation using the Arduino serial monitor. Bingo.

For figuring out the rest, I looked a lot at this tutorial that details how to use GRBL for a laser engraver. It's a little outdated, but has tons of good info!

For some defaults, I tried what is found on the GRBL wiki. That didn't work too well with the MakeBlock setup I have. Instead I ended up on using something like this:

$0=12.650 (x, step/mm)
$1=9.000 (y, step/mm)
$2=25.000 (z, step/mm)
$3=5000.000 (x v_max, mm/min)
$4=5000.000 (y v_max, mm/min)
$5=500.000 (z v_max, mm/min)
$6=500.000 (x accel, mm/sec^2)
$7=500.000 (y accel, mm/sec^2)
$8=10.000 (z accel, mm/sec^2)
$9=200.000 (x max travel, mm)
$10=200.000 (y max travel, mm)
$11=200.000 (z max travel, mm)
$12=10 (step pulse, usec)
$13=2500.000 (default feed, mm/min)
$14=192 (step port invert mask, int:11000000)
$15=25 (step idle delay, msec)
$16=0.050 (junction deviation, mm)
$17=0.005 (arc tolerance, mm)
$18=3 (n-decimals, int)
$19=0 (report inches, bool)
$20=1 (auto start, bool)
$21=1 (invert step enable, bool)
$22=1 (soft limits, bool)
$23=0 (hard limits, bool)
$24=1 (homing cycle, bool)
$25=224 (homing dir invert mask, int:11100000)
$26=100.000 (homing feed, mm/min)
$27=500.000 (homing seek, mm/min)
$28=100 (homing debounce, msec)
$29=2.000 (homing pull-off, mm)

An error that had me stumped for a long time was that the limit switches would be hit all the time causing the GRBL error:

ALARM: Hard/soft limit. MPos?

I searched and searched until I found this post regarding testing of homing in 0.9. Oh my... GRBL wan't to work with a 3 axis setup? How on earth could I know that... Well. I guess I could change the Z-axis a bit. That way I could even fit a Dremel on there? Hmmm! That sounds interesting...

X/Y robot with MakeBlock (Part 2)

04 Feb

X/Y robot with MakeBlock (Part 2)

Looks like I won't be able to progress as fast as I want on this project. Being a father, husband, freelancer and more takes away the hours, but I'll document the process here anyway in case others want to try something similar. Today I re-did the X-axis completely and also modified the Y axis a bit. In addition, I printed a cable chain so the wiring don't cause any problems as well as some endstop-mounts for Sainsmart/MakeBlock. Look mom - it moves!

This is starting too look like something. This is just a few lines of code with the AccelStepper library. Servo-arm up next!

Making a scale for Arduino with INA125

03 Jun

Making a scale for Arduino with INA125

For the recent project I did at EIS (The Energy Centre at Hunderfossen Amusment Park), I needed to build a scale. As kids walk around the exhibition, they're answering questions and at the exit there is a cool-looking scale. Here you select felt-bags based on your answers and their weight decide if you got the earth (or rather scale) in balance.

I picked up a couple Load Cells from Ebay and thought they were like the many other analog sensors that I've used. It turns out that a Load Cell does output a signal, but it's really weak. To get the signal I needed, I had to find a suitable "Load Cell Amplifier". After some quick searching, I realized that these come in many flavors and industrial versions are somewhat expensive ($200 and upwards). I did some more digging and found this nice little board from LeoBodnar as well as a nifty IC: the INA125. This is an IC that does exactly the required amplification for $7.

The premade board was nice and easy to mount, but I wasn't happy with the resolution I got from it. Since it has no adjustment options, I'd have to read up on the IC, get the correct SMD components, desolder and resolder. It seemed easier to build the circuit myself and with this great article as a guide - this is the circuit I made:

My Load Cell has other colors, so signal+ cable is blue, signal- is white, 5V is red and GND is black. I've seen load sensors with colors all over the spectrum, so make sure you have this documentation before buying from Ebay. Later this week I'll head up to the Hunderfossen Amusement Park to mount this modified version that gives me pretty much all the levels I want by just changing a single resistor. Not bad!

The image at the top is the finished version with screw-terminals on a proto-board (click to zoom). Below you can see how the scale looks like up at EIS:


Project: pressure sensitive floor

28 May

Project: pressure sensitive floor

I just came back from the most challenging physical computing project I've ever done. It's a 13 by 8 meter labyrinth where you walk in the dark and get a sensory experience based on more than 300 sensors. The main challenge was actually how much time it took to execute it, but it was such a fun project that I didn't really mind. You can now try it out yourself at Energisenteret in the theme park Hunderfossen (Troll-themed!) near Lillehammer, Norway. I don't know for sure, but I think this is the worlds first "pressure sensitive floor"? (video further down)

I've worked on several projects with the company SixSides and about a year ago, they asked me if I could build a floor that reacted to the people walking on it. The basic idea was to play back sounds of walking on other surfaces than you really were. Of course I said yes to the challenge!


My first idea was to make a button-matrix that sensed where you stepped, but after making a quick prototype I realised that this wouldn't create a very believable experience. Then it dawned on me that it would be MUCH more fun if it was actually pressure sensitive. During this project, I've played around with different conductive fabrics and it's been a blast! I really cannot praise the company PlugAndWear (Texe srl) enough. They're simply the best source of conductive fabric that I have found and they ship crazy fast from Italy to Norway (2 days!).

This is how you'll receive 14 meters of conductive fabric!

One of the many products they have is called Velostat. This material has a very unique property - it's resistance decrease with pressure. It does so in a way that if you just put a layer of Velostat in between two conductive layers, it will give you about 800 levels of pressure for an adult person stepping on it. If the person weighs more than 90Kg, you will most probably be able to read out the remaining 200 levels using the 10-bit analog inputs of an Arduino.

So I knew that Velostat was a good idea, but I needed a conductive layer both at the bottom and above and one of them should perferably lift up to ensure that there was no contact if pressure was not applied. Copper tape is a really good conductor, so I figured that I could use that as the bottom layer. It is easily taped to the floor and you can solder onto it quite easily. You can get this at multiple locations. I found mine at a shop for artists that make glass paintings.

The upper layer was more difficult. I eventually settled for the fabric called "Doubleface knitted conductive fabric" that has a polyester-thread layer and a stainless steel-thread layer that are knitted together. In my tests, this has stood up to quite a bit of physical abuse so I'm pretty sure it'll last quite long before being fully compressed. The only drawback of such a fabric is that it's really hard to work with, given how different these two layers and velostat are. I tried sowing these together, but it was incredibly hard to get the fabric to stay straight.


After settling on Velostat and the knitted fabric, I started prototyping and this is what I ended up with:

I tried various methods for making the sensors, but the most lasting solution seemed to be using textile tape from Tesa. Just tape together a layer of the knitted fabric ( with the steel side up) onto the Velostat. My only problem was of course that this was a manual job and I needed 300 of them. More about that later.

Above the sensors there were to be a floor of some sort. I did my test using Linoleum, but we ended up using a softer floor covering. I also used Fritzing to make a custom PCB for this (download below). It's not that it was really required, but it made the installation look professional and simplified the mounting a lot.


Since my prototype was just one of the 7 strips required for a full meter, I really had no idea how much work was required before I started. I ended up spending two full weeks (14 hr days!) on making two 1 by 3 meter floors. This is how the process looked like:

First add 4mm plywood to put the sensors on, making a sort of cable-duct in between them. This ensured that the soft, silicone-covered cables were not too exposed to the constant pressure of people walking on them.

Add the copper tape...

Solder the copper tape to the 5V output of the Arduino Nano's...

Connect the cables to the analog inputs of the Arduino Nano's...

Mount the handmade sensors and secure them to the floor with two-sided tape. Then connect the analog input cables (using the grey tape) and repeat for another meter...

After this has been done to the entire floor, I put sounds on the SD cards, programmed the Arduino's with their sound-cards and mounted them along with some suitable speakers.


I'm really happy with the result! The finished floor is so sensitive that I can sense a soda-bottle cap falling onto it! The sound playback happens the instance you put pressure on the floor and it really seems like you're walking on ice or other things. Selecting the correct sounds is of course a difficulty, but it's easy to adjust this. It's just files on a SD card after all.

I've also written the software so that wear'n'tear on the sensors won't affect how the installation work. They don't use the real pressure-level, but rather changes in an averaged level. If a floor tile becomes fully compressed so it no longer produces level changes, you can just rip it up and tape down another, so maintenance is easy.

The floor consists of 40 strips of 15 cm width, each with an Arduino Nano measuring up to 8 sensors. The complete installation is using 55 Arduino Nano's as well as sound cards from Gravitech. I opted for these since they're small and thus easy to mount. They're also very easy to get replacements for if that should be required.

Lessons learned

During the project I've learned a few things:

  • I now know that I should have used a much wider copper tape rather than three separate ones. Each one of these needs a soldered joint. Having just one rather than three, would have saved me 600 solder points and it would have been just as good.
  • Another thing I've learned in the project is that building a small prototype really does not cut it. You need to build a bigger prototype to correctly estimate the amount of work required. In the end I spent about 16 hours on each meter of pressure sensitive floor. My estimate was just a third of this, so since this was a fixed price project I didn't exactly become rich. If I do a similar project, I'll definitely insist on hourly pay or get somebody else to do the actual construction of the floor.
  • I'm using .OGG formatted files. MP3 files will add a few milliseconds of silence at the start of the sound and in this case, it ruined the experience. The OGG format does not have this problem.
  • The next time I design electronics that require multiple similar resistors, I'll definitely look into using a resistor-network instead.
  • Plan ahead for the carpentry and expect lot's of adjustments as the project progress...
  • Making the pressure sensor tiles took forever... Help is required if you do something like this, so a big thank you to Liv @ Sixsides for helping me out!
  • As soon as the walls are closed, it's a lot more work to get cables to the right spot, so make cable ducts that are wider than expected.
  • Arduino's are really solid for use in installations, but poor quality USB cables will affect both sound and stability.

Despite taking a long time, this has been a fantastic project! I really loved to do the whole thing from concept, research and realisation. It's so many other things one could use such a floor for, so I can easily see people building similar things as inputs for games and music. It also involved lots of other sensors (touch + distance + movement), but I'll do a separate post on those at a later time.

If anyone is interested in such a floor, I also have several ideas for how to simplify and industrialise the production of such floors, so feel free to contact me smile



My first PCB - a DS1307 based realtime clock

14 Mar

My first PCB - a DS1307 based realtime clock

The last months at Bitraf has been quite hectic in terms of workshops & activities. First there was a soldering workshop that I helped put on, then a PCB design workshop and that was followed by a PCB etching workshop. I also organized our third 3D Printer Meetup there. Peter, Trygve and Carl at the hackerspace has now gotten my dad's old Roland CNC to drill all the required holes in a PCB based on the Eagle files, so it's really possible to make nice things at Bitraf these days.

My first PBC, an RTC for Arduino

When an Arduino looses power, it's clock will always start in 1970 when it gets power again. For a client project I'm working on, I needed the correct time after a power outage. It was easy to find several RTC's online and they all cost something between $5 and $10. My problem was that getting it fast would be expensive and I happened to have the most used IC for this purpose. The DS1307 used in most of these modules is about a dollar each and the remaining components are not much either. Here's the Bill Of Materials along with links to where I bought them:

1 x DS1307

1 x 32.768 Crystal

3 x 10k resistors

1 x 104 capacitor (0.1 uF)

1 x 2032 battery holder

2 x 6-header pins

All together this is about $2 in parts, even for a very modest volume. Not shabby and I highly recommend both TaydaElectronics (Thailand) and Spiratronics (UK). Both are great shops that ship quickly to places in Europe and I use them a lot in addition to

Designing it

I looked online, but couldn't find something that others had made that was "free to use" and I had an idea: why not make it plug straight into one of the header rows on the Arduino? That way it would be real plug-and-play since both power and the analog pins used for i2c are on the same side. Above you can see how this turned out - it plugs right into the Arduino Ethernet shield.

I looked up the reference design and looked at how others had done it before and then made a first go in Eagle. After a couple fails (I forgot to "fill" with ratsnest + had counted the pins incorrectly) I got a couple nice looking PCB's.

Making it

The etching went really well and with all the helpful people at Bitraf, it's not hard to get this right. I drilled this one manually, but I'll definitely use the Roland CNC as soon as we have a good way to cut consistent PCB sizes. Here's how it looked after cleaning with Acetone:

I didn't have the required clock crystals, but I got these from Spiratronics in just 3 days. Today I soldered it up and plugged it in. Guess what - it didn't work... I looked over the PCB with a magnifier glass and cleaned up some excess solder along the traces and it still didn't work. Bummer. I went online and looked at how Adafruit did theirs and then it struck me - I had put the IC on the wrong side of the PCB.

Using it

After doing this, it worked like a charm! I used the Adafruit 1307 library and it works just as I hoped. I'll definitely make a couple more of these for other projects and so can you! Below you can find the Eagle schematic + board and here's the final stencil to use for the etching.

See more pictures of the PCB etching process on Flickr

Meetup Pocket Sign

08 Mar

Meetup Pocket Sign

My brother is thinking about going back into the signage business and as he would start up his own company, he'll need to build himself a network. My favorite way to connect with people and communities these days is - a website that help you host meetings with ease. So - I set out on a mission to help people remember my brother and what his company delivers.

I've long wanted to do something with the neat little 1.8" LCD screen I picked up from Adafruit some months back and looking through their site I found that they also have this neat Lipo charger as well as slim, matching batteries. What if I made a small LCD-sign that he could drop in his pocket? I ordered the components and started modeling.

About a week later, the parts arrived and I modified Adafruit's example file a bit to load images one by one from the SD card beneath the screen. That gave me a simple, but effective slideshow. All my brother needs to do is to to change the contents is to make some BMP images and dump them onto the SD card. Easy!

After a few iterations I came up with this case. The part containing the battery is not the slimmest, but it's also meant to go inside your shirt pocket. I could have made it slimmer, but then I would have to sacrifice battery time. With it's 1300mhA battery pack, it lasts 2 hours on one charge and charging it takes a little less than an hour. I could have saved a little space by skipping the proto-board that lies in between the electronics and the battery, but it made mounting things and getting the USB-port right for charging. I might remove that if I do a next iteration.

The part that is visible on the outside of the pocket is much slimmer and it looks like the red and white logo. It took quite a bit of fiddling to get the case right. I learned that by slanting the print 28 degrees while printing, a lot less cleanup was required.

The supports came off really easy and printing the parts like this actually made them much stronger and easier to glue together in the end. I usually use PLA plastic for all my 3D printing, but for this I used ABS since it can be grinded and polished (PLA can't). Towards the end of the project I didn't quite get the time required, but it was a fairly polished thing I gave away. It took me 4-5 evenings to make this project and I think it was worth it. I could of course have bought a CD or something from a shop, but this was a personal gift that (as far as I know) nobody has. Much more fun!

Here's a shot of junior showing off the final sign and if you want to make your own - grab the files on Thingiverse and components from Adafruit.