## Notes on Implementing a Timer

Iâ€™m currently working on a project at work that includes a timer that will turn relays on during certain time periods and off outside them. The timer wasnâ€™t nearly as easy as I thought it would be so I decided to prototype the code on the PC as itâ€™s a lot easier to debug than on a tiny little PIC18F. All of the code in this post will be in C# which I what I used to prototype with.

The weird thing about this timer is that the day is assumed change at 3am and not midnight. So a day starts at 3am and ends at 2:59am, this is apparently so that the relay can be on across midnight. This caused massive confusion and I struggled to implement it.

The idea is that the timer will store and work with an internal representation of time and then convert to hours/minutes only when displaying settings to the user and when getting the time from the RTC. This internal representation is a single integer number of minutes from midnight offset in such a way that times less than 03:00am are offset by a day. This means that 03:00am is 180 minutes as you would expect but 02:55 is actually 1615 minutes. Using this representation means that comparing time is really easy and that makes the whole timer and user interface much easier to implement. Below are some constants

```const int MinutesPerDay = 1440;
const int MinInternalTime = 180;
const int MaxInternalTime = 1619;```

Below is a function that converts hours and minutes to the internal representation. If the time is less than the minimum internal time then itâ€™ll add a whole day to the time.

```int TimeToInternal(int hrs, int min)
{
int time = hrs*60 + min;
if( time < MinInternalTime) {
time += MinutesPerDay;
}
return time;
}```

Next I needed a function to convert the internal representation to actual time, in hours and minutes. Here the time is returned as a tuple of two integers, in the C version I used two pointer parameters instead.

```Tuple<int, int> InternalToTime(int time)
{
if( time > MinutesPerDay ) {
time -= MinutesPerDay;
}
return new Tuple<int, int>(time/60, time%60);
}```

I have also implemented a similar timer elsewhere in the project, but it was much simpler and the day changed at midnight as you would expect. This is the code I used to implement the timer that turns on a feature during a time period, then turns off. This period can span across midnight. The time is really simple, just multiply hours by 100 then add the minutes so 11:32 is 1132.

```bool IsInPeriod(int time, Period period)
{
if( period.Start < period.Stop ) {
return (time >= period.Start) && (time <= period.Stop);
} else if ( period.Start > period.Stop ) {
return (time >= period.Start) || (time <= period.Stop);
} else {
return false;
}
}```

Here is the Period class as I implemented it, nothing special or interesting here

```public class Period {
public Period() {
}

public Period(int start, int stop) {
this.Start = start;
this.Stop = stop;
}

public static int HrsMinToInt(int hrs, int min) {
return hrs*100 + min;
}

public int Start { get; set; }
public int Stop { get; set; }
}```

Sorry if none of this make any sense, this post has mostly just been a brain dump so that if in the future I work on this again, or something similar I can remind myself of all this.

## C# Bit Manipulation

This post is a collection of C# method extensions that I have written recentlyÂ to help me do bit manipulations on unsigned integers. These methods allow you to set, clear, toggle, and write bits. Iâ€™ve also added a read method for testing bits.

```public static UInt32 SetBit(this UInt32 Value, byte bit)
{
if (bit >= 32) {
throw new ArgumentException("bit must be between 0 and 31");
}

Value |= (UInt32)(1U << bit);
return Value;
}

public static UInt32 ClearBit(this UInt32 Value, byte bit)
{
if (bit >= 32) {
throw new ArgumentException("bit must be between 0 and 31");
}

Value &= ~(UInt32)(1U << bit);
return Value;
}

public static UInt32 WriteBit(this UInt32 Value, byte bit, bool state)
{
if (bit >= 32) {
throw new ArgumentException("bit must be between 0 and 31");
}

if (state) {
Value |= (UInt32)(1U << bit);
} else {
Value &= ~(UInt32)(1U << bit);
}

return Value;
}

public static UInt32 ToggleBit(this UInt32 Value, byte bit)
{
if (bit >= 32) {
throw new ArgumentException("bit must be between 0 and 31");
}

if ((Value & (1 << bit)) == (1 << bit)) {
Value &= ~(UInt32)(1U << bit);
} else {
Value |= (UInt32)(1U << bit);
}

return Value;
}

public static bool ReadBit(this UInt32 Value, byte bit)
{
if (bit >= 32) {
throw new ArgumentException("bit must be between 0 and 31");
}

return ((Value & (1 << bit)) == (1 << bit));
}```

I also added wrappers so these methods are avaliable UInt16 and Byte types.

## Converting a String to a Double (with SI prefixes)

Engineers and scientists will often use SI prefixes to make writing down very large, and very small, numbers easier. Writing down 3 GV is much better than 3000000000 V :). Iâ€™m currently working on a couple of software projects, both at home and work, where Iâ€™d like the ability to enter numbers with SI prefixes for convenience.

First I decided to write down the different styles of input my code will have to support, below is the list of styles I came up with.

• +2.2, or -2.2 => I want to be able to specify the sign of a number explicitly
• .33333 => Iâ€™d like to omit the starting zero
• 2.2k => Have SI prefixes
• 2k2 => This style is commonly found in the electronics industry.

Now I know what I want the code to do I can start writing it. I created a dictionary containing the prefixe character and the associated multiplier. I am writing this code in C# by the way, and used LINQPad to try it all out. Once I had it working I put into the class library I was working on.

```private readonly Dictionary Prefixes = new Dictionary(){
{'P', 1e15},
{'T', 1e12},
{'G', 1e9},
{'M', 1e6},
{'k', 1e3},
{'h', 1e2},
{'d', 1e-1},
{'c', 1e-2},
{'m', 1e-3},
{'u', 1e-6},
{'n', 1e-9},
{'p', 1e-12},
{'f', 1e-15},
};```

Then I wrote a method that will take in the input string and convert it to a double. The first thing the method does is check to see if it is a plain number that Double.Parse() can take care of, it does this check using a regex. If the Regex matched then it simply calls the Double.Parse() method and returns the result.

If the regex fails then it check using two more regexes if the number looks like it contains SI prefixes. If it does then we find out what prefix is used then remove the prefix and convert the number.

I am not very good with regular expressions so there may be better ways of writing them than this. I have tested this code quite a bit with different types of input and it seems pretty solid. It will throw a FormatException if anything goes wrong.

```// These are the regexes used by the method. These are initialised in a constructor.
Regex plain_number_regex = new Regex(@"^[+-]?(?=[\.\d])\d*(\.\d+)?\$"); // For .2222, 0.222, 2.32
Regex si_number_a_regex = new Regex(@"^[+-]?[\d]+[PTGMkcmunpf]?[\d]*\$"); // for 2k, 2k2
Regex si_number_b_regex = new Regex(@"^[+-]?[\d]+(\.\d+)?[PTGMkcmunpf]?\$"); // For 1.2k

public double ParseInputStringSI(string input)
{
// Test to see if it is a plain number with no SI prefixes
if (plain_number_regex.IsMatch(input)) {
return Double.Parse(input);
}

// Test to see if it is a number with an SI prefix.
if(si_number_a_regex.IsMatch(input) || si_number_b_regex.IsMatch(input) ) {
// Find where in the string the prefix is and what
// kind of prefix it is.
var input_prefix = from p in Prefixes.Keys
where input.IndexOf(p) > 0
select input[input.IndexOf(p)];

// Make sure the above query worked. There should be
// no reason for it to fail because the Regex checks
// the prefix characters.
if (input_prefix.Count() == 0) {
throw new FormatException("Invalid Input");
}

// Get the multiplier for the prefix
var multiplier = Prefixes[input_prefix.First()];

// Ether replace the prefix with a decimal point or
// remove it entierly. Depends on the format of the
// input.
string inputp;
if( si_number_a_regex.IsMatch(input) ) {
inputp = Regex.Replace(input, @"[PTGMkhdcmunpf]", ".");
} else {
inputp = Regex.Replace(input, @"[PTGMkhdcmunpf]", "");
}

// Attempt the conversion, multiply it then return it.
var tmp = Double.Parse(inputp);
return tmp * multiplier;
} else {
throw new FormatException("Input String is Invalid");
}
}```

## Getting a List of the Available COM Ports in C#

Itâ€™s really nice to show the user a list of the COM ports they actually have on their machines. All too often I have seen software that makes you type in the COM port name. Even worse are the applications that force you to select from a list of COM ports, usually COM1 to COM5, without the option of typing in a different one!

Below is some really simple code that generates a list of the available COM ports and inserts the list into a drop-down selection control in a WinForms application.

```string[] ports = SerialPort.GetPortNames();
if (ports.Length > 0) {
Array.Sort(ports);
COMPort.Text = ports[0];
} else {
COMPort.Text = "Unable to Detect COM ports";
}```

## Formatting Numbers using SI Prefixes

Well itâ€™s time for another post. A couple of weeks ago I was working on an interface program for a rig at work. We were adding some extra features to a controller board and I thought while I was working on that I might as well make some changes to the interface program as well.  The feature I wanted to add to the program was to make it format some of the numbers that are displayed in the UI using SI prefixes and with units of measure.

So after a quick look on the web to see if I can find some example code on how to do this, I decided to have a go writing the code on my own without looking at other stuff too much. This is what I came up with, Itâ€™s a function written in C# that can be used to convert floating point numbers to formatted strings. So the number 0.102 will be printed as â€ś102mâ€ť, and it can append units to the end like this â€“ â€ś102mAâ€ť.

```public static string FormatStringEng(double input, string units, string format)
{
string prefix = "";
double value = 0.0;

if (input >= 1e+12 && input < 1e+15) {
prefix = "T"; value = (input / 1e+12);    // Tera (1e+12)
} else if (input >= 1e+9 && input < 1e+12) {
prefix = "G"; value = (input / 1e+9);     // Giga (1e+9
} else if (input >= 1e+6 && input < 1e+9) {
prefix = "M"; value = (input / 1e+6);     // Mega (1e+6)
} else if (input >= 1e+3 && input < 1e+6) {
prefix = "k"; value = (input / 1e+3);     // Kilo (1e+3)
} else if ((input >= 1) && (input < 1e+6)) {
prefix = ""; value = input;               // Unity
} else if (input >= 1e-3 && input < 1) {
prefix = "m"; value = (input * 1e+3);     // Milli (1e-3)
} else if (input >= 1e-6 && input < 1e-3) {
prefix = "ÎĽ"; value = (input * 1e+6);     // Micro (1e-6)
} else if (input >= 1e-9 && input < 1e-6) {
prefix = "n"; value = (input * 1e+9);     // Nano (1e-9)
} else if (input >= 1e-12 && input < 1e-9) {
prefix = "p"; value = (input * 1e+12);    // Pico (1e-12)
} else if (input >= 1e-15 && input < 1e-12) {
prefix = "f"; value = (input * 1e+15);    // Fempto (1e-15)
}

return value.ToString() + prefix + units;
}```

This code is working quite well so far. Havenâ€™t had any problems with itâ€¦ yet anyway. Thatâ€™s it for now, see ya!