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!

iotrelay

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 | Leave a 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"

#ifdef STRUCTTEST_EXPORTS
#define STRUCTTEST_API __declspec(dllexport)
#else
#define STRUCTTEST_API __declspec(dllimport)
#endif

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;
			t++;
		}
	}
}

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.fillonestruct(byref(struct1))
    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
//pins
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()
{
  Serial.begin(9600);
  
  //I don't know if setting them to
  //input is necessary, but I do it
  //anyways.
  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("\t");
  Serial.print((yAxisValmV - supplyMidPointmV) / mVperg);
  Serial.print("\t");
  Serial.print((zAxisValmV - supplyMidPointmV) / mVperg);
  Serial.print("\t");   
  
  Serial.println();
  
  delay(100);
}

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.

accelchart

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 | Leave a comment

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:


INTEROPSTRUCTTEST_API int GetInteger()
{
	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):

[DllImport(&quot;InteropStructTest.dll&quot;)]
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).

https://github.com/cheydrick/CSInteropStructTest

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)));
            Console.ReadLine();
        }
    }
}

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():
    try:
        import Tkinter, tkFileDialog
    except ImportError:
        print "Tkinter not installed."
        exit()
    
    #Suppress the Tkinter root window
    tkroot = Tkinter.Tk()
    tkroot.withdraw()
    
    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())
    else:
        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