BBC micro:bit Temperature Measurement with Scilab

Introduction

The Micro Bit also referred to as BBC Micro Bit, stylised as micro:bit is an ARM-based embedded system designed by the BBC for use in computer education.

microbit

In my previous tutorial here in this blog,I showed how to read temperature with a purpose written app in App Inventor for Android phone that connects to BBC micro:bit through Bluetooth Low Energy (BLE). With an edge connector more pins can be accessed facilitating connection to other devices. Despite BBC micro:bit having hardware capable of allowing the device to work as a BLE device, it has disadvantage that only has 16k of RAM. The BLE stack alone takes up 12k RAM which means there is little room to run MicroPython and bigger codes.

Scilab is a free and open-source, cross-platform numerical computational package and a high-level, numerically oriented programming language. It can be used for signal processingstatistical analysisimage enhancementfluid dynamics simulations, numerical optimization, and modeling, simulation of explicit and implicit dynamical systems and (if the corresponding toolbox is installed) symbolic manipulations.

Scilab is one of the two major open-source alternatives to MATLAB, the other one being GNU OctaveScilab puts less emphasis on syntactic compatibility with MATLAB than Octave does, but it is similar enough that some authors suggest that it is easy to transfer skills between the two systems.

Objectives

Connect BBC micro:bit to Scilab for reading anf plotting temperature of the processor on micro:bit. Write the codes, using the simplest ways, for the BBC micro:bit and Scilab, and test the setup.

Requirements

  • BBC micro:bit
  • Edge-connector for BBC micro:bit: We used micro:bit IO F5 board  ( 8x OUTPUT, 6x INPUT) – INPUT signal to 5V)  Note that it is not needed in this project, only in next one when we will do control with Scilab.

  • Mini-USB cable connector for programming and serial connection
  • Scilab duly installed in your PC

Our Setup

Connect the small end of the cable to your micro:bit and the other end to your computer’s USB port.

Windows 10 & 8.1: Windows Update will fetch any necessary drivers. For earlier versions of Windows, (Windows 7, or Vista) if you would like to use serial communication (not necessary to program your micro:bit) you will also need the Arm MBED serial port driver.

Mac OS and LInux require no driver installs.

1. Coding the BBC micro:bit

Coding can be of several type offered for BBC micro:bit. You can code your BBC micro:bit using Blocks, JavaScript, Python, and mbed platform. We will use Blocks offered at http://microbit.org/code/ to install the firmware in simplest way.

We will use Serial communication with Scilab. Before we can use the micro:bit serial port, we need to install a serial terminal program, and we also need to install the USB serial driver. In this tutorial, we will be using Tera Term. To get the driver, start by following the links below, then follow the installation instructions.

The following image shows the Blocks we are going to chose that is available for USB serial communication found under Advanced blocks;

Now you are ready to write the code. Let’s code! We will write the following code with Blocks:

You can review the code under Javascript tab which will be as follows:

serial.redirect(
    SerialPin.USB_TX,
    SerialPin.USB_RX,
    BaudRate.BaudRate9600
)
basic.forever(function(){
    serial.writeString("\n" + "\r" + input.temperature())
    basic.pause(100)
})

Save the code giving it a name. And download the respective .hex file. I have also provided the hex file you can download from here. At this stage you should connect the BBC micro:bit to your PC (in my case with Windows 7 OS).

You are now ready to install the firmware on BBC micro:bit which behaves like a drive in your PC and will be visible. You will need to copy, or drag and drop, the hex file into BBC micro:bit:

microbit6

The hex file once dropped or pasted (“Colar” in above image means “Paste”) will install itself in BBC micro:bit, and run.

2. Testing the set up

We need to verify that the BBC micro:bit is sending the temperature readings through the USB. Im our case we tested with Tera Term that is free and open source and can be installed in one’s PC with Windows.

Download the Arm Mbed Windows serial port driver and install it.

We need to know the port name that our PC has given to the BBC micro:bit through USB connection.

To check the BBC micro:bit is seeen by PC As a serial device we open Device Manager and look under Ports (COM and LPT):

In our case here it is COM4. So let us view it on Tera Term. We select Serial and chose our Port (in our case COM4).

Clicking on OK immediately we will see on the Terminal opened by Tera Term the temperature readings:

3) Read temperture and plot with Scilab 

The test was carried on Scilab 5.5.1 as besides being stable has many modules. The most recent version of Scilab 6.0.1 presented problems and it is unwise to use it at the moment. We will not explain how to install Scilab 5.5.1.- There are plentiful of tutorialsshowing how to do.

Assuming Scilab is intalled we will ass he Serial communication module by a simple command:

atomsInstall("serial")

You may need to update the database of Scilab, and to install ATOMS library.

To avoid mistakes in script writing to read and plot the temperature, it is availalbe for download.

Once downloaded and opened in Scilab verify the line 62 position 4 and change the name of the port from “= 4” to whatever is port number is BBC micro:bit recognised by your PC:

We are now ready to run the script. Run the script by clicking onto Execute:

The script will open a window as shown with indiaction “Waiting for start”:

Clicking onto “Start measuring…” button Scilab will read the temperature and plot it as shown:

 The plot shows variation of temperature by blowing air with mouth, over the processor. If we click onto “Stop measuring“, Scilab will stop reading the temperature and the plot will stop.

Clicking again on “Start measuring…” button, Scilab will continue reading the temperture and plotting it.

Conclusions

Of course you can do more things with Scilab and BBC micro:bit, as we expect to do in our future post. Scilab is a powerful tool that can be used for signal processingstatistical analysisimage enhancementfluid dynamics simulations, numerical optimization, and modeling, simulation of explicit and implicit dynamical systems and symbolic manipulations.

Acknowledgments

A special thank you to Github for providing their free repository to facilitate sharing. Scilab and  Microbit coding sites also have special right to acknowledgements for their free services. Also a special mention is due to Paraschos Paraschos for inspiring me towards this post.

DISCLAIMER

THE SOFTWARE HERE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

Posted in Electronic Projects, Information Technolody, Programming | Tagged , , , , , , , , , , , , , , | Leave a comment

BBC micro:bit Robot Controlled with Swipe Gestures on Android Phone

Introduction

The Micro Bit also referred to as BBC Micro Bit, stylised as micro:bit is an ARM-based embedded system designed by the BBC for use in computer education.

microbit

In my previous tutorial I showed how to read temperature with a purpose written app in App Inventor for Android phone that connects to BBC micro:bit through Bluetooth Low Energy (BLE). With an edge connector more pins can be accessed facilitating connection to other devices. Despite BBC micro:bit having hardware capable of allowing the device to work as a BLE device, it has disadvantage that only has 16k of RAM. The BLE stack alone takes up 12k RAM which means there is little room to run MicroPython and bigger codes.

Objectives

Build a simple BBC micro:bit Robot. Write the code, using the simplest ways, for the BBC micro:bit and Android smartphone, and test the setup.

Requirements

Robô Móvel de Controlo Remoto (R2Bot)

  • L298 H-bridge module:

Módulo Excitador Duplo Ponte-H com L298N (MDB-L298N)

  • Two battery holders for powering BBC micro:bit and L298 H-module seoarately
  • Easy cables connections
  • Mini-USB cable connector for programming
  • A smartphone with Bluetooth Low Energy BLE

Circuit

Our proposed circuit is as shown below and note that we removed the jumpers of ENA and ENB in order to control the speed of motors,

Setup

Build the Robot, something similar to my mounting below:

 

1. Coding the BBC micro:bit

Coding can be of several type offered for BBC micro:bit. You can code your BBC micro:bit using Blocks, JavaScript, Python, and mbed platform. We will use Javascript offered at http://microbit.org/code/ to install the firmware in simplest way.

To use Bluetooth in your micro:bit application you first need to add the Bluetooth package to your project using the menu More/Add Package.

codethemicrobit

Once this is done (you may receive a warning of some incompatibilities, but do accept them) , you will have a complete collection of Bluetooth related Blocks with which can build the Bluetooth capabilities of your application. Many are very simple and merely result in a given Bluetooth service being available at run-time. But there are also blocks which provide access to Bluetooth connect and disconnect events and the Bluetooth UART service can be used to transmit arbitrary data to a connected peer or to receive data from a peer service.

The following image shows all the the blocks that will become available

codethemicrobit2

Now you are ready to write the code. Let’s code! We will write the following code in Javascript:

let uartData = ""
let connected = 0
bluetooth.onBluetoothDisconnected(() => {
    basic.showIcon(IconNames.No)
    connected = 0
    motorsoff()
})
bluetooth.onBluetoothConnected(() => {
    basic.showIcon(IconNames.Yes)
    connected = 1
    while (connected == 1) {
        uartData = bluetooth.uartReadUntil(serial.delimiters(Delimiters.NewLine))
        if (uartData.charAt(0) == "S") {
            motorsoff()
            basic.showLeds(`
            . . . . .
            . . . . .
            . . # . .
            . . . . .
            . . . . .
            `)
        }
        if (uartData.charAt(0) == "F") {
            motorson()
            pins.digitalWritePin(DigitalPin.P5, 1)
            pins.digitalWritePin(DigitalPin.P12, 0)
            pins.digitalWritePin(DigitalPin.P0, 1)
            pins.digitalWritePin(DigitalPin.P8, 0)
            basic.showArrow(ArrowNames.North)
        }
        if (uartData.charAt(0) == "B") {
            motorson()
            pins.digitalWritePin(DigitalPin.P5, 0)
            pins.digitalWritePin(DigitalPin.P12, 1)
            pins.digitalWritePin(DigitalPin.P0, 0)
            pins.digitalWritePin(DigitalPin.P8, 1)
            basic.showArrow(ArrowNames.South)
        }
        if (uartData.charAt(0) == "L") {
            motorson()
            pins.digitalWritePin(DigitalPin.P5, 0)
            pins.digitalWritePin(DigitalPin.P12, 0)
            pins.digitalWritePin(DigitalPin.P0, 1)
            pins.digitalWritePin(DigitalPin.P8, 0)
            basic.showArrow(ArrowNames.East)
        }
        if (uartData.charAt(0) == "R") {
            motorson()
            pins.digitalWritePin(DigitalPin.P5, 1)
            pins.digitalWritePin(DigitalPin.P12, 0)
            pins.digitalWritePin(DigitalPin.P0, 0)
            pins.digitalWritePin(DigitalPin.P8, 0)
            basic.showArrow(ArrowNames.West)
        }
    }
})
basic.forever(() => {
    bluetooth.startUartService()
})
basic.showString("I LOVE FAIZ")

function motorson() {
    pins.analogWritePin(AnalogPin.P2, 500)
    pins.analogWritePin(AnalogPin.P1, 500)
}

function motorsoff() {
    pins.digitalWritePin(DigitalPin.P2, 0)
    pins.digitalWritePin(DigitalPin.P5, 0)
}

Save the code giving it a name. And download the respective .hex file. I have also provided the hex file you can download from here. At this stage you should connect the BBC micro:bit to your PC (in my case with Windows 7 OS).

microbit5

You are now ready to install the firmware in BBC micro:bit which behaves like a drive in your PC and will be visible. You will need to copy, or drag and drop, the hex file into BBC micro:bit:

microbit6

The hex file once dropped or pasted (“Colar” in above image means “Paste”) will install itself in BBC micro:bit, and run.

microbit7

NOTE: I have since written an mbed code with slight modifications to connections to BBC micro:bit. You can find the direct link here.

2. Writing the App for Android

We will write now an App for Android smartphones using visual programming. MIT has MIT App Inventor (now version 2) that we will use to write the App.

MIT App Inventor is an open-source web application originally provided by Google, and now maintained by the Massachusetts Institute of Technology (MIT).

It allows newcomers to computer programming to create software applications for the Android operating system (OS). It uses a graphical interface, very similar to Scratch and the StarLogo TNG user interface, which allows users to drag-and-drop visual objects to create an application that can run on Android devices. In creating App Inventor, Google drew upon significant prior research in educational computing, as well as work done within Google on online development environments.

MIT App Inventor and the projects on which it is based are informed by constructionist learning theories, which emphasizes that programming can be a vehicle for engaging powerful ideas through active learning. As such, it is part of an ongoing movement in computers and education that began with the work of Seymour Papert and the MIT Logo Group in the 1960s and has also manifested itself with Mitchel Resnick‘s work on Lego Mindstorms and StarLogo.

MIT App Inventor is also supported with the Firebase Database extension. This allows people to store data on Google’s firebase.

a) Register yourself at http://ai2.appinventor.mit.edu/ using a Google or other accepted email account. We will first add Bluetooth Lower Energy blocks to MIT App Inventor-

b) First and foremost we need now to add the necessary extension. In the Palette windows click on Extension at the bootm and then on “Import extension” and click on “URL”. Paste the URL:

http://iot.appinventor.mit.edu/assets/com.bbc.microbit.profile.aix

c) I have done all the hard work and written the whole code that you can download from here. The file is named RobotControl.aia is made available at github.com repository that you can import into your MIT App Inventor account. You will, once imported, have to build and compile, and export the application with .apk extension into your Android phone, and install. You will find plenty of information in Internet on how to do it. If you are too lazy to do itor find difficult you can download the apk from here.

I have Voice so every time the robot is controlled a female robotic voice is heard on the phone, courtesy of  text2speech site that converts text to mp3 for us.

If you have difficulties for any parts of this tutorial do not hesitate to contact me.

3) Pairing Android phone with BBC micro:bit

Making your BBC micro:bit pair requires you to follow some simple steps which will be described shortly. What you do with the device you’re pairing it to will vary slightly depending on what that device is. We’ll look at how it’s done with common smartphones and tablets here too.

To get your micro:bit ready for pairing do the following:

  1. Hold down buttons A and B on the front of your micro:bit together. The front is the side with two buttons and the LED display. Keep the two buttons held down. Don’t let go of them yet!
  2. While still holding down buttons A and B, press and then release the reset button on the back of the micro:bit. Keep holding down buttons A and B.
  3. You should see “PAIRING MODE!” start to scroll across the micro:bit display. When you see this message start to appear you can release buttons A and B.
  4. Eventually you’ll see a strange pattern on your micro:bit display. This is like your micro:bit’s signature. Other people’s micro:bits will probably display a different pattern.

Your micro:bit is now ready to be paired with the other device.

4)Installing the App on Android phone

If you have installed the apk compiled from the .aia file (or the downloaded one) that I have provided you will see the following icon in your Android phone inside the red square:

Click on icon to start the App. Click on Scan button:

You will see the paired BLE devices including BBC micro:bit. Click on white letters containing data on the device that is paired that will become grey, and next click on  Connect button:

If all is well you will see the Status as Connected:

You will see the right sign on the BBC micro::bit robot and you will hear a female robotic voice in your Android phone saying “micro:bit Robot at your service!”.

If Bluetooth is disconnected by pressing Disconnect button or for any other reason, the display will show X which means disconnected!

5) Test your Robot

With swipe gesture on the screen in UP direction you will make our Robot move forward, and the female robotic voice in your phone saying “Forward”. If your swipe on the screen is in DOWN direction that will make the robot move backward, and again you hear the female robotic voice saying “Backward”. Swipe gesture to the LEFT will turn the robot to the left, and again the voice saying “Left”, and swipe gesture to RIGHT will turn the robot to the right, and the voice saying “Right”. If you click on the Stop / Reset button it will stop the robot, and the voice will say “Stop!”. Also you will see arrows on the display of the micro:bit. If you click on Disconnect button you will hear the voice saying “Goodbye!” and communication to the Robot will be lost.

Demo Video

Conclusions

Of course you can do more things with the Robot, for exmple detect obstacles and automatically make robot turn back, to avoid the obstacle and turn,  etc. If you do use any parts of my tutorial, please acknowledge my work with links to this blog.

Acknowledgments

A special thank you to Github for providing their free repository to facilitate sharing. MIT App Inventor and  Microbit coding site also have special right to acknowledgements for their free services. Also a special mention is due to Bit:Bot Tutorial website for inspiring me with code for Bluetooth UART.

I think I am the first person to share the whole project for micro:bit and writing an App for Android with App Inventor. May be I am wrong, and if I am please correct me.

DISCLAIMER

THE SOFTWARE HERE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

Posted in Electronic Projects, Information Technolody, Internet of Things, Mobile Apps, Programming, Robotic Projects, Uncategorized | Tagged , , , , , , , , , , , , , , , , , , , , | Leave a comment

Remote Reading of Temperature with BBC micro:bit and Bluetooth Low Energy BLE

Introduction

The Micro Bit also referred to as BBC Micro Bit, stylised as micro:bit is an ARM-based embedded system designed by the BBC for use in computer education.

microbit

The BBC micro:bit is a pocket-sized computer that lets you get creative with digital technology. Each order contains just the micro:bit board. You can code, customize and control your micro:bit from anywhere! You can use your micro:bit for all sorts of unique creations, from robots to musical instruments and more. At half the size of a credit card, you will be surprised at the amount of hardware each board is equipped with, including 25 red LED lights that can flash messages. There are two programmable buttons that can be used to control games or pause and skip songs on a playlist. The micro:bit can even detect motion and tell you which direction you’re heading. It can also use Bluetooth Low Energy (BLE) to interact with other devices and the Internet.

Taking a closer look at the front of the board, we can see the 5×5 LED array that you can use as a light sensor, a tiny screen to draw on, display words, numbers and other information, and the two programmable buttons! On the back of the board you will find the brains of the micro:bit, a 16MHz, 32-bit ARM Cortex-M0 microcontroller with 256KB Flash, 16KB RAM and a built-in temperature sensor. Additionally, the back of the micro:bit is populated by an accelerometer, compass and Bluetooth Smart antenna, as well as a microUSB and two-pin JST connector for different power options. Finally, at the bottom of the board you will find 20 gold-tabbed edge pins and five ring connectors (three for digital/analog I/O, two for power and ground) for hooking up external components. The tabs with larger holes can be easily used with alligator clips to prototype added components quickly.

Micro:bit has even supplied an intuitive mobile app that lets you send your code to your micro:bit over Bluetooth (without using a USB cable) and more. With this app you will be able to interact with your micro:bit on a higher level of accessibility.

Important: The micro:bit does not include any cables or power sources. This is just the board. We recommend picking up a micro:bit AA battery holder or a micro USB cable as well to power your board.

Features:

  • 32-bit ARM Cortex-M0 CPU
  • 256KB Flash
  • 16KB RAM
  • 5×5 Red LED Array
  • Two Programmable Buttons
  • Onboard Light, Compass, Accelerometer and Temp Sensors
  • BLE Smart Antenna
  • Three Digital/Analog Input/Output Rings
  • Two Power Rings — 3V and GND
  • 20-pin Edge Connector
  • MicroUSB Connector
  • JST-PH Battery Connector (Not JST-XH)
  • Reset Button with Status LED

Objectives

Read temperature remotely on an Android phone with BBC micro:bit and Bluetooth Low  Energy BLE. Write the codes, using the simplest ways, for the BBC micro:bit and Android smartphone, and test the setup.

Setup

Duly connected BBC micro:bit  through USB connector to PC and use an Android smartphone compatible with Bluetooth Low Energy BLE.

microbit3

1. Coding the BBC micro:bit

Coding can be of several type offered for BBC micro:bit. You can code your BBC micro:bit using Blocks, JavaScript, Python, and mbed platform. We will use Blocks offered at http://microbit.org/code/ to install the firmware in simplest way. Blocks provide a visual programming, drag-and-drop tool involving building application logic by arranging graphical programming blocks representing predefined, parameterised functions. And it’s very easy to use.

To use Bluetooth in your micro:bit application you first need to add the Bluetooth package to your project using the menu More/Add Package.

codethemicrobit

Once this is done (you may receive a warning of some incompatibilities, but do accept them) , you will have a complete collection of Bluetooth related Blocks with which can build the Bluetooth capabilities of your application. Many are very simple and merely result in a given Bluetooth service being available at run-time. But there are also blocks which provide access to Bluetooth connect and disconnect events and the Bluetooth UART service can be used to transmit arbitrary data to a connected peer or to receive data from a peer service.

The following image shows all the the blocks that will become available

codethemicrobit2

Now you are ready to write the code. Let’s code! Drag and drop the blocks to get the following result:

microbit4

Save the code giving it a name. And download the respective .hex file. At this stage you should connect the BBC micro:bit to your PC (in my case with Windows 7 OS).

microbit5

Yo are now ready to install the firmware in BBC micro:bit which behaves like a drive in your PC and will be visible. You will need to copy, or drag and drop, the hex file into BBC micro:bit:

microbit6

The hex file once dropped or pasted (“Colar” in above image means “Paste”) will install itself in BBC micro:bit, and run.

microbit7

2. Writing an App for Android

To stay in visual programming we will write now an App for Android smartphones. MIT has MIT App Inventor (now version 2) that we will use to write the App.

MIT App Inventor is an open-source web application originally provided by Google, and now maintained by the Massachusetts Institute of Technology (MIT).

It allows newcomers to computer programming to create software applications for the Android operating system (OS). It uses a graphical interface, very similar to Scratch and the StarLogo TNG user interface, which allows users to drag-and-drop visual objects to create an application that can run on Android devices. In creating App Inventor, Google drew upon significant prior research in educational computing, as well as work done within Google on online development environments.

MIT App Inventor and the projects on which it is based are informed by constructionist learning theories, which emphasizes that programming can be a vehicle for engaging powerful ideas through active learning. As such, it is part of an ongoing movement in computers and education that began with the work of Seymour Papert and the MIT Logo Group in the 1960s and has also manifested itself with Mitchel Resnick‘s work on Lego Mindstorms and StarLogo.

MIT App Inventor is also supported with the Firebase Database extension. This allows people to store data on Google’s firebase.

a) Register yourself at http://ai2.appinventor.mit.edu/ using a Google or other accepted email account. We will first add Bluetooth Lowe Energy blocks to MIT App Inventor-

b) First and foremost we need now to add the necessary extension. In the Palette windows click on Atension at the bootm and then on “Import extesnion” and click on “URL”. Paste the URL:

http://iot.appinventor.mit.edu/assets/com.bbc.microbit.profile.aix

c) We will not show all the steps you need to undertake nor of how to build the blocks blocks. I suggest you follow the tutorial by downloading and reading and following the tutorial at: http://iot.appinventor.mit.edu/assets/howtos/MIT_App_Inventor_Microbit_Temperature.pdf

If you are too lazy to write the App cyou can download the code here. The file named BLE_Temp_Mon.aia is made available at github.com repository that you can import into your MIT App Inventor account. You will, once imported, have to compile and export the application with .apk extension into your Android phone and isntall. You will find plenty of information in Internet on how to do it.

If you have difficulties for any parts of this tutorial do not hesitate to contact me.

3) Pairing Android phone with BBC micro:bit

Making your BBC micro:bit pair requires you to follow some simple steps which will be described shortly. What you do with the device you’re pairing it to will vary slightly depending on what that device is. We’ll look at how it’s done with common smartphones and tablets here too.

To get your micro:bit ready for pairing do the following:

  1. Hold down buttons A and B on the front of your micro:bit together. The front is the side with two buttons and the LED display. Keep the two buttons held down. Don’t let go of them yet!
  2. While still holding down buttons A and B, press and then release the reset button on the back of the micro:bit. Keep holding down buttons A and B.
  3. You should see “PAIRING MODE!” start to scroll across the micro:bit display. When you see this message start to appear you can release buttons A and B.
  4. Eventually you’ll see a strange pattern on your micro:bit display. This is like your micro:bit’s signature. Other people’s micro:bits will probably display a different pattern.

Your micro:bit is now ready to be paired with the other device.

4) Testing the App on Android phone

If you have installed the apk compiled from the .aia file that I have provided you will see the following icon in your Android phone:

Screenshot_20180307-143806

Click on icon to start the App. Click on Scan button:

Screenshot_20180307-143815

You will see the paired BLE device that is BBC micro:bit. Click on black labelled button containing data on the device that is paired and next click on  Connect button:

Screenshot_20180307-143822

If all is well you will see the Status as Connected and read the temperature in ºC:

Screenshot_20180307-144046

You will see the right sign on the BBC micro::bit:

microbit8

If Bluetooth is disconnected by pressing Disconnect button or for any other reason, the display will show X which means disconnected!

PSX_20180307_172216

Conclusions

Of course you can do more thinks like hearing the temperature om the Android phone writing a modification to App, and other things. Also, instead of using the ready made temperature block you can write your own one for the BBC micro:bit. If you do use any parts of my tutorial please acknowledge as I do here.

Acknowledgmenets

A special thank you to y Martin Woolley for inspiring articles and videos on BBC micro:bit, and one of his tutorial already acknowledged above. Also a special thanks to Github for providing their free repository to facilitate sharing. MIT App Inventor and  Microbit coding sites also have special right to acknowledgements for their free services.

Posted in Electronic Projects, Internet of Things, Mobile Apps, Programming, Uncategorized | Tagged , , , , , , , , , , , , , , , , | Leave a comment

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:
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:
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