Fez Project 2–LED with button

Expanding on Project 1, we will add a button to light our LED.  In canonical circuits, you might just add a switch in-line with your LED.  That would work fine.  However, we have a fancy MCU we want to use and burn cycles on.  So lets turn on and off the LED with code instead of hacking wires.  This is great because we can leave the rest of our project the same and just add a button.  The button is normally “High” when un-pressed.  When pressed, the button switch to take the Signal wire to GND.  So the signal wire will go “LOW”.  NETMF offers an InterruptPort class so we can get an interrupt when a pin goes Low and/or High.  We will use the Button sold on the FEZ site.  But you could use any switch you have.  You could even use two wires and touch them together to bring pin to Ground (i.e. Low).

1) Hook button signal wire to Di7.  We could use any InterruptPort, but we just picked Di7.

2) Hook button’s GND wire to a free GND pin on the FEZ.

3) Update your led code like so: (Sorry for the code formatting. I can’t figure out an easy way in Live Writer and WordPress to get it right.)

static InterruptPort but;
static OutputPort led;
public static void Main()
{     led = new OutputPort((Cpu.Pin)FEZ_Pin.Digital.Di8, false);     but = new InterruptPort((Cpu.Pin)FEZ_Pin.Interrupt.Di7, true, Port.ResistorMode.PullUp, Port.InterruptMode.InterruptEdgeBoth);     but.OnInterrupt += new NativeEventHandler(but_OnInterrupt);     Thread.Sleep(-1);     Debug.Print("Exit");
static void but_OnInterrupt(uint port, uint state, DateTime time)
{     Debug.Print("Pressed port: " + port + " State: " + state);     if (state == 0)         led.Write(true);     else         led.Write(false); // turn off.

Notice we add an InterruptPort.  This sets up the port to call an event when the pin goes low or high.  We also add the Port.ResistorMode.PullUp.  A PullUp resister is a feature of the pin that will “Pull” the pin high by default.  So there will be current on the pin and it will appear High normally.  When we press the button, it will go to ground and the pin will appear low.  The OS will call our event and we can test if event was called because pin was high or low.  If “state” is zero (low), then we know button was pressed and we write “true” to the LED pin, which lights the LED.  If signal is high, then we turn LED off.

Pretty simple, but some real power there.  We used two pin in concert to turn on and off a device using code.

This entry was posted in .Net Micro Framework, C#, FEZ, LED and tagged , , , . Bookmark the permalink.