Design a Front Panel in ProfiLab-Expert to Control Digilent ChipKIT Uc32 and Basic I/O

Introduction

The ProfiLab-Expert software allows you to develop your own digital or analogue measuring technology projects. It does not matter if you want to create analogue measurements or digital controls – you can realize it all. And for all this you do not have to write a single program-line. You create your projects just like drawing a wiring diagram. Simply add buttons, displays, etc. to your diagram and build your project step by step. ProfiLab-Expert is equipped with an integrated compiler that can create executable files for stand-alone applications that run on systems without ProfiLab-Expert. As an interesting act, the distribution of these compiled applications is unlimited, so ProfiLab-Expert becomes a complete and professional developers system.

The Digilent chipKIT uC32 board is based on the popular Arduino™ open-source hardware prototyping platform and adds the performance of the Microchip PIC32 microcontroller. This board is the same form factor as the Arduino™ Uno board and is compatible with many Arduino™ shields. It features a USB serial port interface for connection to the IDE and can be powered via USB or an external power supply. The uC32 board takes advantage of the powerful PIC32MX340F512 microcontroller. This microcontroller features a 32-bit MIPS processor core running at 80Mhz, 512K of Flash program memory and 32K of SRAM data memory.

Objectives

A Front Panel can be quite an interesting proposition in controlling a ChipKIT uC32 board, and that is what we will do here  We will program uC32 to switch on and off LEDs on Basic I/O board, design a Front Panel in ProfiLab-Expert to control uC32 board.

Requirements

tempmon1

Software DAQ ProfiLab-Expert 4.0

Pre-Requirements

Basic knowledge of Digital Electronics.

MPIDE software for programming chipKIT Digilent Uc32 board must be installed in your PC. Also ProfiLab-Expert 4.0 valid license must have been already installed.

Procedures

A) The hardware setup

Install the Basic I/O shield on top of UNO32 as shown on the above image . Connect to the PC with USB cable. USB connection will power UNO32 and the Basic I/O shield simultaneously.

We assume that you have already installed MPIDE environment.

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

Run MPIDE

Now do File -> New and write a new Sketch:

/*
This program switches the digital pins of the arduino Uno based on a
command sent by a connected PC via the RS-232/USB interface.
The syntax is [PinNo],[status]\n. PinNo ranges from 2 to 13 and the
status can be 1 (High) or 0 (Low). Example: 5,1\n sets the PIN 5 to
High, whereas 5,0\n sets it to Low.
Written by Benjamin Roeben; used examples: 'Blink' and
'ReadASCIIString'.

Adapted for Digilent chipKIT uC32 and Basic I/O boards by Tayeb
Habib tayeb.habib@gmail.com htt://redacacia.me

*/

void setup() {
  // initialize serial:
  Serial.begin(9600);
  // switch the pinmodes of pins 26 to 33 to OUTPUT
  for(int i=26; i<=33; i++) {
  pinMode(i, OUTPUT);
  // switch off the LEDs on Basic I/O board
  digitalWrite(i, LOW);
  }
}

void loop() {
  // if there's any serial available, read it:
  while (Serial.available() > 0) {

     // look for the next valid integer in the incoming serial
     // stream:
     int pinNo = Serial.parseInt();
     // do it again:
     int state = Serial.parseInt();
     // look for the newline. That's the end of the sentence:
       if (Serial.read() == '\n') {
         //Set the Pin states
           if (state==1)  {
           digitalWrite(pinNo, HIGH);
           }
           if (state==0)  {
           digitalWrite(pinNo, LOW);
           }
       }
     }
}

Save this sketch as ControlLEDs.pde

Make sure of serial port to which the board is connected.

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

If successful you will see the following results at bottom of MPIDE environment:profilab1Note that for my case chipKIT uC32 is connected to COM30.

We are now ready to make our Front Panel in ProfiLab-Expert 4.0

B) ProfiLab-Expert project

Start a new project in ProfiLab-expert 4.0 File – > New.

Next in Control elements choose Digital controls

profilab2In Digital controls choose Switch profilab3

We can see the Switch on the Front Panel by clicking Show front panel profilab3a:

profilab3bWe will leave the toggle switch for now to be changed later and proceed with the data input defining them. The switch will behave as a simple Data Selector. In Miscellaneous choose Strings:

profilab4

Now choose $Const profilab5 as we will be dealing with string constants. It will be dropped into Workspace. Do the action a second time in order that another string constant drops into Workspace. Align them adequately to look like as follows:

profilab6We are now ready to define these constants which will be two different data selector inputs. Click twice over first String Constant component CNST, and in pop up window, write the value of String 26,0 which means PIN26 on uC32 is OFF (check the uC32 Sketch we have just written)

profilab7Click OK. Do the same with second Constant component CNST and write the value of String 26,1 which means PIN26 is ON, and click OK to close the pop up window.

Now we need to pass this through a Multiplexer (MUX), which in effect is a Data Selector . This is found also in Miscellaneous -> Strings, it is called $Multiplexer:

profilab8Just click on the icon, and the component will be placed in Workspace. Right click onto it, and choose Properties:

profilab8aIn pop up window, choose two channels as each switch can be either ON or OFF, i.e. these two states will be the data inputs.

profilab8bChoose 2 for number of Channels and click OK, and the pop up will close, and the result will be as shown:

profilab10Now connect the Switch and the two Constants, clicking the Connect button profilab9 and connect as follows:

profilab11Now select the whole circuit, and duplicate from menu with Edit -> Duplicate. Do this eight times until you have all of 8 circuits that are required:

profilab12I have zoomed out the image in order to show all eight Data Selector circuits.

Now we are ready to define the constants in each Data Selector. On second Data Selector from top onwards click on CNST and change the values to 27,0 and for second CNST change to 27,1, and do so, for all Data Selectors, until the last two that will have constant values of 33,0 and 33,1.

As this juncture it is advised to save the project. Give it a name, may be   profilab_uC32.prj.

We will join together all Data Selectors into a new Multiplexer (MUX) for Parallel-to-Serial Conversion.  The Multiplexer is found as mentioned before in Miscellaneous -> Strings, and it is called $Multiplexer:

profilab8Just click on it, and it will be placed in Workspace. The default Properties are 8 channels as seen before, so we do not need to change the Properties.

Now connect all Data Selectors to this Multiplexer as shown below:

profilab14I have zoomed out the image to show all the connections.

For Parallel-to-Serial Conversion we will add now a Decade counter. This is found in Logic Components -> Counter

profilab15Choose Decade counter (4-bit):

profilab16Just click on it, and it will be dropped into Workspace.

We also need to add a Clock. We will add a Pulse generator 1Hz…10kHz profilab17a. This is found in Logic components -> Timer

profilab17Click on Pulse generator 1Hz…10kHz. and it will also drop into Workspace. Click on Pulse generator component, and define clock as 10Hz:

profilab19Now connect the Pulse generator to the Counter, and the Counter to Multiplexer, as shown:

profilab18Now we are ready to add Rs232 communication. The RS232 component is named COM Send string profilab21 and is found in Hardware components -> RS-232:

profilab20Choose the component by clicking on it. RS232 component will be placed in Workspace. Next connect as shown. To synchronize with the Multiplexer we will also connect the Function generator component to RS232 component:

profilab22We are now ready to work with the Front Panel. The switches will be stacked on top of each other. Just push them sideways as shown, and rearrange them so that SW8 will be on the extreme right side, and SW1 on extreme left side:

profilab23Toggle switches are not very convenient to indicate the status of the LED on the Basic I/O board so we will change each one to another type of switch say “Plastic lamp switch”:

profilab25Do with every Switch, and change Hint with “LED number” on uC32. So SW1 will be “LED26”, and so on. The final result will be as shown:

profilab26We are now ready to test and to debug our project in ProfiLab-Expert 4.0. Before you do anything else, we need to define the port and baud rate. Double click on COM component in order to configure the COM port. In my case the port is COM30, in your case t may be another that you used to program your uC32 board:

profilab27Change the Frame value under Options clicking on profilab28 button. In pop up window change Suffix (send after data) to 10 and the rest is as shown in image:

profilab29Click OK. The window will close. And now, you can you click OK the Properties pop up window, without changing any other parameters, and the window will close.

Save the ProfiLab-Expert project.

C) Testing and debugging the Project

Make sure that uC32 board with Basic I/O board on top is connected to the PC. Next in Profilab-Expert 4.0 Run the project clicking on Start profilab30 button or F9 key on your PC’s keyboard. The Front Panel will pop up:

profilab31Now we can test our Project. Just click the leftmost button, and you will see LED26 on Basic I/O light up. The button will become RED as result of our clicking. If we click again the button, it will become DARK red, and the LED26 will switch off. The following image shows the button in ON status:

profilab33The photo below shows my actual set up with the LED26 in ON state:

photo1Test all other buttons on Front Panel. All of buttons should work. If not, either the circuit of the ProfiLab project has some wrong or bad connections, or parameters have not been defined correctly. You can verify pin status with Show pin status profilab32 which will show circuit animation, and pointing a node with the mouse, you will see actual values there.  The following image shows pin status $=26,1 on output pin of $MUX1:

profilab34You can label the buttons and order a bit more the buttons on the From Panel to look like the following image:

profilab35Do a final test to make that the Front Panel displays correctly.

Demonstration of the Project

I have published a video in YouTube, that shows the simulation of the Project and the Front Panel controlling a chipKIT uC32 board with Basic I/O. You will notice that right at the beginning I have slowed down the rate of the last stage of Parallel-to-Serial conversion to 1Hz. So here is the video:

What’s Next?

1) You can add Remote Control with Bluetooth, as I have shown with previous tutorials found in this blog, so that Front Panel will control uC32 at a distance.

2) Add more features to your Front Panel, using other resources and components in ProfiLab-Expert 4.o

3) Make stand-alone application of the Project that runs on systems without ProfiLab-Expert making use of integrated compiler that can create executable files.

4) Run the Front Panel from the Web making use of PL Webserver that can be supplied together with ProfiLab-Expert 4.0. The web page can be password protected so your application will not run by unauthorized persons.

Acknowledgments

A special thank you is due to the authors of ideas porposed in Arduino – Digital Output discussion of Abacom-online forum.

Conclusions

We have shown that one can design a Front Panel with ProfiLab-Expert 4.0 without any programming as such and to control a powerful microcontroller board such as Digilent ChipKIT uC32. We have used step by step method to show all that needs to be done to launch a Front Panel. Of course a Basic Digital Electronics knowledge is required.

Posted in Electronic Projects | Tagged , , , , , , , , , , | Leave a comment

Controlling a Robot with Gestures on the Air with Leap Motion Controller

Introduction

For decades, motion controls have held a persistent place in our visions of the future. We’ve watched the super heroes, mad scientists, and space cowboys of popular media control digital experiences with just a wave of their hands. We’ve been captivated by these powerful, natural, and intuitive interactions; imagining what it would be like to have that power at our own fingertips. Tony Stark’s workshop, Star Trek’s ‘Holodeck’, Firefly’s holographic brain scanner, and Minority Report’s pre-crime visioning computers all exude a sense of power and mastery, along with paradoxical senses of simplicity, ease, intuitiveness, and humanity. Simply, these experiences feel — “Arthur C. Clarke” style—magical.(1)

gestures1The Leap Motion Controller senses how you naturally move your hands and lets you use your computer in a whole new way. Point, wave, swipe, reach, grab. Pick something up and move it or just tap. The Leap Motion Controller doesn’t replace your keyboard, mouse, stylus, or trackpad. It works with them, and without special adapters. With the Leap Motion software running, just plug it into the USB on your Mac or PC, and you’re off.

Controlling a robot with swipe gestures on the air seems to be an interesting proposition. In fact it is quite easy to implement with any of the development environments such as JavaScript, Unity/C#, C++, Java, Python and Objective-C, and others. The Leap Motion controller provides application programming interfaces (APIs) for most of the established programming languages like the ones referred before.

Objectives

Control a robot with gestures on the air with Leap Motion controller, using bluetooth to comunicate between the PC and the robot.

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 a Leap Motion controller:

Robo-51

Robo-51

ZX-Bluetooth

ZX-Bluetooth module

Leap Motion controller

Leap Motion controller

Installing Leap Motion Controller

You need first of to install Python in your PC.

To help you get started programing with the Leap Motion API for Python, the following articles provide an overview of the Leap Motion tracking data, how the Leap Motion hardware and software works, and how to setup a project that uses the SDK:

And for the fastest possible introduction to the Leap Motion API, here’s the essential:

Once you have a good idea of what you CAN do, take a moment and consider what you SHOULD do. These articles can help:

For an in-depth discussion of the Leap Motion API, refer to the following articles:

Installing Modules in Python

You will need to install PySerial and Win32com.Client modules. Once duly installed you are ready to write the Python code.

Python code

Write the following Python code:

################################################################################
# Copyright (C) 2012-2013 Leap Motion, Inc. All rights reserved.               #
# Leap Motion proprietary and confidential. Not for distribution.              #
# Use subject to the terms of the Leap Motion SDK Agreement available at       #
# https://developer.leapmotion.com/sdk_agreement, or another agreement         #
# between Leap Motion and you, your company or other organization.             #
################################################################################

# Adapted by: Tayeb Habib tayeb.habib@gmail.com http://redacacia.me
# from: https://github.com/michieldwitte/ code for LeapMotion VLC controller

# imports
import Leap, sys, time, serial, win32com.client
from Leap import CircleGesture, KeyTapGesture, ScreenTapGesture, SwipeGesture

# Serial port parameters
serial_speed = 9600
# Your serial port instead of ttyUSB0
serial_port = 'COM6'
ser = serial.Serial(serial_port, serial_speed, timeout=1)

# Initializing voice output
speaker = win32com.client.Dispatch("SAPI.SpVoice")
speaker.Speak("I'm Robo-51.I'm at your command!!")

class SampleListener(Leap.Listener):
    alarm = 0
    def on_init(self, controller):
        pass
        #print ""

    def on_connect(self, controller):
        print "Connected"

        # Enable gestures
        controller.enable_gesture(Leap.Gesture.TYPE_CIRCLE);
        controller.enable_gesture(Leap.Gesture.TYPE_KEY_TAP);
        controller.enable_gesture(Leap.Gesture.TYPE_SCREEN_TAP);
        controller.enable_gesture(Leap.Gesture.TYPE_SWIPE);

    def on_disconnect(self, controller):
        # Note: not dispatched when running in a debugger.
        print "Disconnected"

    def on_exit(self, controller):
        print "Exited"

    def on_frame(self, controller):
        # Get the most recent frame and report some basic information
        frame = controller.frame()
        if not frame.hands.is_empty: 
            for gesture in frame.gestures():
                if gesture.type == Leap.Gesture.TYPE_SWIPE:
                    swipe = SwipeGesture(gesture)

                    if swipe.direction[0] > 0.5 and self.alarm < time.time():
                        self.alarm = time.time() + 1.00
                        print "Right"
                        #voice output
                        speaker.Speak("Right!")
                        #write data to robot
                        ser.write('b')
                        
                    if swipe.direction[0] < -0.5 and self.alarm < time.time():
                        self.alarm = time.time() + 1.00
                        print "Left"
                        #voice output
                        speaker.Speak("Left!)
                        #write data to robot
                        ser.write('c')
                        
                    if swipe.direction[1] > 0.5 and self.alarm < time.time():
                        self.alarm = time.time() + 1.00
                        print "Forward"
                        #voice output
                        speaker.Speak("Forward!")
                        #write data to robot
                        ser.write('d')
                        
                    if swipe.direction[1] < -0.5 and self.alarm < time.time():
                        self.alarm = time.time() + 1.00
                        print "Backward"
                        #voice output
                        speaker.Speak("Backward!")
                        #write data to robot
                        ser.write('a')
                        
                if gesture.type == Leap.Gesture.TYPE_SCREEN_TAP and self.alarm < time.time():
                        self.alarm = time.time() + 1.00
                        print "Stop"
                        #voice output
                        speaker.Speak("Stop!")
                        #write data to robot
                        ser.write('s')
                        
                if gesture.type == Leap.Gesture.TYPE_KEY_TAP and self.alarm < time.time():
                        self.alarm = time.time() + 1.00
                        print "Stop"
                        #voice output
                        speaker.Speak("Stop!")
                        #write data to robot
                        ser.write('s')

    def state_string(self, state):
        if state == Leap.Gesture.STATE_START:
            return "STATE_START"

        if state == Leap.Gesture.STATE_UPDATE:
            return "STATE_UPDATE"

        if state == Leap.Gesture.STATE_STOP:
            return "STATE_STOP"

        if state == Leap.Gesture.STATE_INVALID:
            return "STATE_INVALID"

def main():
    print "swipe right for turning right"
    print "swipe left for turning left"
    print "swipe up for going forward"
    print "swipe down for going backward"
    print "key/screen tap for stopping"
    print ""

    # Create a sample listener and controller
    listener = SampleListener()
    controller = Leap.Controller()

    # Have the sample listener receive events from the controller
    controller.add_listener(listener)

    # Keep this process running until Enter is pressed
    #print "Press Enter to quit..."
    sys.stdin.readline()

    # Remove the sample listener when done
    controller.remove_listener(listener)


if __name__ == "__main__":
    main()
[/code]

Running the code

Run the Python code. Note that you will have to pair your PC with bluetooth with the bluetooth module on your robot and know the correct COM port (in my case it is COM6). If all is going well you will see the robot to be controller with swipe gestures and tap.  The results on my PC are:

controlo_leapThe gestures used here are swipe left, swipe right, swipe up, swipe down and tap.

A video showing the robot being controlled by Leap Motion controller with swipe gestures and tap will be made soon and published here.

Conclusions

Controlling a device (in our case a robot) through gestures on the air, is quite an interesting endeavor. In fact it is quite easy to control a device with Leap Motion controller. With little more coding and refining our strategy, we can ensure that right commands are sent every time to the device, through gestures on the air, and those commands are not misinterpreted by the Leap Motion controller.

 

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

Cloud-enabling with Exosite: Local Temperature with chipKIT Digilent uC32, Digilent Basic I/O and Raspberry Pi

Introduction

Exosite is a technology company focused on connecting devices and systems. They have been developing embedded technologies for over 20 years – and have first-hand experience dealing with the lack of connectivity between devices, networks and users. Their cloud-based data platform makes it easy to put real-world information online.

The exponential growth in electronic data implores a ubiquitous connection tool. Exosite’s platform is that tool. Their software provides a central vantage point, enabling the next generation of connected products and supplying insight into operations.

According to Gartner, there will be nearly 26 billion devices worldwide on the Internet of Things by 2020. The Gartner report can be purchased for US$199,00.

Exosite offers a zero cost free developer account. It has everything one needs to start interacting with one’s devices real-time over the Internet. One gets a web dashboard account, full access to the API, a cloud scripting environment, and the ability to upgrade features a-la-carte.

Objectives

  • Capture the local temperature read by Microchip TCN75A temperature sensor on Digilent Basic I/O shield connected to chipKIT Digilent uC32 board
  • Send the values read by chipKIT Digilent uC32 to Exosite platform through Raspberry Pi.

Pre-Requirements

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

tempmon3
Procedure

a) Having run the sketch as shown in previous tutorial (it is a pre-requirement to have done) you will see on Basic I/0 shield’s OLED: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) Registering at Exosite and configuration of dashboard 

i – Visit the Exosite at http://portals.exosite.com. Here you can register if you are not already registered:

remote3ii – Once in your working area you can manage your portal. You need to add Devices (choose the link shown in red rectangle):

remote4iii – Add device clicking at + Add Device link on top right side:remote5

iv – In next screen choose the default option “I want to create a generic device”remote6

Click CONTINUE button.

v – In next step choose your time zone and add your geolocation: remote7Click CONTINUE button.

vi –  Fill in the name of your New Device. I have called it “TCN75A on BIO”                                remote8Click SUBMIT button. If you forget to give a name you will be greeted with the following warning on top of this configuration window:

remote10vii -A final window will open with your configuration. The following image shows my Device:

remote12Your Device will be now available.Click the link on top right that says to add Data remote11We are interested in this tutorial in reading degrees Centigrade and whether Alarm condition is met. In our firmware code for chipKIT Digilent uC32 when 24ºC is read and above Alarm is ON. Below temperature is OK. At the moment where I am temperature even in my Office is higher than 24ºC so the OLED display on BASIC I/O shield says ALARM! and this is transmitted serially.  So two Data values will be sent to portal TEMP1 and condition, the former has the temperature and second is string Alarm or OK.

viii – Let us configure our two Data entries. We will start with condition:

remote13We give the name condition and we say that the Exosite must expect a string. If the reviewed information is correct click on SUBMIT button. Up to 100 data entries can be configured for the Device. You will be greeted next with a window that says that your configuration has been successful.

ix – Now Add Data again clicking remote11And fill in as shown, naming TEMP1 and stating that Exosite must expect a float type data and unit as ºC:

remote14Click SUBMIT button and you will again see the window that Data has been added successfully.

x – Now we configure our Device and obtain valuable information from it for our code that we will write after.

Click on your Device to configure it (the name I gave is “TCN75A on BIO”. BIO means “Basic I/O”, the shield that contains the temperature sensor Microchip TN75A):

remote9A configuration window will open:

remote15CIK number will be need. I have blackened my CIK number. Copy it and past somewhere else. Note that our Data entries are already in our Device configuration TEMP1 and condition. You can close clicking CLOSE button or UPDATE (if you make any changes to your Device) and CLOSE buttons.

Exosite Porta’s dashboard is read. We will now proceed to Raspberry Pi.

c) Reading values with Raspberry Pi and sending to Exosite

On LXTerminal of Raspberry Pi desktop write

ls /dev/tty*

And the response now will be something similar to:

remote1Connect USB cable between Digilent USB cable and Raspberry Pi and do write again on the Terminal:

ls /dev/tty*

And the last part of the response will be as shown:

remote2ttyUSB0 is our connection on Raspnerry Pi. We are now ready to write Python program

In /home/pi write the following code with:

nano /home/pi/tempmon1.py

Write the following code:

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

#Exosite Cloud-enabled TCN75A sensor

#Imports
import time
import serial
from decimal import *
import urllib
import httplib

#Exosite portal configuration
cik = 'YOUR CIK HERE'
server = 'm2.exosite.com'

# Serial port parameters
serial_speed = 9600
# Your serial port the example uses ttyUSB0
serial_port = '/dev/ttyUSB0'

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

while True:            
     # Request data and read the answer      
     data = ser.readline() # read data from serial      
     if (data != ""):      
            # If the answer is not empty, process & display data         
            processed_data = data.split(',')        
            Data1r = str(processed_data[0])
            Data1 = '%.1f' % Decimal(Data1r)
            print Data1
            Data2 = str(processed_data[2])
            print Data2
            
        print '========================================================================'
        print 'Exosite API Using CIK ', cik
        print '========================================================================'
        print '\r\n'
        
        url = '/api:v1/stack/alias'
        params = urllib.urlencode({'TEMP1': Data1, 'condition': Data2 })
        headers = {'X-Exosite-CIK': cik, 'content-type': 'application/x-www-form-urlencoded; charset=utf-8'}
        print '=================='
        print 'POST'
        print '=================='
        print 'URL: ', url
        print 'Data: ', params
        print ' '
        conn = httplib.HTTPConnection(server)
        conn.set_debuglevel(1)
        conn.request("POST",url,params,headers)
        response = conn.getresponse();
        print 'response: ',response.status,response.reason
        data = response.read()
        end = data.find('<')
        if -1 == end: end = len(data)
        
        print '\r\n\r\n'
        url = '/api:v1/stack/alias?TEMP1&condition'
        headers = {'Accept':'application/x-www-form-urlencoded; charset=utf-8','X-Exosite-CIK':cik}
        print '=================='
        print 'GET'
        print '=================='
        print 'URL: ', url
        print ' '        
        conn = httplib.HTTPConnection(server)
        conn.request("GET",url,"",headers)
        response = conn.getresponse();
        print 'response: ',response.status,response.reason
        data = response.read()
        conn.close()
        print 'response data:', data
                 
time.sleep(30)

Save the code as tempmon1.py. Now we are ready to run the code. In LXTerminal write:

python /home/pi/tempmon1.py

You will see on LXTerminal something similar to following:

remote16I have whitened my CIK value.

At the beginning we see that TEMP1 and condition are both read. Next the values read are sent to Exosite.  The response “204 No Content” which is alright as it is what is expected. Next we get a response from the server that has been delivered with “200 OK”.

If this does not happen with you something you did is wrong. You need to follow this tutorial thoroughly and follow all the steps.

These values are properly registered at Exosite. Click at portal side in your dashboard Data button.remote18You will see something like the following image:

remote189If you click on TEMP you will see the graph being generated and the values that have been read:

remote17

A graph will be generated, something like following image:

remote19You can next play with your Exosite’s portal page. My dashboard’s Home looks like the following two images show:

remote20

remote21We are at the end of this tutorial.

What you can do Next?

You can add a Bluetooth dongle to your Raspberry Pi and a Serial SPP module to the chipKIT Digilent uC32 board. You can use Bluetooth to send the values read on Microchip TCN75A temperature sensor on Digilent Basic I/O shield to Raspberry Pi. So you can achieve a truly wireless connection doing away with USB cable.

Conclusions

More and more applications are now Cloud-enabled. Exosite has lots more of potential that we have not exploited. Connecting up Raspberry Pi with chipKIT Digilent uC32 with Basic I/O shield open up a whole new range of  interesting electronic projects. It is quite easy to Cloud-enable your project and Exosite offers you the possibility of doing for free to test your ideas and gradually grow.

 

 

Posted in Internet of Things | Tagged , , , , , , , , , , | 1 Comment

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.

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 , , , , , , , , , , , , , , , | 5 Comments

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