Telegram Bot Control with Orange Pi Lite Wifi and AXE056 board with Picaxe 18M2

opl0

What are Telegram bots?

Bots are third-party applications that run inside Telegram. Users can interact with bots by sending them messages, commands and inline requests. You control your bots using HTTPS requests to Telegram’s bot API.

What can one do with Telegram bots?

To name just a few things, you could use bots to:

  • Get customized notifications and news. A bot can act as a smart newspaper, sending you relevant content as soon as it’s published.
    Forbes Bot, TechCrunch Bot
  • Integrate with other services. A bot can enrich Telegram chats with content from external services.
    Image Bot, GIF bot, IMDB bot, Wiki bot, Music bot, Youtube bot, GitHub bot
  • Create custom tools. A bot may provide you with alerts, weather forecasts, translations, formatting or other services.
    Markdown bot, Sticker bot, Vote bot (NEW), Like bot (NEW)
  • Build single- and multiplayer games. A bot can play chess and checkers against you, act as host in quiz games, or even take up the dungeon master’s dice for an RPG.
    Trivia bot
  • Build social services. A bot could connect people looking for conversation partners based on common interests or proximity.
    HotOrBot
  • Do virtually anything else. Except for dishes — bots are terrible at doing the dishes.

How do bots work?

At the core, Telegram Bots are special accounts that do not require an additional phone number to set up. Users can interact with bots in two ways:

  • Send messages and commands to bots by opening a chat with them or by adding them to groups. This is useful for chat bots or news bots like the official TechCrunch and Forbes bots.
  • Send requests directly from the input field by typing the bot’s @username and a query. This allows sending content from inline bots directly into any chat, group or channel.

Messages, commands and requests sent by users are passed to the software running on Telegram’s servers. Their intermediary server handles all encryption and communication with the Telegram API for you. You communicate with this server via a simple HTTPS-interface that offers a simplified version of the Telegram API. Telegram calls that interface their Bot API.
A detailed description of the Bot API is available on this page »

How does one create a bot?

There’s a… bot for that. Just talk to BotFather (described below) and follow a few simple steps. Once you’ve created a bot and received your authorization token, head down to the Bot API manual to see what you can teach your bot to do.
You may also like to check out some code examples here »

 

 

How are bots different from humans?

  • Bots have no online status and no last seen timestamps, the interface shows the label ‘bot’ instead.
  • Bots have limited cloud storage — older messages may be removed by the server shortly after they have been processed.
  • Bots can’t initiate conversations with users. A user must either add them to a group or send them a message first. People can use telegram.me/ links or username search to find your bot.
  • Bot usernames always end in ‘bot’ (e.g. @TriviaBot, @GitHub_bot).
  • When added to a group, bots do not receive all messages by default (see Privacy mode).
  • Bots never eat, sleep or complain (unless expressly programmed otherwise).

BotFather

BotFather is the one bot to rule them all. It will help you create new bots and change settings for existing ones.

On Telegram, open the @BotFather profile, and start to talk with “him”. You can open the conversation by clicking here. If the screen remains empty, update your Telegram client, or write “/start

The BotFather will ask you to read a manual, but it’s not necessary!

Use the /newbot command to create a new bot. The BotFather will ask you for a name and username, then generate an authorization token for your new bot.

The name of your bot will be displayed in contact details and elsewhere. Say we call it ‘OrangePi Picaxe’

The Username is a short name, to be used in mentions and telegram.me links. Usernames are 5-32 characters long and are case insensitive, but may only include Latin characters, numbers, and underscores. Your bot’s username must end in ‘bot’, e.g. ‘tetris_bot’ or ‘TetrisBot’. In this tutorial give an appropriate name such as ‘PicaxeBot’.

BotFather will give you an HTTP API token, such as:

87782160:AAGWyE1JSEa8qNqvv4EZzcQQ4kWo7rokMKM

The token is required to authorize the bot and send requests to the Bot API.

If your existing token is compromised or you lost it for some reason, use the /token command to generate a new one.

Edit settings

The remaining commands are pretty self-explanatory:

  • /setname – change your bot’s name.
  • /setdescription — changes the bot’s description, a short text of up to 512 characters, describing your bot. Users will see this text at the beginning of the conversation with the bot, titled ‘What can this bot do?’.
  • /setabouttext — changes the bot’s about info, an even shorter text of up to 120 characters. Users will see this text on the bot’s profile page. When they share your bot with someone, this text will be sent together with the link.
  • /setuserpic — changes the bot‘s profile pictures. It’s always nice to put a face to a name.
  • /setcommands — changes the list of commands supported by your bot. Each command has a name (must start with a slash ‘/’, alphanumeric plus underscores, no more than 32 characters, case-insensitive), parameters, and a text description. Users will see the list of commands whenever they type ‘/’ in a conversation with your bot.
  • /setjoingroups — determines whether your bot can be added to groups or not. Any bot must be able to process private messages, but if your bot was not designed to work in groups, you can disable this.
  • /setprivacy — determines which messages your bot will receive when added to a group. With privacy mode disabled, the bot will receive all messages. We recommend leaving privacy mode enabled.
  • /deletebot — deletes your bot and frees its username.

Please note, that it may take a few minutes for changes to take effect.

opl9

So your bot is now ready.

Telepot, a Telegram client for Python

Telepot is a Python client which is the REST wrapper for Telegram API. Using it we can take commands from user and compute something and give back results to the user.

We are going to install Telepot on Orange Pi Lite  (OPL) Wifi, assuming that you have OPL duly functioning with latest Armbian Jessie desktop, and with Wifi connected to your router.

Orange-Pi-Lite-With-Wifi-Antenna

Let us build a Personal Assistant

First we need to install the sufficient libraries for constructing the Personal Assistant.
opl6

 

Next:

opl7

 

Once Telepot is installed we are ready to write our first bot code.

The following simple bot does nothing but accepts two commands:
– `/roll` – reply with a random integer between 1 and 6, like rolling a dice.
– `/time` – reply with the current time, like a clock.

Write the code at command prompt:

import time
import random
import datetime
import telepot

def handle(msg):
    chat_id = msg['chat']['id']
    command = msg['text']

    print 'Got command: %s' % command

    if command == '/roll':
       bot.sendMessage(chat_id, random.randint(1,6))
    elif command == '/time':
       bot.sendMessage(chat_id, str(datetime.datetime.now()))

bot = telepot.Bot('Token obtained previously')
bot.message_loop(handle)
print 'I am listening ...'

while 1:
    time.sleep(10)

Run diceyclock.py at command prompt python diceyclock.py and response will be I am listening…:

opl10

 

You can now try the two commands /roll and /time on Telegram:

opl11

Preparing AXE056 board with Picaxe 18M2

We want the Picaxe18M2 to be able to communicate by serial connection with Orange Pi Lite Wifi

Wrtie and upload the following code in Picaxe 18M2:

main:
    setfreq m8
    serin C.7, T9600_8, b0
    
    if b0 = "a" then                 'looks for "a"
    high B.1                         'turns on the output 
    
    
    else if b0 = "b" then            'looks for "b" (off)
    low B.1                          'turns off the output 
    
    else if b0 = "c" then             'looks for "c"
    high B.2                          'turns on the output 
    
    
    else if b0 = "d" then            'looks for "d" (off)
    low B.2                          'turns off the output 
    
    else if b0 = "s" then            'looks for "s" (status)
    gosub get_status                 'calls up "get_status" subroutine below
    
    endif
    goto main
 
    get_status:
    
    let b0 = pinB.1                   'checks status of pin B.1
    let b1 = pinB.2                   'checks status of pin B.2 
    
    gosub get_temp                   'calls temp subroutine below
    gosub get_lumin                  'calls lumin subroutine below
    
    serout B.7, T9600_8, (#b0, 32, #b1, 32, #b2, 32, #b3, 13, 10)                                 					
    return
 
    get_temp:
    readtemp 2, b2                   'reads the temperature
    return
 
    get_lumin:
    readadc 0, b3                     'reads adc value on In2
    return

We will now add connections to HC-05 Bluetooth Module. For this we use Inputs Test Points and Output Test Points with headers  (image shows the headers already soldered):
opl12 opl13

Now connect up HC-05 module to the board as shown:

opl14

Adding Bluetooth to Orange Pi Lite Wifi

We have used LogiLink USB Bluetooth V4.0 dongle but it can be any other as most seem to be recognised by Armbian’s Debian Jessie OS for Orange Pi Lite Wifi.

opl19

A possible result duly boxed is as follows (I also added a heat-sink on the ARM microcontroller as it tends to heat up):

opl16

Armbian’s is already Bluetooth-ready. You can chech the Buletooth dongle has been recongised by following command, and a possible response is shown below:
opl20

opl21

We now test the status of Bluetooth:

opl22

 

A possible and likely result will be:

opl23

 

 

 

 

We are now to pair our dongle to HC-06 module on AXE056 board.

The command bluetoothctl will allow us to pair to HC-05

opl24

 

Now run the following sequence of commands:

power on
and next:
scan on

You will see all the Bluetooth devices in neighborhood including HC-05. Copy the MC address of HC-05:

opl25

 

 

 

And now the following sequence:

agent on
default-agent
pair <MAC address of HC-05>

A typical response will be:

opl26

 

 

 

 

Note that MAC address has been blurred.  Pin code of H-05 is 1234 (this can be changed but we are not going to show here how, you can find information on the Internet how to do it

trust    <MAC address of HC-05>
exit

Now create a RFCOMM configuration file  in command prompt

opl27

# RFCOMM configuration file.
rfcomm0 {
# Automatically bind the device at startup
bind yes;
# Bluetooth address of the HC-05
device XX:XX:XX:XX:XX:XX;
# RFCOMM channel for the connection
channel 1;
# Description of the connection
comment "HC-05";
}

We are now ready to bind this at startup by editing and writing into rc.local with the following command:

opl28

 

Add just before exit 0

rfcomm bind 0 xxxxxxxxxxxx 1

Where xxxxxxxxxxxx is the MAC address of HC-05.

Now reboot the Orange Pi Lite Wifi with command reboot, and afiter rebooting if you check under dev:

opl29

 

You will see RFCOMM0

opl30

Writing new Python code for Personal Assistant

Write pa.py with command nano pa.py


# pa.py
import telepot, serial, time
ser = serial.Serial('/dev/rfcomm0',
                    baudrate=9600,
                    timeout=0
                    )
degree = unichr(176)

def handle(msg):
       chat_id = msg['chat']['id']
       command = msg['text']
       if command == '/hello':
           bot.sendMessage(chat_id, "Local status @Aliatron")
       elif command == '/status':
           ser.flushInput()
           ser.flushOutput()
           ser.write(b's')
           time.sleep(1)
           data = ser.readline()
           processed_data = data.split(' ')
           data1 = str(processed_data[0])
           data2 = str(processed_data[1])
           data3 = str(processed_data[2])
           data4 = str(processed_data[3])
           if data1 == '1':
              data10 = "Fan ON"
           elif data1 == '0':
              data10 = "Fan OFF"
           if data2 == '1':
              data20 = "Alarm ON"
           elif data2 == '0':
              data20 = "Alarm OFF"
           bot.sendMessage(chat_id, data10 + " ; " + data20 + " ; Temp: " + data3 + degree + "C ; Lumi: " + data4)

       elif command == '/fanon':
           ser.flushInput()
           ser.flushOutput()
           ser.write(b'a')
           time.sleep(0.25)
           bot.sendMessage(chat_id, "Fan: ON")

        elif command == '/fanoff':
            ser.flushInput()
            ser.flushOutput()
            ser.write(b'b')
            time.sleep(0.25)
            bot.sendMessage(chat_id, "Fan: OFF")

        elif command == '/alaon':
            ser.flushInput()
            ser.flushOutput()
            ser.write(b'c')
            time.sleep(0.25)
            bot.sendMessage(chat_id, "Alarm: ON")
         elif command == '/alaoff':
            ser.flushInput()
            ser.flushOutput()
            ser.write(b'd')
            time.sleep(0.25)
            bot.sendMessage(chat_id, "Alarm: OFF")

         else:
            pass

# Bot API
bot = telepot.Bot('Token obtained previously')
# bot.notifyOnMessage(handle)
bot.message_loop(handle)
print 'I am listening ...'
# Listen to the messages
while 1:
       time.sleep(10)

Now run the Personal Assistant with the command python pa.py and response will be I am listening…:

opl10

 

 

You can now try the several commands /fanon, /fanoff, /alaon, /alaoff /status on Telegram:

opl31

AXE056 board will show LEDs 1 (yellow) and 2 (red) switching ON and OFF according to the commands you will send with Telegram.

The command /status will tell the state of the LEDs, and will give you extra information on local temperature read by DS1820 and luminosity read by LDR on the same AXE056 board.

To run pa.py as a daemon, you can use the following command:

nohup python pa.py &

opl32

 

The response will be similar to:

opl33

and then write exit

Acknowledgments

A special  thank you to the Telegram Messaging team for offering us all Telegram services, and most recently the usage of Telegram Bots!

Armbian offers Debian Jessie for Orange Pi Lite Wifi. There was nothing special, and very easy, to get the Debian Jessie OS on Orange Pi Lite. As a thank you, I donated a small amount to the Armbian.

Also a thank you to for inspiration of this project to:

Addenda

I have added a heatsink and a fan to the Orange Pi Lite Wifi set up. It was heating up before to temperatures as high as 64ºC (of course in plastic box without ventilation).

Now Orange Pi Lite Wifi works at arounf 29ºC.

I know it is a bit of overkill. The following images depict what has been done.

opl36

opl34

Conclusions

We have connected Telegram to a real world device (a PIC micrcontroller, Picaxe is after all a PIC) allowing  us to use it to control, and find status of the pins on the PIC device.  We can add lots of others features to this basic Personal Assistant bot such as:

  1. Tracking time
  2. Running a scheduler and alerts
  3. Taking notes
  4. Controlling remotely our home/office, garage door, etc
  5. etc. imagination is the limit

It is not necessary Orange Pi Lite Wifi to do this project. You can do it easily with Raspberry Pi, or Banana Pi.

If I can be any assistance in your project with Telegram inspired on my project, please write here in comments, and I will do my best to reply. Also, if you do anything different with Telegram inspired on my work, please share links here.

Also if there is anything wrong with this please let me know too.

Posted in Uncategorized | Leave a comment

2015 in review for RedAcacia

2016 is coming, two days to go. A big thank you to all visitors and participans of this humble technical blog.

The WordPress.com stats helpers prepared a 2015 annual report for this blog.

Here’s an excerpt:

Madison Square Garden can seat 20,000 people for a concert. This blog was viewed about 69,000 times in 2015. If it were a concert at Madison Square Garden, it would take about 3 sold-out performances for that many people to see it.

Click here to see the complete report.

Posted in Uncategorized | Leave a comment

Visual Programming Editor ArduBlock for chipKIT

Introduction

In computing, a visual programming language (VPL) is any programming language that lets users create programs by manipulating program elements graphically rather than by specifying them textually. A VPL allows programming with visual expressions, spatial arrangements of text and graphic symbols, used either as elements of syntax or secondary notation. For example, many VPLs (known as dataflow or diagrammatic programming)[1] are based on the idea of “boxes and arrows”, where boxes or other screen objects are treated as entities, connected by arrows, lines or arcs which represent relations [2]

Programming chipKIT, or for that matter Arduino, may be complicated for beginners. Visual Programming environments, such as of ArduBlock, can be a simple and easy solution for such beginners.  ArduBlock is a programming environment designed to make “physical computing with Arduino /chipKIT as easy as drag-and-drop.” Instead of writing code, worrying about syntax, and (mis)placing semicolons, ArduBlock allows you to visually program with an snapped-together list of code blocks.

ArduBlock builds on the simplicity of Arduino /chipKIT, and creates a perfect beginner gateway to physical computing. Instead of tearing your hair out debugging, you can spend your time creating! (2)

Required Materials

IMG_20150512_151527

Installing ArduBlock

ArduBlock will work as an add-on, or more precisely a a tool, in chipKIT programming environment. It requires that you have either MPIDE or UECIDE installed. The benefit of that, though, is – because MPIDE or UECIDE are multi-platform (Windows, Mac, or Linux) ArduBlock works in all of these platforms .

How to install in MPIDE and in UECIDE programming environments? See below:

a) In MPIDE

ArduBlock comes with no installer, just a Java file that needs to be stored in a very specific location in MPIDE.

  • Download and Install MPIDE (if you haven’t already) – Ardublock is a tool that can be installed in MPIDE, so first of all you to have MPIDE installed on your computer.
  • Download ArduBlock – Click the link to the left, or head over to the ArduBlock Sourceforge page to find the latest and most recent version.
  • Identify your MPIDE Sketchbook location – This is a folder on your computer where your sketches and libraries are saved by default. To find your sketchbook location, run MPIDE,  and go to File > Preferences.

preferences1

  • And open Preferences

preferences2

The contents of the top text box defines your sketchbook location. Memorize that location and close MPIDE.

  • Create in sketchbook folder the folders tools/ArduBlockTool/tool/

Note: each folder is case sensitive.

The Ardublock file you downloaded earlier needs to locted inside tool folder within MPIDE sketchbook.

preferences3

  • Start MPIDE – Or restart it if it was open.
  • Select the Board and Serial Port: make your board (our caseuC32) and serial port selections (that you can know from Panel Control) from the “Tools” menu.
  • Open ArduBlock – Run ArduBlock by clicking Tools > ArduBlock. If you don’t see an entry for ArduBlock here, double-check to make sure your directories are all correctly typed and cased.

preferences4

ArduBlock works together with MPIDE editor – it relies on the IDE being open in the background, so MPIDE window must remain open!

b) In UECIDE

  • Download and Install UECIDE (if you haven’t already) – Ardublock is a tool that can be installed in UECIDE, so first of all you to have UECIDE installed on your computer. Check out the tour of UECIDE.
  • You will be asked to add plugins right at beginning. Choose chipKIT and the board your are using (in this case it is uC32)
  • Insstalling ArduBlock tool is straight forward in UECIDE! Open Tools -> Plugin Manager. A popup windows will open. Choose Plugins:

uecide1

 

  • Immediately the download arrow on top menu of this windows will be selected:

uecide2

  • Click on the downard arrow and the ArduBlock tool plugin will be downloaded and installed automatically.
  • Now restart UECIDE and you will see ArduBlock has been installed as a tool. You need to tell UECIDE the port at which your chipKIT board is under Hardware.

uecide3

So tha is it! Just as with MPIDE, ArduBlock works together with UECIDE editor – it relies on the IDE being open in the background, so UECIDE window must remain open!

Usage of ArduBlock

Start ArduBlock either in MPIDE or UECIDE whichever IDE you installed.

The ArduBlock window is split into two halves. The leftside of main interface contains the modules that contain blocks used for programming.

Every ArduBlock program requires a Program block, which you can find in the Control module. The Program block defines the setup and loop functions that every Arduino /chipKIT program requires.

ardu1

From dragging and dropping Program block, you can drag and drop more Blocks over, snapping them into either the setup or loop sections of Program block.

First Project: Blinking Led

Before you start uC32 board must be connected to your PC snd Basic I/O board installed on top of it.

Drag, drop and snap the required blocks to obtain the result shown below:

chap2

Now if you upload clicking Upload to Arduino you will see on MPIDE editor the sketch and this will be automatically uploaded to chipKIT uC32. After uC32 board resetting you will see Led 26 on Basic I/O shield blinking.

All exercises contained in “Getting Started with chipKIT” book by Chuck Hellebuick have been carried out based on uC32, Basic I/O shield and the components mentioned above. Pins have been adapted to work with Basic I/O shield.

Chap 2: As shown above

Chap 3: As shown below:

chap3

Chap 4: As shown below:

chap4

All of chapters have been tried and tested and commented. Only chapter 11 Serial Communication has not been tried and tested, but it should be also to set up.

Download all the duly commented ArduBlock sketches (chap 2 to 10) kept at Bitbucket, an unlimited free private repositories’ site.

Video

Watch a video published on YouTube showing chipKIT uc32 playing various tones through a buzzer:

Conclusion

Before writing this tutorial I tried Scratch for Arduino (S4A),  and other Visual Programming editors. None do seem so much functional as ArduBlock, specially because they all worked only as an interface connecting serially, or by network to Arduino / ChipKIT.

ArduBlock, and now BlocklyDuino,  a new and promising Web-based visual programming editor for Arduino /chipKIT, are ideal for beginners that, after learning to program with graphical elements, can easily progress to more complex Arduino C-like programming language.

 

Posted in Uncategorized | 1 Comment

Remote Control with Telegram and chipKIT uC32, Basic I/O shield with 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
  • Install Telegram in Raspberry Pi
  • Make Raspberry Pi with a Python program to read from the USB port, and to accept commands from Telegram
  • Write a Lua script to accept commands from Telegram, and to control the previously written Python program

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

My setup is as following photo shows:

setup1

Procedure

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.

d) Install Telegram in Raspberry Pi

The starting point of installing Telegram is the vysheng github project which contains also installation instructions.

First we install packages needed to build telegram by typing on Terminal:

 sudo apt-get install libreadline-dev libconfig-dev libssl-dev lua5.2 liblua5.2-dev libevent-dev make

Next, we clone Telegram CLI from github, making sure we are in /home/pi directory:

 git clone --recursive https://github.com/vysheng/tg.git && cd tg 

The recursive call is because two sub-projects tgl and tl-parser are also required. The && cd tg means that you end up in the tg directory ready for the next phase.

Before doing anything else we will make sure you we have enough /tmp for the compilation, by enlarging /tmp. 

We need more space due to the fact that gcc places the intermediate compilation result (i.e. the expanded asm code + macros) in /tmp before linking takes place. Compilation fails if /tmp is too small. We will increase it 100MB. So edit /etc/fstab with:

 sudo nano /etc/fstab

Add the following:

 tmpfs /tmp tmpfs defaults,noatime,mode=1777,size=100m 0 0

The  “size=100m” and similar other parameters force the RAM size used for the corresponding temporary file to certain megabytes. The “m” suffix corresponds to “mega bytes”.

Save and reboot

Make sure you are in /home/pi/tg directory. We make a build directory in order not to clutter the source code with intermediate object files.

 mkdir build && cd build 

Now we carry out the compilation there inside /home/pi/tg/build

  ../configure 

Next we will compile

 make 

Compilation takes a while, but eventually you will be greeted hopefully with a successful installation.

 e) Setting up Telegram

Telegram is based on (free) accounts associating a user name and a mobile phone number. In order to set things up you really need access to TWO phone numbers, although thereafter you only need ONE mobile phone to use it.

It is advisable to set up the Raspberry Pi to use the other mobile phone number that you will not be using. This second phone is only really needed to authenticate the account.

I actually did all the set up in Raspberry Pi.

Initially we can test telegram from the inside the folder /home/pi/build/bin. We will move later the binary files elsewhere so that they are easier to access and use.

First type the command inside /home/pi/tg/build/bin

 ./telegram-cli -k tg-server.pub -W 

You should see some information printed about telegram, ending with a > prompt on the screen.

Press the “Enter” key a couple of times, and wait.

You should then see a prompt phone number:

Type in the phone number of a phone you have just set up, including the country code. eg
+351912345678

Note, we will need access to the mobile phone in order to get a 5 digits authentication code.

We should then see the response:

code (‘call’ for phone call):

After a pause, we should get a SMS on the mobile phone we have just registered containing a 5 digits code number. Alternatively if you don’t receive the code it can ring you 2 minutes later and give you the code with an automatic voice.

Type this number into the Pi terminal and press “Enter”, to authenticate it.

We have set up Telegram in Raspberry Pi. The following image shows steps taken in my case /I have blured relevant information for basic security reasons):

setup

Now we need to install Telegram in our own phone. I have installed “Unofficial IM App for Telegram” in my BlackBerry BB10 from Blackberry World. Apple Store and Google Play have official Telegram apps that you can download and install in your phone.

The first time we start Telegram in our phone we must enter the phone number, including land code (for example Portugal is +351).

Justas before we should receive on our phone a SMS message with a 5 digits code. Write the code and press “Enter”

Now we are ready to use telegram. In Raspberry Pi’s > pronpt write:

 msg <Name_Lastname> testing message from Raspberry 

Substitute <Name_Lastname> with the names you have just registered not forgetting that you need to use _ underscore between the first and last name.

You should get a message in your phone’s Telegram app. You can add the phone number you have used to register Telegram in your Raspberry Pi and then test sending a message.

The Terminal of your Raspberry Pi as well as your phone’s App will show the messages.

e) Write a Python program for Telegram

We will now write a Python program for reading from USB port, and accepting commands from Telegram.

Before we do anything else we need to install Pexpect which is found in The Python Package Index or better knows as PyPi,  which is a repository of Python programs. Hence we will need to install it write in Raspberry Pi’s Terminal:

 sudo apt-get install python-pip 

 

After that, we will download Pexpect from the repository writing:

 pip install pexpect 

 

And that is it.

Now in /home/pi/tg/build/bin directory of your Raspberry Pi, write the following code, and name it tempmon.py. You can use the default nano editor.

#!usr/bin/env
#tempmon.py

import pexpect
import serial

ser = serial.Serial("/dev/ttyUSB0", 9600, timeout=2)

contact = "<Name_Lastname>" # substitute with registered name
telegram = pexpect.spawn('./telegram-cli -k tg-server.pub')

while True:
 ser.flush()
 data = ser.readline()
 telegram.expect('status', timeout=None)
 if (data != ""):
     data = ser.readline()
     processed_data = data.split(',')
     Data1 = str(processed_data[0])
     Data2 = str(processed_data[1])
     Data3 = str(processed_data[2])
     telegram.sendline('msg '+contact+' '+Data1+' '+Data3)
     print ('Message sent to '+ contact)
     telegram.sendline('quit')

Now run this code saved as tempmon.py

python /home/pi/tg/build/bin/tempmon.py

You will see the program waiting for a message from Telegram. Write “status” in your Telegram app. Immediate shortly you will see a message on Raspberry Pi’s Terminal:

Message sent to <Name_Lastname>

In your phone’s Telegram app you will see 26.0 OK or whatever temperature is read in ºC and if it is OK or there’s an ALERT.

IMG_20150423_184505

The following image shows Telegram working from PC’s desktop using the same phone number (Telegram functions in multiple devices):

telegram_desktop NOTE: I am enabling ALERT with rightmost switch on Basic I/O shield in top position.

f) Write a Lua script for Telegram

We will modify test.lua script.

Before writing anything, there were two further packages which needed to be installed on the Raspberry Pi. Write:

 sudo apt-get install lua-lgi libnotify-dev

After installing you can try using the test.lua script

Once /home/pi/tg/build/bin directory type in:

 ./telegram-cli -k tg-server.pub -s test.lua

This should start Telegram with the line before the prompt saying:

Hi, this is lua script

We can try a couple of the procedures already built into it.

From your phone’s Telegram app send the message ping to your Raspberry Pi.

You Raspberry Pi should respond with the reply pong

Next send the message  PING (all caps) to your Raspberry Pi. This time Raspberry Pi will respond with:

Forwarded from Your Name
PING

First we will copy action.lua script in order to keep it intact for any references, or changes:

 cp action.lua tempmon.lua

Now let us edit tempmon.lua with:

 sudo nano tempmon.lua

We will add a path variable to the beginning of the file, so that it will be easy to use telegram and the extra python scripts we will develop from any defined location. Immediately after the first two lines which set the variables started and our_id we will insert a line:

 path = os.getenv("HOME")..'/tg/build/bin'

After function on_msg_receive (msg) find:

do_notify (get_title (msg.from, msg.to), msg.text) 

Next to this add the following code:


if (msg.text == 'check') then
if (msg.to.id == our_id) then
os.execute('python '..path..'/tempmon.py')
send_msg (msg.from.print_name, 'Ready to check status', ok_cb, false)
else
send_msg (msg.to.print_name, 'Ready to check...', ok_cb, false)
end
return
end



Save <strong>tempmon.lua</strong> and we are now ready to test our set up.

<strong>g) Testing the set up for Remote Control</strong>

Run <strong>tempmon.lu</strong>a script by writing the following:

 ./telegram-cli -k tg-server.pub -s tempmon.lua 

In your phone's Telegram app write: check

Next write: status

Raspberry Pi will reply with temperature and if everything is OK or there is an Alert!

The Raspberry Pi's Terminal will show a prompt and the dumping of Python program when closing:

lua_running

The following image shows the Telegram app the sending of commands and messages that have been received in my phone:

IMG_20150423_201434

ALERT is enabled by putting in UP position the righmost switch on Basic I/O shield.

The following image shows the whole set up on a desktop at my company Aliatron:

setup2

What next?

In fact imagination and resources are the limit. We can add a camera that will send us snapshots of our control process, we can control equipment and devices and receive feedback from them, and much more.

In fact IM (Instant Message) apps such as Telegram can add a whole new dimension to Automation, provided security issues are addressed.

Acknowledgements

A special thank you is due to Robin Newman for his excellent tutorial at https://rbnrpi.wordpress.com.  Everything Robin Newman wrote worked, and his post was an inspiration for this one I have just written.

A thank you is also due to Geeky Theory and their execellent website for the tutorial of Pexpect.

I had difficulties in compiling Lua, and could only sort it out after increasing the size of /tmp directory. A special thank you is due to Darmawan Salihun for his simple explanations.

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 and proof of concept, with very same idea of connecting up with Raspberry Pi.

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

Control Remotely a FM Radio module using RDA5807M with a Digilent chipKIT uC32 and Basic I/O

The RDA5807M – an equivalent of Philips TEA5767 and pin-to-pin compatible – is a single-chip broadcast FM stereo radio tuner with fully integrated synthesizer, IF selectivity and MPX decoder. The tuner uses the CMOS process, support multi-interface and require the least external component.  It is completely adjustment-free.

A previous tutorial published here, shows step by step how a Digilent chipKIT  uC32 board and Basic I/O shield communicating in I²C protocol with the RDA5807M module can be quite a powerful, yet simple, FM Radio tuner. 

Requirements

tempmon1

rda5807_radio

sweex_bt

jy_mcu

Software DAQ ProfiLab-Expert 4.0

* Note: The latest MPIDE-0023-wiindows-20140821 does not compile I2C read so you will need to use a test software such as MPIDE-0150-wiindows-20150103

Procedures

a) Install libraries of Basic I/O Shield in MPIDE environment for 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:

tempmon5So here we are to go to next procedure

b) Hardware set up

In the first place prepare Digilent chipKIT uC32 board for I²C communication in pins A5 and A6.

On uC32 you must have Jumpers JP6 and JP8 set in the RG3 and RG2 positions.

jumpersInstall the Basic I/O shield on top of Uc32 as shown on the above image . Connect to the PC with USB cable. USB connection will power the Uc32 and the Basic I/O shield simultaneously. Connect the FM module to uC32 and Basic I/O shield.

The following circuit diagram shows the connections to FM Radio and Bluetooth modules:

fmradio_rcc) Firmware installation

We assume that you have already installed MPIDE environment.

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

Run MPIDE

We will use RDA5807M in Philips TEA5767 mode.

Now do File -> New and write the following Sketch:


/*
Code based on Dr Monk's TEA5767 FM Radio Breakout Board for Arduino
http://www.doctormonk.com/2012/03/tea5767-fm-radio-breakout-board-for.html
A similar but more advanced project have a look at:
http://www.electronicsblog.net/arduino-fm-receiver-with-tea5767/

Adapted for Profilab-Expert 4.0, Digilent chipKIT uc32 and Basic I/O shield
by Tayeb Habib tayeb.habib@gmail.com http://redacacia.me
For manual mode with potentiometer and remote mode withe Bluetooth   
*/
#include <Wire.h>
#include <IOShieldOled.h>

unsigned char frequencyH = 0;
unsigned char frequencyL = 0;

unsigned int frequencyB;
double frequency = 0;

unsigned char buffer[5];

int LED = 26;
int BUTTON = 35;
int freq=0;
int tensf = 0;
int onesf = 0;
int dot_tensf = 0;
int dot_onesf = 0;

int level = 0;
int onesl = 0;
int tensl = 0;

void setup()
{
  Wire.begin();
  frequency = 89.5; //starting frequency
  setFrequency();
  Serial.begin(9600);
  IOShieldOled.begin();
  IOShieldOled.displayOn();
  pinMode(LED,OUTPUT);
  pinMode(BUTTON,INPUT);
}

void loop()
{
   if (digitalRead(BUTTON) == LOW) // manual mode
      {
       digitalWrite(LED,LOW);
       int reading = analogRead(0);
       frequency = ((double)reading * (108.0 - 87.5)) / 1024.0 + 87.5;
       setFrequency();
       setDisplay();
       }
   if (digitalRead(BUTTON) == HIGH) // remote mode
      {
       digitalWrite(LED,HIGH);
       // send data only when you receive data:
       while (Serial.available() > 0) {
        // read the incoming byte:
        if (Serial.read() == '\n')
        {
          frequency = Serial.parseFloat();
          setFrequency();
          setDisplay();
        }
       }
     }
}

void setFrequency()
{
  frequency = ((int)(frequency * 10)) / 10.0;
  frequencyB = 4 * (frequency * 1000000 + 225000) / 32768;
  frequencyH = frequencyB >> 8;
  frequencyL = frequencyB & 0XFF;
  delay(100);
  Wire.beginTransmission(0x60);
  Wire.write(frequencyH);
  Wire.write(frequencyL);
  Wire.write(0xB0);
  Wire.write(0x10);
  Wire.write((byte)0x00);
  Wire.endTransmission();
  delay(100);  
}

void setDisplay()
{
  Wire.requestFrom(0x60,5); // reading from RDA5807M
        if (Wire.available());
          {
          for (int i=0; i<5; i++) {
          buffer[i] = Wire.read();
          }
     
 
          // OLED display start up
          IOShieldOled.displayOn();
 
          // Display information on OLED display
          IOShieldOled.setCursor(0, 0);
          IOShieldOled.putString("    FM RADIO");
          IOShieldOled.setCursor(0, 2);
          IOShieldOled.putString("FREQ ");
          
          freq = frequency*100;
          dot_onesf = freq%10;
          freq = freq/10;
          dot_tensf = freq%10;
          freq = freq/10;
          onesf = freq%10;
          freq = freq/10;
          tensf = freq%10;
          freq = freq/10;
 
 
          //convert data to ASCII
          tensf = tensf+48;
          onesf = onesf+48;
          dot_tensf = dot_tensf+48;
          dot_onesf = dot_onesf+48;
          IOShieldOled.setCursor(6, 2);
          if (tensf <= 48)
           {
            IOShieldOled.putString("1");
           }
          else
           {
             IOShieldOled.putString(" ");
           }
          IOShieldOled.setCursor(7, 2);
          IOShieldOled.putChar(tensf);
          IOShieldOled.setCursor(8, 2);
          IOShieldOled.putChar(onesf);
          IOShieldOled.setCursor(9, 2);
          IOShieldOled.putString(".");
          IOShieldOled.setCursor(10, 2);
          IOShieldOled.putChar(dot_tensf);
          // IOShieldOled.setCursor(11, 2);
          // IOShieldOled.putChar(dot_onesf);
          IOShieldOled.setCursor(12, 2);
          IOShieldOled.putString("MHz ");
          IOShieldOled.setCursor(0, 3);
          if (buffer[2]&0x80)
           {
            IOShieldOled.putString("STE ");
           }
          else
           {
             IOShieldOled.putString("MON ");
           }
 
          IOShieldOled.setCursor(5, 3);
          IOShieldOled.putString("SIG");
          level = buffer[3]>>4;   //extract level of signal
          // Serial.println(level);
          onesl = level/10;
          // Serial.println(onesl);
          tensl = level/10;
          tensl = level%10;
          // Serial.println(tensl);
          // Convert into ASCII
          onesl = onesl + 48;
          tensl = tensl + 48;
          IOShieldOled.setCursor(9, 3);
          IOShieldOled.putChar(onesl);
          IOShieldOled.setCursor(10, 3);
          IOShieldOled.putChar(tensl);
          IOShieldOled.setCursor(11, 3);
          IOShieldOled.putString("/16");
          }
}
 

Now first run the code with Verify verify to check if it compiles with errors. If does not compile, check the code and compare with the one above. A successful compilation MPIDE will  show a message similar to the following:

rda5807m_rc1Check that your COM port. In my case it is COM30.

Now click on Upload button upload_button. With a successful upload MPIDE will show a message similar to the following:rda5807m_rc

If all is well you can now tune FM Radio stations.

d) Manual Mode Tuning

The pot on Basic I/O shield is used to tune in the radio stations in manual mode. The following image shows a tuned station in Manual mode i.e. with switch 35 in position OFF:

rda5807m_rc2e) Remote Mode Tuning

For this a Front Panel for PC must be designed. In our case here I have designed a project in Profilab-Expert 4.0 as shown below:

rda5807m_rc23You can download the project from here, that s being kept at BitBucket a free and unlimited repository for private usage.

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 system tray a Bluetooth symbol. After activating Bluetooth, I have the option to find the local Bluetooth connections:

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

hc06_detectedNext, we will connect to JY-MCU Bluetooth module (found in my PC in COM15):

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

hc06_pairing_requestI 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_pairedWe next connect HC-06 to the serial port of your PC (in my case it is COM15):

rda5807m_rc3The HC-06 icon will now change to green:

hc06_connectedThe LED on JY-MCU will stop blinking and will be ON continuously.

Now make sure that the COM port used by your ProfiLab-Expert 4.0 project is same as the one of your Bluetooth connection. You will note that in my case it COM15. Double click COM icon and change the value in ProfiLab-Expert 4.0 project:

rda5807m_rc4Now Run the ProfiLab-Expert 4.0 project clicking the Start button rda5807m_rc5 or by clicking F9 button of your keyboard.

First connect external power supply to set up consisting of the Digilent chipKIT uC32 board and Basic I/O shield.

You will now need to place the switch 35 in Basic I/O in ON position. LED 26 on Basic I/O will be ON. The tuning of Radio station can be done by moving the Tuning Knob on the Front Panel. In our case we have tuned again 92MHz (Radio Amalia in Portugal):

rda5807m_rc6The following image shows what is going on with the Basic I/O shield:

rda5807m_rc8The interesting feature of the ProfiLab-Expert 4.0 project is that the Panel remembers the last tuned station.

Our full set up in Remote Mode tuning:

rda5807m_rc7

What Next?

1) Use the EEPROM on Basic I/O shield to memorize tuned Radio stations.  Memorization can be done remotely on pressing a button on the Front Panel, or a physical button on Basic I/O shield.

2) Get feedback on Front Panel that a station has been tuned in by reading the signal strength on RDA5807M

3) Make a stand-alone application of the Front Panel Project that runs on systems without ProfiLab-Expert 4.0 making use of integrated compiler that can create executable autonomous 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 be run by unauthorized persons.

 

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

2014 in review of RedAcacia blog

The WordPress.com stats helper prepared a 2014 annual report for this blog.

Here’s an excerpt:

The concert hall at the Sydney Opera House holds 2,700 people. This blog was viewed about 60,000 times in 2014. If it were a concert at Sydney Opera House, it would take about 22 sold-out performances for that many people to see it.

Click here to see the complete report.

Posted in Uncategorized | Leave a comment

FM Radio using RDA5807M module with Digilent chipKIT uC32 and Basic I/O

Introduction

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.

The RDA5807M – an equivalent of Philips TEA5767 and pin-to-pin compatible – is a single-chip broadcast FM stereo radio tuner with fully integrated synthesizer, IF selectivity and MPX decoder. The tuner uses the CMOS process, support multi-interface and require the least external component.  It is completely adjustment-free. The RDA5807M has a powerful low-IF digital audio processor, this make it have optimum sound quality with varying reception conditions. The RDA5807M can be tuned to the worldwide frequency band.

The Digilent chipKIT  uC32 and Basic I/O shield  communicating in I²C protocol with the RDA5807M module can be quite a powerful, yet simple, FM Radio tuner. I²C uses only two bidirectional open-drain lines, Serial Data Line (SDA) and Serial Clock Line (SCL), pulled up with resistors. Typical voltages used are +5 V or +3.3 V although systems with other voltages are permitted.

Requirements

tempmon1

rda5807_radio

Procedures

a) Install libraries of Basic I/O Shield in MPIDE environment for 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:

tempmon5So here we are to go to next procedure

b) Hardware set up

In the first place prepare Digilent chipKIT uC32 board for I²C communication in pins A5 and A6.

On uC32 you must have Jumpers JP6 and JP8 set in the RG3 and RG2 positions.

jumpersInstall the Basic I/O shield on top of Uc32 as shown on the above image . Connect to the PC with USB cable. USB connection will power the Uc32 and the Basic I/O shield simultaneously. Connect the FM module to uC32 and Basic I/O shield.

The following circuit diagram shows the connections to FM Radio Module:

fmradioc) Firmware installation

We assume that you have already installed MPIDE environment.

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

Run MPIDE

We will use RDA5807M in Philips TEA5767 mode.

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


/*
Code based on Dr Monk's TEA5767 FM Radio Breakout Board
for Arduino at:
http://www.doctormonk.com/2012/03/tea5767-fm-radio-breakout-board-for.html
For a similar but more advanced project have a look at:
http://www.electronicsblog.net/arduino-fm-receiver-with-tea5767/

Adapted for Digilent chipKIT uc32 and Basic I/O shield by
Tayeb Habib tayeb.habb@gmail.com http://redacacia.me

*/

#include <Wire.h>
#include <IOShieldOled.h>

unsigned char frequencyH = 0;
unsigned char frequencyL = 0;

unsigned int frequencyB;
double frequency = 0;

int tensf = 0;
int onesf = 0;
int dot_tensf = 0;
int dot_onesf = 0;
int freq=0;
void setup()
{
Wire.begin();
frequency = 89.5; //starting frequency
setFrequency();
Serial.begin(9600);
IOShieldOled.begin();
IOShieldOled.displayOn();
}

void loop()
 {
   int reading = analogRead(0);

   frequency = ((double)reading *(108.0 - 87.5))/1024.0 + 87.5;
   frequency = ((int)(frequency * 10))/10.0;

   setFrequency();

   // to view frequency with Tools >> Serial Monitor
   // Serial.println(frequency);

   freq = frequency*100;
   dot_onesf = freq%10;
   freq = freq/10;
   dot_tensf = freq%10;
   freq = freq/10;
   onesf = freq%10;
   freq = freq/10;
   tensf = freq%10;
   freq = freq/10;

   //convert the digits data to ASCII
   tensf = tensf+48;
   onesf = onesf+48;
   dot_tensf = dot_tensf+48;
   dot_onesf = dot_onesf+48;

   // OLED display start up
   IOShieldOled.displayOn();

      {// Display information on OLED display
   IOShieldOled.setCursor(0, 0);
   IOShieldOled.putString("FM Radio");
   IOShieldOled.setCursor(0, 2);
      if (tensf <= 48) //ASCII equivalent of zero
      { IOShieldOled.putString("1");
      }
      else
      {
        IOShieldOled.putString(" ");
      }
   IOShieldOled.setCursor(1, 2);
   IOShieldOled.putChar(tensf);
   IOShieldOled.setCursor(2, 2);
   IOShieldOled.putChar(onesf);
   IOShieldOled.setCursor(3, 2);
   IOShieldOled.putString(".");
   IOShieldOled.setCursor(4, 2);
   IOShieldOled.putChar(dot_tensf);
   IOShieldOled.setCursor(5, 2);
   IOShieldOled.putChar(dot_onesf);
   IOShieldOled.setCursor(7, 2);
   IOShieldOled.putString("MHz");
  }

void setFrequency()
 {
   frequencyB = 4* (frequency*1000000 + 225000)/32768;
   frequencyH = frequencyB >> 8;
   frequencyL = frequencyB & 0XFF;
   delay(100);
   Wire.beginTransmission(0x60);
   Wire.write(frequencyH);
   Wire.write(frequencyL);
   Wire.write(0xB0);
   Wire.write(0x10);
   Wire.write((byte)0x00);
   Wire.endTransmission();
   delay(100);
 }

Now first run the code with Verify verify to check if it compiles with errors. If does not compile, check the code and compare with the one above. A successful compilation MPIDE will  show a message similar to the following:

compilingNow we are ready to upload the firmware.

Check that your COM port. In my case it is COM30.

Now click on Upload button upload_button. With a successful upload MPIDE will show a message similar to the following:

uploadedIf all is well you can now tune FM Radio stations. The pot on Basic I/O is to be used to tune in the radio stations.

Demonstration Video

I have uploaded a video on Youtube that you can view to see the FM Radio tuner in action:

Next Step

You can add more features like a LED switching on when a station is tuned in. If the station is STEREO or MONO broadcast show it on OLED dspaly, and many other options that RDA5807M module allows. RDA5807M is superior to Philips TEA5767, and has many other possibilities and features.

Conclusions

The Digilent chipKIT  uC32 and Basic I/O shield  communicating in I²C protocol with the RDA5807M module can be quite a powerful, yet simple, FM Radio tuner.

What we have done effectively is a proof-of-concept, i.e. that Digilent chipKIT uC32 can be an adequate replacement to Arduino Uno board to work as a tuner of FM Radio.

 

 

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

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