by on Nov.17, 2015, under Uncategorized

My treadmill is horribly inaccurate.  The console’s controls don’t actually sense the speed and keep it to the setting, but it uses a calculation that doesn’t work too well.

I didn’t realize how bad it was until I painted a white blog on my belt, measured the belt to within a couple of mm and set an Arduino to count the number of belt cycles.  I figured I could measure a mile plus or minus a meter or so.  I quickly discovered that the speed was off up to 15 seconds per mile depending on the speed.  No wonder I had to add 1% elevation for compenstation to make it more like running on the road.  It was quite a bit slower!

For a couple of years I been using this system and just adjusting the speed to about where I want it.  This is of course tedious as the treadmill will change speed even though I haven’t touched the controls.

I finally saved up enough money to get a digital oscilloscope and yesterday my shiny new Siglent SDS 1052DL 50Mhz scope arrived.  What fun!  I spent some time figuring how it worked and then thought of my treadmill.

Some time ago I had opened up my treadmill and discovered a technicians sheet that had what all the pins on the treadmill controller did and some specification information.  Using this information I tried to control the treadmill with an Arduino but could never get it work.  I was guessing that the PWM of the Arduino and the treadmill controller didn’t match.  I eventually gave up for the time being.

With my new oscilloscope I could now answer some questions.  First I wanted to see how accurately my Arduino Uno could produce a PWM through bit banging in other words manually switching the digital pins from off to on.

I eventually came up with this sketch:

```bool up = false;
bool up2 = false;
long next = 0;
long next2 = 0;
void setup() {
// put your setup code here, to run once:
pinMode(3,OUTPUT);
pinMode(4,OUTPUT);
next2 = next = micros();
Serial.begin(115200);
}

const int cycle = 2245;
int duty = 1660;
int duty2 = 1433;
void loop()
{
digitalWrite(3,HIGH);
digitalWrite(4,HIGH);
long start = micros();
long endTime = start + cycle;
bool high = true;
long dutyEnd = start + duty;
bool high2 = true;
long duty2End = start + duty2;
while(high || high2)
{
long now = micros();
if ( high && now > dutyEnd )
{
digitalWrite(3,LOW);
high = false;
}

if ( high2 && now > duty2End )
{
digitalWrite(4,LOW);
high2 = false;
}
}

while( micros() < endTime )
{
if ( Serial.available())
{
switch(c)
{
case '1': duty = 800; break;
case '2': duty = 1000; break;
case '3': duty = 1200; break;
case '4': duty = 1400; break;
case '5': duty = 1600; break;
case '6': duty2 = 800; break;
case '7': duty2 = 1000; break;
case '8': duty2 = 1200; break;
case '9': duty2 = 1400; break;
case '0': duty2 = 1600; break;
}
}
}
}
```

blah

This would produce PWM on two different channels at 440Hz with increadible accuracy.  I figured about 5?s accuracy.  This was okay, except squeezing in other tasks would end up being very difficult if not impossible.  Adding other tasks made the timing difficult.

I wondered if there was a way to use interrupts and the timers on the board.  I did some searching and discovered the library TimerOne.  This allowed for some interesting features.  It had methods to produce PWM on a pin, but it also had a method to hook up a method to be called on a schedule.  That could be useful in the future for sure.

Anyway I came up with the following sketch to produce PWM within a given specifications.  The great thing was that the main loop was now wide open without having to deal with producing the PWM.

```#include "TimerOne.h"

TimerOne timer;

void setup() {
timer.initialize(50000);
timer.pwm(9,0);

Serial.begin(115200);
}

void loop() {

if ( Serial.available())
{
int start = micros();
int value = Serial.parseInt();
timer.pwm(9,value);
int fin = micros();
Serial.println(fin-start);
}
}

```

Now with a sketch that could produce a good PWM signal on a pin it was time to attach my treadmill.  I pulled the cover off to get access to the controller board.  I hooked up my oscilloscope to the appropriate pins and started the treadmill up.  Here’s what I captured:

I was surprised at a couple of things.  First that the peak was only about 1.5V instead of the 5V I had assumed.   I was next surprised by how noisy the signal was.  There were some pretty big spikes that made it difficult to get a decent trigger on the square wave.  With a little counting I discovered that the PWM signal was 50ms long meaning a 20Hz rate.  This is much slower than the default Arduio PWM generation.  No wonder my last attempt didn’t work.

I made the adjustments to the sketch to match the measured parameters . I added simple voltage divider comprised of a 47? resistor and two 10? resistors to lower the voltage and hooked up the board.  It my joy it worked!  I was finally able to control the treadmill.

I discovered that much of the annoying behavior was part of the console not the actual controller board itself.  For instance without the console I was able to change the speed of the treadmill much faster.  Instead of 10-20 seconds to get it to full speed it was more like 2 seconds.  Further I seemed to be able to make it go much faster than the set 12 mph, perhaps as fast as 15mph, but I’m not sure as I didn’t have my measuring application going.

One thing I have to be careful of though is the safety magnet didn’t work.  I could pull that off and the treadmill would continue to go.  That is something that the arduino controller will have to handle.

So the next steps are as follows:

1. Add code and hardware to handle the safety cord signal.
2. Figure out how to read the built in tachometer in the treadmill via an interrupt.
3. Implement a PID controller to provide accurate speed control.
4. Integrate with old sensor board
5. Build an interface

## Laser Cave Scanner

by on Jul.01, 2014, under Uncategorized

This project is a device that can be used to scan a cave to get the basic shape.

Version 1. Details

1. A stand will hold the phone/camera, laser, and stepper motor.
2. The device will be mountable on a standard tripod.
3. A line laser will be used to determine the distance of a column of rock from the camera.
4. A stepper motor will allow the device to take a full 360 degree scan.
5. An Arduino Uno will control the laser and stepper motor
6. A Lumina 920 windows phone will take the images and process them into 3d data.
7. A bluetooth serial module will provide the linkage between the phone and the arduino

The first thing to do is build the stand to hold the electronics.

Since this is a prototype the parts aren’t to particular.Parts:

1. 3d printed laser holder
2. A red line-laser module (3v)
3. 2.kK ohm variable resistor
4. Aluminum bar ~1.5″ x 1/8″ x 24″
5. 3d printed phone holder

Comments Off on Laser Cave Scanner more...

## Battery or Grid selector

by on Jun.08, 2013, under arduino, solar

### Stage 0

I finally completed a little project to control whether to use my solar panels to charge my battery or to divert my power to the Grid.  My solar setup contained several parts before this project was under taken.

1. 170W combined solar panels.  There is a 140W and a 30W unit tied together in parallel.
2. SunSaver-10 Battery charger.  This takes the solar power and charged a 12v flooded battery.
3. 250W Grid Tie Power inverter.  This takes the power from the panels converts it to 120v and inserts into the house’s grid.
4. Kill O Watt amp meter.  I use this to determine how much power I’m pushing into grid.
5. 12v 14AH Lead Acid Battery.  It was a deep cycle battery and seemed in good condition when I got it.

This system worked pretty well for a while.  I discovered it had a problem.  I couldn’t charge the battery and have it connected to the grid tie inverter at the same time.  I quickly discovered that my SunSaver-10 Battery Charger would allow electricity to run from the battery to the inverter though the inverter.  This meant that all of the solar power went to the inverter, and all of the power stored in the battery went to the inverter too.  My battery was quite dead when I realized this.  So I disconnected the inverter and let the battery charge again.

My next solution was to just let the power go into grid tie, and occasionally switch it to the battery to keep the battery charged.  Well I gave myself too much credit in being able to remember.  So I just let the battery sit until it discharged itself and eventually destroyed itself.  So I was out a battery.  Luckily it wasn’t an expensive one.

I realized that I need to get an automatic way to switch between charging the battery and sending power to the grid.

### Stage 1

I jumped on to Amazon.com and decided on getting a couple of new components.  I needed something to switch from one power sync to another so I found an electronically controlled relay.  I settled on a SainSmart 2-Channel 5V Relay Module.  It was inexpensive and I could easily control it with an Arduino microcontroller.  I also needed a new battery as the old one only registered 6v and wouldn’t even charge with my trusty car battery charger.  This battery was an upgrade to a 12v 22AH sealed lead acid battery.  This also wasn’t expensive but it was new and in a nice package that I didn’t have to worry about adding water or spilling dangerous chemicals.

When the parts arrived I wanted to get a minimal system up as soon as possible.  But couldn’t find time for a while.  Finally I decided I’d better make time or I’d loose another battery.  So I started that night after the family was in bed.

I started fiddling with the relay controller.  Wow this was easy to use!  Just set the output pin to LOW to turn on the relay and HIGH to shut it off.  I configured the relay so that when the relay was on it would power the grid and when it was off it would power the battery.  That way if the power goes out electricity is put into the battery passively.  This is a safety measure so that people working on a power outage won’t get electrocuted from my solar panels.

I worked out the following code to control the relay.  My idea was to put electricity into the grid for 5 minutes and then into the battery for 30 seconds to keep it charged, without wasting too much electricity.  Not the best setup, but easy enough.

I ended up with the following code:

```void setup() {
// initialize the digital pin as an output.
pinMode(relay1, OUTPUT);
pinMode(relay2, OUTPUT);

digitalWrite(relay1, HIGH);
digitalWrite(relay2, HIGH);
}

void loop() {
digitalWrite(relay1, HIGH);
delay(30 *1000);
digitalWrite(relay1, LOW);
delay(300 * 1000);
}```

I got it all mostly working that night.  It though it wouldn’t switch from the grid back to the battery.  I just couldn’t figure out why, but midnight was coming up and I still had to get up in the morning.

A little while latter I came back to the problem.  Again I didn’t want my new battery ruined.  So after testing I discovered it was getting caught on the last line of the code: delay(300 * 1000);  Which was suppose to delay for 30 seconds.  After a lot of googling around I found the answer, and gave myself a face palm.  The int type in Arduino was a 16 bit value.  Which means that 300 * 1000 didn’t fit in the range of ~32,000 to -32,000.  It must have entered some negative number which caused the delay to never fire.  Arg!  Little things like that just eat up valuable time.  So the one line change was to: delay(300L * 1000L) to use a long or 32bit integer instead.  This immediately fixed the problem.

After several days of letting it run, I tested my batter and was very pleased to see it topped off at 13.15v or so.  This was good enough for the moment, but it bothered me that 10% of the electricity was potentially wasted when the batter was completely full, and if I used the battery and depleted it it would take a very long time to charge.

Stage 2

A couple of weeks have passed with work being so busy that I haven’t wanted to program or create anything so I didn’t.  But it was still niggling at me to work on my battery charge controller again.

The last couple of days I finally got to it. I wanted the path of the electricity to be dependent on the battery condition.  If the batter is in good condition then just a quick top of  charging of a few seconds is good.  If the battery is low then I want the electricity to charge the battery until its full.  And if the battery is dead then to just put all the electricity to the grid.

The Arduino has an analog to digital converter that I can use to measure the voltage of the battery, but it only measures between 0v and 5v.  This won’t work with a 12v batter that can have voltages as high as 14.2 during  charging.  The first item of business was to create a voltage divider that I can use to check the voltage of the battery.  I decided to build a divider that divided by 3.  This should keep the voltage below the maximum 5v of the Arduino.  I also chose resistors with large resistance so as to keep the current low so that I don’t drain the battery or fry the Arudino.

I picked the resistor values of R1 = 2M? and R2 = 1M?.  This gave me the desired output of 1/3 the input voltage.  I did some soldering and got it all together

Perhaps it’s a bit messy.  I could have covered the the solder joints but didn’t feel like it.  I ran the wire across the room to the Arudino.  And hooked it up.  Here’s what it looks like.

I got my signal pretty quickly I was surprised how noisy the signal seemed to be.  The output voltage varried about .3v from reading to reading.  The next step was to figure out the logic.  That was a bit trickier than I expected.  The idea was that if the battery was lower than 13v then to give it 5 minute charge blasts, otherwise just occasional top off spurts, the rest of the time I wanted the electricity to go to the grid.    I finally came up with a bit of code that worked, though it took a while, and the results are a bit messy.  I came up with the following:

```int relay1 = 8;
int relay2 = 9;
double R1 = 1986000;
double R2 = 993000;
double factor = (R1 + R2)/R2;

/* States */
const int ToGrid = 0;
const int ToBattery = 1;
const int TestBattery = 2;

/* timing information in seconds */
const int GridTime = 600;
const int BatteryTopOffTime = 7;
const int BatteryChargeTime = 300;
const int TestTime = 30;

/* runtime state variables */
int state = ToGrid;
int fromGrid = 0;
int loop_count = 0;

void setup() {
// initialize the digital pin as an output.
pinMode(relay1, OUTPUT);
pinMode(relay2, OUTPUT);

// setup serial port
Serial.begin(9600);

// put relays into know state
digitalWrite(relay1, LOW);
digitalWrite(relay2, HIGH);

// initialize the state machine
state = TestBattery;
loop_count = TestTime;
}

void loop() {

// read the voltage of the battery
double vout = reading * 0.00478;
double vin = vout * factor;
Serial.print("state: ");
Serial.print(state);
Serial.print(" cnt: ");
Serial.print(loop_count);
Serial.print(" v: ");
Serial.println(vin, 2);

// handle state transitions and relay logic
switch( state )
{
case ToGrid:
if (loop_count <= 0)
{
state = TestBattery;
loop_count = TestTime;
fromGrid = 1;
Serial.println("TestBattery");
}
break;
case ToBattery:
if (loop_count <= 0 )
{
digitalWrite(relay1, LOW);
loop_count = TestTime;
state = TestBattery;
fromGrid = 0;
Serial.println("TestBattery");
}
break;
case TestBattery:
// DO WE HAVE A GOOD BATTERY?
if (loop_count <= 0 )
{
if ( vin > 10.0 )
{
Serial.println("Have a battery.");
// change states
state = ToBattery;
if (vin < 13.0)
{
digitalWrite(relay1, HIGH);
loop_count = BatteryChargeTime; // let it charge fosr 5 minutes
Serial.print( "ToBattery ");
Serial.println( loop_count );
}
else if ( fromGrid )
{
digitalWrite(relay1, HIGH);
loop_count = BatteryTopOffTime; // just enough to refresh the battery
Serial.print( "ToBattery ");
Serial.println( loop_count );
}
else
{
state = ToGrid;
Serial.println("ToGrid");
loop_count = GridTime; // let it feed the grid for 10 minutes
}
}
else
{
state = ToGrid;
Serial.println("ToGrid");
loop_count = GridTime; // let it feed the grid for 10 minutes
}
}
break;
}

loop_count--;
delay(1000);
}```

The final touch was to add a small capacitor to the voltage input. I realized that it did have a 10 foot wire and all of the other electronics hooked to the battery. I added a 10pf cap. It did wonders for the signal and really chopped out the noise. Now it’s finished

Comments Off on Battery or Grid selector more...

## WCF Resolving error ‘The caller was not authenticated by the service.’

by on Sep.17, 2009, under .NET, c#, coding, WCF

I ran across an easy way to get wsHttpBinding to work on a remote machine.  This involves just a little bit of code on the client side to complete the authentication.

```                VPortalDataServiceClient client = new VPortalDataServiceClient();

The UserName is the windows account user name that is hosting the service. This user may just need to be one on the domain that the machine can see — not exactly sure though.  And the Password is the password of that user.

134 Comments :, , , more...

## c# Getting a nullable attribute to serialize to xml

by on Jul.23, 2009, under .NET, c#, c# coding GUI, coding, linq

It isn’t straight forward to get a nullable field to serialize. Technically it isn’t supported. But I just discovered a way today. You see null strings are supported. The idea is to ignore the real nullable property while substituting the string version as follows:

```    [XmlRoot("Comment")]
public class Comment
{
[XmlIgnore]
public DateTime? CommentTime { get; set; }

[XmlAttribute("CommentTime")]
public string CommentTimeStr
{
get
{
return (CommentTime.HasValue) ? CommentTime.Value.ToString() : null;
}

set
{
if (string.IsNullOrEmpty(value))
CommentTime = null;
else
CommentTime = DateTime.Parse(value);
}
}
}
```

Now it can be serialized.

## c# finding those blasted predefined IEqualityComparer classes!

by on Apr.14, 2009, under .NET, c#, coding

Why there isn’t any reference in the IEqualityComparer documentation to pre-implmented classes that override the function I don’t know.

But here’s one for string comparisons:

```StringComparer
```

This static class contains many different predefined IEqualityComparer instances to be used in functions like “Contains”. Enjoy.

## Gay Marriage — The farce.

by on Apr.14, 2009, under Uncategorized

Here we go again.  I suppose my beliefs will be mocked and I’ll be called a bigot, but public discussion needs to be open and full.  Not just one side.  So I’ll share my beliefs.

Marriage between a man and a women, fulfill a useful role to our society.  They raise citizens.  Even at 50% divorce rate the marriage relationship is by far the most stable, and best environment to raise children to become productive members of a society.  It has been proved that a child is mostly likely to grow up well adjusted with both a Father and a Mother.  As such it is in the interest of our society to protect and foster marriage between a man and a women.

In the eyes of the society in general the purpose of marriage is NOT sexual fulfillment, and NOT expression of love, but a means of perpetuating a sustainable society with productive citizens.

So what good are homosexual marriages to the state?  There is none.  They cannot procreate.  They also cannot provide both a father and a mother through adoption.  They cannot reliably raise well adjusted individuals.

I hear the cries of we have a right!  It’s not fair!  I ask when did you have the right to do what was wrong?

Jesus would never condone such homosexual actions.  Why?  Because he loves us and wants us to be truly happy.  He has said no unclean thing can enter the kingdom of God.  He has defined homosexuality as an action that will defile an individual and disqualify him/her to enter the kingdom of God.  How can we be happy if we cannot enter God’s kingdom in the end?  You cannot.  Nor can you have peace in this life.

Again I’m sure I’ll be mocked as old fashioned and out of touch.  But true principles do not change regardless of whether you believe them or not.

One unchanging fact is that God lives.  I witness it, and am not ashamed to stand as a witness.   From my own experience I know God lives.

Go on ahead and call me a bigot.  Mock if you wish.   I stand for virtue, I stand for that which is right and good and beautiful.

by on Mar.17, 2009, under .NET, c#, c# coding GUI, coding, networking

Here is the simple way to get all of the IP addresses for you machine. This code filters out everything but IPv4 address, but to truly get everything just remove the if statement.

```string hostName = Dns.GetHostName();
bool hasIP = false;
for (int i = 0; i < addrs.Length; i++)
{
{
hasIP = true;
break;
}
}
```

## c# setting caret position for a richedit control

by on Jan.06, 2009, under .NET, c#, GUI

Here’s the code to set the position of the caret in a richedit control

```int position = 12;
richedit1.Select( position, 0 );
richedit1.ScrollToCaret(); // if you want the position to be shown
```

It’s that simple.

## c# logging linq to sql

by on Jan.01, 2009, under .NET, c#, linq, mmsql, sql

I’ve often been frustrated by the sql that linq produces.  Usually it’s really good, but occasionally it produced monstrosities.   The hard part is getting at the sql that’s produced by a function.  Hovering over the statement in the idea is a real pain so instead I created the following class that dumps the sql to a file

```public class DCLogger : IDisposable
{
private StringWriter writer;

public DCLogger(System.Data.Linq.DataContext dc)
{
writer = new StringWriter();
dc.Log = writer;
}

#region IDisposable Members

public void Dispose()
{
writer.Flush();
System.IO.File.WriteAllText( "c:\\temp\\sql.log", writer.ToString() );
}

#endregion
}
```

To use it just create it passing it you data context. The results are written to the file when it’s disposed.

```  using( DCLogger( dc ) )
{
// ... some linq statement that executes
}
```

### Looking for something?

Use the form below to search the site:

Still not finding what you're looking for? Drop a comment on a post or contact us so we can take care of it!