Thursday, June 11, 2015

Win 10 IoT on RPi 2: Simple C++ Code to Control an LED via a RadioButton

Microsoft's sample documentation for Windows IoT on the Raspberry Pi 2 includes a C# example that shows how to use a timer to blink an LED (called Blinky).  To get started with Windows 10 IoT Core and Windows Universal applications, I wanted to try something even simpler. I also wanted to use C++.  Below is a very minimal example that shows how to use a XAML RadioButton to turn an LED off and on.

This example assumes that you have Windows 10 IoT Core set up already and have configured Visual Studio to work with your device. This is covered in the MS getting started documentation.  For what it's worth, I'm using the preview version of Visual Studio 2015 installed on a Windows 10 preview VM running under Parallels on my Mac.


For this example, connect the LED's anode (positive pin/longer pin) with an appropriate resister to the RPi's 3.3V and the cathode (negative/shorter pin) to the the RPi 2's GPIO 5 pin. Setting pin 5 to high will turn off the LED and setting it to low will turn it on.

Add Reference to Visual Studio Project

You will need to add the reference to the Windows IoT Extension SDK to be able to use GPIO.  In the Solution Explorer,  right click on References and select "Add Reference."  Under Windows Universal, click on "Extensions."  Check the box for the "Windows IoT Extension SDK."  Note that you have to mouse over the entry in the list to see the checkbox.

All of the code below assumes a project named LEDOnOff.  

XAML File (MainPage.xaml)


    <Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
        <StackPanel Width="200" Height="200">
            <RadioButton x:Name="OnRadioBtn" GroupName="OnOffRadioBtnGroup" 
                         FontSize="21" FontWeight="Bold" Content="On" 
            <!-- Off button is selected to start -->
            <RadioButton x:Name="OffRadioBtn" GroupName="OnOffRadioBtnGroup" 
                         FontSize="21" FontWeight="Bold" Content="Off"
                         IsChecked="True" Click="OffRadioBtn_Checked"> 
            <TextBlock x:Name="SwitchStatus" FontSize="27"  Margin="3" />

Header File (MainPage.xaml.h)

#include "MainPage.g.h"

namespace LEDOnOff
  public ref class MainPage sealed

      Windows::Devices::Gpio::GpioPinValue pinValue;
      // Connect LED cathode/ground to RPi GPIO pin 5
      const int LED_PIN = 5;
      // Handle providing access to pin
      Windows::Devices::Gpio::GpioPin^ pin;

      void MainPage::InitGPIO();
      // Event handlers called when on/off radio button is checked
      void OnRadioBtn_Checked(Platform::Object^ sender,
           Windows::UI::Xaml::RoutedEventArgs^ e);
      void OffRadioBtn_Checked(Platform::Object^ sender,
           Windows::UI::Xaml::RoutedEventArgs^ e);


C++ Code File (MainPage.xaml.cpp)

#include "pch.h"
#include "MainPage.xaml.h"

using namespace LEDOnOff;

using namespace Platform;
using namespace Windows::Foundation;
using namespace Windows::Foundation::Collections;
using namespace Windows::UI::Xaml;
using namespace Windows::UI::Xaml::Controls;
using namespace Windows::UI::Xaml::Controls::Primitives;
using namespace Windows::UI::Xaml::Data;
using namespace Windows::UI::Xaml::Input;
using namespace Windows::UI::Xaml::Media;
using namespace Windows::UI::Xaml::Navigation;
using namespace Windows::Devices::Enumeration;
using namespace Windows::Devices::Gpio;


void MainPage::InitGPIO()
  auto gpio = GpioController::GetDefault();

  if(gpio == nullptr)
    pin = nullptr;
    SwitchStatus->Text = "No GPIO controller on this device.";
  // I have dropped the trailing _ on member var pin
  pin = gpio->OpenPin(LED_PIN);
  // Set pin direction to output
  // Set pin to High to turn LED off to start.
  // Set status message
  SwitchStatus->Text = "Switch is Off.";

// Event handler to turn LED on when On is clicked
void LEDOnOff::MainPage::OnRadioBtn_Checked(Platform::Object^ sender
  Windows::UI::Xaml::RoutedEventArgs^ e)
  // Shows how to access button content
  SwitchStatus->Text = "Switch is " + OnRadioBtn->Content + ".";
  // Setting GPIO 5 to low allows current through

void LEDOnOff::MainPage::OffRadioBtn_Checked(Platform::Object^ sender,
  Windows::UI::Xaml::RoutedEventArgs^ e)
  SwitchStatus->Text = "Switch is " + OffRadioBtn->Content;
  // Setting GPIO 5 to high blocks current

Additional Notes:

  • Remember to set architecture to ARM via the dropdown near the top of the Visual Studio window.  
  • You won't be able to test/debug a program that uses GPIO on your local development computer.
  • You may need to set the computer name for your RPi running Win 10 IoT in the Debugging section of the project's properties. This should match the device name that shows on the screen for your RPi after it boots. 
  • Make sure that authentication is turned off in the project's debugger settings.
  • So far, I have only run the code via the debugger. I haven't deployed the application as the starter on my RPi 2. 

Tuesday, April 7, 2015

gcc-4.9 & g++-4.9 for the Raspberry Pi (C/C++ 11 & 14 Support)

I haven't done any posting here for a while, but I found information good information about installing newer versions of the GCC compilers with support for C11/C++11 and C++14:

Solarian Programmer -Raspberry Pi - Install GCC 4.9 and compile C++14 programs  (posted by Sol on 01/13/2015).

Tuesday, July 15, 2014

C# (Mono) Code to Read an TMP102 I2C Temperature Sensor on a Raspberry Pi

Mono is an open source implementation of the Microsoft .NET framework that allows you to compile and run .NET programs on non-Windows platforms.  That includes the Raspberry Pi.  It actually proved to be quite easy to install Mono (v. 3.2.8) on the RPi and get some C# code running.  This example shows how to call the i2cget utility from a C# program to read the temperature from a TMP102 and print the results in degrees Celsius and Fahrenheit in the terminal window.

To install Mono, run the following apt-get command as root:

apt-get install mono-complete

The will get you the complete Mono package.

For this example, I am using the TMP102 on a breakout board from Sparkfun.

Connect the SDA and SCL pins between the TMP102 and the RPi.  Connect VCC to 3.3V and connect the ground.  With the solder jumper on the TMP102 in place (by default) the I2C device address is 0x48.

The i2cget utility is included with the i2c-tools package. If you don't already have it installed, you can run the following command as root to install it -

apt-get install i2c-tools 

C# Code

Use your favorite text editor to save this code to a file called Tmp102.cs.

using System;
using System.Diagnostics;
using System.Threading;

public class Tmp102
    private string i2cgetExe = "/usr/sbin/i2cget";
    private string i2cgetCmdArgs = "-y 1 0x48 0 w";
    private string hexString = "";
    private Process p;

    public Tmp102()
        p = new Process();

    public double tempC
        get { return readRawTempData() * 0.0625; }
    public double tempF
        get { return this.tempC * 1.8 + 32; }

    private int readRawTempData()
        // Don't raise event when process exits
        p.EnableRaisingEvents = false;
        // We're using an executable not document, so UseShellExecute false
        p.StartInfo.UseShellExecute = false;
        // Redirect StandardError
        p.StartInfo.RedirectStandardError = true;
        // Redirect StandardOutput so we can capture it
        p.StartInfo.RedirectStandardOutput = true;
        // i2cgetExe has full path to executable
        // Need full path because UseShellExecute is false

        p.StartInfo.FileName = i2cgetExe;
        // Pass arguments as a single string
        p.StartInfo.Arguments = i2cgetCmdArgs;
        // Now run i2cget & wait for it to finish
        // Data returned in format 0xa017
        // Last 2 digits are actually most significant byte (MSB)
        // 2 digits right after 0x are really least significant byte (LSB)
        string data = p.StandardOutput.ReadToEnd();
        // Get LSB & parse as integer
        hexString = data.Substring(2, 2);
        int lsb = Int32.Parse(hexString,
        // Get MSB & parse as integer
        hexString = data.Substring(4, 2);
        int msb = Int32.Parse(hexString,
        // Shift bits as indicated in TMP102 docs & return
        return (((msb << 8) | lsb) >> 4);

    public static void Main()
        Tmp102 t = new Tmp102();
            // Print temp in degrees C and F to console
            Console.WriteLine("{0}°C  {1}°F", t.tempC , t.tempF);

Compiling & Running the Code

To compile a Mono executable, run the following command:

gmcs Tmp102.cs

Then execute the program by running 

mono Tmp102.exe

Press Ctrl-C to terminate the program.

Saturday, July 12, 2014

Displaying Current Temperature on a Web Page Using a TMP102 & PHP on a Raspberry Pi

Here is an example of using PHP to read the current temperature from a TMP102 I2C temperature sensor and display it (in degrees Fahrenheit) in a Web page.


Make sure that you have installed the i2c-tools package because this package provides i2cget to read the registers on the TMP102.  The following apt-get command will install it for you:

sudo apt-get install i2c-tools

Install the Apache2 Web server:

apt-get install apache2

Then install PHP5:

apt-get install php5

Granting Access to I2C System Device

By default, and for the sake of security, the account used to run the Apache2 Web server doesn't have permission to access the /dev/i2c-1 device.  To fix this, edit the udev configuration file that controls the file permissions for /dev/i2c-1.

Use nano or your favorite text editor to edit /lib/udev/rules.d/60-i2c-tools.rule. Replace the contents of the file with these two lines.  

KERNEL=="i2c-0", GROUP="i2c", MODE="0660"
KERNEL=="i2c-1", GROUP="i2c", MODE="0666"

This leaves the i2c-0 device with the default permissions and changes the access to i2c-1 to allow a non-privileged user to read the device.

PHP Code

Here is a simple PHP page that reads the temperature data using i2cget, converts it to degrees Fahrenheit and displays it.  Put this code in /var/www/temp.php -

    $output = `/usr/sbin/i2cget -y 1 0x48 0 w`;
    $msb = hexdec(substr($output, 4, 2));
    $lsb = hexdec(substr($output, 2, 2));
    $tempF = ((($msb << 8) | $lsb) >> 4) * 0.0625 * 1.8 + 32;
    echo "Temp: $tempF&deg;F";

The backticks (` `) tell PHP to run the enclosed command in a (Linux) command shell.  The backtick is on the key to the left of the 1 key near the top of the keyboard (on the same key as the ~).

In the command i2cget -y 1 0x48 0 w

  • -y cancels the user prompt that asks if you really want to read from the device
  • 1 actually refers to the 2nd I2C bus, /dev/i2c-1
  • 0x48 is the default I2C device address for the TMP102
  • 0 is the register with the temperature data
  • w means we want to read a word (rather than just a byte).

Note that when i2cget reads the data, the byte order is reversed.  The first byte is actually the least significant byte (LSB) and the second byte is the most significant byte (MSB).  The string returned by i2cget is something like 0xb01d.  The code uses substr() to pull out the two digits for each byte, and then hexdec() to convert a string representing a hexadecimal value to a decimal numeric value.

From a computer on the same network, access the URL for the page (where the IP address will vary):

Sample Java Code to Read Temperature from an TMP102 via I2C & Save Data to a MySQL Database Table

The Java code below reads current temperature data from the TMP102 temperature sensor using the i2cget command line utility to read the TMP102's registers.  The reading is taken every second and the result is saved to a MySQL database table.  The table contains a column for the date and time and a column for the temperature in degrees Fahrenheit.  The code below should work with Java 6, 7, or 8.  You will need to have the complete JDK installed to compile the code.


The i2cget command line utility is part of the I2C Tools package.  You can install this package on the Raspberry Pi using the following apt-get command:

apt-get install i2c-tools

To install MySQL, use the following command and follow the prompts:

apt-get install mysql-server

The following command installs the Java database (JDBC) driver that allows your code to access the database:

apt-get install java-mysqldb

Database Structure

  date_time        datetime NOT NULL,
  temp_f            double,
  PRIMARY KEY (date_time)

Java Code

import java.util.*;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.PreparedStatement;

public class Tmp102 {
    // i2cget command to read raw data as a word (16-bit value)
// from TMP102 sensor.  -y tells command to run 
    // without confirmation from user.
    // I2C address for TMP102 by default is 0x48.
    // Command is passed a separate String, unlike loadPinMapCmd
    // that has to be passed as an array of Strings.
    String runI2CGetCmd = "i2cget -y 1 0x48 0 w";

    Connection conn = null;
    PreparedStatement stmt = null;
    // Change gpsdb to name of your DB. Also change
    // DB user name & password
    String url = "jdbc:mysql://localhost/temperature?" +

    String insertSQL = "INSERT INTO tmp102(date_time, temp_f) " +
        "VALUES (now(), ?)";

    public Tmp102() {
        // Constructor sets up DB connection
        try {
            conn = DriverManager.getConnection(url);
        catch(Exception ex) { ex.printStackTrace(); }

    // Read temperatures from both sensors & print it out to terminal
    public void readTemperature() {
        short tempData = 0;
        double temp = 0.00;
        tempData = runI2CGet(runI2CGetCmd);
        tempData = reverseBytes(tempData);
        temp = convertToDegreesF(tempData);
        try {
            stmt = conn.prepareStatement(insertSQL);
            stmt.setDouble(1, temp);
            System.out.printf("%.3f\n", temp);
        catch(Exception ex) { ex.printStackTrace(); }

    // Need to reverse bytes in value returned by i2cget command
    private short reverseBytes(short tempData) {
        int b1 = (byte)  tempData & 0xFF;
        int b2 = (byte) (tempData >> 8) & 0xFF;
        return (short) (b1 << 8 | b2);

    // Convert raw temperature data to degrees Fahrenheit
    private double convertToDegreesF(short tempData) {
        return (tempData >> 4) * 0.0625 * 1.8 + 32;

    private short runI2CGet(String cmd) {
        String line = "";
        short data = 0;
        try {
            Process p = Runtime.getRuntime().exec(cmd);
            // Use Scanner to read results from i2cget command
            Scanner scan = new Scanner(
                new InputStreamReader(p.getInputStream()));
            // Shell command returns hex number as string like 0x6017.
            // Need to use substring to skip over 0x for parsing.
            // Using Short.parseShort() sometimes throws NumberFormatExceptions.
            if(scan.hasNext()) {
                data = (short) Integer.parseInt((scan.nextLine())
                .substring(2), 16);
        catch(Exception ex) { ex.printStackTrace(); }
        return data;

    private void closeDBConn() {
        try {
        } catch(Exception exc){ exc.printStackTrace(); }

    public static void main(String[] args) {
        Tmp102 temp = new Tmp102();
        try {
            while(true) {
        catch(Exception ex) { ex.printStackTrace(); }
        finally { temp.closeDBConn(); }

Compiling & Running the Program

javac -cp /opt/mysql-connector-java-5.1.31/mysql-connector-java-5.1.31-bin.jar

Adjust the -cp path for the MySQL-Connector .jar file to match your installation, if needed.

The following command runs the program.  The temperature readings are printed to the terminal, while the current timestamp and temperature are saved in the database. 

java -cp .:/opt/mysql-connector-java-5.1.31/mysql-connector-java-5.1.31-bin.jar Tmp102

Again, adjust the -cp path to match the location of your MySQL-Connector .jar file.

Stop the program by pressing Ctrl-C.

Saturday, July 5, 2014

Note about External Connections to a MySQL Instance Running on the Raspberry Pi

If you want to connect to a MySQL DB server instance running on a Raspberry Pi, a couple bits of additional configuration are required.  

On the Raspberry Pi, use nano or another text editor to edit the /etc/mysql/my.conf file.  Under the [mysqld] section, edit the bind-address to match the RPi's IP address, if you wish to restrict access to one IP interface's address or set it to to all access using the IP address for any available network interface.

To allow remote access via the MySQL root login, (re)run the mysql_secure_installation script and answer the relevant question about remote access for root appropriately.  The following MySQL command (issued at the MySQL command line) has the same effect.  Change the password as appropriate.

 grant all privileges on *.* to 'root'@'%' identified by 'MyRootPassword' with grant option;

Tuesday, June 24, 2014

Java Code to Read GPS Data from a Sparkfun Copernicus II DIP Module & Store Readings in a JavaDB Database Table on a Raspberry Pi

This example uses Java 8 to connect to the Copernicus II GPS module via a serial connection. For instructions on how to install Java 8 on a Raspberry Pi, see this Adafruit tutorial.

To install the RXTXComm serial library for Java, run the following apt-get command:

apt-get install librxtx-java

Last year, I posted a similar example that uses MySQL, but since JavaDB (also known as Derby) comes with the Java 8 installation, it is very convenient and easy to use.

Configuring JavaDB

While JavaDB comes with the Java 8 JDK, a small amount of configuration is needed.  JavaDB can run in embedded or in network server mode.  In this example, I am running it as a network server so that it can be accessed by more than one application running in different Java virtual machines.

 Make sure that your JAVA_HOME environment variable is set.  If you used the Adafruit tutorial above and have the JDK installed in /opt/jdk1.8.0, add the following line to your .bashrc file.  If you have your JDK installed in a different location, adjust as needed.

export JAVA_HOME=/opt/jdk1.8.0

Then add the following lines to set DERBY_HOME and adjust your path to include the JavaDB executables.

export PATH=$PATH:/$JAVA_HOME/db/bin

Run source ~/.bashrc to load the settings from your edited .bashrc file. 

Edit your java.policy file to allow access to port 1527.  If you have the JDK installed in /opt/jdk1.8.0, your policy file should be /opt/jdk1.8.0/jre/lib/security/java.policy.  Add the following line to this file before the closing bracket of the grant block -

permission "localhost:1527", "listen";

Now start the JavaDB server with the following command:

/opt/jdk1.8.0/db/bin/startNetworkServer &

It may take a moment to start, but the output should indicate that the security policy has been applied and that the server is now running on port 1527.

For this example, I used the ij client utility to connect to JavaDB, create the gpsdb database, and create the gps_readings table.  I won't go into a lot of detail about ij, but you can find good documentation online.  With the path to the JavaDB/Derby binaries included in your path, you can simple run the ij command to start the command line DB client.

To create the database, I used the following connect statement at the ij> prompt:

connect 'jdbc:derby://localhost:1527/gpsdb;create=true';

I ran the following SQL at the ij> prompt to create the gps_readings table:

create table gps_readings (
 utc_time_date timestamp not null,
 lat varchar(15) not null,
 long varchar(15) not null,
 constraint pk_gps_readings_utc_time_date primary key(utc_time_date)

Connecting the Copernicus II GPS Module

GPS Module  Raspberry Pi (Rev. B)
VCC         3.3V       
GND         GND
TX-B        GPIO15
RX-B                 GPIO14

Java 8 Code

Here is the source code from -

import java.util.*;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.Statement;
import java.time.LocalDate;
import java.time.ZoneId;

public class Gps {
    private static String port = "/dev/ttyS80";
    private InputStream inStream;
    private OutputStream outStream;
    // NMEA command to set Copernicus II to output $GPGLL every second.
    private static String nmeaString = "$PTNLSNM,0002,01*55\r\n"; 

    private Connection connect = null;
    private Statement statement = null;
    private static String driverClass = "org.apache.derby.jdbc.ClientDriver";
    private String jdbcURL = "";
    private static String sql = "INSERT INTO GPS_READINGS(UTC_TIME_DATE, LAT, LONG) VALUES(?,?,?)";

    // Constructor takes JDBC URL for JavaDB server as argument
    public Gps(String url) { jdbcURL = url; }

    public void recordGPS() {
        try {
            // RXTXComm library uses /dev/ttyS80, so symbolic link needed
            String lnPortCmd = "ln -s /dev/ttyAMA0 /dev/ttyS80";
            Process p = Runtime.getRuntime().exec(lnPortCmd);
            CommPortIdentifier portId = CommPortIdentifier.getPortIdentifier(port);
            SerialPort serialPort = (SerialPort)"GPS", 5000);
            // Change serial port speed as needed
            serialPort.setSerialPortParams(19200, SerialPort.DATABITS_8,
                SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);
            inStream = serialPort.getInputStream();
            outStream = serialPort.getOutputStream();
            byte[] nmeaCmd = nmeaString.getBytes();
            String gpsData = "";
            outStream.write(nmeaCmd, 0, nmeaCmd.length);
            connect = DriverManager.getConnection(jdbcURL);
            PreparedStatement statement = connect.prepareStatement(sql);
            while(true) {
                if(inStream.available() > 0) {
                 int b =;
                    if(b != 13) {
                        gpsData += (char)b;
                    else {
                        gpsData = gpsData.trim();
                        String[] datum = gpsData.split(",");
                        gpsData = "";
                        // Check for valid $GPGLL NMEA sentence
                        if(datum.length < 8 || !("$GPGLL").equals(datum[0]) || datum[1] == null || 
                                 !("A").equals(datum[6])) {
                        else {
                            LocalDate todayUTC ="UTC"));
                            String t = datum[5].substring(0,2) + '.';
                            t += datum[5].substring(2,4) + '.';
                            t += datum[5].substring(4,6);
                            statement.setString(1, todayUTC.toString() + '-' + t);
                            statement.setString(2, datum[1] + ' ' + datum[2]);
                            statement.setString(3, datum[3] + ' ' + datum[4]);    
        catch (Exception ex) {
        finally {
            try {
            catch(Exception exc) {

    public static void main(String[] args) {
        Gps copernicus = new Gps("jdbc:derby://localhost:1527/gpsdb");

Compiling & Running the Program

I have tested compiling and running the program as root (superuser).

Use the following command to compile the program -

javac -cp /usr/share/java/RXTXcomm.jar:$JAVA_HOME/db/lib/derby.jar

After compiling, use the following command to run the program.  Note that when running the code you need to use derbyclient.jar.

java -Djava.library.path=/usr/lib/jni/ -cp /usr/share/java/RXTXcomm.jar:$JAVA_HOME/db/lib/derbyclient.jar:. Gps

When the program runs, the GPS data read from the Copernicus II is printed out in the terminal window and records are inserted into the gps_readings table.  You can use ij to query the data in the database.  Since JavaDB is running in network server mode, you can access it using ij while the Java Gps program is running.