When I was trying to compile my first OpenWRT program I searched around the web, but didn’t found any useful (at least to me) tutorials/guides that would help me. After spending a few hours behind a computer and figuring out how to do this I found the easiest way to do it.

The are two ways of compiling:

simply compiling your application

building a package for it

Differences? If you have a package it’s easier to install and uninstall it, and probably easier to update it. However, in most of my cases I just simply want to compile my source code to a single executable and copy it to the device. Here I will show you the easiest way to do it and go from source code to final executable in a few minutes.

Change path to your toolchain, your device’s IP address, path to where you want to put your executable and name of your C file. If you want to include additional files just copy main.o to something.o, add it to program: section, and change the names accordingly.
If you need to link your program with additional library (e.g. pthread), you can add that to CC variable (e.g. gcc -lpthread).

What can I do with this Makefile?

command make – compile program for your PC (compile with the toolchain available on your computer and be able to test it out on it)

command make cc – compile program for OpenWRT device and deploy it to the device

This is an example of Makefile for a program that I use to control stairway lights at home. Lights are connected to my router via Launchpad MSP430 microcontroller, and I can communicate with them through TCP. I am also linking pthread library because I need threads (one for listening/communicating with serial port and one for TCP connections).

This is probably the simplest way you can compile your own programs without having to bother with creating your own packages.

If you need fast way to hash passwords with MD5/SHA1, or to encrypt and decrypt data with AES I recommend OpenSSL library. This library supports more than 25 algorithms for ciphering, hashing and public-key cryptography. It’s open source and supports most platforms, including Linux, OS X and Windows. To use OpenSSL from C# you need to use a wrapper. I hadn’t had much problems with OpenSSL.Net and it’s supposed to be cross-platform.

You can build library with assembly optimizations or without them. Optimizations provide faster code execution, according to some benchmarks they can speed up execution by up to 4 times, depending on selected algorithm. To successfully build them you need Visual Studio Professional or better, because VS Express doesn’t offer assembly compiler NASM.

I was always interest in knowing how much energy am I using and have been experimenting with different approaches to measure consumption. My favorite way to measure electricity consumption is the use of current transformers/clamps around wires coming into the house. Sadly, I don’t have any space left in electrical box to p ut them in.

About a year ago I found a solution, which is to direct web camera to electricity meter, watch blinking LED and calculate consumption. I made a simple prototype in the form of gluing webcam to outside electrical box (where we have electricity meter) and simple Forms application made in C# with bindings to OpenCV library.

The problem was that this prototype consumed almost whole core on older dual core AMD Turion laptop, which consumes more than 40 Wh. That is not a cheap solution and I also need that laptop for other purposes.

After a week or two of testing, I finally removed laptop and kinda forget about everything this idea. Later, I tried two different ways to capture blinking LED but neither worked as it should.

Two days ago I remembered about it and wanted to port everything to Raspberry PI, and in the future maybe even to a small router.

Over the last two days I tried two different approaches:

1.) Capture frames using v4l2 (in my opinion this was the best idea, and it should be as much as possible lightweight)

Capturing frames with v4l2 seemed like a hard thing to do, and it would actually be really hard, should I not use code from mjpeg-streamer. I went through the source of mjpeg-streamer, quickly found most interesting module – input_uvc and searched for usable source code.

After I successfully got frames, I needed to process them in figure out when the LED blinked. For debugging purposes I also added code to measure performance (frames per second) and to save captured frames.

Application runs in background (it’s a console application), watches captured frames for change of color intensity in specified area of interest, and makes http request to server to save results.

How it works?

Main function gets raw frames in YUYV format from web cam.

Function do_my_thing uses two for loops to iterate over received frame and get the average intensity of red color in specified area of interest.

If current intensity level is larger than average intensity level of previous 10 frames + 10 levels (to discard noise) then we mark it as blink of an LED.

We wait for a frame that has intensity level lower than the one marked as blink, and then make a http request to web server. (Single blink can be captured on multiple frames)

Simple PHP script running on web server saves data to database.

I should also mention my genius idea of how to keep intensity levels of last 10 frames – circular buffer. When it gets full it replaces oldest position with a new intensity level – that way I always have last 10 intensity levels and don’t need to move any data around.

I need to test this solution in the following week to see if there are any problems with capturing LED, but only improvement I could see right now is to add threads. One thread for frame capturing and processing, and another for sending http requests. Currently http request blocks capturing new frames and this may introduce a slight delay or lower fps.

Here is a picture of my current “GUI”:

MySQL Workbench running a query which counts reported blinks in the last minute. Now I need to make a web app that will show statistics and current consumption of electricity.

2.) Capturing and processing frames done with OpenCV library (should be the easiest)

I also tried this approach, and it really reduces the number of lines of code written, but Raspberry PI captures about 1 frame per second via OpenCV library, and about 15-20 with v4l2 API.

Recently I have been working on some personal projects where I need to use Linux – from building OpenWRT packages to programming apps with libraries that are Linux only. Sometimes I just work on Linux because it’s easier to set up any kind of libraries, doesn’t matter if it’s for C/C++ or Python development, in both cases nothing can beat apt-get install libwhatever-dev and additional flag when invoking a compiler.

( Few days ago I spent more than half an hour setting up paths for OpenGL project in Visual Studio to use glfw and similar libraries. On Linux that can be achieved in less than 1 minute by adding additional flags. )

However, I still prefer Windows environment for everything but programming, because it’s hardware support is supsrb, GUI (even Metro) is cool and most of the work I do on Linux can be done in virtual machine.

Sadly, my latest project needs v4l2 library to communicate with webcam and every time I tried connecting USB webcam through VirtualBox VM it would stop responding. Only viable solution was to use native installation on Linux. Since I removed my Crunchbang installation about a month ago, I needed to install new OS. I promptly went to Google and searched for Ubuntu download and downloaded 13.04 thinking that it was still in beta.

After installation, which went smoothly, I saw a lot of visual as well as technical improvements. I didn’t really follow development of this version so I was really surprised. A quick visit to OMG Ubuntu quickly helped me realize that I actually installed final version and not beta as I thought.

Why was I so pleasantly surprised?

Very nice looking design changes. 🙂

Graphics support out of the box. What what?? It actually worked for the first time (for me) without any tearing. Connecting and disconnecting external monitor correctly resized my desktop.

Waking from suspend without any problems? Yeah.

I just might use native Linux a bit more in the following months than I used to.

Servo motors are not robust as I am used to them, but they will be good enough to hold a light web cam.

Servos are controlled by PWM (pulse width modulation) and they need special hardware support. Thankfully, ordinary Arduino supports 6 PWM channels which should be enough for most projects.

Arduino already has a library called Servo to support these motors and there are a lot of articles explaining how it works, so I won’t go into details.

In my case I want to control it from a computer (or in the future from Raspberry Pi or some router running OpenWRT) and therefore need a way to communicate with Arduino.

Servos can be set to a fixed angle where they will stay no mater what (if you don’t put too much force to them) and this angle is from 0 to 180 degrees – half a circle.

Communication between Arduino and computer is usually in the form of data transfer through USB emulated serial port. Serial port communication is intended for transferring text so you must send/receive chars – which are represented by bytes. Byte consists of 8 bits and therefore can represent 128 different states or numbers.

Since 180 degrees is a bit bigger than 128 we need to find another way. I chose to separate data about each angle into two bytes.

First byte holds number from 0 to 127, and second one holds the reminder to 180. For example 160 degrees angle is sent as 127 and 33 – together they represent number 160.

The only remaining question is how do we know when byte from first motor starts? What if communication is interrupted before sending every byte? We need a unique identifier identifying the start of this sequence.

I decided to firstly post 127 and after that our sequence. However, we need to change the first byte for both motors from 0-127 to 0-126, so that 127 is never send anywhere else except at start.

At the start motors are at 90 degrees, and then we wait for 5 available bytes with first of them equal to 127. After that we simply add bytes and change global variables which will be latter sent to Servo library.

Example C# code with serialPort and two trackBars on form looks like this:

Couple of weeks ago, when I was thinking about what temperature sensors to use with my heating controller, I remembered DS18S20 and instantly order samples from Maxim.

Today I finished programming software for main controller – MSP430 chip and I want to show you, how I got those sensors working by bitbanging data pin. Sensors are connected in parasitic mode (which may not be such a good idea since turning oil burner/water heater on and off causes some unwanted interference, and it certainly doesn’t help that data & ground wires are near AC cables). I also found out, that chip’s internal pull-up isn’t powerful enough to drive temperature sensor while it’s converting temperature.

How to talk to one-wire DS18S20 / DS1820 sensor?

Reset

Check if there is a device present

Send skip ROM command

Send convert command

Reset

Send skip ROM command

Send read scratchpad command

Read byte from the bus

Firstly, we need to reset the device, then it’s necessary to sample bus to see if device responded and after that we send skip command, because we only have one sensor connected to the line and don’t care about it’s unique ID and then we request from sensor to convert (take temperature).

After that we do another reset, then skip ROM and read scratchpad commands, and after that we read received data – scratchpad from the device.

I talked more about specific commands and which data scratchpad contains previously on this blog, but I will nonetheless paste code which converts temperature to human readable float number:

If I understand this right (I mostly overslept class about bytes, bits, bitwise operators and other low level stuff about computers), you write byte to the bus by shifting bits to right and comparing them to 0x01 to decide if we want to write logical high or logical low.

Let’s for example take hexadecimal number 0xCC which indicates temperature sensor to skip ROM check:
0xCC is 204 in decimal and 1100 1100 in binary format.

Firsly, we check if this is true: 0xCC & 0x01. Ampersand (&) represents bitwine AND operator which checks every single bit of both numbers and results in 1 if bits in same place in both numbers are 1. Otherwise it results in 0.

For example:
0010 1011 &
0100 0010 equals:
0000 0010
because only second bit from the right side is true in both numbers.

0xCC & 0x01 equals:
1100 1100 & 0000 0001 which returns 0000 0000 because there the last bit in first number is not positive. Because 0000 0000 equals logical false, the condition of if statement is false and we use function to write 0 on the one-wire bus.

Secondly, we right shift bits for one place and get 0110 0110.

This repeats eight times, to write all bits of the byte to the bus. This type of bit shifting means that device receives byte from least significant bit (LSB) or right-most bit to the most significant bit.

Now we have taken care of resetting and writing bytes to the device. Only thing left to do is to read received byte to actually read the temperature from the sensor.

Reading byte from device

Again, we need to read byte from device bit by bit and here is the code for reading a single bit:

We make pin an output, drive bus low for 6 us and release it for 9 us. Then we change direction of the pin to input and read bit’s state. After that we need to wait 55 us before reading another one.

I like to complicate things so here is my code for reading a whole byte (I’m quite certain that there is a better way to doing this, but this is what I came up with):

byte j=0x01;
byte r=0x00;
for(int i = 0;i<8;i++) {

if(read_bit(bi)) {
r=r| j;
}else{
r=r& ~j;
}

j<<=1;
}

So, what we do here is to define two variables, first equals 0x01 or 0000 0001 and the second is 0. After that we check is we read logical true or false as current bit and modify variable r accordingly with the help of variable j, which is shifted left after every turn.

Again, we are dealing with byte represented from the least significant bit forward.

r = r | j represents bitwise OR which compares each bit of both bytes and results in 1 if bit of either one of bytes is 1 or true.

If, for example, we are trying to read 0xAC (1010 1100) we start with the rightmost bit/LSB and go to the left:

1.) First bit is 0, so we execute r & ~j which means:
0000 0000 & ~0000 0001 and ~ (tilde) inverses all bits, so we get:
0000 0000 & 1111 1110 which leaves alone every bit except the rightmost bit, which is set to 0.

2.)After that we shift j to left by 1, which gives us: 0000 0010.

Second bit is 0, so we again clear that bit from the final byte by using 0000 0000 & 1111 1101 to get: 0000 0000.

3.) Third bit is 1 and by using 0000 0000 | 0000 0100 we get: 0000 0100.

4.) Fourth bit is 1: 0000 0100 | 0000 1000 equals 0000 1100

5.) Fifth bit is 0: 0000 1100 & 1110 1111 leaves byte unchanged

6.) Sixth bit is 1: 0000 1100 | 0010 0000 equals 0010 1100

7.) Seventh bit is 0, byte stays the same

8.) Eight and the last bit is 1 which means that: 0010 1100 | 1000 000 equals 1010 1100 and we get our final number 0xAC.

That is all you need to know to communicate to a single one-wire temperature sensor from DS1820 family. It actually seems a lot easier than it seemed when I read this from different datasheets.

Here is the link to code containing all functions needed to get temperature data from this sensor: ds18s02

You need to call function get_temp to get the temperature and it’s only argument is bit from second port of the micro controller. Code was written and tested using Energia IDE (which has the same crappy IDE as Arduino, but libraries are excellent) so it should work fine with msp430 gcc compiler.

Today I was searching for something at home and stumbled upon old printing calculator, that hasn’t been in use for a few years.

Firstly, I plugged it in the wall socket and tried pressing different keys to see what it can do. Since I don’t really know how to use it, only thing I got were some random numbers printed on paper.

Secondly, I started thinking what I can do with it … well, I can at least open it to see what’s inside.

Picture below shows how it looks inside. On the upper right there is a mains transformer which has two outputs, first one is probably for micro controller and logic circuit and outputs about 6V, and the second one has output of approximately 22V and might be used to drive printer and display.

On the upper left there is a numeric printed which is surprisingly made by Epson.

On the middle/bottom part there is a logic board with the screen and a second board which holds keys.

Logic board has Mitsubishi 8-bit micro controller MS50754-125SP which has (according to datasheet) 6144 bytes on ROM and 160 bytes of RAM and apart from supply circuit it also features three Mitsubishi Darlington transistor arrays M54531P which are used to control numeric printer.

I don’t really have any use of screen and keyboard, but printer looks quite interesting. I don’t really know how much time will I have in the near future, but I would really like to control this printer from micro controller/computer.

About a year ago I decided to replace analog heating controller at home with something a bit more advanced. I have designed circuit and PCB at that time, but haven’t made until recently. It consisted of ATmega328 microcontroller, 4 relays and ENC28J60 breakout board for network connection. When I was writing source code, I thought about noisy relays and my distrust to using ENC28J60 (I previous had problems with AVR hanging after too much requests).

I quickly scrapped the plan and started thinking about more reliable approach, something like separating controller logic from network access. That day (or maybe day before) I got 3 MSP430 Launchpad boards I ordered online a few weeks ago. I heard about those boards quite frequently before, but did’t want to jump on that bandwagon = frankly, I didn’t have a good reason for buying it. But when I saw ad or something about it, I said what the heck and bought it. So I instantly saw an opportunity to use it for heating controller in combination with WR703N wireless router.

So my plan is like this:
– WR703N provides web interface, logs statistics in combination with USB flash drive, and fetches temperature from Ethernet temperature module
– MSP430 controls optocoupler-triac board according to temperature sensors, and reports data about current state of sensors/triacs back to router (it should also be possible to put it in a manual mode and circumvent control logic)
– optocoupler-triac board featuring 4 BTA12 triacs controlled by MOC3063 optocoupler

So for about 40€ I will have a really powerful controller with data logging capabilities.

I need to control 4 devices:
– electric boiler for heating water in summer
– oil burner for heating water boiler and central heating
– pump for heating water boiler
– pump for circulation of water through radiators

Electric boiler and oil burner have additional temperature sensors to prevent overheating of water, so even if my system screws up, it won’t cause any unwanted behavior except a bit warmer water and rooms in the house.

I bought STM32F4 Discovery board from Farnell two months ago, but I got to it only two days ago. After testing some examples and trying to interface with ENC28J60 Ethernet Controller, I quiclky found out, that free versions of development tools cannot build executables bigger than 32KB. So I decided to install toolchain on Ubuntu 12.04.