Display a PNG Image on small 128×128 OLED LCD

Now that my small OLED display automatically loads the device drivers on boot, it was time to see if I could display an image on my new frame buffer device.

To start with I went looking for a very basic graphics library that would allow me to experiment on frame buffer devices. There is certainly no shortage of libraries to choose from. The library that I settled on was the “Lightweight C 2D graphics API agnostic library with parallelism support” written by grz0zrg. It had both PNG and JPG routines that could output to a simple frame buffer device, being written in C was also a winner.

Flicking through the various examples the quickstart.c file seemed to have nearly everything I needed to display a PNG file on my OLED. Not so long ago a fellow AREG club member shot me some icon files for our club website; one of these icons was 512×512 pixels in size which made it an excellent candidate for shrinking to 128×128 pixels and using it on my OLED.

Downloading the library was as easy as;

$ cd ~
$ git clone https://github.com/grz0zrg/fbg

If you don’t have git installed use the relevant apt-get command. The example files can then be found in the following directory;

$ cd ~/fbg/examples 

I then copied the quickstart.c file and hacked on it a little, modifying it like so;

#include <sys/stat.h>
#include <stdio.h>
#include <signal.h>
#include "fbgraphics.h"

int file_exists( const char* filename )
{
    //define file handle
    FILE *file;

    //attempt to open file read only
    if( (file = fopen(filename, "r")) )
    {
        fclose(file);    // release file handle
        return 1;        // tell someone we found it
    }
    else
    {
        return 0;         //no one home
    }
}

int main(int argc, char* argv[])
{
    const char* framebuffer_name = "/dev/fb1";
    const char* logo_filename = "logo.png";

    //check we have a framebuffer to talk to
    struct _fbg *fbg = fbg_setup( (char *)framebuffer_name, 0);
    if (fbg == NULL)
    {
        return -1;
    }

    // make sure logo file exists
    if( !file_exists( logo_filename ))
    {
        printf("File not found: %s\r\n",logo_filename);
        return -2;
    }

    //draw something on the display
    struct _fbg_img *logo = fbg_loadPNG(fbg, "logo.png");
    fbg_clear(fbg, 0);
    fbg_image(fbg, logo, 0, 0);
    fbg_flip(fbg);
    fbg_draw(fbg);

    //release memory
    fbg_freeImage(logo);
    fbg_close(fbg);

    return 0;
}

Which was built with the following command line from within the examples directory;

gcc ../src/lodepng/lodepng.c ../src/nanojpeg/nanojpeg.c ../src/fbgraphics.c display_logo.c -I ../src/ -I. -std=c11 -pedantic -D_GNU_SOURCE -D_POSIX_SOURCE -Wno-unused-value -Wno-unknown-pragmas -O2 -Wall -lm -o display_logo

Hacking upon the Makefile is also not that difficult, I simply added the relevant lines the SRC and OUT sections, then copied the quickstart section and renamed display_logo. There is lots of information about on how to do this on the internet so I’ll not repeat it again unnecessarily.

All I had to do then was place my 128×128 PNG file alongside the display_logo executable (renamed logo.png) and run it… wallah ! I was greeted by the AREG logo on my small OLED display in all of its 128×128 pixel glory; see the image at the top of this post.

So the next trick is to move this to the boot process… So by the looks the plymouth package might be the go, only one way to find out.

Starting a fbtft_device on Boot

After having woken up my small 128×128 OLED display I was wondering how to get it to start automatically each time my rPi booted rather than having to log in and run the commands manually.

It turns out this is rather easy and just required me to edit two files. I’m also glad that these Waveshare OLED displays are effectively compatible with the Freetronics OLED 128×128 graphics display. A big thanks to the Freetronics team for making this driver available for SED1351 chip sets.

So I created the following file with my favourite editor (as root) /etc/modprobe.d/fbtft.conf with the following contents;

options fbtft_device name=freetronicsoled128

What this effectively does is tell the system how to configure the fbtft_device as it boots, much like if we started it with modprobe from the command line i.e used the following command;

sudo modprobe fbtft_device name=freetronicsoled128

So now the system knows how to configure the driver, we need to tell modprobe to load it by placing an entry in the /etc/modules file. So using your favourite editor (as root) edit /etc/modprobe and append the last two lines.

# /etc/modules: kernel modules to load at boot time.
#
# This file contains the names of kernel modules that should be loaded
# at boot time, one per line. Lines beginning with "#" are ignored.

i2c-dev
spi-bcm2835
fbtft_device

It appears that the SPI bus is a little slow to load if it’s called as a dependency of fbtft_device, which is a classic chicken and egg driver problem. So by starting it manually we make sure it’s available by the time the fbtft driver tries to do anything.

The i2c-dev entry in the same file fires up the i2c bus and was already pre-configured in my system by raspi-config way back when. I’m using it in my project, YMMV. All that is left to do is test it, so reboot and login and run the following command;

$dmesg | grep graphics

We should see something like the following;

[6.128978] graphics fb1: fb_ssd1351 frame buffer, 128x128, 32 KiB video memory, 4 KiB buffer memory, fps=20, spi0.0 at 20 MHz

That tells us that the little OLED display has registered as /dev/fb1 and that it’s ready to go. You can use the con2fbmap trick in my last post to test it’s working.

Now to work out how to get it to throw up an image on boot…

Maple Mini’s & a STM32F103CBT6

I recently found myself at the very limits of what you can ask an Arduino Uno to do, both in terms of flash and speed. I’ve used Atmel AVR processors for nearly 20 years so I know them and their foibles very well.

At work a while back we started using various STM32 processors and that has been somewhat enjoyable, I now like throwing floats around instead of having to resort to fixed point maths and excel for algorithm development. I’d heard that you could run up the Arduino framework on the STM32 platforms so was keen to try it.

So I initially went looking for a well supported board and simply struggled to find one. It seemed that this space had come and gone rather rapidly. Further research showed why, the Chinese clones has effectively decimated this market due to price. I was still keen to give it ago so placed an order for two Maple Mini boards with the STM32F103CBT6 processors on them off eBay for the princely sum of A$20 with free freight. Little wonder everyone abandoned ship in mid 2016.

A big thanks has to go to Leaflabs since they have left all of the circuits, boot-loaders & design files in a GitHub repository here (click).

So what did we have to do to get these working ? It wasn’t as trivial as the Arduino Uno that is for certain.

The first step was to get Windows 7 drivers (yes I know it runs out next year) for the Maple Mini, I found some here (click). I basically hit the green button marked “Clone or Download”, saved the file on my local machine. Extracted the files from the archive to a temp directory, then via the System Manager clicked on the “Maple 003” device that appears, told it I wanted to update the drivers from a specific location then pointed it at the temp directory I’d stored the files in previously. It figured it out and installed the ones I needed. What I found amusing is it then appeared under a category called “Atmel Devices” since I’d installed tools based on libdfu for these devices once upon a time ago. YMMV.

Once I had drivers installed I could then fire up PlatformIO in the VSCode editor and attempt to create a new project. I selected the board type “Maple Mini Original” and “Arduino” for the platform and let it do its business. Unfortunately the processor I have and the one on the original maple mini are different, so I had to change a few things in the platformio.ini file; my config is below. This config is based on a PlatformIO blog post written by Vortex314, can’t thank them enough for sharing this information (click).

[env:maple_mini_origin]
platform = ststm32
board = maple_mini_origin
framework = arduino
board_build.mcu = stm32f103cbt6
board_build.f_cpu = 72000000L
build_flags = 
    -D USBD_USE_CDC
    -D PIO_FRAMEWORK_ARDUINO_ENABLE_CDC
    -D PIO_FRAMEWORK_ARDUINO_USB_FULLMODE
    -D USBCON
    -D USBD_VID=0x0483
    -D USB_MANUFACTURER="Unknown"
    -D USB_PRODUCT="\"BLUEPILL_F103C8\""
    -D HAL_PCD_MODULE_ENABLED

So what is so special? Firstly there are separate board_build definitions to set the processor and speed for the board. Thankfully the cores between the original board and my Chinese clone are similar enough for this to work. Secondly there’s a heap of additional build flags that will build in a USB serial port. So if you’re used to the USB serial to debug your code this will still work. You can find out a little more about why this is necessary on Roger Clark’s website here (click).

It is interesting that the boot-loader contains only DFU code and that the application needs to have the USB serial built in separately. In the above configuration you may notice that the VID is 0x0483 which is by design, this means the Communications Device Class (CDC) will trigger the ST Serial drivers on a Windows installation if you have them installed. If you don’t you can find them here (click).

So from within the PlatformIO environment we can write our code and build for our target. Here’s my very simple test program that flashes the onboard LED (pin 33) and will send some test data to the USB serial port.

#include <Arduino.h>

void setup() 
{
  // put your setup code here, to run once:
  pinMode( 33, OUTPUT );
  Serial.begin(115200);
  
}

void loop() 
{
  static int i = 0;
  
  // put your main code here, to run repeatedly:
  digitalWrite( 33, HIGH );
  delay(500);
  digitalWrite( 33, LOW );
  delay(500);

  Serial.print("Test #");
  Serial.println(i++,DEC);
}

So the last comment I need to make is in the programming of the device. When you hit the upload button from within PlatformIO you’ll see OpenOCD start and then pause with the comment “Searching for DFU device [LEAF:0003]” and if you wait long enough a subsequent message flashes by reading “Couldn’t find the DFU device: [LEAD:0003]” and nothing appears to happen.

Initially I thought my board was dead when it dawned on me… The Arduino uses a separate ATmega8U2 that is capable of resetting the target ATMega328 under software control, the STM32F103Cx is using the internal USB port and does not have this reset function (*face palm*). So when we start the program cycle we need to wait for the “Searching for DFU device” to appear and then manually reset our target to force the boot-loader into DFU mode momentarily where it is then caught and updated. Once done the process carries on as expected and you find you haven’t bricked your device.

Happy programming !

PCB Cleaning for Beginners

I’ve been doing a lot of PCB assembly of late both re-flowing SMD in a toaster oven and a heap of hand soldering.  One thing that bugs me is cleaning up the various rosin’s, flux and solder paste without making a bigger mess.

My usual clean up method is to use IPA and cotton buds, however the IPA has a nasty habit of dissolving the flux/rosin/paste and redistributing it across the surface of the PCB making a slightly tacky mess worse than when I started.   Dang it !   I then resort to using cotton make up removal pads (stolen from the medicine cupboard) and with a blotting technique try to pick up as much of the mess as I can with copious amounts of IPA.  There simply has to be a better/cheaper/simpler way !

So after speaking to a few production Engineers at work I was pointed towards various brands of PCB wash and the suggestion was made to use an ultrasonic cleaner.   A bit of poking around the internet suggested that a good ultrasonic cleaner could be had for less than A$200 and PCB wash should be A$15 to A$20 per litre.

Thankfully my local Jaycar had both locally available which makes supply and  warranty much easier.  I also like supporting my local shops where I can.

The ultrasonic unit I purchased can be found here (click), part number YH5412.  It has a total transducer power of 160W and a tank that can hold up to 2.1L of liquid.  This unit is manufactured in China and if you look carefully you’ll see the same OEM unit on various sites all for about the same price.   This is certainly big enough to hold quite large PCB’s up around 250mm x 150mm and has an inbuilt heater as a bonus.

The PCB wash was yet another story.  This stuff is far cheaper in large quantities but I just wanted a little bit to see how we go.  So I found Jaycar also sold 1L bottles from Chemtools which you can find here (click), part number NA1070.  This stuff is biodegradable which means it should be ok to go down the sink, however I’ve got some 5L bottles I can decant the used liquid into and dispose of at the local EPA as required.  All of the technical stuff can be found on the Chemtools website here (click).  It’s worth reading the TDS and SDS sheets of this stuff and making sure you take the necessary precautions.

So to clean some PCBA’s !

I filled the machine to it’s minimum level (~700ml) and turned on the heater.  Within 10 minutes the fluid was warm (not hot) so I turned off the heater and loaded a number of small PCB’s into the fluid, being careful not to overlap the boards.  The TDS for this PCB wash says the fluid can be heated to  +40 degrees Celsius but is designed to work between 20-30 degrees Celsius.  So I just used it warm, not hot.   I ran the unit for 180 seconds (one of the presets) with the lid on. The ultrasonic cleaner certainly made the right noises and there were lots of little bubbles ripping into the contaminants.  I really like the lid on this unit as a warm liquid evaporates and with the lid on there was certainly condensation under the lid keeping everything in.

Once the countdown timer expired it was into one bowl of distilled water and then rinsed again in a second smaller bowl of distilled water.  I had a spare pair of plastic tongs I could use to move the PCB’s between tanks without using fingers.  The idea of the two baths is to get the bulk of the PCB wash off in the first bowl and then the last dregs off in the latter.   It helps to change the water in the first bowl often, since it takes the bulk of the PCB wash off in the first instance.

Then it was into the drying cupboard at 50 degrees Celsius for 40 minutes to evaporate the last of the water off the board.  My drying cupboard is a 20L toaster oven that I used to use for reflow soldering, nothing high tech but it will idle along at 50 degrees nicely unlike other ovens I’ve tried.   I’ve seen videos online where others have used a paint stripper gun to blow hot air across the boards, YMMV.

So the result ?  I’m impressed.  Quite simply impressed with how clean the boards have come out of this very simple process.   They are now clean and you’d be hard pressed to tell that they didn’t come from a professional board loader.  Inspecting the results under the microscope I see there is very little residue on the boards, both the flux and rosin from the hand soldering processes have been completely removed.  There is no trace of any solder paste balls either.  They are clean as a whistle.

I will have to work out a way to take photo graphs down my microscope to show the results, my feeble attempts at trying to take a macro shot with my phone failed dismally.

Now I have to hurry up with the Whizoo controller and my smaller 9L toaster oven conversion.  Must remember to blog that too.