€2 Robots in DIT

In this video, I chat with Kevin Chubb about his final-year project on ultra low-cost swarm robotics, here in DIT’s School of Electrical and Electronic Engineering. Kevin’s designing robots that can be built by hand from less than €2 worth of off-the-shelf parts. He doesn’t quite have a swarm yet, but in the video we get to see one of his tiny robots scuttling to and fro.

I for one welcome our competitively priced new robotic overlords!

Advertisements
Posted in Uncategorized | Tagged , , , , , , , , , , , , | Leave a comment

A brief introduction to binary numbers…

Posted in Uncategorized | Tagged , , , , | Leave a comment

Can the PIC12F675 drive motors directly from its GPIO pins?

As I mentioned in my previous post, my project student Kevin Chubb is developing tiny ultra low cost robots using a PIC12F microcontroller. One of the things that’s great about PICs is that they can source and sink relatively high current through their digital i/o pins. Kevin and I have been hoping that it might be possible to build a robot that powers its actuators directly from the microcontroller pins, so that was a big factor in choosing the PIC12F. Anyway, yesterday I received a package of tiny “coreless” motors in the post from AliExpress, so I’ve just carried out an experiment to see if they can be powered directly from the GPIO pins of a PIC12F.

I received two types of motors in yesterday’s delivery, but the ones I’m using in this experiment are these ones:

To begin with, I measured the current drawn by one of the motors when it was running unloaded at 3V, which turned out to be approximately 31 mA. Although that’s slightly higher than the rated pin current on the PIC12F (25 mA), I decided it was worth taking a chance and I set up an experiment with two of the motors connected directly to a PIC12F675. Here’s the video:

The complete code is used is shown below:

//
// PIC12F675 example: motors on GP4 and GP5
// Written by Ted Burke - 20-4-2017
//
// To compile:
//
//    xc8 --chip=12F675 main.c
//
 
#include <xc.h>
 
#pragma config FOSC=INTRCIO,WDTE=OFF,MCLRE=OFF,BOREN=OFF
 
void main(void)
{
    TRISIO = 0b11001111; // Make pins GP4 and GP5 outputs
    ANSEL  = 0b00000000; // Disable all analog inputs
     
    while(1)
    {
        GP4 = 1;         // Set pin GP4 high
        GP5 = 0;         // Set pin GP5 low
        _delay(500000);  // 0.5 second delay
        GP4 = 0;         // Set pin GP4 low
        GP5 = 1;         // Set pin GP5 high
        _delay(500000);  // 0.5 second delay
    }
}
Posted in Uncategorized | Leave a comment

Minimum Viable Program for PIC12LF1572

Kevin Chubb (currently a final-year project student here in DIT) is designing a tiny robot using Microchip’s compact PIC12LF1572 microcontroller. It’s an interesting chip and Kevin’s doing great things with it. I decided to strip back one of the example programs he sent me just to find out exactly what’s required in the code to get a minimal program (flashing LED) working. In this example, I’m just blinking an LED twice a second on pin RA5 (pin 2). Thanks for the example code Kevin!

//
// MVP (minimum viable program) for PIC12LF1572
// Written by Ted Burke based on an example by Kevin Chubb
// Last updated 13-4-2017
//

#include <xc.h>

#pragma config FOSC = INTOSC    // Select INTOSC (internal) oscillator: I/O function on CLKIN pin
#pragma config WDTE = OFF       // Disable Watchdog Timer
#pragma config MCLRE = OFF      // Disable MCLR Pin (MCLR/VPP pin function is digital input)
#pragma config LVP = OFF        // Disable Low-Voltage Programming (High-voltage on MCLR/VPP must be used for programming)

int main(void)
{
    OSCCON = 0b01111010;  // 16 Mhz oscillator (optional)
    TRISAbits.TRISA5 = 0; // Make RA5 an output
    
    while(1)
    {
        LATAbits.LATA5 = 1; // LED on
        _delay(1000000);    // 250ms @ Fosc=16MHz
        LATAbits.LATA5 = 0; // LED off
        _delay(1000000);    // 250ms @ Fosc=16MHz
    }
}

This is the circuit:

I’m using a PICkit 2 programmer in Linux, so I used the pk2cmd command line application to transfer the program to the microcontroller. Unfortunately, the standard device file (PK2DeviceFile.dat) does not include the relatively recent PIC12LF1572, so I needed to download an edited version of the file from here:

http://github.com/GBert/misc/blob/master/pickit2/pk2cmd/pk2cmd/PK2DeviceFile.dat

Once I placed the updated PK2DeviceFile.dat file into my program’s folder, pk2cmd worked perfectly. These were the commands I used to build the code and program the microcontroller:

xc8 --chip=12LF1572 main.c
sudo pk2cmd -PPIC12LF1572 -M -F main.hex -T

If the location of pk2cmd is not included in the path, you’ll probably need to specify its location in the command.

Thai Phan pointed out in one of his comments below that you don’t need to run pk2cmd as root (as I did above, using “sudo”). You can configure udev so that all users have permission to access the PICkit 2. As Thai explained it:

Create a new file /etc/udev/rules.d/99-pickit2.rules containing the following:

SUBSYSTEM==”usb”, ENV{DEVTYPE}==”usb_device”, SYSFS{idVendor}==”04d8″, SYSFS{idProduct}==”0033″, MODE=”0666″

Then restart udev, as follows:

/etc/init.d/udev restart

Unplug your PICkit 2 and then plug it back in. It should now be possible to use pk2cmd without sudo. Thanks for the useful tip Thai Phan!

Finally, Kevin had quite a few additional configuration options at the beginning of his original example program. I’ll list them here because, although they weren’t required to get my example running, some of them presumably would be required in other situations. Here they are:

// Other configuration settings from Kevin's example that I didn't use:
#pragma config BOREN = OFF      // Brown-out Reset Enable (Brown-out Reset disabled)
#pragma config CLKOUTEN = OFF   // Clock Out Enable (CLKOUT function is disabled. I/O or oscillator function on the CLKOUT pin)
#pragma config PWRTE = OFF      // Power-up Timer disable
#pragma config CP = OFF         // Flash Program Memory Code Protection (Program memory code protection is disabled)
#pragma config WRT = OFF        // Flash Memory Self-Write Protection (Write protection off)
#pragma config PLLEN = OFF      // PLL Enable (4x PLL disabled)
#pragma config STVREN = OFF     // Stack Overflow/Underflow Reset Enable (Stack Overflow or Underflow will not cause a Reset)
#pragma config BORV = LO        // Brown-out Reset Voltage Selection (Brown-out Reset Voltage (Vbor), low trip point selected.)
#pragma config LPBOREN = OFF    // Low Power Brown-out Reset enable bit (LPBOR is disabled)

Thanks again to Kevin Chubb for the example code.

Posted in Uncategorized | Tagged , , , , , , , , , , , , , , | 6 Comments

dsPIC30F Quadrature Encoder Interface (QEI) – Basic Example

This video shows a basic example of using the Quadrature Encoder Interface (QEI) on Microchip’s dsPIC30F4011 microcontroller. I expect that the same approach will work with other microcontrollers in the dsPIC30F family.

In this example, I place two TCRT5000 reflective infrared sensors in front of a spinning black and white checkered disc to generate a pair of quadrature encoded signals. These signals are connected to pins QEA and QEB (the QEI input pins) on the dsPIC. The program shown in the example enables QEI so that the rotation of the disc is recorded in the POSCNT (position count) register. The value of POSCNT is printed via UART every 200 ms, so that it can be monitored on the PC screen.

This is the complete code:

//
// Quadrature Encoder Interface (QEI) example for dsPIC30F4011
// Written by Ted Burke, Last updated 12-4-2017
//

#include <xc.h>
#include <libpic30.h>
#include <stdio.h>
 
// Configuration settings
_FOSC(CSW_FSCM_OFF & FRC_PLL16); // Fosc=16x7.5MHz, i.e. 30 MIPS
_FWDT(WDT_OFF);                  // Watchdog timer off
_FBORPOR(MCLR_DIS);              // Disable reset pin
 
void main()
{
    // Use RD0 to blink an LED so that we can see program in running
    _TRISD0 = 0;
     
    // Setup UART so that we can monitor POSCNT value
    U1BRG = 48;            // 38400 baud @ 30 MIPS
    U1MODEbits.UARTEN = 1; // Enable UART
    
    // To use pins 6 and 7 as QEA and QEB (quadrature encoding inputs)
    // analog input must be disabled on both pins by setting the bits
    // for AN4 and AN5 in the ADPCFG register.
    _PCFG4 = 1;
    _PCFG5 = 1;
    
    // Enable the QEI module (x4 mode with POSCNT reset by MAXCNT match)
    _QEIM = 0b111;

    while(1)
    {
        // Print current value of position counter register
        printf("POSCNT = %d\n", POSCNT);
        
        _LATD0 = 1;         // LED on
        __delay32(3000000); // 100 ms
        _LATD0 = 0;         // LED off
        __delay32(3000000); // 100 ms
    }
}
Posted in Uncategorized | 1 Comment

Simple example program for the PIC12F675 microcontroller

The PIC12F675 is a very inexpensive 8-bit microcontroller from Microchip that’s available in an 8-pin DIP package (i.e. it’s suitable for breadboard use). I’ve had a small tube of these on the shelf for a few years, but I’ve only just got around to trying one out. In this post, I present a simple example circuit and program, which flashes an LED on one of the GPIO pins. The example circuit includes connections to the PICkit2 USB programmer that I’m using to program the device. The PICkit2 also supplies power to the circuit.

First, here’s the video of the example program running on the PIC12F675.

Example Code

This is the full C code for the flashing LED example. I built it using Microchip’s XC8 compiler (the compiler command line is shown in the opening comments).

//
// PIC12F675 example: blink an LED on pin GP5
// Written by Ted Burke - 18-2-2017
//
// To compile:
//
//    xc8 --chip=12F675 main.c
//

#include <xc.h>

#pragma config FOSC=INTRCIO,WDTE=OFF,MCLRE=OFF,BOREN=OFF

void main(void)
{
    TRISIO = 0b11011111; // Make pin GP5 a digital output
    
    while(1)
    {
        GP5 = 1;         // Set pin GP5 high
        _delay(500000);  // 0.5 second delay
        GP5 = 0;         // Set pin GP5 low
        _delay(500000);  // 0.5 second delay
    }
}

Example Circuit

pic12f675_circuit

Here’s my breadboard circuit:

20170217_162941

Posted in Uncategorized | Tagged , , , , , , , , , , , | Leave a comment

A simple way to read and write audio and video files in C using FFmpeg (part 2: video)

In my previous post, I demonstrated how FFmpeg can be used to pipe raw audio samples in and out of a simple C program to or from media files such as WAV files (based on something similar for Python I found on Zulko’s blog). The same idea can be used to perform video processing, as shown in the program below.

Reading and writing a video file

In this example I use two pipes, each connected to its own instance of FFmpeg. Basically, I read frames one at time from the input pipe, invert the colour of every pixel, and then write the modified frames to the output pipe. The input video I’m using is teapot.mp4, which I recorded on my phone. The modified video is saved to a second file, output.mp4. The video resolution is 1280×720, which I checked in advance using the ffprobe utility that comes with FFmpeg.

The full code is below, but first let’s see the original and modified videos:

The original and modified MP4 video files can be downloaded here:

The program I wrote to convert the original video into the modified version is shown below.

//
// Video processing example using FFmpeg
// Written by Ted Burke - last updated 12-2-2017
//

#include <stdio.h>

// Video resolution
#define W 1280
#define H 720

// Allocate a buffer to store one frame
unsigned char frame[H][W][3] = {0};

void main()
{
    int x, y, count;
    
    // Open an input pipe from ffmpeg and an output pipe to a second instance of ffmpeg
    FILE *pipein = popen("ffmpeg -i teapot.mp4 -f image2pipe -vcodec rawvideo -pix_fmt rgb24 -", "r");
    FILE *pipeout = popen("ffmpeg -y -f rawvideo -vcodec rawvideo -pix_fmt rgb24 -s 1280x720 -r 25 -i - -f mp4 -q:v 5 -an -vcodec mpeg4 output.mp4", "w");
    
    // Process video frames
    while(1)
    {
        // Read a frame from the input pipe into the buffer
        count = fread(frame, 1, H*W*3, pipein);
        
        // If we didn't get a frame of video, we're probably at the end
        if (count != H*W*3) break;
        
        // Process this frame
        for (y=0 ; y<H ; ++y) for (x=0 ; x<W ; ++x)
        {
            // Invert each colour component in every pixel
            frame[y][x][0] = 255 - frame[y][x][0]; // red
            frame[y][x][1] = 255 - frame[y][x][1]; // green
            frame[y][x][2] = 255 - frame[y][x][2]; // blue
        }
        
        // Write this frame to the output pipe
        fwrite(frame, 1, H*W*3, pipeout);
    }
    
    // Flush and close input and output pipes
    fflush(pipein);
    pclose(pipein);
    fflush(pipeout);
    pclose(pipeout);
}

The FFmpeg options used for the input pipe are as follows.

FFmpeg option Explanation
-i teapot.mp4 Selects teapot.mp4 as the input file.
-f image2pipe Tells FFmpeg to convert the video into a sequence of frame images (I think!).
-vcodec rawvideo Tells FFmpeg to output raw video data (i.e. plain unencoded pixels).
-pix_fmt rgb24 Sets the pixel format of the raw data produced by FFmpeg to 3-bytes per pixel – one byte for red, one for blue and one for green.
- This final “-” tells FFmpeg to write to stdout, which in this case will send it into our C program via the input pipe.

The FFmpeg options used for the output pipe are as follows.

FFmpeg option Explanation
-y Tells FFmpeg to overwrite the output file if it already exists.
-f rawvideo Sets the input format as raw video data. I’m not too sure about the relationship between this option and the next one!
-vcodec rawvideo Tells FFmpeg to interpret its input as raw video data (i.e. unencoded frames of plain pixels).
-pix_fmt rgb24 Sets the input pixel format to 3-byte RGB pixels – one byte for red, one for blue and one for green.
-s 1280x720 Sets the frame size to 1280×720 pixels. FFmpeg will form the incoming pixel data into frames of this size.
-r 25 Sets the frame rate of the incoming data to 25 frames per second.
-i - Tells FFmpeg to read its input from stdin, which means it will be reading the data out C program writes to its output pipe.
-f mp4 Sets the output file format to MP4.
-q:v 5 This controls the quality of the encoded MP4 file. The numerical range for this option is from 1 (highest quality, biggest file size) to 32 (lowest quality, smallest file size). I arrived at a value of 5 by trial and error. Subjectively, it seemed to me to give roughly the best trade off between file size and quality.
-an Specifies no audio stream in the output file.
-vcodec mpeg4 Tells FFmpeg to use its “mpeg4” encoder. I didn’t try any others.
output.mp4 Specifies output.mp4 as the output file.

Epilogue: concatenating videos and images

As an interesting aside, the video I embedded above showing the original and modified teapot videos was spliced together using a slightly modified version of the example program above. Of course, it’s possible to concatenate (splice together) multiple files of different formats using ffmpeg on its own, but I couldn’t quite figure out the correct command line, so I just wrote my own little program to do it.

The files being joined together are:

The full source code is shown below.

//
// combine.c - Join multiple MP4 videos and PNG images into one video
// Written by Ted Burke - last updated 12-2-2017
//
// To compile:
// 
//    gcc combine.c
// 

#include <stdio.h>

// Video resolution
#define W 1280
#define H 720

// Allocate a buffer to store one frame
unsigned char frame[H][W][3] = {0};

void main()
{
    int count, n;
    FILE *pipein;
    FILE *pipeout;
    
    // Open output pipe
    pipeout = popen("ffmpeg -y -f rawvideo -vcodec rawvideo -pix_fmt rgb24 -s 1280x720 -r 25 -i - -f mp4 -q:v 5 -an -vcodec mpeg4 combined.mp4", "w");
    
    // Write first 50 frames using original video title image from title_original.png
    pipein = popen("ffmpeg -i title_original.png -f image2pipe -vcodec rawvideo -pix_fmt rgb24 -", "r");
    count = fread(frame, 1, H*W*3, pipein);
    for (n=0 ; n<50 ; ++n)
    {
        fwrite(frame, 1, H*W*3, pipeout);
        fflush(pipeout);
    }
    fflush(pipein);
    pclose(pipein);
    
    // Copy all frames from teapot.mp4 to output pipe
    pipein = popen("ffmpeg -i teapot.mp4 -f image2pipe -vcodec rawvideo -pix_fmt rgb24 -", "r");
    while(1)
    {
        count = fread(frame, 1, H*W*3, pipein);
        if (count != H*W*3) break;
        fwrite(frame, 1, H*W*3, pipeout);
        fflush(pipeout);
    }
    fflush(pipein);
    pclose(pipein);

    // Write next 50 frames using modified video title image from title_modified.png
    pipein = popen("ffmpeg -i title_modified.png -f image2pipe -vcodec rawvideo -pix_fmt rgb24 -", "r");
    count = fread(frame, 1, H*W*3, pipein);
    for (n=0 ; n<50 ; ++n)
    {
        fwrite(frame, 1, H*W*3, pipeout);
        fflush(pipeout);
    }
    fflush(pipein);
    pclose(pipein);
    
    // Copy all frames from output.mp4 to output pipe
    pipein = popen("ffmpeg -i output.mp4 -f image2pipe -vcodec rawvideo -pix_fmt rgb24 -", "r");
    while(1)
    {
        count = fread(frame, 1, H*W*3, pipein);
        if (count != H*W*3) break;
        fwrite(frame, 1, H*W*3, pipeout);
        fflush(pipeout);
    }
    fflush(pipein);
    pclose(pipein);
    
    // Flush and close output pipe
    fflush(pipeout);
    pclose(pipeout);
}

Note: I used Inkscape to create the video title images. Click here to download the editable Inkscape SVG file.

Posted in Uncategorized | Tagged , , , , , , , , , , , , , , , , , , , , | 3 Comments