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
Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
constint MinutesPerDay = 1440;
constint MinInternalTime = 180;
constint MaxInternalTime = 1619;
const int MinutesPerDay = 1440;
const int MinInternalTime = 180;
const int MaxInternalTime = 1619;
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.
Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
intTimeToInternal(int hrs, int min)
{
int time = hrs*60 + min;
if( time < MinInternalTime){
time += MinutesPerDay;
}
return time;
}
int TimeToInternal(int hrs, int min)
{
int time = hrs*60 + min;
if( time < MinInternalTime) {
time += MinutesPerDay;
}
return 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.
Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
Tuple<int, int>InternalToTime(int time)
{
if( time > MinutesPerDay ){
time -= MinutesPerDay;
}
returnnew Tuple<int, int>(time/60, time%60);
}
Tuple<int, int> InternalToTime(int time)
{
if( time > MinutesPerDay ) {
time -= MinutesPerDay;
}
return new Tuple<int, int>(time/60, time%60);
}
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.
Here is the Period class as I implemented it, nothing special or interesting here
Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
publicclass Period {
publicPeriod(){
}
publicPeriod(int start, int stop){
this.Start = start;
this.Stop = stop;
}
publicstaticintHrsMinToInt(int hrs, int min){
return hrs*100 + min;
}
publicint Start {get; set; }
publicint Stop {get; set; }
}
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; }
}
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.
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.
Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
public static UInt32 SetBit(this UInt32 Value, byte bit)
{
if(bit >= 32){
throw newArgumentException("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 newArgumentException("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 newArgumentException("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 newArgumentException("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 newArgumentException("bit must be between 0 and 31");
}
return((Value &(1<< bit)) == (1<< bit));
}
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));
}
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.
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.
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.
Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
// These are the regexes used by the method. These are initialised in a constructor.
Regex plain_number_regex = newRegex(@"^[+-]?(?=[\.\d])\d*(\.\d+)?$"); // For .2222, 0.222, 2.32
Regex si_number_a_regex = newRegex(@"^[+-]?[\d]+[PTGMkcmunpf]?[\d]*$"); // for 2k, 2k2
Regex si_number_b_regex = newRegex(@"^[+-]?[\d]+(\.\d+)?[PTGMkcmunpf]?$"); // For 1.2k
publicdoubleParseInputStringSI(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.
// Attempt the conversion, multiply it then return it.
var tmp = Double.Parse(inputp);
return tmp * multiplier;
}else{
thrownewFormatException("Input String is Invalid");
}
}
// 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");
}
}
// 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");
}
}
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.
Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
string[] ports = SerialPort.GetPortNames();
if(ports.Length>0){
Array.Sort(ports);
COMPort.Items.AddRange(ports);
COMPort.Text = ports[0];
}else{
COMPort.Text = "Unable to Detect COM ports";
}
string[] ports = SerialPort.GetPortNames();
if (ports.Length > 0) {
Array.Sort(ports);
COMPort.Items.AddRange(ports);
COMPort.Text = ports[0];
} else {
COMPort.Text = "Unable to Detect COM ports";
}
string[] ports = SerialPort.GetPortNames();
if (ports.Length > 0) {
Array.Sort(ports);
COMPort.Items.AddRange(ports);
COMPort.Text = ports[0];
} else {
COMPort.Text = "Unable to Detect COM ports";
}
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โ.
We use cookies on our website to give you the most relevant experience by remembering your preferences and repeat visits. By clicking โAccept Allโ, you consent to the use of ALL the cookies. However, you may visit "Cookie Settings" to provide a controlled consent.
This website uses cookies to improve your experience while you navigate through the website. Out of these, the cookies that are categorized as necessary are stored on your browser as they are essential for the working of basic functionalities of the ...
Necessary cookies are absolutely essential for the website to function properly. These cookies ensure basic functionalities and security features of the website, anonymously.
Cookie
Duration
Description
cookielawinfo-checkbox-analytics
11 months
This cookie is set by GDPR Cookie Consent plugin. The cookie is used to store the user consent for the cookies in the category "Analytics".
cookielawinfo-checkbox-functional
11 months
The cookie is set by GDPR cookie consent to record the user consent for the cookies in the category "Functional".
cookielawinfo-checkbox-necessary
11 months
This cookie is set by GDPR Cookie Consent plugin. The cookies is used to store the user consent for the cookies in the category "Necessary".
cookielawinfo-checkbox-others
11 months
This cookie is set by GDPR Cookie Consent plugin. The cookie is used to store the user consent for the cookies in the category "Other.
cookielawinfo-checkbox-performance
11 months
This cookie is set by GDPR Cookie Consent plugin. The cookie is used to store the user consent for the cookies in the category "Performance".
viewed_cookie_policy
11 months
The cookie is set by the GDPR Cookie Consent plugin and is used to store whether or not user has consented to the use of cookies. It does not store any personal data.
Functional cookies help to perform certain functionalities like sharing the content of the website on social media platforms, collect feedbacks, and other third-party features.
Performance cookies are used to understand and analyze the key performance indexes of the website which helps in delivering a better user experience for the visitors.
Analytical cookies are used to understand how visitors interact with the website. These cookies help provide information on metrics the number of visitors, bounce rate, traffic source, etc.
Advertisement cookies are used to provide visitors with relevant ads and marketing campaigns. These cookies track visitors across websites and collect information to provide customized ads.