IoT : Raspberry-Pi/Arduino with Node-Red

After interfacing Arduino with Raspbeery-Pi with the help of Python and Firmata now I am ready to explore the possibility of all IoT stuffs. To know how to interface with Arduino+Raspberry-Pi+Python see my previous blog:  Let us RAP…

Node-Red

Node-red Installation steps:

In my raspberry-Pi3, I am using Raspbian OS, in which Node-red is pre-installed.

But as per Node-red guide it is recommended to install the latest version. For upgrade or fresh installation of Node-Red, refer below guide:

Node-Red Installation

After successful installation try out with LED blink example.

Then few more stuffs need to install before getting on board.

  1.  Install  Node-Red DashBoard
  2. Install Arduino Node-Red
  3. Install Node-Red GPIO

Please make sure you have installed Wiring-Pi and Pi-Firmata in your raspberry Pi .

Watch this youtube video to see the example for controlling Arduino from Node-Red:

Arduino Node-Red Youtube

Below You Tube video shows the power of node-red !!

Let us RAP…

Raspberry pi controls Arduino using Python (RAP)

The Raspberry Pi is sometimes seen as competition to micro controllers like the Arduino. However the Raspberry Pi has a different sweet spot and can easily be combined with an Arduino to accomplish a wider range of tasks than otherwise possible. For example the missing Analog inputs.

arduino

Setting up your Arduino for Firmata

Firmata control of the Arduino requires loading an Arduino with the special Firmata sketch. You can download the Arduino software from the Arduino website. After opening the Arduino IDE, follow these steps to install Firmata on your Arduino:
1. Click File->Examples->Firmata->StandardFirmata
2. From the Tools->Board menu, select the type of Arduino you are using.
3. From the Tools->Serial Port menu, choose the USB port to which your Arduino is connected.
4. Click the upload button (it looks like a right arrow, just next to the checkmark) and wait for your sketch to upload. A message in the bottom black window will indicate success or failure
5. Once the Firmata sketch is loaded on your Arduino, you can test it out with the Firmata Test Program. (http://www.firmata.org/wiki/Main_Page)

Controlling your Arduino from Python

Next, your Raspberry Pi must be setup with the python firmata libraries. Run the following commands:

sudo apt-get install python-pip python-serial
sudo pip install pyfirmata

Use a USB cable to connect the Arduino with the Raspberry Pi (remember to use the big USB Standard A connector and not the smaller Micro B power connector). You can now find the USB name of the Arduino by running ‘ls -lrt /dev/tty*’. On my Raspberry Pi, it was listed as /dev/ttyUSB0. Remember this value for later.
Connecting to an Arduino
To control an Arduino from a Python script on your Raspberry Pi, you must first import the Arduino and util classes from the pyfirmata module. Then, create an object using the USB address you found in the previous step

>>> from pyfirmata import Arduino, util
>>> board = Arduino('/dev/ttyUSB0')

Controlling Arduino GPIO
The Arduino’s digital input and output ports can be controlled using the board.digital[] list. Calling write() can set the pin values high or low (1 and 0 respectively). The read() method returns the current value of the pin.

>>> board.digital[2].write(1)
>>> print board.digital[2].read()

If you’d like to use a pin repeatedly, its cumbersome to keep referring to it as board.digital[2]. Instead, you can get a reference to a pin with the board.get_pin() function. To this function, you pass a string of the format “[a|d]:[pin#]:[i:o:p:s]”. It is split by colons into three sections. The first section determines if the pin will be used in analog or digital mode. The second section is the number of the pin you would like to use. The third section selects the pin mode between input, output, pwm, and servo. The returned pin can be assigned to a variable and then later used to call read() and write() methods.

>>> pin2 = board.getpin('d:2:o')
>>> pin2.write(1)

Controlling Analog Pins
To read the value on an analog pin, you have to first turn on the analog value reporting on that pin. However, this continuously sends the analog value from the Arduino to the Raspberry Pi. If not continuously read, this will clog up the serial connection and prevent the rest of your script from running properly. To read the values, it is helpful to use an iterator thread.

>>> it = util.Iterator(board)
>>> it.start()
>>> board.analog[0].enable_reporting()
>>> board.analog[0].read()
>>> it.start()

To turn off the reporting of analog values, call disable_reporting() on the pin object

Sample code

Read LM35 temperature  from AI0 pin and store in CSV

# Python27
import csv
import pyfirmata
import time
from time import sleep


port = '/dev/cu.usbmodemfa1331' #'COM3' for Windows
board = pyfirmata.Arduino(port)
#pin =[0]
it = pyfirmata.util.Iterator(board)
it.start()
a0 = board.get_pin('a:0:i')
#a0.enable_reporting()
with open('SensorDataStore.csv', 'w') as f:
    w = csv.writer(f)
    w.writerow(["Number","Temperature"])
    i = 0
    while i < 25:
        Temperature = a0.read()
        if (Temperature != None):
            Temperature = Temperature*100 # to read value in decimal
        sleep(1)
        i += 1
        row = [i, Temperature]
        w.writerow(row)
        print (Temperature)
    print ("Done. CSV file is ready!")
board.exit()

 

Remote Debug on Raspberry Pi by PyCharm

pycharm

Recently I’ve been getting into embedded Linux, particularly the Raspberry Pi and have consequently been learning Python. I really don’t like programming directly on these small devices since the environment is typically spare and slow.

What I really needed was something that I could work on in my main dev environment but deploy and execute on the RPi. It also needed to be able to run as root because all RPi GPIO requires root privileges.

Most importantly, PyCharm has a remote debugging feature which coupled with automatic deployment makes everything super easy.

Setting Up Remote Debugging

Below is how I set up my environment. Much of this is found in the PyCharm help documentation. You can find how to set up remote debugging particularly the section on setting up a remote interpreter via SSH.

Automatic Deployment

First we need to setup automatic deployment of our files to the RPi. This part isn’t strictly required but if you don’t do it you’ll have to manage uploading your changes.

  1. Important: The login you use here is the credentials that the remote process will be run as. You can use the “pi” user, as we have another way of gaining root privileges to access GPIO detailed below.

Run Configuration

Still with me? Now that we’ve got deployment set up and an interpreter that will use our remote virtual environment, the final step is to create a run configuration to actually run a script.

  1. Create a simple python script and call it hello_world.py. Give it the following contents.
    • import RPi.GPIO
    • print “hello world!”
  2. Click in the upper right of the main window and choose “Edit Configurations…”.
    rd3-01 Run Configuration
  3. Click the plus button and choose Python.
    rd3-02 Add Python Interpreter
  4. Give the new configuration the name “hello_world (remote)”. For the script, choose the script we just created. For Python interpreter, choose the remote interpreter we created in the last section.
    rd3-03 Run Configuration
  5. Now add a path mapping to map from your local project path to the remote path. This lets the interpreter find the source file for what’s executing remotely.
    rd3-04 Edit Path Mappings
    rd3-05 Run Configuration With Paths
  6. Save the new configuration and click the run button. You should see PyCharm connect and the hello world print on the debug console.
    rd3-06 Run Success

Running as Root

Rather than enabling logging in as root over SSH, there’s another approach that will work without opening that security hole. Using permissions, we can cause our python interpreter to simply run as root.

  1. Reconnect using PuTTY and navigate to the project root folder.
    cd /home/pi/remote_debug/remote_debug_ex
  2. Change ownership of the python interpreter to root and cause it to be executed as its owner whenever it’s run.
    • sudo chown -v root:root venv/bin/python
    • sudo chmod -v u+s venv/bin/python

This will cause pip to act a bit funny when you want to install anything later on so just reverse the above changes from step 2 as needed. Just use the same commands but with pi instead of root and with u-s.

I have a couple of scripts that I keep in the project root for just this purpose. You can use below:

python_as_pi.sh 

#!/usr/bin/env bash

DIR=$(dirname $(readlink -f "${BASH_SOURCE}"))

if [ ! -f $DIR/venv/bin/python ]; then
  echo "This script should be located in the project root directory"
  echo "and the virtual environment should be created."
else

    # Change python back to run as pi
    sudo chown -v pi:pi "$DIR/venv/bin/python"
    sudo chmod -v u-s "$DIR/venv/bin/python"

fi

python_as_root.sh

#!/usr/bin/env bash

DIR=$(dirname $(readlink -f "${BASH_SOURCE}"))

if [ ! -f $DIR/venv/bin/python ]; then
  echo "This script should be located in the project root directory"
  echo "and the virtual environment should be created."
else

    # Change python to run as root
    sudo chown -v root:root "$DIR/venv/bin/python"
    sudo chmod -v u+s "$DIR/venv/bin/python"

fi

Conclusion

Now you have a way to remote debug your RPi with the interpreter running as root, allowing access to the Pi’s GPIO. You can do this with multiple projects and even have multiple projects or instances of projects open and debugging remotely.

PyCharm is a great IDE and I encourage you to look into using it to improve your development environment. For example, check out Zeal and the Dash plugin that will cause PyCharm to perform a documentation lookup when you press Ctrl+Shift+D. There are also plugins to provide support for Markdown and bash scripts.

Ethernet JTAG Adapter with Raspberry Pi

jtagpi

 I recently wanted an ethernet JTAG adapter for a project I was working on. Unfortunately ethernet JTAG adapters can cost upwards of $300, and even then they can be specific to particular chipset and toolchains.

However, were already using OpenOCD with ST-LINK/V2 programmers to communicate with out hardware, and it turns out that it’s very easy to set up OpenOCD on the Raspberry Pi. You can then plug the programmer into the Pi, connect a debugger (gdb in our case) to the OpenOCD instance, and debug your firmware remotely!

The Raspberry Pi is also a very convenient platform for adding additional interfaces to your hardware. For our project, we have FTDI serial cables and some ADC’s connected to ours as well. This lets us flash and debug our hardware, communicate with it over serial (forwarded over a socket), and continuously monitor power consumption of key components on our board. And we can do it from anywhere with an internet connection. It’s basically magic.

1. Acquire a Pi

First you’ll need a Rapsberry Pi and an SD card with the Raspbian installed on it. You can get a Raspberry Model B Starter Kit from Newark. This comes with a power adapter and an SD card with Noobs (which can automatically install Raspbian for you) pre-installed and is probably the easiest way to get started.

2. Install a Recent Version of OpenOCD

There is a version of OpenOCD already in the package database for Raspbian, but it’s version 0.6.1, which was too old for our platform. Fortunately it’s quite easy to install the latest OpenOCD from scratch. There are pretty good instructions on how to do this at SourceForge. But specifically for the Pi you can just do the following:

From your Pi:

sudo apt-get update
sudo apt-get install libtool libusb-dev libusb-1.0 autoconf automake texinfo

And then:

git clone git://git.code.sf.net/p/openocd/code openocd-code
cd openocd-code/
./bootstrap
./configure

This should spit out a bunch of stuff and then if everything worked you should see this at the end:

OpenOCD configuration summary
--------------------------------------------------
MPSSE mode of FTDI based devices        yes (auto)
ST-Link JTAG Programmer                 yes (auto)
TI ICDI JTAG Programmer                 yes (auto)
Keil ULINK JTAG Programmer              yes (auto)
Altera USB-Blaster II Compatible        yes (auto)
Segger J-Link JTAG Programmer           yes (auto)
OSBDM (JTAG only) Programmer            yes (auto)
eStick/opendous JTAG Programmer         yes (auto)
Andes JTAG Programmer                   yes (auto)
Versaloon-Link JTAG Programmer          yes (auto)
USBProg JTAG Programmer                 yes (auto)
Raisonance RLink JTAG Programmer        yes (auto)
Olimex ARM-JTAG-EW Programmer           yes (auto)
CMSIS-DAP Compliant Debugger            no

Make sure support for the programmer you are using is enabled, and then type make. Once that finishes, type sudo make install.

Now OpenOCD should be installed and ready to go!

3. Run OpenOCD

Now you can run OpenOCD. For example, if you were using an F4 discovery board, you could so something like this:

sudo openocd -f board/stm32f4discovery.cfg

If it worked, you should see something like:

Info : stm32f4x.cpu: hardware has 6 breakpoints, 4 watchpoints

Which means your programmer is ready to go!

You can then use telnet ip_of_pi 4444 to connect to your OpenOCD session and run OpenOCD commands. You can also connect to it with gdb. The most convenient way is to create a .gdbinit file with something like:

target remote my_pi_ipaddress:3333
file my_firmware.elf
monitor reset halt
load
And then you can type gdb (or in my case arm-none-eabi-gdb), and my_firmware.elf is flashed onto the hardware and is ready for debugging!

Reference: 
https://spin.atomicobject.com/2014/04/01/ethernet-adapter-jtag/

Open OCD bin compiled:

http://www.embeddedhelper.de/blog/raspberry-pi-openocd-binary/

A few minor corrections:

1. Using “extended-remote” over “remote” is recommended as it enables “run” and “start” GDB commands;
2. There’s no need to do “reset halt” before “load” with any >= 0.8.0 OpenOCD version;
3. To avoid typing “file” you can start gdb passing the filename as the first argument.

Configure Notepad++ to run a python

notepad_logo

Install python (3.4)

  1. Download the python 3.4(preferable 32 bit) windows installer from http://www.python.org/download/
  2. Run through the installer using the default settings for everything.  It should install python in the folder: C:\Python34.  If you’re using a different version of python, just substitute out the version number wherever you see 34.

Install Notepad++

  1. From http://notepad-plus-plus.org/download, download the Notepad++ installer.
  2. Run through the installer using the default settings for everything.
  3. Open Notepad++

Configure Notepad++ to run a python script

  1. Open up a command prompt
  2. Run the following command:
set PATH=%PATH%;C:\Python34

Note: If your version of python was installed in a different location, make sure to substitute out that location with the one in the command.

You can use the following command to make sure the python path was added to the PATH variable:
echo %PATH%

You should see the location of the python directory at the end of the output.

  1. Switch back to Notepad++, and go up to the menu bar, select Run, and then select Run… (F5)
  2. Insert the following in the text box that appears:
    C:\Python34\python.exe -i "$(FULL_CURRENT_PATH)"
  3. Click Save…
  4. Configure CTRL+R to be the command.  Give it a name, and press OK.
Now whenever you want to run the python script you’re working on, press CTRL+R and it will be executed.  Also you should see the window stay opened after command execution for debugging purposes because of the -i flag. Remove it if you don’t want that feature.

Setting up Python 3.4, numpy, SciPy and matplotlib on Windows PC

There are two different, incompatible versions of Python in general use around the world — Python 2.7 and Python 3.4. Significant changes to the Python language were made between Python 2.x and Pyt…

Source: Setting up Python 3.4, numpy, SciPy and matplotlib on Windows PC

GPIO control using Python

GPIO

The RPi.GPIO Python library allows you to easily configure and read-write the input/output pins on the Pi’s GPIO header within a Python script. Thankfully this library is now including in the standard Raspbian image available from the Foundations Download Page.

If you are using a fresh image you don’t need to install it but I’ve kept the instructions here in case you ever want to try a manually installation.

Method 1 – Install from repository

If the package exists in the Raspbian repository is can be installed using apt-get. First you need to update the available package versions :

sudo apt-get update

Then attempt to install the RPi.GPIO package :

sudo apt-get install rpi.gpio

If it isn’t already installed it will be installed. If it is already installed it will be upgraded if a newer version is available.

Method 2 – Manual Installation

The package is available from http://pypi.python.org/pypi/RPi.GPIO and the current version is 0.5.11 (February 2015). If this version is updated you will need to make appropriate changes to the version number in the commands below.

Step 1 – Download the library

wget https://pypi.python.org/packages/source/R/RPi.GPIO/RPi.GPIO-0.5.11.tar.gz

Step 2 – Extract the archive to a new folder

tar -xvf RPi.GPIO-0.5.11.tar.gz

Step 3 – Browse to the new directory

cd RPi.GPIO-0.5.11

Step 4 – Install the library

sudo python setup.py install

Step 5 – Remove the directory and archive file

cd ~
sudo rm -rf RPi.GPIO-0.*

This will now mean you can use the library within Python.

Example Usage

import RPi.GPIO as GPIO
 
# to use Raspberry Pi board pin numbers
GPIO.setmode(GPIO.BOARD)
 
# set up the GPIO channels - one input and one output
GPIO.setup(11, GPIO.IN)
GPIO.setup(12, GPIO.OUT)
 
# input from pin 11
input_value = GPIO.input(11)
 
# output to pin 12
GPIO.output(12, GPIO.HIGH)
 
# the same script as above but using BCM GPIO 00..nn numbers
GPIO.setmode(GPIO.BCM)
GPIO.setup(17, GPIO.IN)
GPIO.setup(18, GPIO.OUT)
input_value = GPIO.input(17)
GPIO.output(18, GPIO.HIGH)

Example to run script on key press

import RPi.GPIO as GPIO
import time
import os
GPIO.setmode(GPIO.BCM)
#This will import the necessary libraries in the GPIO namespace and set the pin numbering to correspond to your breakout board.
#Now we need to set the pin as input, pin 18 is used in this example.
GPIO.setup(18,GPIO.IN)
#Reading the pin is now as easy as:
input = GPIO.input(18)
#If we want to print Button Pressed each time a button is pressed
while True:
 if (GPIO.input(18)):
 print("Button Pressed")
 time.sleep(1)
 os.system('startx')
 #os.system('reboot')
 #os.system('/etc/network/if-up.d/sayIP')
 else:
 print("Button Not pressed")
 time.sleep(1)
 # use 0.1 for 1 ms delay