Jul 01 2009

Seven-Segment Display for .NET

Seven-segment displayI’m usually not a big fan of custom controls except in the most extreme circumstances. From the point of view of usability, it should always make the most sense to use the controls that are shipped with the Operating System. Your user base is already familiar with the OS’s native controls, so creating custom controls would only add to the learning curve for your application. But I digress. Sometimes, there are certain controls that just beg to be written, whether they’re useful or not.

That’s why I decided to write this seven-segment LED control: not because it’s any more "useful" than a standard Label control, but because it looks freakin’ sweet. I also wrote the control to become more familiar with the internals of C# and .NET in general. And, if you like the control and are able to use it, or learn from it, so much the better.

Even if you haven’t heard the name "seven-segment display" before, you’ve probably seen quite a few in your lifetime. They appear on pretty much every piece of electronic equipment that needs to display numbers for any reason, like the timer on a microwave oven, the display on a CD player, or the time on your digital wristwatch.

They’re called seven-segment displays because they’re actually made up of seven "segments" — seven individual lights (LEDs or otherwise) that light up in different patterns that represent any of the ten digits (0 – 9).

downloadSo, what are you waiting for? Download the control, or download the test application which the screen shot is from.

Using the code

This custom control can be built into your application by simply including the "SevenSegment.cs" file in your project. Rebuild your project, and you’ll be able to select the SevenSegment control from your tool palette and drop it right onto your forms.

To replicate the look of a seven-segment display, I draw seven polygons that precisely match the physical layout of a real display. To model the polygons, I drew them out on graph paper, and recorded the coordinates of each point in each polygon. To draw the polygons on the control, I use the FillPolygon function, passing it the array of points that represent the polygon. Let’s examine the control’s Paint event to see exactly what’s going on:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
private void SevenSegment_Paint(object sender, PaintEventArgs e)
{
	//this will be the bit pattern that gets shown on the segments,
	//bits 0 through 6 corresponding to each segment.
	int useValue = customPattern;
 
	//create brushes that represent the lit and unlit states of the segments
	Brush brushLight = new SolidBrush(colorLight);
	Brush brushDark = new SolidBrush(colorDark);
 
	//Define transformation for our container...
	RectangleF srcRect = new RectangleF(0.0F, 0.0F, gridWidth, gridHeight);
	RectangleF destRect = new RectangleF(Padding.Left, Padding.Top, this.Width - Padding.Left - Padding.Right, this.Height - Padding.Top - Padding.Bottom);
 
	//Begin graphics container that remaps coordinates for our convenience
	GraphicsContainer containerState = e.Graphics.BeginContainer(destRect, srcRect, GraphicsUnit.Pixel);
 
	//apply a shear transformation based on our "italics" coefficient
	Matrix trans = new Matrix();
	trans.Shear(italicFactor, 0.0F);
	e.Graphics.Transform = trans;
 
	//apply antialiasing
	e.Graphics.SmoothingMode = SmoothingMode.AntiAlias;
	e.Graphics.PixelOffsetMode = PixelOffsetMode.Default;
 
	// Draw elements based on whether the corresponding bit is high!
	// "segPoints" is a 2D array of points that contains the segment coordinates to draw
	e.Graphics.FillPolygon((useValue & 0x1) == 0x1 ? brushLight : brushDark, segPoints[0]);
	e.Graphics.FillPolygon((useValue & 0x2) == 0x2 ? brushLight : brushDark, segPoints[1]);
	e.Graphics.FillPolygon((useValue & 0x4) == 0x4 ? brushLight : brushDark, segPoints[2]);
	e.Graphics.FillPolygon((useValue & 0x8) == 0x8 ? brushLight : brushDark, segPoints[3]);
	e.Graphics.FillPolygon((useValue & 0x10) == 0x10 ? brushLight : brushDark, segPoints[4]);
	e.Graphics.FillPolygon((useValue & 0x20) == 0x20 ? brushLight : brushDark, segPoints[5]);
	e.Graphics.FillPolygon((useValue & 0x40) == 0x40 ? brushLight : brushDark, segPoints[6]);
 
	//draw the decimal point, if it's enabled
	if (showDot)
		e.Graphics.FillEllipse(dotOn ? brushLight : brushDark, gridWidth - 1, gridHeight - elementWidth + 1, elementWidth, elementWidth);
 
	//finished with coordinate container
	e.Graphics.EndContainer(containerState);
}

You can set the value displayed in the control through two properties: Value and CustomPattern. The Value property is a string value that can be set to a single character such as "5" or "A". The character will be automatically translated into the seven-segment bit pattern that looks like the specified character.

If you want to display a custom pattern that may or may not look like any letter or number, you can use the CustomPattern property, and set it to any value from 0 to 127, which gives you full control over each segment, since bits 0 to 6 control the state of each of the corresponding segments.

The way it’s done in the code is as follows. I have an enumeration that encodes all the predefined values that represent digits and letters displayable on seven segments:

1
2
3
4
5
6
7
8
9
10
11
public enum ValuePattern
{
    None = 0x0, Zero = 0x77, One = 0x24, Two = 0x5D, Three = 0x6D,
    Four = 0x2E, Five = 0x6B, Six = 0x7B, Seven = 0x25,
    Eight = 0x7F, Nine = 0x6F, A = 0x3F, B = 0x7A, C = 0x53,
    D = 0x7C, E = 0x5B, F = 0x1B, G = 0x73, H = 0x3E,
    J = 0x74, L = 0x52, N = 0x38, O = 0x78, 
    P = 0x1F, Q = 0x2F, R = 0x18,
    T = 0x5A, U = 0x76, Y = 0x6E,
    Dash = 0x8, Equals = 0x48
}

Notice that each value is a bit map, with each bit corresponding to one of the seven segments. Now, in the setter of the Value property, I compare the given character against our known values, and use the corresponding enumeration as the currently displayed bit pattern:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
//is it a digit?
int tempValue = Convert.ToInt32(value);
switch (tempValue)
{
	case 0: customPattern = (int)ValuePattern.Zero; break;
	case 1: customPattern = (int)ValuePattern.One; break;
	...
}
...
//is it a letter?
string tempString = Convert.ToString(value);
switch (tempString.ToLower()[0])
{
	case 'a': customPattern = (int)ValuePattern.A; break;
	case 'b': customPattern = (int)ValuePattern.B; break;
	...
}

Either way, the bit pattern to be displayed in the control ends up in the customPattern variable, which is then used in the Paint event as shown above.

You can also "italicize" the display by manipulating the ItalicFactor property. This value is simply a shear factor that gets applied when drawing the control, as seen in the Paint event. An italic factor of -0.1 makes the display look just slightly slanted, and a whole lot more professional.

If you begin noticing that the segments are being drawn outside the boundary of the control (perhaps from too much italicizing), you can use the Padding property and increase the left/right/top/bottom padding until all of the shapes are within the control’s client rectangle.

The control has several other convenient properties for you to play with, such as the background color, the enabled and disabled color for the segments, and the thickness of the segments.

Seven-segment array

In addition to the seven-segment control itself, I’m throwing in another control which is an array of seven-segment displays. This allows you to display entire strings on an array of 7-seg displays. Check out the demo application, and dig around the source code to see how it’s used; it’s really simple.

To use the array control, include the "SevenSegmentArray.cs" file in your project and rebuild. You’ll then be able to select the SevenSegmentArray control from the tool palette.

This control has an ArrayCount property that specifies the number of 7-seg displays in the array, as well as a Value property that takes any string to be displayed on the array. Easy, right?

Other thoughts

I must say I had a lot of fun writing this control, and .NET helped put a lot of the fun into it by making it incredibly easy to draw your own shapes, transform coordinates, and introduce truly powerful properties.

Also, coming from somewhat of an electronics background, for me, seeing this control brings a certain nostalgia for simpler times. I hope you enjoy it.

Share and Enjoy:
  • Digg
  • del.icio.us
  • Google Bookmarks
  • Facebook
  • Mixx
  • Sphinn


Jun 29 2009

Star Photos at Machu Picchu

Category: Daily Events, Photos

Early in the morning on our way to Machu Picchu, I was able to take a few stunning sky photos. This was done by simply putting the camera on the ground, and setting the exposure to 30 seconds. Here are the photos, followed by copies of the photos that I’ve annotated with constellation names and lines.

Share and Enjoy:
  • Digg
  • del.icio.us
  • Google Bookmarks
  • Facebook
  • Mixx
  • Sphinn


Jun 28 2009

Inca Trail and Machu Picchu, Part 4

Category: Daily Events, Photos
Share and Enjoy:
  • Digg
  • del.icio.us
  • Google Bookmarks
  • Facebook
  • Mixx
  • Sphinn


Jun 28 2009

Inca Trail and Machu Picchu, Part 3

Category: Daily Events, Photos
Share and Enjoy:
  • Digg
  • del.icio.us
  • Google Bookmarks
  • Facebook
  • Mixx
  • Sphinn


Jun 28 2009

Inca Trail and Machu Picchu, Part 2

Category: Daily Events, Photos
Share and Enjoy:
  • Digg
  • del.icio.us
  • Google Bookmarks
  • Facebook
  • Mixx
  • Sphinn


Jun 28 2009

Inca Trail and Machu Picchu, Part 1

Category: Daily Events, Photos
Share and Enjoy:
  • Digg
  • del.icio.us
  • Google Bookmarks
  • Facebook
  • Mixx
  • Sphinn


May 06 2009

The open-mindedness of skeptics

Today I’d like to briefly discuss the issue of open-mindedness, since I grow more and more alarmed by the rate at which this issue comes up in debates between skeptics and “believers” in alternative medicine, religion, the paranormal, the supernatural, and all sorts of other products of human imagination.

At this point the astute reader might point out, “Aha, you’re already presupposing that these things are products of imagination, so your mind is already closed to other options!” This is not the case. I believe that these things are products of imagination because that’s what they appear to be, based on all available evidence, so they are very probably imaginary. Is it possible that they are real, and not imagined? Of course! Show me evidence that is convincing enough (that is, evidence that’s as grandiose as the claim itself), and you’ll make me a believer (that is, you’ll make me believe that your claim is very probably real)!

I have changed my mind regarding various claims plenty of times in the past, precisely for this reason: I was shown convincing evidence (or found it myself) that made me reverse my views on a particular subject.

A brief analogy. Okay, not so brief.

When I was younger, I used to believe that I exerted some sort of energy that made street lights turn off exactly as I would drive underneath them in my car (this is apparently a common illusion). This didn’t quite sit well in my mind: why me? Am I really that extraordinary? Why doesn’t every driver cause street lights to go out? Then I decided to research the facts: I found out how street lights work, and I read up on some of the workings of human psychology, namely selective memory. And before long, I understood that the light bulbs are on a duty cycle (they periodically turn on and off to prevent overheating), and that my mind was assigning special significance to the times when a street light happened to turn off directly above me!

Did I feel saddened by the notion that I was no longer extraordinary? Maybe for a brief moment, but the reality check was soon overtaken by a feeling of enlightenment. It felt good to understand the real reason behind a phenomenon that was poorly understood (by me, at the time). Instead of living with a superficial pseudo-understanding of how things work (where I am endowed with street light powers), I felt extraordinary because I gained a much more meaningful understanding of the real world.

So what does this have to do with an open mind? Well, consider this. Suppose I meet a person (let’s call her Alice) who absolutely insists that the street light phenomenon is actually genuine — that people do, in fact, emit an energy field that causes street lights to turn off above them.

When I present all the research I did regarding street lights and human psychology, Alice dismisses it as inconclusive and insufficient. When I say that there is a perfectly good natural explanation for the phenomenon, Alice claims that her explanation is better because it feels right to her. She gives me a list of testimonials from her friends who have also experienced the phenomenon, and says, “they can’t all be wrong, can they?” When I show her the mathematics that proves how statistically likely it is to see a street light turn off during any drive, she insists that the number of times that she’s seen it can’t be a coincidence.

When I ask her to show me peer-reviewed publications on the reality of this effect, she says that she doesn’t have access to them at the moment, but assures me that they exist. When I ask her if she would be willing to perform a blinded test of her abilities, she refuses, saying that the street lights turn off only when she doesn’t think about it or least expects it.

When I ask her to explain the physical processes that she thinks are behind the phenomenon, she begins talking about quantum mechanics, saying that all particles are entangled, that our intentions can change the course of quantum reality, and that we, as observers, can choose the outcome of wavefunction collapse.

When I try to correct her naive understanding of quantum mechanics, she says that science doesn’t have all the answers. When I tell her that I used to believe in the same explanation that she does, except I learned better, she proceeds to state that I am hopelessly closed-minded and, with a tone of pity, says that I will never be able to control street lights like she can, because I don’t believe in it enough.

Sound familiar?

While the above analogy is a bit of a straw man (or straw woman in this case), the vast majority of debates between skeptics and “believers” take on exactly the above format. The believer, frustrated by the skeptic’s unwillingness to accept her extraordinary claim without sufficient evidence, resorts to calling the skeptic closed-minded.

Let’s think about the definition of an open mind. I would consider an open-minded person to be someone who is able to objectively evaluate new evidence, and integrate it into his or her framework of theories regarding the world. “Objectively” evaluating evidence means evaluating it regardless of personal interests, emotional appeal, profit motive, or peer pressure.

It is abundantly clear that, in the above scenario, it’s Alice who is closed-minded, because she is either unable or unwilling to honestly evaluate the real reasons for the street light effect.

However, the question remains: Am I closed-minded for being unwilling to consider Alice’s theory that she has psycho-kinetic powers? Well, that’s a bit of a loaded question. First of all, Alice does not have a theory that explains the effect. Saying that the effect is caused by telekinetic powers is a bit like saying, “It’s magic” — it doesn’t constitute an explanation, because it doesn’t explain how the process actually works.

Alice would have to define what exactly her powers are, their range and intensity, and how these powers can be reconciled with currently known laws of physics. If she claims that current physics are insufficient to explain her powers, or that she has tapped into a “new” law of physics, she suddenly has an entire world of physicists to contend with, all of whom agree on well-established physical laws that preclude such powers.

The only thing that would pique the interest of the world’s physicists is a simple test — an experiment that shows, repeatably, that the laws of physics do not apply to Alice. Is that too much to ask? As long as such an experiment does not exist, we have no reason to believe that Alice has any powers except an overly active imagination.

Replace the street light effect with any other extraordinary claim (energy medicine, life-force, zero-point fields, astrology, dowsing, etc), and the conclusions turn out the same: if the claim is real, it would undermine one or more laws of physics. In any case, the evidence for such a claim would have to be at least as spectacular as the claim itself.

In short, I am open-minded to any new evidence, whether it supports my worldview or contradicts it. However, I have some sensible constraints on what passes as “evidence.” As the immortal saying goes, I have an open mind, but not so open that my brain falls out.

If you are making extraordinary claims that are not supported by our current theories about the world, all I ask is that you demonstrate something, anything, that supports your claims, and shows that whatever you’re demonstrating isn’t just in your mind.

Share and Enjoy:
  • Digg
  • del.icio.us
  • Google Bookmarks
  • Facebook
  • Mixx
  • Sphinn


Apr 21 2009

DiskDigger – Version 0.8.0

Today I released the latest version of the DiskDigger data recovery utility. Highlights from this version include:

  • Ability to actually undelete files (complete with file names) from the following file systems: FAT12, FAT16, FAT32, NTFS, and exFAT.
  • Split the program into two modes of operation: undelete and deep scan (lovingly dubbed “dig deep” and “dig deeper”).
  • Built in a better manifest file that automatically asks for admin privileges in Vista.

As far as I can tell, DiskDigger is the first utility (at least the first free one) that can undelete files from exFAT partitions.

So what are you waiting for? Download it and try it out!

Share and Enjoy:
  • Digg
  • del.icio.us
  • Google Bookmarks
  • Facebook
  • Mixx
  • Sphinn


Mar 12 2009

Reiki clinic at MetroHealth

Category: Daily Events

In local news, the Plain Dealer reported on the “Hands to Heart” Reiki clinic at MetroHealth hospital. The same reporter wrote about her own Reiki session a day earlier.

Finally! A clinic dedicated to administering placebo. Naturally, we have to give it an Eastern-sounding name, and plenty of positive testimonials, and it becomes a virtual gold mine! Of course, they assure us that the sessions at the clinic are free, but what about when their clients become hooked, and start wanting private sessions? And what about the peddling of CDs, books, and other merchandise along with the sessions?

While the article felt like it was trying to do its best to remain neutral, there was definitely a strong hint of implied acceptance of Reiki for what it claims to be. There were several points in the article that would threaten to mislead an unknowing consumer into thinking that Reiki is a plausible treatment.

From the article:

The hospital’s clinic offers unconventional therapy for those who have found conventional medicine only goes so far.

Only goes so far?! And how far, pray tell, does Reiki go? This would imply that Reiki somehow goes beyond “conventional” medicine. If this were true in any sense, then Reiki would become conventional medicine!

The article is a bit deceptive in a few other places. It says,

…[R]eiki has found acceptance among the hospital’s nurses as a complementary therapy. But the doctors are “a bit of a more challenging group to get,” she said, because there are no medical studies that prove [R]eiki’s effectiveness.

What it should really say is, “There are studies that tested Reiki’s effectiveness, and found no effect.“. Here’s one, for good measure.

The article also fails to mention that, if the principles behind Reiki are true, they would invalidate most of our laws of physics and our understanding of biology and physiology. So why haven’t any “Reiki masters” been invited to Stockholm for the Nobel ceremony?

I applaud the doctors for being “hard to get” with respect to this foolishness.

Share and Enjoy:
  • Digg
  • del.icio.us
  • Google Bookmarks
  • Facebook
  • Mixx
  • Sphinn


Feb 11 2009

(Extreme) Camping

Category: Daily Events, Photos
Share and Enjoy:
  • Digg
  • del.icio.us
  • Google Bookmarks
  • Facebook
  • Mixx
  • Sphinn


Next Page »