Local Temperature with chipKIT Digilent uC32, Digilent Basic I/O and Raspberry Pi

Introduction

chipKIT Digilent uC32 (or Uno32) and Raspberry Pi are both pretty cheap, almost of the same size, and although they look similar, they are different. The Raspberry Pi is effectively a mini-computer, running a Linux operating system (OS), and the chipKIT is a microcontroller, without a typical typical OS, but purpose-built with important features such as EEPROM, analog inputs and PWM outputs, features that Raspberry Pi does not have. On other hand, Raspberry Pi offers Ethernet connection, USB Master, video and audio outputs, all of these that are not available on chipKIT, can enhance any electronic project.

There is already a marriage between chipKIT and Raspberry Pi, called chipKIT Pi that makes it easy to connect Raspberry Pi to chipIT. The chipKIT Pi board fits nicely on the Raspberry Pi interfacing directly on the IO header of the Raspberry Pi. The board can be used without Raspberry Pi, in stand-alone mode and for this reason there is a DC plug, useful to power the board with a power supply. The ICSP header (JP3) has been added to program the on-board microcontroller PIC32MX250F128B  using a Microchip PICkit or a ICD in-circuit debugger/programmer.

Objectives

  • Capture the local temperature with Microchip TCN75A temperature sensor on Digilent Basic I/O shield using chipKIT Digilent uC32 board
  • Make the reading available through USB port to Raspberry Pi
  • Make Raspberry Pi with a Python program to read from the USB port, and display the  values of temperatures as read from USB port.

Setup

  • chipKIT Digilent uC32 with Digilent Basic I/O shield on top, and power supply

tempmon1

  • Raspberry Pi Model B and power supply (and I recommend a powered USB hub)

tempmon2

  • USB A to mini-B cable

tempmon3Procedure

a) Install libraries of Basic I/O Shield in MPIDE environment for uC32 board

On uC32 you must have Jumpers JP6 and JP8 set in the RG3 and RG2 positions. Install the Basic I/O shield on top of UNO32 as shown on the above image . Connect to the PC with USB cable. Although USB connection will power uC32 and the Basic I/O shield simultaneously, we will use external power supply to uC32 board.

We assume that you have already installed MPIDE environment.

You will need to know the location of MPIDE sketches folder:

Run MPIDE  . In menu do File -> Preferences find the sketchbook location:

tempmon4Take note of the location of your sketches (MPIDE codes are called “sketches”). In your Windows navigate to where the folder is, and create a directory named ‘Libraries’.

Download from here the zipped file containing libraries and documentation for using the Basic I/O Shield™ with the chipKIT MPIDE and unzip into the Libraries folder you have just created:

tempmon5Now if you do File -> Examples you will see three folders IOShieldEEPROM, IOShieldOled and IOShieldTemp. Open the sketch IOShieldTemp_Demo:

mpide4

Next choose the board (in our case chipKIT uC32):

tempmon6And choose Serial Port to which the board is connected in Tools >> Serial Port >> (port where UC32 is connected). In my case it is COM30.

Now we are ready to upload the sketch to the board. Click the Upload button  on MPIDE environment.

If successful you will see the following results at bottom of MPIDE environment:

tempmon7We are now ready to check what is being sent to our COM30 port (your PC’s may be other) in Tools >> Serial Monitor.

A new window will pop up showing the readings sent to your PC’s serial port:tempmon8We are  getting readings in degrees C and degrees F. Note that Alarm is not displayed even though the temperature is above 24ºC as set in our sketch (you can check – it is clearly written). This happens because in uC32 and Uno32 boards you need to toggle to top the rightmost switch on Basic I/O shield   If you do so, ALERT will sent to serial port. You can use the switch to switch off the Alarm by toggling down the switch.

If you are here, the rest will go smoothly.

We will now change this sketch, and adapt it to Raspberry Pi to be read easily by Python. Also ,we will add code to show the temperature on OLED display of Basic I/O shield.

/* Original source code at
http://chipkit.net/tag/temperature-sensor/
Modified and adapted by Tayeb Habib tayeb.habib@gmail.com
http://redacacia.me
*/

#include <IOShieldTemp.h>
#include <IOShieldOled.h>
#include <Wire.h>
#define ALERT_PIN 2

int tensc = 0;
int onesc = 0;
int dot_tensc = 0;
int dot_onesc = 0;
int tensf = 0;
int onesf = 0;
int dot_tensf = 0;
int dot_onesf = 0;
int tempC=0;
int tempF=0;

void setup()
{
  Serial.begin(9600);
  pinMode(ALERT_PIN, INPUT);
  //set up the OLED display
  IOShieldOled.begin();
  IOShieldOled.setCharUpdate(0);
  IOShieldOled.displayOn();
  IOShieldTemp.config(IOSHIELDTEMP_ONESHOT | IOSHIELDTEMP_RES11 | IOSHIELDTEMP_ALERTHIGH);
  //Set the range to bring the alert pin high if it's above 78F (25.5C), alert will stay
  //high until the temp drops below 75.2F (24C).
  IOShieldTemp.setTempLimit(IOShieldTemp.convFtoC(78)); // 78.0F ~ 25.5C
  IOShieldTemp.setTempHyst(24); // 75.2F ~ 24.0C

}
void loop()
{
  float tempf, tempc;
  //Get Temperature in Celsius.
  tempc = IOShieldTemp.getTemp();

  // Convert the result to Fahrenheit.
  tempf = IOShieldTemp.convCtoF(tempc);
 
  //Print Temperature to serial port
  Serial.print(tempc);
  Serial.print(",");
  Serial.print(tempf);
  Serial.print(",");
  if(digitalRead(ALERT_PIN) == HIGH)
    Serial.print("ALERT!");
  else
    Serial.print("OK");
  Serial.print("\r\n");

  //parse data for temperature in celcius
  tempC=tempc*100;
  dot_onesc = tempC%10;
  tempC = tempC/10;
  dot_tensc = tempC%10;
  tempC = tempC/10;
  onesc = tempC%10;
  tempC = tempC/10;
  tensc = tempC%10;

  //convert data to ASCII for temperature in celcius
   tensc = tensc+48;
   onesc = onesc+48;
   dot_tensc = dot_tensc+48;
   dot_onesc = dot_onesc+48;

  //parse data for temperature in Fahrenheit
  tempF=tempf*100;
  dot_onesf = tempF%10;
  tempF = tempF/10;
  dot_tensf = tempF%10;
  tempF = tempF/10;
  onesf = tempF%10;
  tempF = tempF/10;
  tensf = tempF%10;

  //convert data to ASCII for temperature in Fahrenheit
   tensf = tensf+48;
   onesf = onesf+48;
   dot_tensf = dot_tensf+48;
   dot_onesf = dot_onesf+48;

  //Clear the virtual buffer
  IOShieldOled.clearBuffer();

  //Draw a rectangle over wrting then slide the rectagle
  //down slowly displaying all writing
    IOShieldOled.clearBuffer();
    IOShieldOled.setCursor(0, 0);
    IOShieldOled.putString("Aliatron Office");
    IOShieldOled.setCursor(0, 1);
    IOShieldOled.putChar(tensc);
    IOShieldOled.setCursor(1, 1);
    IOShieldOled.putChar(onesc);
    IOShieldOled.setCursor(2, 1);
    IOShieldOled.putString(".");
    IOShieldOled.setCursor(3, 1);
    IOShieldOled.putChar(dot_tensc);
    IOShieldOled.setCursor(4, 1);
    IOShieldOled.putChar(dot_onesc);
    IOShieldOled.setCursor(6, 1);
    IOShieldOled.putString(" Degrees C");
    IOShieldOled.setCursor(0, 2);
    IOShieldOled.putChar(tensf);
    IOShieldOled.setCursor(1, 2);
    IOShieldOled.putChar(onesf);
    IOShieldOled.setCursor(2, 2);
    IOShieldOled.putString(".");
    IOShieldOled.setCursor(3, 2);
    IOShieldOled.putChar(dot_tensf);
    IOShieldOled.setCursor(4, 2);
    IOShieldOled.putChar(dot_onesf);
    IOShieldOled.setCursor(6, 2);
    IOShieldOled.putString(" Degrees F");
    IOShieldOled.setCursor(0, 3);
    if(digitalRead(ALERT_PIN) == HIGH)
       IOShieldOled.putString("A L E R T !");
    IOShieldOled.updateDisplay();
  delay(1000);
}

The OLED display on BASIC I/O shield will show something similar to following image:

tempmon9Note that rightmost switch is toggled to up position. Only in this position the Alert for temperature above 24ºC will work.

Now we are ready for Raspberry Pi!

b) Preparing Raspberry Pi

As a requirement your Raspberry Pi must have an already working Raspbian OS, and mouse and keyboard duly configured, and with network connection to Internet duly installed. If not, you need to do all those things before proceeding.  The aim of this tutorial is not to install OS in Raspberry Pi or to connect peripherals to this board.

So, we assume that mouse, keyboard, monitor and Internet connection will be working. Check if your installation has already Python serial with following command on LXTerminal of Raspberry Pi desktop:

dpkg -s python-serial

If it is not installed, the response will be the following or something very similar to:

dpkg-query: package 'python-serial' is not installed and no information is available

The result you will see on Terminal screen if it is installed will be:

tempmon17Now, if it is not installed, write the following command:

sudo apt-get install python-serial

After duly installing we are ready to connect our setup of chipKIT Digilent uC32 board and Basic I/O shield with USB to mini-B cable to Raspberry Pi! But, do not connect yet!

c) Connect chipKIT Digilent uC32 with BASIC I/O shield to Raspberry Pi

On Terminal of Raspberry Pi write:

lsusb

You will get a response similar to following:

tempmon10I have an USB hub. where all my USB connections are made. I also have installed a TP-Link wireless dongle.

Now connect chipKIT Digilent uC32 board to Raspberry Pi board with USB cable.

On Terminal write again:

lsusb

And the response now will be:

tempmon11Our chipKIT Digilent uC32 is recognized as having a FTDI serial IC.

We can check a bit more with the following command:

dmesg | tail

The response will be similar to following:

tempmon12The last bit is what interests us. We have identified our recent connection as ttyUSB0 (it can be 1 or 2 or whatever is your setup). We will use this information for next part of our Procedure.

Before anything else we will install Minicom if you have not already installed. You can read in b) how to check if it is installed with following command:

 dpkg -s minicom

If it is not indtalled, write the following command:

sudo apt-get install minicom

After installation run the following command:

minicom -b 9600 -o -D /dev/ttyUSB0

If all is well with your setup you will see the following on Terminal:

tempmon13Alert is shown because we have this feature enabled and our temperature is over 24ºC threshold defined in our chipKIT Digilent uC32 firmware.

We are now ready to write the Python program.

d) Write Python program for reading and displaying serial code

In /home/pi of your Raspberry Pi write the following code and name it tempmon.py. You can use the default nano editor.

#!/usr/bin/python
#tempmon.py

# Graphical User Interface for TCN75A sensor

# Imports
import time
import serial
from Tkinter import *

# Serial port parameters
serial_speed = 9600
# Your serial port instead of ttyUSB0
serial_port = '/dev/ttyUSB0'

ser = serial.Serial(serial_port, serial_speed, timeout=1)

# Main Tkinter application
class Application(Frame):

    # Measure data from the sensor
    def measure(self):

          # Request data and read the answer
          data = ser.readline() # read data from serial
          # port and strip line endings

          # If the answer is not empty, process & display data
          if (data != ""):
               processed_data = data.split(',')
               self.tempC_data.set("Temp. in " + unichr(176) + "C: " + str(processed_data[0]))
               self.temperatureC.pack()

               self.tempF_data.set("Temp. in " + unichr(176) + "F: " + str(processed_data[1]))
               self.temperatureF.pack()

               self.alertT_data.set(str(processed_data[2]))
               self.alertT.pack()

          # Wait 1 second between each measurement
          self.after(5000,self.measure)

    # Create display elements
    def createWidgets(self):

              self.temperatureC = Label(self, textvariable=self.tempC_data, font=('Verdana', 24, 'bold'))
              self.tempC_data.set("Temp in C")
              self.temperatureC.pack()

              self.temperatureF = Label(self, textvariable=self.tempF_data, font=('Verdana', 24, 'bold'))
              self.tempF_data.set("Temp in F")
              self.temperatureF.pack()

              self.alertT = Label(self, textvariable=self.alertT_data, font=('Verdana', 24, 'bold'))
              self.alertT_data.set("")
              self.alertT.pack()

     # Init the variables & start measurements
     def __init__(self, master=None):
              Frame.__init__(self, master)
              self.tempC_data = StringVar()
              self.tempF_data = StringVar()
              self.alertT_data = StringVar()
              self.createWidgets()
              self.pack()
              self.measure()

# Create and run the GUI
root = Tk()
root.title('Aliatron Office')
app = Application(master=root)
app.mainloop()

Now run this code saved as tempmon.py

python /home/pi/tempmon.py

You will see immediately the TKinter graphical interface showing the temperature as the following photo shows:

tempmon14My setup is as following photo shows:

tempmon15A view of the the whole setup:

tempmon16

What next?

In fact imagination and resources are the limit. When threshold temperature Raspberry Pi could connect to my gmail account (or another specially opened) and send me the readings and alert information. A server can be set up and with IP forwarding one can monitor the temperature values from outside. A camera can stream images of the whole process. What else? I invite the next person to experiment with my set up and to follow my tutorial to post here his extra work.

Conclusions

Connecting up Raspberry Pi with a board such as chipKIT Digilent uC32 opens up a whole  new range of  interesting electronic projects. Microchip has already made it easy with chipKIT Pi, as mentioned at the beginning of this tutorial. Raspberry Pi offers lots of interesting and powerful solutions at low price, that can be combined with another low-priced board yet equally interesting and powerful chipKIT Digilent uC32. Digilent Basic I/O shield, that also offers more interesting electronic projects, with very same idea of connecting up with Raspberry Pi.

Advertisements
Posted in Electronic Projects | Tagged , , , , , , , , , | 3 Comments

BlackBerry 10 Accelerometer Sensor ”AccelMote” Control of a Robot

Introduction

Smartphones running BlackBerry 10 have many sensors that collect data about the phone’s external environment. Some are low-level, real-time sensors such as the accelerometer, and others are higher-level, event-driven sensors, like the holster sensor. The following sensors are present in Blackberry 10:

– Accelerometer
– Ambient Light
– Compass
– Gyroscope
– Holster
– Infrared Proximity
– Light
– Magnetometer
– Orientation
– Proximity
– Rotation

The accelerometer reports on changes to the acceleration of the phone along three axes. This sensor is particularly useful if your application is designed to handle motion input from a user. When the user moves the device, the accelerometer can sense the movement of the device in 3-D space along the x,y, and z axis. For example, in a racing game, the steering can be controlled by the user tilting the device from side to side.

Requirements

A 8051 robot “Robo-51” (could be a robot with any other micrcontroller) with serial bluetooth ZX-Bluetooth module, running a firmware for bluetooth control, and an account with App Inventor.

Robo-51

Inex´s Robo-51

ZX-Bluetooth

Inex’s ZX-Bluetooth Module

App Inventor Code

To be able to control the robot you will need to download the source code file AccelMote.zip kept at Bitbucket, an unlimited free private repositories’ site. If you already have an App Inventor folder, you can download the source code by scanning the following QR barcode:

qrcode_accelmote

Downloading the Android apk

If you are absolute beginner with App Inventor, the excellent resources and tutorials found at MIT’s App Inventor site are very good and easy to follow. Once installed, the source code you will need to download the Android apk. The screen and app has been optimized for Z10 .

Converting apk to bar

The downloaded apk will have to be uploaded to Good Reader’s website to convert into BB10 bar file. The link to apk2bar online converter is:

http://apps.goodereader.com/apk-2-bar/

I have found Good Reader’s website to be friendly and easy to use. If you just want to use the bar app as it is, you can download clicking AccelMote_v1.0.1.bar kept at Bitbucket.

Side-loading the bar file into Blackberry 10 smartphone  

The following Good Reader’s link has a tutorial on how to install bar app into your Blackberry 10 smartphone (my app is optimized for Z10): http://apps.goodereader.com/playbook/playbook-android-apps/?did=177 It has also a video on how to install in Z10. You will need to turn Development Mode On and select an easy to remember Password to be able to install the bar app.

The control program

The Blackbery 10 application controls Robo-51 from Inex, with the following Bluetooth send commands: Key letter “d” results in forward movement of the robot, “a” in backward, “c” in turning leftward, “b” in turning rightward and “s” in stopping.  With the BlackBerry phone in landscape mode, tilting the phone forward, backward, to right or to left, the smartphone  sends these commands to Robo-51 in order to control it. The following image of the BlackBerry shows the app’s icon (inside the red square) after it has been installed:

IMG_20140602_182139

Pairing the Bluetooth module to Blackberry

Before running the application, you will need to pair the Bluetooth module on Robo-51 with your BlackBery’s Bluetooth:

IMG_20140521_131527

 

Running the App

Next, when you run the app you will need to tell it which paired devices, your BlackBerry will it talk to by clicking Select Device:

IMG_20140602_182159

Which in our case is the Spp device which you will select by clicking on it:

IMG_20140602_182217

Note MAC addresses are not shown at all as I have blurred them. You will see your MAC addresses.

We will then connect, clicking the Connect button:

IMG_20140602_182733

I have blurred the MAC addresses of my Bluetooth modules. Your will have your own MAC addresses. Once connected you will hear “I’m Robo-51 I’m at your command” and the screen will show the button Disconnect:

IMG_20140602_182241

After clicking twice over Start button, you can control the robot tilting the phone forward, backward, to the right or to the left. Clicking twice over the Start/Stop button will stop the robot. At slightest tilt of the phone, the robot will move again

After you have played with the control of the robot, you can disconnect by clicking on Disconnect button on top right of BlackBerry screen. Clicking More at bottom right of your phone’s screen you will see the option to close the app:

IMG_20140602_182654

By clicking Stop this application you will have be asked if you want to continue or go back to application:

IMG_20140602_182702

Video demonstration

The following Youtube video demonstrates accelerometer on my BlackBerry 10 smartphone (Z10 4G LTE) controlling the robot (Robo-51) :

Conclusion

This project adds a new feature into existing Robo-51 projects. We have shown that the accelerometer in BlackBerry 10 can interact with external world, in this case a Robot. I can now tick as successful this project on acceleration sensor in BlackBerry 10.

Posted in Mobile Apps, Robotic Projects | Tagged , , , , , , , , , | Leave a comment

Blackberry 10 Remote Temperature Viewing and Listening

Introduction

“The BlackBerry runtime for Android keeps getting sweeter”, as BlackBerry Developper site says. The documentation on BlackBerry’s site includes a collection of resources that discuss how one can use the BlackBerry Tools for Android development to repackage, and port one’s Android apps to the BlackBerry 10 OS.

One has two options for porting one’s Android apps to the BlackBerry 10 OS. One can choose to take your existing Android APK files, and repackage them as BAR files that run on BlackBerry 10 devices, or one can develop one’s app from scratch using the BlackBerry 10 Native SDK.

Which option you choose will depend on many factors, including your app’s functionality when it has been repackaged as a BlackBerry 10 app. Before deciding which option to choose, we can use our repackaging tools to run a compatibility test on your APK file. This test allows us to assess the level of compatibility that our Android app has to the BlackBerry Runtime.

Our set up:

wiring2

Necessary material

You need the following boards:

frdm-kl25zchipKIT-BasicIOShield-obl-600

And Bluetooth adapter for PC, Bluetooth module and power supply unit, these last two for the boards:

sweex_bt                 jy_mcu       mb_102

– Freescale FRDM-KL25Z board
– Digilent BASIC I/O shield
– Power supply unit (MB-102)for the set up
– Mobile Processing software
– Class I or II Bluetooth adapter
– JY-MCU Bluetooth Module (available from Aliatron)

Pre-Requirements:

You must have already done:

  • Installation in Windows of your FRDM-KL25Z board.
  • Tested FRDM-KL25Z with simple exercise such as blinking the RGB LED on it

If you done neither of the two above exercises, you ought to follow the introduction“Getting Started with mbed and Freescale FRDM-KL25Z board”.

Also you must have done:

Temperature measurement with temperatur sensor TCN75A on Digilent Basic I/O shield.

And

Remote Viewing of Temperature with FRDM-KL25Z and TCN75A on Basic I/O Shield. (at least to point 9) Display the temperature on Terminal of PC)

Display the Temperature on a Blackberry 10 smartphone

I have written code for Android phone on MIT’s App Inventor Classic. The code is based on one written by kerimil at Instructables’ website.

I have modified kirimil’s code to read the incoming continuing string, and to split it into two variables, and made other minor adjustments, and given the project a new name TempMon. It is beyond the aim of this tutorial to teach how to write code for App Inventor. There is ample teaching material on the Web, if you are interested.

So, if you want to write code, or modify, or even import, I have made it available on Bitbucket kept at Bitbucket, an unlimited free private repositories’ site. You can download the zip file, and upload to App Inventor Classic’s website. Click here to download the code.

The Android App, TempMonitor.apk, can be downloaded, if you do not want to write code. It is again available at at Bitbucket repository.  Click here to download it.

Converting apk to bar

The downloaded apk will have to be uploaded to Good Reader’s website to convert into BB10 bar file. The link to apk2bar online converter is: http://apps.goodereader.com/apk-2-bar/. I have found Good Reader’s website to be friendly, and easy to use. If you are too lazy to go through the previous two step you can download the bar app clicking here. If eventually the bar app is not available at the link, you can download clicking here for the app at Bitbucket.

Side-loading the bar file into Blackberry 10 smartphone  

The following Good Reader’s link has a tutorial on how to install bar app into your Blackberry 10 smartphone (my app is optimized for Z10):

http://apps.goodereader.com/playbook/playbook-android-apps/?did=177

It has also a video on how to install in Z10. You will need to turn Development Mode On and select an easy to remember Password to be able to install the bar app.

BlackBerry 10 App

Once installed our App will look like this on App’s folder of BlackBerry 10 smartphone (the red square shows the App):

IMG_20140524_153351

Pair the Bluetooth module HC-06 to Blackberry 10

Before running the application, you will need to pair the Bluetooth module HC-06 with your BlackBerry’s Bluetooth. Tje PIN to pair is 1234.

Run the App

Next, when you run the app you will notice that the App is not connected to Bluetooth module:

IMG_20140524_153401

You need to tell the App to which paired devices to connect to by clicking Choose device to connect to button. A new screen will allow you to choose, which in our case is HC-06:

IMG_20140524_163259

Clicking HC-06 the device will be selected and you will see in top left of screen Connected in green colour letters. The local temperature will be read:

IMG_20140524_165411

 

You can listen to the local temperature as read by clicking Say temperature… button.

To close the App click the bottom right corner of screen with it says More. 

That’s all about it!

Video demonstration

The following video demonstrates the app and shows the electronic set up:

Conclusions

Our Android app works perfectly on Blackberry 10 phone and performs as it is expected. In fact the easiness with which one can convert Android apk’s into Blackberry 10 bar’s opens in Blackberry 10 smartphones the whole world of Android apps.

We can thus measure local temperature connecting our Blackberry 10 phone to a Bluetooth module (JY-MCU)  that transmits serial data from a microcontroller,  a Freescale FRDM-KL25Z board connected to a Digilent Basic I/O board containing a Microchip TCN75A temperature sensor.

 

Posted in Electronic Projects, Mobile Apps | Tagged , , , , , , , , | 1 Comment

BlackBerry 10 Basic Gestures of Swipe to Control a Robot

Introduction

BlackBerry 10 is a proprietary mobile operating system developed byBlackBerry Limited (formerly Research In Motion) for its BlackBerry line of smartphone and tablet handheld devices. Devices running BlackBerry 10 are the Q5Q10Z3Z10Z30 and the P’9982 smartphones. BlackBerry 10 is based on the QNX operating system, which is popular in industrial computers and used in many car computers, which was acquired by BlackBerry in April 2010.(1)

The BlackBerry 10 operating system uses an innovative combination of gestures and touches for navigation and control. These make a “back” button unnecessary and it is actually possible to enter all commands on the BlackBerry 10 operating system without having to press any of the physical buttons, with the exception of the power button that switches the device on/off.(1)

BlackBerry 10 introduced an Android runtime layer. This allows developers to easily package and distribute their applications designed to work on the Android platform. As of BB10.2, applications developed for Android 4.2.2 (Jelly Bean) and below are supported.(1)

Basic gesture of swipe to control movements of a robot can be quite interesting, and may add an intuitive interactive dimension to electronic projects.

I have published in this blog several tutorials on 8051-based robot controlled with Bluetooth-enabled cell phone. Some time ago I  published also two tutorials for Android phone one using button images on device’s touchscreen and another basic gestures of swipe on touchscreen.

Requirements

A 8051 robot “Robo-51” (could be a robot with any other micrcontroller) with serial bluetooth ZX-Bluetooth module, running a firmware for bluetooth control, and an account with App Inventor.

Robo-51

Inex´s Robo-51

ZX-Bluetooth

Inex’s ZX-Bluetooth Module

App Inventor Code

Our code is based on two codes BennyBlue and Swype routine both made with App Inventor .

To be able to control the robot you will need to download the source code file Bluemote2_2.zip kept at Bitbucket, an unlimited free private repositories’ site. If you already have an App Inventor folder, you can download the source code by scanning the following QR barcode:

qrcode_bluemote2

Downloading the Android apk

If you are absolute beginner with App Inventor, the excellent resources and tutorials found at MIT’s App Inventor site are very good and easy to follow. Once installed, the source code you will need to download the Android apk. The screen and app has been optimized for Z10 .

Converting apk to bar

The downloaded apk will have to be uploaded to Good Reader’s website to convert into BB10 bar file. The link to apk2bar online converter is:

http://apps.goodereader.com/apk-2-bar/

I have found Good Reader’s website to be friendly and easy to use. If you are too lazy to go through the previous two step you can download the bar app clicking here. If eventually the bar app is not available at the link, you can download clicking Bluemote2_2.bar kept at Bitbucket.

Side-loading the bar file into Blackberry 10 smartphone  

The following Good Reader’s link has a tutorial on how to install bar app into your Blackberry 10 smartphone (my app is optimized for Z10): http://apps.goodereader.com/playbook/playbook-android-apps/?did=177 It has also a video on how to install in Z10. You will need to turn Development Mode On and select an easy to remember Password to be able to install the bar app.

The control program

The Blackbery 10 application controls Robo-51 from Inex, with the following Bluetooth send commands: Key letter “d” results in forward movement of the robot, “a” in backward, “c” in turning leftward, “b” in turning rightward and “s” in stopping. Gestures on the screen of BlackBerry 10 send these commands to Robo-51 in order to control it. The following image of the BlackBerry shows the app’s icon (inside the red square) after it has been installed:

IMG_20140521_131358

 

Pairing the Bluetooth module to Blackberry

Before running the application, you will need to pair the Bluetooth module on Robo-51 with your BlackBery’s Bluetooth:

IMG_20140521_131527

 

Running the App

Next, when you run the app you will need to tell it which paired devices, your BlackBerry will it talk to by clicking Select Device:

IMG_20140521_202037

Which in our case is the Spp device which you will select by clicking on it:

IMG_20140521_204748

Note MAC addresses are not shown at all. You will see your MAC addresses.

We will then connect, clicking the Connect button:

IMG_20140521_131421

I have blurred the MAC addresses of my Bluetooth modules. Your will have your own MAC addresses. Once connected you will hear “I’m Robo-51 I’m at your command” and the screen will show the button Disconnect:

IMG_20140521_211144

You can control the robot with gestures of swipe with the finger to the left, or to the right, or forward (up finer swipe gesture) and backward (with down finger swipe gesture) , and you will hear in your Android phone voice of corresponding “forward”, “backward”, “turning left” etc. and the robot will move accordingly leftward, rightward, forward and backward. The Reset/Stop button will stop the robot.

After you have played with the control of the robot, you can disconnect by clicking on Disconnect button on top right of BlackBerry screen. Clicking More at bottom right of your phone’s screen you will see the option to close the app:

IMG_20140521_131438

By clicking Stop this application you will have be asked if you want to continue or go back to application:

IMG_20140521_131450

Video demonstration

The following Youtube video demonstrates basic swipe gestures on my BlackBerry 10 smartphone (Z10 4G LTE) controlling the robot (Robo-51) :

Conclusion

This project adds a new feature into existing Robo-51 projects. The main objective of this actual project was to achieve, with little work, similar results to those obtained with Java-based Nokia N97 and BlackBerry Bold 9700 and Android phones. I can now tick as successful this project on basic gestures of swipe for BlackBerry 10.

Posted in Mobile Apps, Robotic Projects | Tagged , , , , , , , , , , , | Leave a comment

Writing a Playbook App for Blockly, a Google’s Visual Programming Language

Introduction

Writing a Playbook App is an interesting proposition as BlackBerry’s WebWorks makes it so easy.  Currently the runtime for BlackBerry WebWorks on the BlackBerry smartphones is based on Java while that for the BlackBerry PlayBook is based on Adobe AIR. WebWorks is fully Open Sourced and is developed transparently. 

WebWorks is aligned with Apache CordovaWebWorks is also the main way to deliver WebGL-based applications. WebWorks repositories at GitHub include:

In the summer of 2010, Google released Blockly, a completely Visual Programming language that will let you build software without typing a single character.  It is reminiscent of Scratch, a platform developed at MIT that seeks to turn even young children into programmers.

You create programs by joining pieces together, and are restricted in the same way puzzle pieces are, by what fits where, just like Legos. This is an ingenious and easy to understand method of ensuring that the program is correct. It short cuts the process of having to learn correct syntax. If the pieces fit, the program works.

Blockly is something of an experiment in teaching people to program. Instead of having to learn the intricacies of a language like JavaScript, you can show Blockly to teenagers or even younger kids, and visually explain the concepts and engage their brains.

Requirements

Follow the tutorial published here in Redacacia blog Writing a “Resistor Code” App for BlackBerry Playbook up to Preparing our App. This tutorial will explain how to obtain BlackBerry’s Code Signing keys, as well as how to install debug token in your Playbook, a requirement to install the App that we will write next.

Preparing our App

We are now ready to write our App.  Our App will open Blockly Apps website at https://blockly-demo.appspot.com/static/apps/index.html. There are several Blockly Apps on that website that you can play with, and do some serious programming. My favourite App is Maze, but I have never managed to pass level 6.

Crackberry has a post with a a Youtube link that shows Tim Neil from RIM whipping together a basic CrackBerry.com App in 3 minutes. Actually it is quite easy to turn a website into a BlackBerry PlayBook app as we will do next.

a) Write config.xml 

Our App will have very basic structure. So here is the code for config.xml an important component for writing our App.

<?xml version=“1.0” encoding=“UTF-8”>
<widget xmlns=“http://www.w3.org/ns/widgets”
            xmlns:rim=“http://www.blackberry.com/ns/widgets”
            version=“1.0.0.1”>
      <author href=“https://redacacia.me/”; email=“tayeb.habib@gmail.com”
      rim:copyright=“Copyright 2014 Aliatron”>Aliatron</author>
      <name>Blockly Apps</name>
      <icon src=“images/icon.png” />
      <content src=“https://blockly-demo.appspot.com/static/apps/index.html”>
      <access uri=“https://blockly-demo.appspot.com/static/apps/” subdomains=“true”>
      <feature id=“blackberry.ui.dialog” />
      <feature id=“blackberry.app.event”/>
      <feature id=“blackberry.invoke”/>
      <license>
          Copyright (c) 2014 Tayeb Habib
          THE SOFTWARE IS PROVIDED &quot;AS IS&quot;, WITHOUT WARRANTY OF ANY KIND,
          EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
          OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
          NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
          HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
          WHETHER IN AN ACTION OF CONTRACT, INSULT OR OTHERWISE, ARISING
          FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
          OTHER DEALINGS IN THE SOFTWARE.
      </license>
</widget>

b) Create a zip file

Next, we need to prepare an icon, that must have 82×82 pixels and save as icon.png. Once this is done, we will create a zipped file blockly.zip which will contain config.xml and an images folder with icon.png as the following image shows:

zip_image

To make it easy for this tutorial you can use my zipped file blockly.zip which you can download from Bitbucket, an unlimited free private repositories’ site.

c) Compile a bar file

To avoid error unknown protocol: c you need to first create a temp directory in your C: drive (if you don’t have it already) and then issue the following commands in your DOS terminal:

SET TEMP =C:\TEMP
SET TMP=C:\TEMP

This solution was found at Blackberry’s Discussion Forum. I did not find any alternative solution yet.

So let us compile blockly.zip and output as blockly.bar. Go to your  DOS terminal and navigate to your PlayBook WebWorks SDK

cd C:\Program Files\Research In Motion\BlackBerry WebWorks SDK for TabletOS 2.2.0.5\bbwp

To make it easy, create a directory myapp, and a sub-directory inside called output.  Drop blockly.zip file into myapp directory (or one that you modded) and run the DOS command:

bbwp c:\myapp\blockly.zip -d -o c:\myapp\output

The results will be similar to ones as follows (I have blockly.zip in my c:\ drive’s bb folder and output to blockly folder:

compiling

If you check your output directory, you will now find blockly.bar.

Install and run the App

Now we will deploy this App in our Playbook. Navigate to tablet-sdk with the following DOS command:

cd blackberry-tablet-sdk\bin

Run the following command to install the App:

blackberry-deploy -installApp -password 123 -device (your Playbook IP) -package c:\myapp\output\blockly.bar

Hopefully it will install itself correctly, and you will see the reassuring icon in your Playbook:

IMG_00000033

If you run this App, and wireless connection to your router with Internet is not available, or if you have not tethered your PlayBook to your BlackBerry phone to share Internet connections, you will get the following message (in english or in your PlayBook’s default language, of course):

IMG_00000032

So, if your PlayBook is connected to Internet you will be greeted with the following screen:

IMG_00000034

You can use any of Apps. Here is an image of Maze app working:

IMG_00000029

I will not show you how each of apps work. You can change the language, for example. Blockly is translated into numerous world languages.

One final consideration: The link shown of  Googlecode’s site does not work. I have done it for obvious reasons.

IMG_00000031

If you want to learn how each of the apps works I suggest you check around the Web. There is enormous amount of teaching material from Educators, and others interested in Blockly, and Visual Programming languages.

Conclusions

I have shown how easy it is to integrate a webpage into an App with BlackBerry’s WebWorks. Blockly, Google’s Visual Programming language, is quite powerful and it has lots of potential to be more and more widely used so an App for PlayBook is an interesting proposition. To make your App permanent, you will need to sign your blockly.bar file and re-install it. I leave it to you to do this exercise.

Posted in Mobile Apps, Programming | Tagged , , , , , , , , | Leave a comment

Remote Viewing of Temperature with FRDM-KL25Z and TCN75A on Basic I/O Shield

Introduction

The Freescale FRDM-KL25Z board is an ultra-low-cost development platform for Kinetis L Series KL1x (KL14/15) and KL2x (KL24/25) MCUs built on ARM® Cortex™-M0+ processor. Features include easy access to MCU I/O, battery-ready, low-power operation, a standard-based form factor with expansion board options and a built-in debug interface for flash programming and run-control. The FRDM-KL25Z is supported by a range of Freescale and third-party development software, including mbed platform.

The Digilent Basic I/O shield  is an input/output expansion board designed for use with chipKIT microcontroller boards such as the Uno32™ and the Max32™.

The Basic I/O Shield provides simple digital input devices such as switches and buttons, and digital output devices such as discrete LEDs and high current open FET drivers. It provides more advanced devices such as an I2C EEPROM, an I2C temperature sensor, and organic LED graphic display. A potentiometer is also provided for use as an analog input device.  The Basic I/O Shield is designed to the same form factor as the Uno32 board, but is also usable with the FRDM-KL25Z board.

Remote viewing is an interesting proposition that we will dwell upon here with these two boards, and some extra material, such as a Bluetooth module and, at the end, Bluetooth-enabled phones.

Pre-Requirements:

You must have already done:

  • Installation in Windows of your FRDM-KL25Z board.
  • Tested FRDM-KL25Z with simple exercise such as blinking the RGB LED on it

If you done neither of the two above exercises, you ought to follow the introduction“Getting Started with mbed and Freescale FRDM-KL25Z board”.

Also you must have done temperature measurement with temperatur sensor TCN75A on Digilent Basic I/O shield.

Necessary material

You need the following boards:

frdm-kl25zchipKIT-BasicIOShield-obl-600

And Bluetooth adapter, Buletooth module and power supply unit:

sweex_bt                 jy_mcu       mb_102

– Freescale FRDM-KL25Z board
– Digilent BASIC I/O shield
Power supply unit (MB-102)for the set up
– Mobile Processing software
– Class I or II Bluetooth adapter
– JY-MCU Bluetooth Module (available from Aliatron)

Procedures:

1 – Preparing our programming setup

The following connections will allow us to program the mbed board, and to prepare it

wiring1

FRDM KL-25Z board is going to communicate with Microchip’s TCN75A temperature sensor on Digilent Basic I/O Shield.

2. Connect your mbed-enabled FRDM-KL25Z to your PC

Use the USB lead to connect your FRDM-KL25Z to a PC, using the USB female connector labelled OpenSDA.

frdm_open_sda

The status light will come on, indicating FRDM-KL25Z has power. After a few seconds of activity, your PC will recognise the mbed Microcontroller as a standard USB drive.

3. Visit the mbed website to get logged in, and to compile

The URL for mbed website is:

http://mbed.org

Log in with your normal username and password.  This will give you access to the website, tools, libraries and documentation.

4. Open the mbed Compiler 

Open the IOShield_Temp program and edit main.cpp (that you may have already written before) 

Write the following code (just copy and paste):


int main() {
   char cmd[2];
   while (1) {
      cmd[0] = 0x01;
      cmd[1] = 0x00;
      i2c.write(addr, cmd, 2);

      cmd[0] = 0x00;
      i2c.write(addr, cmd, 1);
      i2c.read(addr, cmd, 2);

      float tmpC = (float((cmd[0]&lt;&lt;8)|cmd[1]) / 256.0);
      float tmpF = (float(9.0*tmpC)/5.0 + 32.0);
      // convert Centigrade into Fahrenheit
      pc.printf(&quot;%.2f&quot;, tmpC);
      pc.printf(&quot;,&quot;);
      // comma (,) separator necessary for string splitting
      pc.printf(&quot;%.2f&quot;, tmpF);
      pc.printf(&quot;&quot;);
      // somehow this extra line makes the reading more stable
      wait(0.5); // wait 0.5s
   }
}

Before anything else save your code.

5. Compile and Download the Program

To compile the program, click the Compile button in the top toolbar.

tut21This will compile the program source code files within the program folder.

compiling

And a binary program will be created.

  • After a successful compile, you will get a Success! message in the compiler output, and the download dialog will pop up to Save the binary program, or it will be automatically downloaded to your PC’s default Downloads folder. If you can Save, save it directly to FRDM-KL25Z board (acting as a drive), otherwise drag and drop, or cut and paste into your FRDM-KL25Z.

tut24

If everything goes well, FRDM-KL25Z is programmed. Power reset your FRDM-KL25Z.

6. Display the temperature on Terminal of PC

Launch a Terminal program such as Putty, or Termite.  Ensure that the configuration settings of the port are  Baud Rate 9600, Data bits 8, Stop bits 1, Parity none, Flow Controlnone. My port number is COM23 as can be seen (Termite’s port settings). 

tcn75f

My FRDM-KL25Z board is connected to  port 23. The port number can be seen at Device Manager of your Windows.

You will see immediately the temperature values being displayed:

terminal2

We are now ready to add the Bluetooth connection.

7. Final setup

Connect up the boards, JY-MCU Bluetooth module, and power supply as shown:

wiring2

My actual set up looks like as the photo shows:

bt_temp_monitor

Note: the power supply and the way to connect the voltage supply is just my proposition. You can connect power supply in other ways.

Once the set up is powered you will see a blue LED blinking on your JY-MCU module.

Basic I/O shield must be installed on top of FRDM-KL25Z.

8 – Bluetooth installation in your PC

You must have your bluetooth adapter duly installed in your PC. My PC’s Bluetooth Sweex adapter shows in my sytem tray a bluetooth symbol. After activating bluetooth, I have the option to find the local bluetooth connections:

bt_Image1

Do a search, and eventually you will find HC-06 (default name of JY-MCU module, a name that can be changed if required):

hc06_detected

Next, we will connect to JY-MCU bluetooth module (found in my PC in COM31):


hc06_pairing_procedure

You will need to introduce the password which is ‘1234’:

hc06_pairing_request

I have blurred the MAC address of my bluetooth module. After introducing the password, click the OK button. You will see HC-06 connection as paired.

hc06_paired

We next connect HC-06 to the serial port of your PC (in my case it is COM31):

hc06_port

The HC-06 icon will now change to green:

hc06_connected

9) Display the temperature on Terminal of PC

We are ready to run the Terminal program.  Ensure that the configuration settings of the port are  Baud Rate 9600, Data bits 8, Stop bits 1, Parity none, Flow Control none. My port number is correct (in my case it is COM31).  The result will be displayed as:

terminal3

Having tested remote readings of temperature, we are now ready to write Apps for Bluetooth-enabled cellphones that will read the temperatures.

10) Display the temperatures on cellphones

The aim now is to display the temperature in a convenient way on:

Android phone / tablet
Blackberry phone

a) For Android, I have written code on MIT’s App Inventor Classic. The code is based on one written by kerimil at Instructables’ website.

I have modified kirimil’s code to read the incoming continuing string, and to split it into two variables, and made other minor adjustments, and given the project new name TempMon. It is beyond the aims of this tutorial to teach how to write code for App Inventor. There is ample teaching material on the Web, if you are interested.

So, if you want to write code, or modify, or even import, I have made it available on Bitbucket kept at Bitbucket, an unlimited free private repositories’ site. You can download the zip file, and upload to App Inventor Classic’s website. Click here to download the code.

The Android App, TempMonitor.apk, can be downloaded, if you do not want to write code. It is again available at at Bitbucket repository.  Click here to download it.

I assume you know how to upload, and to install an Android app. Once installed you will need to launch the App, but before that you need to enable Bluetooth in your Android phone, and to pair the JY-MCU module to your Android phone.

screenshot_0124150535

Next pair JY-MCU after searching for it, by pressing onto HC-06, and choosing to pair.

Introduce 1234 to pair, and click OK

bt_pair

You will see that JY-MCU (named as HC-06) is paired:

bt_paired2

Now you are ready to launch the App which will be in your Android’s Apps folder:

screenshot_0124150211

You will be greeted with following screen:

screen1

Click Choose device to connect to button, in next screen, click onto MAC address of your HC-06 (I have blurred the MAC Address of my device).

screen2 On clicking, you will see the first screen on top and you will see that the device is connected, and the temperature will be displayed in ºC and ºF

screen3

You can hear the temperature, by clicking Say temperature button.

b) For Blackberry (not BB10, but previous ones with Java OS – mine is Blackberry 9900) I have written code in Mobile Processing. f you do not know how to write Blackberry Apps in Mobile Processing, I suggest you follow my tutorial published here in this blog Write a Drawing App “myArtwork” for Blackberry with Social Networking Sharing Capability. You will need Mobile Processing, that you can download from Mobile Processing website.

You’ll also need a slightly patched Mobile Processing Bluetooth library:mobileprocessing-bluetooth-patched.zip.  In the “libraries” directory of the Mobile Processing application, move the existing “bluetooth” library directory out of the way and unzip the above zipfile in its place.

The processing sketch is as follows:


import processing.bluetooth.*;
import processing.phone.*;

Bluetooth bt; //new bt device
Service[] services;

PFont font;

int state;
String msg;
String DEGREE = &quot;\u00b0&quot;; //to display correctly degrees symbol
Client c;

final int STATE_START = 0; //different states, similiar to events.
final int STATE_FIND = 1; //find devices
final int STATE_HOST = 2;
final int STATE_PLAY = 3; //once connected to device

byte[] inBuffer = new byte[11]; //store the bytes read from mBed in array.
//For the temperature sensor, there are only 11 digits

int counter;

void setup() {
font = loadFont();
textFont(font);
bt = new Bluetooth(this, Bluetooth.UUID_SERIALPORT);

counter = 1;
}

void draw() {
background(255);

if (state == STATE_START) {
fill(0);
textAlign(LEFT);
text(&quot;Welcome to mBed Bluetooth TempMon.\n\nFind device...\nPre   ss any key&quot;, 2, 2, width - 4, height - 4);
}
else if (state == STATE_FIND) {
fill(0);
textAlign(LEFT);
if (services == null) {
text(&quot;Looking for SPP device...\n\n&quot; + msg, 2, 2, width - 4, he   ight - 4);
}
else {
String list = &quot;SPP device found\n\n&quot;;
for (int i = 0, length = length(services); i &lt; length; i++) {
list += i + &quot;. &quot; + services[i].device.address + &quot;\n&quot;; //this will list discovered devices
}
text(list, 2, 2, width - 4, height - 4);
}
}
else if (state == STATE_PLAY) {
c.readBytes(inBuffer); //Assigning assign the readBytes data into the inBuffer array for storing.
String inB2 = new String(inBuffer); //change the byte values into strings data int chars = inBuffer.length();
String[] dat = split(inB2, ','); // parse comma-separated number string into numbers
if (inBuffer != null) {
String data = dat[0] + DEGREE + &quot;C / &quot; + dat[1] + DEGREE + &quot;F&quot; ;
text(&quot;Local Temperature:\n&quot; + data, 2, 2, width - 4, height - 4); //draw the message
}
text(&quot;Local Temperature:\n&quot;, 2, 2, width - 4, height - 4);
}
}

void libraryEvent(Object library, int event, Object data) {
if (library == bt) {
switch (event) {
case Bluetooth.EVENT_DISCOVER_DEVICE:
msg = &quot;Found device at: &quot; + ((Device) data).address + &quot;...&quot;;
break;
case Bluetooth.EVENT_DISCOVER_DEVICE_COMPLETED:
msg = &quot;Found &quot; + length((Device[]) data) + &quot; devices, looking for service...&quot;;
break;
case Bluetooth.EVENT_DISCOVER_SERVICE:
msg = &quot;Found SPP service on &quot; + ((Service[]) data)[0].device.address + &quot;...&quot;;
break;
case Bluetooth.EVENT_DISCOVER_SERVICE_COMPLETED:
services = (Service[]) data;
msg = &quot;Search complete.&quot;;
break;
case Bluetooth.EVENT_CLIENT_CONNECTED:
c = (Client) data;
state = STATE_PLAY;
break;
}
}
}

void keyPressed() {
if (state == STATE_START) {
//if any key is pressed.
services = null; // it will begin the search
bt.find(); //bt.find goes through the whole process of bluetooth searching
state = STATE_FIND;
msg = &quot;Looking for devices...&quot;;
}
else if (state == STATE_FIND) { //this section will help connect to which device is found
if (services != null) {
if ((key &gt;= '0') &amp;&amp; (key &amp;lt;= '9')) {
int i = key - '0';
if (i &lt; length(services)) {
msg = &quot;connecting...&quot;;
c = services[i].connect();
state = STATE_PLAY;
msg = &quot;ready&quot;;
}
}
}
}
}
void destroy() {
bt.stop();
}

catch (java.io.IOException err)
{
}
catch (java.lang.SecurityException e)
{
}
catch (java.lang.IllegalArgumentException iae)
{
}
catch (IOException ioe)&lt;/pre&gt;
{
}

You will now save the project with a name such as TempMon with  File->Save As in the main dropdown menu.

Before proceeding, you will create an Icon for our App. It needs to be 62×62 pixels.  You can download here an icon we have designed, together with pde file of above code. The file is hosted by Bitbucket. Bitbucket offers unlimited public and private repositories, and it is free for small teams. In your PC’s My Documents -> MobileProcessing ->TempMon folder paste data folder that includes icon image file icon.png and TempMon.pde sketch (Mobile Processing and other Processing codes are known as ‘sketches’).

Export as MIDlet with File-> Export MIDlet:

mp1

The MIDlet will be created and your PC´s My Documents -> MobileProcessing ->TempMon -> MIDlet folder (will open automatically to show TempMon.jadTempMon.jar and My Documents -> MobileProcessing ->TempMon.java files:

mp2

Note: If you care to check TempMon folder you will also see a new folder proguard.ProGuard is included in Mobile Processing to make the apps smaller, and more efficient jar files. We will not use the jad and jar files in this folder.

We are now ready to copy TempMon.jad and TempMon.jar into the Blackberry.

After connecting your Blackberry to your PC with USB cable, run Blackberry Desktop software and choose Files:

ma_img14

Click the Start button. You will see the next screen:

ma_img15

In your PCs folder MIDlet folder select TempMon.jad and TempMon.jar files:

mp3

And with right click of your mouse button Copy these files, and paste them into theBlackberry Desktop folder you have just opened:

Both files will be now in your Blackberry phone’s documents folder.

NOTE: If you are too lazy to write code you can  install jad and jad files found here  (after unzipping) into your Blackberry as shown. Note jad and jar files are hosted at Bitbucket, a free and unlimited public and private repositories hosting site.

Now disconnect the USB cable between your Blackberry and your PC. In your Blackberry go to All group of folders, and choose Applications folder:

mp4

Open the folder, and select Files folder:

Screen_20140422_041416

Open the Files folder and navigate to the documents folder. In my Blackberry, I found it in File Folders -> Device -> home -> user. In documents folder within user folder, you will find TempMon.jad and TempMon.jar .  Select TempMon.jad and click on it:

Screen_20140422_041520

You will see the next screen:

Screen_20140422_041539

Click the Download button. Our app will start to be installed. You will get next a warning window that the application does not contain a signature, just click Yes and let the App be installed. If successful, you will be invited to immediately Run it. 

Once installed, the App’s icon will be as show below:

Screen_20140422_041622

Make sure your Blackberry is paired to HC-06 (the name of JY-MCU Bluetooth module). The password is 1234. 

Run the App, and if everything is alright you will see the following screen:

Screen_20140422_134248

Conclusions

We have achieved remote temperature viewing of temperature read by our Freescale FRDM-KL25Z board from the temperature sensor Microchip TCN75A on Digilent Basic I/O shield.

We have used App Inventor Classic and Mobile Processing to read remotely temperature on two smartphones, respectively Android and Blackberry.

I shall appreciate any comments, and suggestions.  I will also appreciate if you point out  any errors or omissions in this tutorial.

Posted in Electronic Projects | Tagged , , , , , , , , , , , , , , , | 1 Comment

Temperature measurement with Freescale FRDM-KL25Z and TCN75A on Digilent Basic I/O shield

Introduction

The Freescale FRDM-KL25Z board is an ultra-low-cost development platform forKinetis L Series KL1x (KL14/15) and KL2x (KL24/25) MCUs built on ARM® Cortex™-M0+ processor. Features include easy access to MCU I/O, battery-ready, low-power operation, a standard-based form factor with expansion board options and a built-in debug interface for flash programming and run-control. The FRDM-KL25Z is supported by a range of Freescale and third-party development software, including mbed platform.

The Digilent Basic I/O shield  is an input/output expansion board designed for use with chipKIT microcontroller boards such as the Uno32™ and the Max32™.

The Basic I/O Shield provides simple digital input devices such as switches and buttons, and digital output devices such as discrete LEDs and high current open FET drivers. It provides more advanced devices such as an I2C EEPROM, an I2C temperature sensor, and organic LED graphic display. A potentiometer is also provided for use as an analog input device.  The Basic I/O Shield is designed to the same form factor as the Uno32 board, but is also usable with the FRDM-KL25Z board.

Objectives

  • Connect the mbed-enabled Freescale Freedom FRDM-KL25Z board to the Digilent Basic I/O shield
  • Write the code for displaying the temperature reas by Microchip’s TCN75A I2C temperature sensor on the Digilent Basic I/O shield.

Required Equipment

The following boards are required:

frdm-kl25z

Freescale FRDM-KL25Z board

chipKIT-BasicIOShield-obl-600

Digilent Basic I/O shield

It is strongly recommended to solder headers on FRDM-KL25Z as they will be required to connect up with the Basic I/O shield.

Pre-Conditions

You must have already done:

  • Installation in Windows of your FRDM-KL25Z board.
  • The test of FRDM-KL25Z with simple exercise such as blinking the RGB LED.

If you done neither of the two above exercises, you ought to folow the introduction “Getting Started with mbed and Freescale FRDM-KL25Z board”.

Procedures

1) Wire up your boards

The following connections are recommended for this tutorial:

Wiring diagram

Connections between FRDM-KL25Z and Basic I/O shield

FRDM KL-25Z board is going to communicate with Microchip’s TCN75A temperature sensor on the Basic I/O Shield.  The circuit diagram of temperature sensor TCN75A is:

tcn75a

Circuit diagram of TCN75A on Basic I/O Shield

2. Connect your mbed-enabled FRDM-KL25Z to your PC

Use the USB lead to connect your KL25Z to a PC, using the USB connector labelledOpenSDA.

OpenSDA connector on FRDM-KL25Z

FRDM-KL25Z board. Red rectangle shows poaition of OpenSDA USB connector

The status light will come on, indicating it has power. After a few seconds of activity, the PC will recognise the mbed Microcontroller as a standard USB drive.

3. Visit the mbed website to get logged in and to compile

The URL for mbed website is:

http://mbed.org

Log in with your normal username and password.  This will give you access to the website, tools, libraries and documentation.

Logged in

Already logged in

4. Open the mbed Compiler 

Open the online Compiler clicking the Compiler button in the site menu (top-right of the page). This will open the Compiler in a new tab or window.

Showing logged in

Red rectagnle shows the option to be chosen, and red arrow shows already logged in

NOTE: It will be your chosen name that will appear as logged in, obviously!

5. Write a new  program

To write a new program in your personal Program Workspace:

  • Right-click on My Programs, and select New Program…
tut10

Adding “New Program…” in Program Workspace

  • Enter the name of the new program (e.g. IOShield_Temp), and click OK

Your new program folder will be created under My Programs

6. Add a source code to the program

  • Add a new file by right clicking on IOShield_Temp program name. Give it the name of main.cpp.
Create a new file

Pop up window to create a new file name

After adding new file, click on the main.cpp file in your new program, to open it in the file editor window. This is the main source code file in your program, and by default it is empty. Write the following program.


#include "mbed.h"

I2C i2c(PTC9, PTC8);
Serial pc(USBTX, USBRX); // tx, rx
const int addr = 0x90;

int main() {
     char cmd[2];
     while (1) {
        cmd[0] = 0x01;
        cmd[1] = 0x00;
        i2c.write(addr, cmd, 2);

        wait(0.5);

        cmd[0] = 0x00;
        i2c.write(addr, cmd, 1);
        i2c.read(addr, cmd, 2);

        float tmp = (float((cmd[0]<<8)|cmd[1]) / 256.0);
        pc.printf("Temp = %.2f\n", tmp);
     }
}

The result will be as shown:

tcn75b

It is always a good idea to comment your code.  I have commented acknowledging the source of the code (in this case, the code was not written by me, although it is not “rocket science” and is used as an example of I2C code at mbed website).

  • Add mbed library to the program folder

The other item in the program folder is the mbed library – this provides all the useful functions to start up and control the mbed Microcontroller, such as the I2C interface used in this example. Right-click on IOShield_Temp, choose Import Library… and From Import Wizard…

 Choose mbed library and then click on Import button on the top right-side.

Import library

Import mbed library

Our Program Workspace will show that mbed library has been added to  IOShield_Temp  program.

7. Compile and Download the Program

To compile the program, click the Compile button in the top toolbar.

Compile button

Compile button

This will compile the program source code files within the program folder.

Compiling...

Compiling the code

And a binary program wil be created.

  • After a successful compile, you will get a Success! message in the compiler output and the download dialog will pop up to Save the binary program, or it will be automatically downloaded to your default Downloads folder.
Successful compilation

Compiler output for IOShield_Temp

  • Save it to the location of your PC in case of download dialog pop up.

NOTE: In Goggle’s Chrome browser, the compiled file will be downloaded to Downloads folder.

tcn75e

Compiler output for IOShield_temp in Downloads folder of PC

NOTE: If there are errors, they will show up in the “Compiler Output” window, and will need to be fixed!

  • FRDM-KL25Z behaves a drive, so you find it in My Computer of your PC.
FRDM-KL25Z in My Computer

FRDM-KL25Z behaves as a drive in My Computer

  • Cut, or drag, the IOShield_Temp_KL25Z.bin file in your PC’s Downloads folder and paste, or drop, in the mbed Microcontroller folder, wait a few seconds for the drive folder to close automatically, and then hit reset on the microcontroller to start it running!

If everything goes well, FRDM-KL25Z is programmed.

7. Display the temperature

Launch a Terminal program such as Putty, or Termite.  Ensure that the configuration settings of the port are  Baud Rate 9600, Data bits 8, Stop bits 1, Parity none, Flow Control none. My port number is COM23 as can be seen (Termite’s port settings). 

Settings

Serial port settings

My FRDM KL-25Z board is connected to  port 23. The port number can be seen at Device Manager of your Windows.

You will see immediately the temperature values being displayed:

Output

Temperature output

As shown on above figure, once the program is running, the temperature is displayed. Now by putting your finger on the TCN75A sensor on the Basic I/O Shield, it is possible to raise the temperature and to view its value.

tcn75h

TCN75A on Basic I/O shield

Conclusions

Mbed offers the development environment — editor, compiler, libraries and reference materials — entirely on the web. There is no software to install or maintain on the host system. With quick proof-of-concept solutions such as Basic I/O shield we can easily test our ideas and projects.

We have the read the temperature writing code for FRDM-KL25Z board. The same system could be used to control fans or other items in a house based on specific temperatures.

Posted in Electronic Projects | Tagged , , , , , , , | 1 Comment

Getting Started with mbed and Freescale FRDM-KL25Z board

Introduction

mbed is a platform for developing smart devices that are based on 32-bit ARM Cortex-M microcontrollers. It is designed to provide a highly productive solution for rapid prototyping and product development, with a focus on connected Internet of Things devices.

It is a project developed by ARM, its technology partners and a community of core developers, and it is used by tens of thousands of professional developers to create intelligent products that take advantage of the power of modern microcontrollers and connectivity. (Source).

The Freescale FRDM-KL25Z board is an ultra-low-cost development platform forKinetis L Series KL1x (KL14/15) and KL2x (KL24/25) MCUs built on ARM® Cortex™-M0+ processor. Features include easy access to MCU I/O, battery-ready, low-power operation, a standard-based form factor with expansion board options and a built-in debug interface for flash programming and run-control. The FRDM-KL25Z is supported by a range of Freescale and third-party development software, including mbed platform.

Objectives

This tutorial guides you through mbed-enabled Freescale Freedom FRDM-KL25Z board, and getting started with the mbed online tools platform. An mbed-enabled FRDM-KL25Z board gives you:

  • USB drag and drop programming
  • USB Virtual COM port for serial terminal
  • CMSIS-DAP interface for programming and debugging from offline tools
  • Free access to the mbed online compiler, mbed C/C++ SDK, and developer community

It is assumed from now on that you have a Freescale  FRDM-KL25Z board and that it is already mbed-enabled.

It is really simple to setup and program, and it is free, so let us get started!

Procedures

1. Connect your mbed-enabled FRDM-KL25Z to your PC

 Use the USB lead to connect your KL25Z to a PC, using the USB connector labelled OpenSDA.

frdm_open_sda

FRDM-KL25Z board. Red square shows poaition of OpenSDA USB connector

The status light will come on, indicating it has power. After a few seconds of activity, the PC will recognise the mbed Microcontroller as a standard USB drive. Also your PC will detect that a driver is needed.

2. Install the drivers in your PC

After your PC detecting the FRDM-KL25Z board, it will invite you to install drivers, Choose the second option of Advanced installation of driver as shown.

installation of drivers

Windows’ requirement for a driver. The red rectangle shows Advanced installation

Note: This installation is under Windows XP in portuguese, your Windows will take you through similar procedures.  

Click Next and choose to find the driver (by this time most certainly FRDM-KL25Z is recognised as a drive).

Installation of drivers

Red rectangles show the option to use a location and FRDM-KL25Z as drive

The required drivers are included in FRDM-KL25Z’s flash memory. Install the drivers, following all the normal steps of installation.

Install the drivers, following all the normal steps of installation.

NOTE: You may be warned that the driver is not officially recognised to be compatible with Windows. You will need to accept it as trustworthy.

Warning!

Warning of  driver incompatability to be ignored

troubleshooting

3. Visit the mbed website to get logged in and to compile

The URL for mbed website is:

http://mbed.org

If you do not have an mbed account, choose “Signup”, and create your mbed Account. Otherwise, log in with your normal username and password.

Logi

Login or signup at left corner of page

Login will give you access to the website, tools, libraries and documentation.

On top left of Home page you will see the menu where you will choose your platform by clicking on Platforms button.

Platforms option

Red rectangle indicates Platforms option of menu

Now choose the right Platform that for this case is FRDM-KL25Z, by clicking on this option.

FRDM-KL25Z platform

Blue rectangle indicates Platform option to be chosen for FRDM-KL25Z

Having chosen the Platform, you will now add your FRDM-KL25Z board to your Compiler. 

Adding the board

Red rectangle shows the option to be chosen for adding the board

After adding the board to the Compiler you are ready to compile your first code.

4. Open the mbed Compiler 

Open the online Compiler clicking the Compiler button in the site menu (top-right of the page). This will open the Compiler in a new tab or window.

Open the compiler

Red rectagnle shows the option to be chosen, and red arrow shows already logged in

NOTE: It will be your chosen name that will appear as logged in, obviously!

5. Write a New Program

To create a new program in your personal Program Workspace:

  • Right-click on My Programs, and select New Program…
New program

Adding “New Program…” in Program Workshpace

  • Enter the name of the new program (e.g. “HelloWorld”), and click OK
Write name

Pop up window to create new program name

Your new program folder will be created under My Programs

6. Add a source code to the program

Add a new file by right clicking on HelloWorld program name.

New file

Adding “New File…” to “HelloWorld” program name

  • Enter the name of the new file main.cpp and click OK.
tut13

Pop up window to create new file name

After adding new file, click on the main.cpp file in your new program, to open it in the file editor window. This is the main source code file in your program, and by default it is empty. Write the following program.

#include "mbed.h"
DigitalOut myled(LED1);
int main() {
    while(1) {
        myled = 1;
        wait(0.2);
        myled = 0;
        wait(0.2);
    }
}

The result will be as shown:

Code

Code in main.cpp file

  • Adding mbed library to the program folder

The other item in the program folder is the mbed library – this provides all the useful functions to start up and control the mbed Microcontroller, such as the DigitalOut interface used in this example. Right-click on HelloWorld, choose Import Library… and From Import Wizard…

Importing library

Import library wizard

Now choose mbed library and then click on Import button on the top right-side.

med library

Import mbed library

Program Workspace will show that mbed library has been added to HelloWorld program.

tut20

Program Workspace with HelloWorld and main.cpp file and mbed library

In our main.cpp file LED1 stands for red colour LED on the FRDM-KL25Z. Before proceeding any further, make changes to second line at the end of DigitalOut command, substituting LED1 with LED3. On the right-side of editor you will see the Enumerator telling you that LED3 corresponds to blue LED on FRDM-KL25 RGB LED.

Enumerator

LED3 enumerator indicating what it corresponds  to

Our main.cpp file’s content will be now:

#include "mbed.h"
DigitalOut myled(LED1);
int main() {
    while(1) {
        myled = 1;
        wait(0.2);
        myled = 0;
        wait(0.2);
    }
}

Before proceeding save main.cpp file by right-clicking on it, and choosing the option Save…

7. Compile and Download the Program

To compile the program, click the Compile button in the top toolbar.

Compile button

Compile button

This will compile all the program source code files within the program folder to create a binary program.

Compiling

Compiling “HelloWorld” program

  • After a successful compile, you will get a Success! message in the compiler output and the download dialog will pop up to Save the binary program, or it will be automatically downloaded to your default Downloads folder.
Success!

Compiler output for “HelloWorld”

  • Save it to the location of your PC in case of download dialog pop up.

NOTE: In Goggle’s Chrome browser, the compiled file will be downloaded to Downloads folder.

PC folder

Compiler output for “HelloWorld” in Downloads folder of PC

NOTE: If there are errors, they will show up in the “Compiler Output” window, and will need to be fixed!

  • FRDM-KL25Z behaves a drive, so you find it in My Computer of your PC.
FRDM-KL25Z as a drive

FRDM-KL25Z as a drive in My Computer

  • Cut, or drag, the HelloWorld_KL25Z.bin file in your PC’s Downloads folder and paste, or drop, in the mbed Microcontroller folder, wait a few seconds for the drive folder to close automatically, and then hit reset on the microcontroller to start it running!

If everything goes well, FRDM-KL25Z is programmed and the blue LED on RGB LED on FRDM-KL25Z will blink!

Main source of this tutorial is mbed.org website, specially the Handbook section at: https://mbed.org/handbook/mbed-FRDM-KL25Z-Getting-Started

See also:

And an enormous wealth of information on mbed’s website!

Posted in Electronic Projects | Tagged , , , , , , | 4 Comments

Design and Simulate a 4-Bit Parity Generator in Multisim and Implement on a Digilent Basys 2 Spartan-3E FPGA Board

Introduction

Parity bits are extra signals which are added to a data word to enable error checking. There are two types of parity – even and odd. An even Parity Generator will produce a logic 1 at its output if the data word contains an odd number of 1s. If the data word contains an even number of 1s then the output of the Parity Generator will be 0. By concatenating the parity bit to the dataword, a word will be formed which always has an even number of 1s i.e. has even parity.

Parity is used on communication links (e.g. modem lines) and is often included in memory systems. If a dataword is sent out with even parity, but has odd parity when it is received then the data has been corrupted and must be resent. As its name implies the operation of an Odd Parity generator is similar but it provides odd parity. The table shows the parity generator outputs for various 4-bit data words.

Objectives

  • Use a Truth Table to construct odd parity generator.
  • Derive the logic circuit from algebraic function obtained from Truth Table
  • Design and simulate the Parity Generator in NI Multisim 13.0
  • Implement the Parity Generato on a Digilent Basys 2 Spartan-3E FPGA board

Hardware Requirements

Digilent Basys2 Spartan-3E FPGA Board (the board comes with an USB programming cable)

BASYS2-top-400

Software Requirements

  • NI Multisim 13.x Education Edition (to download an evaluation edition, please click here)
  • ISE WebPACK Design Software (available here)
  • Xilinx iMPACT 13.x or later, part of the ISE WebPack (link as shown in previous line)

Installation Instructions

  • Download the attached Digilent Basys 2 file.
  • Unzip the file to your local disk.

Two files will be unzipped: DigilentBasys2.mspc and DigilentBasys2.ucf.

  • Copy and paste the two unzipped files to the pldconfig folder in the main Multisim 13.0 install directory, by default, this should be:

Program Files->National Instruments->Circuit Design Suite 13.0->pldconfig

In my PC it looks like as show using WinRAR (evaluation copy):

pladconfig

Pressing OK the files will be duly copied.

Procedure

A) Derive the Logic Circuit of 4-Bit Parity Generator

The Truth Table of 4-Bit Parity Generator is:

4_bit_gen

The equivalent Karnaugh Map (K-Map) is:

k-map_4bit

From K-Map, we can derive the algebraic function which is (P is the parity result):

P = A’B’C’D+A’B’CD’+A’BC’D’+A’BCD+AB’C’D’+AB’CD+ABC’D+ABCD’

This result can be simplified as:

P = A’B'(C’D + CD’) + A’B (C’D’+CD) + AB'(C’D’ + CD) + AB (C’D + CD’)

= (A’B’ + AB) . (C’D + CD’) + (A’B + AB’) . (C’D’ + CD)

P is the result in our case for Odd Parity.

We note that above algebraic simplification is representing XOR (short for Exclusive-OR) and XNOR (short for Exclusive-NOR) gates. You can read an excellent tutorial here.

Hence:

P = (A ⊕ B)’ . (C ⊕ D) +  (A ⊕ B) . (C ⊕ D)’

= (A ⊕ B) ⊕ (C ⊕ D)

This algebraic function is represented by following logic circuit:

parity_generator

B) Design the Schematic and Simulate

We will first design the top level schematic in NI Multisim 13.0 which is used for simulation purposes and contains the PLD subsheet.

The top level schematic, as part of this project, allows for simulation. It places the PLD logic in place around the IO contained on the board. To achieve this we use a PLD sub-circuit. The PLD sub-circuit allows us to place the PLD code within a single component as if it was being run on the FPGA.

The steps below describe the process for creating a sub-circuit.

1. Open a new schematic in Multisim.

2. Select Place » New PLD sub-circuit

parity_13. Choose Digilent Basys 2 and click Next button

parity_2
4. Provide a name for the PLD schematic. I chose “Parity Generator”, as can be seen in image, leaving the default PLD part number as it is:

parity_3

5. Select the connectors that you will be using on the Basys 2 Spartan-3E FPGA board. For the Parity Generator in this tutorial we will be using:

sw_0, sw_1, sw_3 and sw_4 for simulating input values A, B, C and D respectively on Basys 2 FPGA board.  Led_0 for output on the Basys 2 board and to indicate Odd Parity.

parity_4We will keep all other default values as they are, and click Finish button.

6. Place the sub-circuit

The sub-circuit is created:

parity_5Save the Multisim schematic giving it a name. I have called it “my_Parity_Generator”.

After completing the top level circuit, we need to create the digital logic within the PLD schematic. We will next edit the sub-circuit and connect it up.

To create the PLD schematic right-click the PLD sub-circuit and select Properties. A window will pop up:

parity_12

Click Open subsheet button. An empty schematic with connectors for sw_0, sw_1, sw_3, sw_4 and Led_0

Connect up the logic circuit obtained before as shown:

parity_6Save the circuit.

7. Simulating the Logic

The top-level  schematic can be simulated by adding a Logic Analyzer and a Word Generator as shown:

parity_13

Set up the Word Generator first. Doube-click on XWG1.

Settings window will pop up. On Display group of options choose Binary

parity_8a

Controls group of options click Set… button

parity_8

Choose up counter and keep the default Initial pattern.

parity_9

Up counter will be generated. We will now limit at 1111. Click on this pattern and right-click with mouse and choose Set Final Position.

parity_10

Now double-click on XLA1, Logic Analyzer. On Word Generator click the Step button. As you Step through the patterns you will see the Logic Analyzer displaying the patterns as well the Parity result.

sim1

sim2

You can verify the Truth Table for Odd Parity outputs:

4_bit_gen

In fact Even Parity is inverse of Odd Parity, therefore in our PLD sub-circuit we could have also obtained this result by just placing an Inverter at output.

We can also test the circuit by connecting a LED to the output of PLD, and by stepping through the patterns in Word Generator. Everytime the LED is ON it means that it is Odd Parity.

8. Deploying the Logic

There are three options for exporting the digital logic from the PLD schematic:

– Programming the connected Hardware – allows students to deploy the digital logic and learn the response of using the hardware.
– Generate a PLD bit file – students can take this away and deploy when they have the hardware available.
– Generate VHDL file – allows students to explore the VHDL behind the logic.We will focus on programming the connected hardware.

NOTE: If your Windows OS is not in english language,  you will need to edit the TEMP and TMP localization in My Computer  -> Properties -> Advanced -> Environment Variables. You will have to change it from %USERPROFILE%\Local definitions to %SYSTEMROOT% to avoid XST Synthesis failure. This happens as the command lines of compilation do not accept foreign language characters such as çõ and others of similar nature . Of course you will need to restart your PC, after having made these changes to your Windows’ Environment Variables.

Right-click the PLD sub-circuit and select Properties. A window will pop up:

parity_12

Click Open subsheet button.  The logic circuit that we designed before will be shown:

parity_6

  • Make sure that your Basys 2 board is connected to your PC with USB cable that comes with it.
  • Select: Transfer » Export to PLD from the menu bar.

parity_15

  • Here you will see the three export options. We want to export to physical hardware so select Program the Connected PLD.

PLD_export1We want to program the connected PLD. Click Next.PLD_export2In my Windows environment I have already installed Xilinx ISE Design Suite 14.2. Note that Device Status is not checked. Make sure first of all that Basys 2 board is connected. You may need to install Adept software and make sure that the board is recognised by your PC.

  • Click on Refresh button. Multisim will try to detect the Basys 2 FPGA board. Note that Multisim 12.0 does not detect the board.

PLD_export3If detected you will see the following reassuring information on this step.

parity_16

  • Now click Next. You will see first of 11 steps that Multisim 13.0 will go through

PLD_export5If all goes well your Basys 2 FPGA board (or any other supported Digilent boards such as Nexys 2 and 3 – you will need to install in Multisim the adequate constraints files) , you will see the following reassuring result:

parity_179. Testing the logic

On Basys 2 FPGA board test the logic by switching HIGH and LOW the switches sw_0, sw_1, sw_2 and sw_3, and confer with the Truth Table by the Led_0 being lit (in HIGH state) or not (in LOW state):

4_bit_gen

parity_18

Conclusions

A parity bit is used for the purpose of detecting errors during transmission of binary information. We have used two excellent tools NI Multisim and Digilent Basys 2 FPGA board. We first derived the logic circuit of 4-Bit Parity Generator from the Truth Table, simulated the derived circuit in NI Multism, and then finally implemented it physically on a Digilent Basys 2 FPGA board.

Acknowledgments

(1)http://www.webopedia.com/TERM/P/parity_checking.html

Posted in Electronic Projects, Electronic Simulation | Tagged , , , , , , , , , | 4 Comments

Design and Simulate a Digital Circuit in NI Multisim and Implement on a Digilent Basys 2 Spartan-3E FPGA Board

Overview

NI Multisim (formerly MultiSIM) is an electronic schematic capture and simulation program which is part of a suite of circuit design programs, along with NI Ultiboard. Multisim is one of the few circuit design programs to employ the original Berkeley SPICE based software simulation. Multisim was originally created by a company named Electronics Workbench, which is now a division of National Instruments. Multisim includes microcontroller simulation (formerly known as MultiMCU), as well as integrated import and export features to the Printed Circuit Board layout software in the suite, NI Ultiboard.

Multisim is widely used in academia and industry for circuits education, electronic schematic design and SPICE simulation. (1)

The Programmable Logic Device (PLD) Schematic in NI Multisim enables students to easily learn digital concepts by using familar digital gate logic to translate boolean logic to symbols/simulation. The PLD schematic can also export and translate digital logic into raw VHDL that can be used to program field-programmable gate array (FPGA) technology used extensively in laboratories to reinforce this theory.

Digilent Inc. is a leading electrical engineering products company serving students, universities, and OEM’s worldwide with technology-based educational design tools.  Digilent offers a wide array of FPGA boards used by educational institutions to help reinforce such theory.

The combination of NI Multisim and Digilent FPGA boards offers now a new and powerful opportunity in quickly implmenting simple to medium sized logic circuits.

Objectives

Show step by step how to desing a digital logic circuit in Multisim, simulate, and for proof of concept export as raw VHDL and with specially developed configuration files that program a Digilent Basys2 Spartan-3E FGPA board.

Pre-Requisites

You must have done or at least browsed  through another two tutorials published here:

https://redacacia.me/2012/07/30/designing-simulating-and-implementing-a-simple-car-alarm-on-a-xilinx-fpga-part-i/

https://redacacia.me/2012/08/01/designing-simulating-and-implementing-a-simple-car-alarm-on-a-xilinx-fpga-part-ii/

Hardware Requirements

BASYS2-top-400Software Requirements

  • NI Multisim 13.x Education Edition (to download an evaluation edition, please click here)
  • ISE WebPACK Design Software (available here)
  • Xilinx iMPACT 13.x or later, part of the ISE WebPack (link as shown in previous line)

Installation Instructions

  • Download the attached DigilentBasys2 file.
  • Unzip the file to your local disk.

Two files will unzipped: DigilentBasys2.mspc and DigilentBasys2.ucf.

  • Copy and paste the two unzipped files to the pldconfig folder in the main Multisim install directory, by default, this should be:

C:\Program Files\National Instruments\Circuit Design Suite 13.0\pldconfig

In my PC it looks like as show using WinRAR (evaluation copy):

pladconfig

Pressing OK the files will be duly copied.

Design and Simulation

We are going to design a Car Alarm. The alarm circuit will light up a LED (Led_0) on Basys 2 board board only when the key (sw_0) is in the ignition and either the door (sw_1) is open or the seatbelt (sw_2) is not fastened. The variables are:

                                    Key = 0      key is not in the ignition
                                    Key = 1      key is in the ignition
                                    Door = 0    door is open
                                    Door = 1    door is closed
                                    Seat = 0     seat belt is not fastened
                                    Seat = 1     seat belt is fastened
                                    Alarm = 0   alarm is not ON
                                    Alarm = 1   alarm is ON

Hence the Truth table is:

Truth Table of Car Alarm

Where A = Door, B= Key and C = Belt

The Karnaugh map of this Truth table is:

Karnaugh Map of Car Alarm

The resulting Boolean expression is Y = A’B + BC’ which translated into logic circuit is:

We will next simulate and test the Truth table in MultiSim 13.0.

Procedure

  • Run Multisim 13.0. Start a new design in menu File ->  New 
  • Start a new PLD design, selecting File > New

pld_topology_9

Select PLD Design and click on Create

  • This will start the New PLD Design Wizard. By default it will show NI Digital Electronics FPGA Board. In drop down menu we will choose Digilent Basys2.

pld_image4

  • Click Next > button. In Step 2 we will give a name to our PLD Schematic. I have called it “myCarAlarm”

pld_topology_2

  • By default Step 2 will show the PLD part number for Basys2. Click Next > button

PLD_export0

  • Check Led_0, sw_0, sw_1 and sw_2.  and click the Finish button. The reult will be an empty schematic with input and output

PLD_export00

We will now use test and measurement tools in Multisim to generate the Boolean expression from Truth table, and then obtain our respective logic circuit.

  • Bring into Multisim workspace Logic converter instrument by pressing onto the icon forLogic converter found at instruments’ tool bar on the right side of Multisim worksapce. The image on workspace looks like this:

  • Press onto the Logic converter instrument  and you will see the conversion setup.

Fill up the Truth table by pressing onto A, B, and C buttons and change the question marks of results ? into respective 0s or 1s according to the Truth table at the beginnng of this post, and as shown in the image above. Now press the button:

The result will be:

Boolean expression obtained from Truth table

This resulting Boolean expression A’B + BC’ is exactly the same as we obtained manually from Karnaugh map at the beginning of this post.

  • We are now ready for the automatic logic conversion offered by Multism 12.0. Press onto the button:

It will result in the same circuit as we have obtained manually at the top of this post from Boolean expression.

  • We are now ready to simulate, and test the logic circuit. Bring into Multisim workspace Word generator instrument by pressing onto the icon of Word generator found at the instruments’ tool bar on the right side of Multisim workspace. Connect up the Word generator as shown and place the Probe found at the icons bar below the menu bar at top of the workspace (note the input connectors in image have been moved to order sw_1, sw_0 and sw_2 – sw_0 is Key in our logic):

pld_sim1

Press onto Word generator instrument. We will set the right word pattern. Press onto Set button:

Intial window. Press Set.. button to set up

The set up window will open. Change the Buffer size to 0010 and in Preset patterns chooseUp counter:

Press OK button. You will see the following window:Almost there  to simulate....

In Controls press Step button and in Display choose Binary. After you have done this, close the Word generator‘s window.

We are ready to simulate. Open the Word generator press onto the Step button and certify that the Truth table we have decided upon earlier is what is seen in the simulation:

pld_sim2

As in our original Truth table, the logic circuit will behave as expected and results can be seen step by step on the Probe lighting up or switching off. We are now ready to export the Multisim circuit to VHDL.

  • Connect the logic circuit as shown, and remove the Word generator instrument, the Probeas well as any other remnants of our simultaion:

Layout and connections before export to Basys 2 FPGA board

pld_topology_8

We are ready now to export and program our Basys 2 board. Save the schematic before you do anything else with File > Save

Export the PLD Logic
There are three options for exporting the digital logic from the PLD schematic:
– Programming the connected Hardware – allows students to deploy the digital logic and learn the response of using the hardware.
– Generate a PLD bit file – students can take this away and deploy when they have the hardware available.
– Generate VHDL file – allows students to explore the VHDL behind the logic.

We will focus on programming the connected hardware.

  • Make sure that your Basys 2 board is connected to your PC with USB cable that comes with it.
  • Select: Transfer » Export to PLD from the menu bar. Here you will see the three export options. We want to export to physical hardware so select Program the Connected PLD.

NOTE: If you are in a different language Windows OS, like I am,  you will need to edit the TEMP and TMP localization in My Computer  -> Properties -> Advanced -> Environment Variables, from %USERPROFILE%\Local definitions to %SYSTEMROOT% to avoid XST Synthesis failure as the command lines of compilation do not accept foreign language characters such as ç, õ and others. Of course you will need to restart your PC, after changing Windows’ Environment Variables.

PLD_export1

We want to program the connected PLD. Click Next.

PLD_export2

In my environment I have already installed Xilinx ISE Design Suite 14.2. Note that Device Status is not checked. Make sure first of all that Basys 2 board is connected. You may need to install Adept software and make sure that the board is recognised by your PC.

  • Click on Refresh button. Multisim will try to detect the Basys 2 board. Note that Multisim 12.0 does not detect the board.

PLD_export3

If detected you will see the following reassuring information on this step.

PLD_export4

  • Now click Next. You will see first of 11 steps that Multisim will go through

PLD_export5

If all goes well your Basys 2 board (or any other supported Digilent boards such as Nexys – you will need to install in Multisim the adequate constraints files as you may have done with  Basys 2) , you will see the following reassuring result:

PLD_export6

  • You are now able to test the logic on Basys 2 using our Truth Table:

A = sw_1, B = sw_0 and C= sw_2. So if you have the key in ignition i.e.  sw_0 = 1, i.e. switch sw_0 is ON (pulled up on Basys 2 board), Alarm (Led_0) will sound (Led_0 will be ON) unless seat belt is fastned and door is closed.

We are now all done! Mission accomplished!

Conclusions

We have shown that one can easily combine Multisim’s industry-standard, best-in-class SPICE simulation environment with Digilent’s technology-based educational design tools such as entry-level Basys 2 FPGA board. Implementing on the board the logic circuit designed in Multisim is now made quite easy as we have learnt.

Resources

(1) http://en.wikipedia.org/wiki/NI_Multisim

Posted in Electronic Projects, Electronic Simulation | Tagged , , , , , , , , , , | 7 Comments