Raspberry Pi – Button as a digital toggle switch

Ability to directly control the GPIO (general purpose input output) pins is one of the reasons the miniature Raspberry Pi is so famous with hobbyist and educationalists.

In this self learning exercise, I will read the status of the button, determine if it is pressed or not and then based on that, switch the LED on or off.

Very basic right? Let’s follow along.

Components

  1. Raspberri Pi 2 Model B (40 pin) with Raspbian OS
  2. Breadboard
  3. Connectors
  4. LED 5mm
  5. Push Button
  6. Resistors – R1 (330 ohm) & R2 (1K ohm)

Wiring It Up

My setup uses the GPIO 23 (pin #16) and GPIO 24 (pin #18), however you can use any GPIO pins for this purpose. If you are using different pins, make sure to update the pin numbers in the program below.

  • GPIO 23 (pin #16) –  Used as input to read the status of button
  • GPIO 24 (pin #18) – Used as output for switching the LED on and off
  • +3.3V (pin #1) – Connected to power rail on the breadboard
  • GND (pin #9) – Connected to ground rail on the breadboard
  • R1 – Connected between LED and ground
  • R2 – Connected between 3.3V power rail and button
20150820-RPI_Push_Button_Toggle_Switch_bb
Push button programmed as a toggle switch to power on/off a load (LED)

Program

You need a program to tie these hardware together; to read the status of the button and send the signals to light up the LED.

I used ‘C’ with WiringPi libraries. I’m quite new to these myself. If you prefer, you can also do the same with Python. Geany is my favorite editor on the Raspberry Pi, works for both C and Python.

Let me quickly explain the functions of WiringPi library used in the program:

digitalWrite() – used to send an output to the GPIO pin. The first parameter is the pin number. Second parameter determines if the pin should be set as either HIGH or LOW (it can take only 2 states).

digitalRead() – used to read the status of the GPIO pin. The only parameter passed is the pin number. The output is either HIGH or LOW and can be checked as below:

Once this part is understood, whipping up a code to capture the pressed state of the button and lighting up an LED is  a piece of cake. Not joking, it really is!

The next part is how to toggle. This is done by remembering the previous state of the button and when it changes, determine whether to switch the LED on or off.

Since the program involves low level access to gpio pins, it will need ‘sudo’ permissions to run this program.

Summary

Here, we saw how to read input from a button and write output to light up an LED using the GPIO pins of a Raspberry Pi. Once we have these basics right, then the same knowledge can be used to drive other loads like a relay, motor etc.

References

WiringPi – GPIO interface library for the Raspberry Pi

WiringPi GPIO Pins – Pin layout for WiringPi specific and Broadcom specific pin modes

Adafruit – Tons of stuff related with Raspberry Pi and Arduino

 

 

 

 

WP7: Checking Weather Forecast Using YQL

I touched upon yahoo query language (YQL) interface in my last post. Today, I will show some quick practical uses of YQL and demonstrate how easy it is for the programmers to tap into this information.

For today’s example, we will examine the table named ‘weather.forecast’, which is available in the YQL interface.

Head over to the YQL Console to examine the parameters to be used for ‘weather.forecast’.

yql_weather_forecast_1

As shown in the screenshot, there is one parameter named ‘location’ that is required for querying data from this table.

The complete URL would look like below:

http://query.yahooapis.com/v1/public/yql?q=%20SELECT%20*%20FROM%20weather.forecast%20WHERE%20location%3D%2263126%22%20%20&diagnostics=true

Windows Phone Application

Create a new ‘Windows Phone Application’ project in Visual Studio.

New_Windows_Phone_Application

Preparing the User Interface

The user will provide the location for which the weather forecast is to be displayed as input.

For this, I added a horizontal StackPanel with a TextBox and a Button into the MainPage.xaml.

For displaying the results, I used a WebBrowser control, as some of the data for ‘weather.forecast’ is returned as HTML.

The XAML listing for the UI is here:

Getting data from YQL

The user enters the zip code for which weather forecast has to be displayed and press on ‘GO’ button.

The program takes this location, construct the correct URL and make a web request to retrieve the data from the internet.

WeatherWatch_1

Windows Phone SDK provides two options to make a web request and get data from the internet, WebClient and HTTPWebRequest. See here for more information.

For this example, I used the WebClient API for it’s inherent simplicity as this is a post more to demonstrate the YQL than about performance.

Since the program did not specify a output format, JQL returns XML by default. The output format can be specified as JSON by adding  parameter to the original URL.

http://query.yahooapis.com/v1/public/yql?q=SELECT%20*%20FROM%20weather.forecast%20WHERE%20location%3D%2263126%22%20%20&format=json&diagnostics=true

Parsing the XML is made simpler by the XDocument class provided in the System.Xml.Linq namespace.

Displaying the results

WebClient returns data on the same thread, so it can directly access the UI elements. On the other hand, HTTPWebRequest returns data on a different thread and the result has to be marshaled back to the UI thread. Since data is returned on a different thread, HTTPWebRequest has the advantage of not locking up the UI thread when it is processing.

WeatherWatch_2

The complete MainPage.xaml.cs code behind:

WP7: WebClient and HTTPWebRequest

Windows Phone 7 SDK has provided two classes for consuming resources from the web. WebClient and HTTPWebRequest.

HTTPWebRequest

HTTPWebRequest is a low level API for web requests. Unlike WebClient, it allows to tinker some of the HTTP aspects like cookies and user agent.

One major advantage of HTTPWebRequest is that it returns on another thread, which comes in handy for large web requests. It will not lock up the UI thread allowing the UI to remain responsive during the request. Since the response is returned on another thread the program should marshal the response back to the UI thread.

HTTPWebRequest is created by the static method HTTPWebRequest.Create().

Call the EndGetResponse() to get the WebResponse, which will contain the stream to read the response.

WebClient

WebClient is a higher level abstraction of the web request. It wraps the HTTPWebRequest to provide a more easier API to make web requests.

WebClient has a built in mechanism to report progress of the request in percentage. WebClient runs on the same thread, so programs don’t have to use the dispatcher to pass data back to the UI thread.

However, since the WebClient runs on the UI thread, it can make the UI unresponsive if the program makes a long running web request.

 

I think there is a place for using both the classes. Being aware of these differences helps to choose the best one for a given situation.

Windows Phone 7: Navigation

Web developers will find themselves in familiar territory with the navigation in Windows Phone 7.

NavigationService Class

Navigate to another page:

Navigate to another page (with parameters):

NavigationContext Class

If a parameter was passed to the destination page using query string, NavigationContext class allows to read the query string as follows

Navigation History

Navigation history is exposed as a read-only enumeration through the property called NavigationServices.BackStack,

There are additional methods exposed for going back and forward one step at a time. It is a good practice to check for the CanGoBack and CanGoForward property before calling the navigation methods to make sure there is more in the history to go back or forward.