Drawing a bounding box over an image with C#/.net and WinForms

Most of the info in this post can be found between the following two links:



Drawing a bounding box over an image to select a region took me longer to figure out than I expected. Here’s a brief bare-bones example demonstrating how to do it.

To follow along, pop a PictureBox form inside of a form, and set a background image. Make sure you can run the program and see this work as expected.

What’s next is pretty straightforward. First you need to create callbacks for the mouse down and mouse up events captured by the PictureBox. We’ll need to set a value in the main form class to indicate that the mouse is currently down.



The way this is going to work is that on the MouseDown event, the location of the mouse is going to be stored, and we’ll also store the current point of the mouse as it moves around (while the mouse button is still held down). Using those two points, we’ll draw a box.

Next let’s update the MouseDown callback to include capturing the initial mouse down point, and also add a MouseMove callback to update the current point.



Now it’s time to do the actual drawing of the box. This is done by making a callback for the Paint event that the PictureBox receives whenever it’s “dirty”. Inside that callback is where the rectangle drawing happens. We’ll trigger this Paint event manually by calling the Invalidate() method on the PictureBox in the MouseDown, MouseUp, and MouseMove callbacks, too.

Here it is all together.


Here is a Gist: https://gist.github.com/anonymous/6788f9f3095ed40ec06b4f5795c2d1c2

And here’s the final result. You’ll have to imagine the mouse cursor on the bottom-right of that red box since printscreen doesn’t capture it.


I usually try to put the code inline with the post, but I got frustrated fighting the WordPress code formatting! The context for this post is that I made a toy Mandelbrot fractal viewer and I wanted to draw a box around an area I wanted to zoom into.

Posted in Uncategorized | Leave a comment

Control a power strip with an Arduino

I’m running some tests at the office that require cycling the power to a device. After spending a few days doing this manually by flipping the switch on a power strip, I started searching for a better way.

Some Googling revealed the IoT Power Relay made by a company called Digital Loggers.

It’s got a +/- screw terminal on the side (the green part) that can be connected directly to an Arduino digital output and ground. Raise the Arduino output high, and two plugs turn on while two others turn off. Perfect!


I control the output on the Arduino through a program that handles all of the test (logging, etc). The Arduino sits in a loop waiting for serial input. If the Arduino program sees “A” come across the serial line from my testing program on the PC, it raises the output high, powering off my device that is plugged it into the “Normally ON” plug. Four seconds later, the Arduino output is set low, powering my device back on.

Pretty slick. I’m glad it worked – Plan B was to hot glue some servos to my power strip to toggle the power switch!

Posted in Uncategorized | 1 Comment

Passing a ctypes array of struct from Python to .dll

I’m working on a small project that requires interfacing Python to a C .dll. I’ve never had to pass an array of structures by reference before with ctypes, so here’s a quick sanity check I did to make sure I was doing it right before diving into something heavier.

The .dll source:

// structtest.cpp : Defines the exported functions for the DLL application.

#include "stdafx.h"

#define STRUCTTEST_API __declspec(dllexport)
#define STRUCTTEST_API __declspec(dllimport)

extern "C" {
	struct structtest {
		char x;
		int y;
		long z;
	STRUCTTEST_API void fillonestruct(struct structtest *t)
		t->x = 'A';
		t->y = 1234;
		t->z = 5678;

	STRUCTTEST_API void fillmultiplestruct(struct structtest *t, int n)
		for (int i = 0; i < n; i++)
			t->x = (char)((int)'A' + i);
			t->y = i;
			t->z = i;

Here’s the Python program that uses the .dll:

from ctypes import *

class structtest(Structure):
    _fields_ = [("x", c_char),
                ("y", c_int),
                ("z", c_long)]

if __name__ == "__main__":
    n_struct2 = 5
    lib = CDLL("structtest.dll")
    struct1 = structtest()
    struct2 = (structtest * n_struct2)()
    print("Before passing to .dll")
    print("Struct1 x:{} y:{} z:{}".format(struct1.x, struct1.y, struct1.z))
    for i in range(n_struct2):
        print("Struct2[{}] x:{} y:{} z:{}".format(i, struct2[i].x, struct2[i].y, struct2[i].z))
    lib.fillmultiplestruct(byref(struct2), c_int(n_struct2))
    print("\nAfter passing to .dll")
    print("Struct1 x:{} y:{} z:{}".format(struct1.x, struct1.y, struct1.z))
    for i in range(n_struct2):
        print("Struct2[{}] x:{} y:{} z:{}".format(i, struct2[i].x, struct2[i].y, struct2[i].z))

The output:
Before passing to .dll
Struct1 x: y:0 z:0
Struct2[0] x: y:0 z:0
Struct2[1] x: y:0 z:0
Struct2[2] x: y:0 z:0
Struct2[3] x: y:0 z:0
Struct2[4] x: y:0 z:0

After passing to .dll
Struct1 x:A y:1234 z:5678
Struct2[0] x:A y:0 z:0
Struct2[1] x:B y:1 z:1
Struct2[2] x:C y:2 z:2
Struct2[3] x:D y:3 z:3
Struct2[4] x:E y:4 z:4

So hooray – everything works as expected.

Posted in Hobbies, Programming, Technology | Leave a comment

ADXL335 Accelerometer on an Arduino

I picked up an ADXL335 accelerometer in a packaging designed to fit onto a solder-less breadboard so that I could interface it to my Arduino. I had a few time-consuming problems interfacing with it because I’m not used to reading chip data sheets.

My assumption was that you’d deliver voltage to it, and it would spit out an analog signal that could be easy translated to acceleration using some constant factor. This isn’t exactly the case. The output resolution, milliVolts per g (1 g = Earth gravity), and voltage bias, is dependent on the voltage delivered to the power pin. I think in hindsight this makes sense, but the data sheet phrases this, and a few other things very peculiarly. I’m fairly inexperienced reading chip data sheets.

The data sheet is here (PDF). On the third page is pretty much everything you need to know to get useful data out of it, and the rest of the doc is stuff most hobbyist level people don’t care about, like how it behaves in different temperatures, and noise expectancy.

The phrase “RATIOMETRIC” shows up a few times. What this means is that a few of the specs are dependent on the power delivered to the chip. The sensitivity (mV/g) is stated to be ratiometric, and the example they give is that when you deliver 3V to the power supply, the sensitivity is 300 mV/g. In a later section called “Use with operating voltages other than 3V” it gives the example of 360 mV/g with a 3.6V power supply, and 195 mV/g with a 2V power supply. You can pretty much gather that the sensitivity in mV/g is the power supply voltage divided by 10. More or less.

Another ratiometric value is the “0g bias”. I don’t do a whole lot of analog electronics stuff, so this took me a bit to figure out. The accelerometer chip can detect negative acceleration, but it doesn’t output a negative voltage signal. What you do is consider the middle point of the power supply voltage range the 0 point. My power supply voltage is 3.3V, so I have to treat 1.6V as the zero point. You’ll add have to subtract that zero point from any voltage reading to get the actual mV/g value.

Here’s some numbers to drive the point home. My power supply is 3.3V, which is 3300 mV. 3300 divided by 10 is 330, so the chip is going to deliver 330 mV per 1g of acceleration. If I have the module on my table with the z-axis point up, it’s going to have 1g of acceleration applied to it, since it’s going to just read the pull of the Earth’s gravity and no other force. The chip’s zero point is the middle of the power supply range, 1.6V (1600 mV), so the actual voltage value it’s going to output for 1g of acceleration is 1930 mV, or 1.93 Volts. Since I know all this, I only need to subtract the zero point voltage to get the true value of 330 mV.

If I turn my accelerometer upside-down, it’s going to feel -1g of force. The voltage it would output would be 1.27V. When you subtract the zero point voltage you get -330 mV, which comes out to -1g.

Anyways, here’s the Arduino code that gets values for the X, Y, and Z axis spit out in units of g.

//Quick accelerometer test
//X is on A0; Y is on A1; Z is on A2

//Analog input pins 0, 1, and 2
//are what I send the x,y, and z
//accelerometer outputs to, respectively
int xAxisPin = A0;
int yAxisPin = A1;
int zAxisPin = A2;

//Variables to hold the returned
//ADC data from the analog input
int xAxisValADC = 0;
int yAxisValADC = 0;
int zAxisValADC = 0;

//Variables to hold the voltage
//values after converting from ADC
//units to mV
float xAxisValmV = 0;
float yAxisValmV = 0;
float zAxisValmV = 0;

//My Arduino Uno has a 10-bit
//AD converter, with a max value
//of 1023
int ADCMaxVal = 1023;

//The AD converter voltage
//is powered by 5V
float mVMaxVal = 5000;

//I measured the power going to the
//accelerometer as actually being 
//3230 mV, so I use this value to 
//define the mid-point
float supplyMidPointmV = 3230 / 2;

//Since the supply is actually 3230
//mV, I know the output will be 323mV
//per 1g detected
int mVperg = 323;

//Multiply any acquired ADC value
//by mVPerADC to convert to mV
float mVPerADC = mVMaxVal / ADCMaxVal;

void setup()
  //I don't know if setting them to
  //input is necessary, but I do it
  pinMode(A0, INPUT);
  pinMode(A1, INPUT);
  pinMode(A2, INPUT);

void loop()
  //Read the x, y, and z values from
  //the analog input pins
  xAxisValADC = analogRead(xAxisPin);
  yAxisValADC = analogRead(yAxisPin);
  zAxisValADC = analogRead(zAxisPin);
  //Convert the ADC values to millivolts
  xAxisValmV = xAxisValADC * mVPerADC;
  yAxisValmV = yAxisValADC * mVPerADC;
  zAxisValmV = zAxisValADC * mVPerADC;
  //This could be prettier. What's happening is the mid-point
  //voltage value is subtracted from the voltage recorded
  //from the analog input, and then that value is divided
  //by how many millivolts per g the accelerometer is
  //ouputing. This results in the value being printed
  //in units of g.
  Serial.print((xAxisValmV - supplyMidPointmV) / mVperg);
  Serial.print((yAxisValmV - supplyMidPointmV) / mVperg);
  Serial.print((zAxisValmV - supplyMidPointmV) / mVperg);

It’s a bit verbose, but I wanted to be super clear about what is going on.

I dumped 20 seconds of gathered data into a .txt file and used Excel to make this pretty graph.


For the first few seconds it’s just sitting on the table, so the z-axis is at 1g, and the x and y-axis are at about 0 (these aren’t calibrated readings, but it’s good enough). You can see when I pick it up and shake it around a bit, then put it back on the table. Neat.

The motivation for writing this post is because it took me about an hour to reconcile the info in the data sheet with the values I was reading on the analog inputs. It was hard to find anything useful online that stated plainly what you need to do on the Arduino end. Hopefully this helps someone out.

Post a comment or message me on Twitter (@cheydrick) if you have any questions.

Posted in Uncategorized | Tagged | 24 Comments

Brief Example of Calling .dll Functions in C#

I don’t like C#, but the free version of Visual Studio only lets you use the interface builder in C#/.net programs, so here we are. My goal was to cheat and write the interesting parts of the program in C/C++, compiling to a .dll, and calling it from C#.

This has turned out to be an ordeal.

I have a great handle on calling functions in a .dll from Python. The CTypes module is amazing, and incredibly well documented. C# has a module (service?) in the System.Runtime.InteropServices namespace and the Platform Invoke service for “consuming un-managed code”, but it has been a real pain getting it to work.

I’ll admit that 80% of the problem is that I’m still fairly new to C#, but there is no shortage of information online for vanilla C# programming. Interfacing to a .dll seems to be uncommon enough that it’s hard to find exactly what I’m looking for when I run into a use-case that hasn’t been discussed much.

Here’s what I’m getting at. Let’s say I have a function in my .dll as such:

	return 42;

Here’s what the function in C# would look like for interfacing with GetInteger() in the .dll (which I put in a class called InteropStructTestDLLWrapper):

public extern static int GetInteger();

And here’s how to call that in C#:

int int_from_dll = 0;
int_from_dll = InteropStructTestDLLWrapper.GetInteger();

This behaves exactly as you would expect – it returns the number 42. Things start getting weird when pointers are involved.

Function in .dll:

INTEROPSTRUCTTEST_API void PassIntegerPointer(int *i)
	*i = 27;

Function for calling the .dll function in C#:

[DllImport(InteropStructTest.dll, CallingConvention = CallingConvention.Cdecl)]
public extern static void PassIntegerPointer([In, Out]ref int i);

Calling the function in C#:

InteropStructTestDLLWrapper.PassIntegerPointer(ref int_from_dll);

Now you have to deal with [In, Out] and ref, and CallingConvention.Cdecl. Much of this was guess-and-check to get working using information I gleaned from dozens of StackOverflow posts and other blogs. Things start getting extra weird when you want to pass a pointer to a struct or array of structs.

I decided it was best to just start making a sample .dll and .cs program that demonstrated a clear use-case for passing various data types to and from a .dll. Something that I could reference and add to as I learn. So far it has returning integers, passing a pointer to integer to be modified, passing a pointer to a struct to be modified, and passing an array of structs to be modified (which was super hard to find anything online about).


Right now it has examples of all the things I’ll have to do in small side-project I’m working on. I’ll flesh it out as needed.

Hopefully I’ll save someone some time. I’m embarrassed at how much time I burned getting this far!

Posted in Hobbies, Programming, Technology | Tagged , | Leave a comment

C# Struct Sizes

I’ve been banging my head against trying to get C# to talk to a .dll written in straight C for the past few days. I finally got a grip on passing basic data types, and pointers to basic data types, to/from my .dll, but I started getting garbage when passing pointers to structs and arrays of structs.

I wrote a master sanity check C# program and C .dll to demonstrate the correct methods for getting structs, pointers to structs, and arrays of structs into the .dll functions, and as soon as I clean it up and comment it I’ll post it.

One of my favorite sanity check tools in C is the sizeof() function, which tells you the size in bytes of a data type or struct. Well, C# has a sizeof() function, too, but it requires some verbosity to get the size of a struct out of it. It must have something to do with C# structs being memory managed. There are a few StackOverflow posts and other blog posts about how to do this, but they’re all overly complex or beyond the scope of simply getting the struct size, so here’s my take on it.

Here’s a small program that demonstrates how to get the size of C# structures.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Runtime.InteropServices;

namespace CSStructSize
    class Program
        public struct SimpleStruct
            public int firstInt;
            public int secondInt;

        public struct ComplexStruct
            public char firstChar;
            public char secondChar;
            public long firstLong;
            public short firstShort;
            public char thirdChar;
            public char fourthChar;
        static void Main(string[] args)
            Console.WriteLine("\nSize of C# char is: {0}", sizeof(char));
            Console.WriteLine("Size of C# short is: {0}", sizeof(short));
            Console.WriteLine("Size of C# int is: {0}", sizeof(int));
            Console.WriteLine("Size of C# long is: {0}", sizeof(long));
            Console.WriteLine("Size of SimpleStruct: {0}", Marshal.SizeOf(typeof(SimpleStruct)));
            Console.WriteLine("Size of ComplexStruct: {0}", Marshal.SizeOf(typeof(ComplexStruct)));

The output is:

Size of C# char is: 2
Size of C# short is: 2
Size of C# int is: 4
Size of C# long is: 8
Size of SimpleStruct: 8
Size of ComplexStruct: 24

Posted in Uncategorized | Leave a comment

File Open Dialog Box in Python

I’m putting the finishing touches on a side project at work that requires opening a file as an argument at the command line, or through a file open dialog box. Here’s a snippet that demonstrates how I implemented it.


import sys
import os

def choose_file():
        import Tkinter, tkFileDialog
    except ImportError:
        print "Tkinter not installed."
    #Suppress the Tkinter root window
    tkroot = Tkinter.Tk()
    return str(tkFileDialog.askopenfilename())
if __name__ == "__main__":
    #If no file is passed at the command line, or if the file
    #passed can not be found, open a file chooser window.
    if len(sys.argv) < 2:
        filename = os.path.abspath(choose_file())
        filename = os.path.abspath(sys.argv[1])
        if not os.path.isfile(filename):
            filename = choose_file()
    #Now you have a valid file in filename

It’s pretty straightforward. If no file is passed at the command line, or if the file passed at the command line isn’t a legitimate file, a file chooser dialog box pops up. If Tkinter isn’t installed, it bails out with an error message.

The bit about suppressing the Tk root window prevents a small box from appearing alongside the file chooser dialog box.


Posted in Programming | Leave a comment

Valve Trouble

It rained real hard Tuesday night. Wednesday morning at about 5am I’m stumbling in my kitchen trying to make coffee and I hear a hissing noise outside.

“Hah”, I says to myself, “my neighbors are watering their lawn on an off day. They’ll get fined by the city if caught”.

The wife goes out to walk the dog, and when she returns she asks me why I’m watering the back yard.

Ruh roh.

One of the sprinkler zones in my back yard was running, and could have been running since we went to bed at 9:30pm the night before. They weren’t running prior to that when I let the dog out before retiring to bed, so it must have spontaneously started itself at some point in the night, meaning it could have been running for up to seven and a half hours!

The control box in the garage didn’t indicate that it was active. I did the first obvious step: I turned it off and on again. No luck. Next I cycled the system through all the zones hoping it would kick it into normal operation. No luck.

I hadn’t even had my coffee yet, so I wasn’t firing on all cylinders. I grabbed a flashlight and started popping open all the valve holes in my yard hoping to at least find the one that was stuck, not knowing what in the world I’d do if I even found it. I could only find four (of the six), and they were all in my front yard. Fortunately I came across one larger covered hole in my front yard and noticed it said “Irrigation” on the cover. Inside there was a master faucet, and closing it finally shut the water off.

This post is a bit of self-flagellation. I’ve been in this house for two years now, and there are LOTS of things (important things!) that I’m still totally unfamiliar with. I should have known about this master faucet. I knew the box was there, but I had assumed it was some electrical thing.

After a bit of Googling how sprinkler systems work, I came to the tentative conclusion that the solenoid that controls the valve for that sprinkler zone must have shorted out and got stuck on – probably due to the rain. Thinking on it more (because solenoids are very simple) this could mean that one of the lines going to the solenoid is always hot, and the control box activates that solenoid by closing the path to ground. Rainwater buildup could have provided a conductive path to ground. There’s probably a good reason that the control box provides the ground path, and not the hot path. Or I could be totally wrong how it works.

I called Collin County Sprinkler that Wednesday morning, and they had someone out this morning (Thursday). It took them 20 minutes to find the valve hole (using a fancy wire tracing tool) and fix it. They showed me a busted seal that let rainwater into the valve and up into the solenoid, and confirmed my “rainwater allowed path to ground” hypothesis (or they were just humoring me because I was asking a lot of annoying questions).

Zone Five Valve

Fortunately my back yard slopes towards the alley so the excessive water didn’t get into the garage, and it’s hot outside so it evaporated very quickly. I don’t feel dumb not knowing where that valve was because it was very well hidden under the grass. There is one last valve I need to track down (which I forgot to ask about before they left), but I think I can find it on my own.

This incident is a big wake-up call for me. There are too many critical things in this house that I take on faith that they’re functional, and will stay functional – AC, plumbing, electricity, sprinklers, garage door, appliances, etc. I need to get a handle on those things. I don’t need to know every detail, but if something goes horribly wrong I need a plan.

Posted in Uncategorized | Leave a comment

Summer Plans

My involvement with Mojo Frankenstein is taking up all my hobby energy lately. We’ve been at it for about a year now and have gigs booked on over half the weekends through the summer (and growing).

I’ve been doing just enough programming for some office skunkworks projects that I don’t feel the need to do it at home to stay sane and keep the skills up. That’s good, I think.

That being said, here are some projects I’d like to tackle this summer.

  • Raspberry Pi security camera: I’m borrowing an RPi and I’d like to get some kind of minimal framework for a wireless network security camera happening. If OpenCV works on an RPi then I’m 80% there – the rest is figuring out where to dump images periodically (FTP?). There’s a great example of what I’m trying to accomplish here.
  • Re-write the Arduino Serial Communications tutorials: They still get ~40-60 page views daily, and I’ve learned so much in the past few years that I could easily make them better. I started writing a small e-book on the subject (using LeanPub) but couldn’t make enough material to justify going through the hassle. I would have had to include 5-10 example projects to demonstrate the material and I’m just not that creative.
  • Write about my ray-caster experiment: I’m bad at math, so I tackled a math-heavy(ish) project. I got results (rays were cast, walls were detected) but I was only able to figure out the naive way of doing it. There is a fancy way to do the ray casting using something called DDA, and I want to wait until I figure it out before writing it up. Every time I think I’ve worked it out with pencil and paper, I run into a massive wall (pun intended). It might be better to instead write about the process of learning this algorithm while I’m trying to learn it. That’s worked wonders for me before.
  • Write about problems I’ve having with Python package/module organization: I’ve been writing a semi-complicated Python package for work stuff. In an effort to be good I’ve tried to not just make it one monolithic .py file and split up the major classes into their own Python modules. For the life of me I can’t figure out any rhyme or reason to how the packages refer to each other, and what role __init__.py has in it. Again, I want to be good and not just have “from foo import *” in every module since it’s considered bad form. I don’t want to put work stuff on this page, so I’d have to write a contrived example that demonstrates my point (and hope that someone on StackOverflow or /r/python can help me out). I’ve found legit issues with the documentation before, and I’m hoping that this is simply a matter of documentation being incomplete as opposed to me being dense.

I think that’s a pretty ambitious set of goals.

Posted in Hobbies, Programming, Technology | Leave a comment

Removing zeros from a Python tuple

I’ve been working with Python’s ctypes module to shuttle data back and forth with a Windows .dll. One of the arrays the .dll fills is pre-allocated, but not necessarily all used. So I’ll wind up with a tuple like this:


(42, 33, 89, 0, 0, 0, 0, 0, 0)

It’s harmless to have the trailing 0’s, but for the sake of tidiness I want to remove them. Python tuples are immutable, so there aren’t any methods for just chopping them out. What you can do is fill a new tuple with just the non-0 values. Here’s a fancy way of doing this using list comprehensions.

>>>some_data_fixed = tuple([x for x in some_data if x])


(42, 33, 89)

Which basically says to fill a list with x for every element x in some_data if it evaluates as true (meaning non-0), and then cast it to a tuple.

This example is in the official documentation for list comprehensions.

Posted in Programming | Leave a comment