Sony Arouje

a programmer's log

Archive for the ‘Raspberry Pi’ Category

Connecting XBee to Raspberry pi

with 19 comments

Last one week I was doing some research in RF communication and controlling devices using RF. So what am I going to control here, I wanted to control the water pump running in my hydroponic reservoir without running wires from my raspberry pi. This way I can extend my hydroponic system to more balconies without buying extra RPi, a single RPi will send a switch on/off command and the RF client will switch on/off the motor via a relay. Also I don’t need to setup a wifi network in my controller RPi’s.

My research for RF communication platform leads to Zigbee protocol and XBee component. XBee is a very popular Zigbee complaint product from Digi. For my testing I got two XBee Pro S2 and two XBee explorer. The explorer I bought uses USB to A/B cable, if you are buying it make sure buy A/B cable as well. You will get micro usb explorer as well.

To configure the XBee’s I use the X-CTU software from Digi, you can download it free from Digi’s website. I use the Legacy X-CTU for configuring my modules and Next Generation X-CTU for issuing commands. Configuration is pretty simple and so many sites will walk you through it. I configure my XBee’s as shown below. One XBee act as Coordinator and enabled API mode and another XBee act as router and enabled Router AT.

XBee Coordinator

  • Modem: XBP24-ZB
  • Function Set: ZIGBEE CORDINATOR API
  • PAN: <set a pan id, say 123>
  • Destination Address Low: FFFF

XBee Router

  • Modem: XBP24-ZB
  • Function Set: ZIGBEE ROUTER AT
  • PAN: <set a pan id, say 123>
  • Destination Address Low: 0000

I left all other settings as default.

Connecting to Raspberry pi

For testing I connected the XBee coordinator to my computer and XBee Router to my RPi. In RPi I created a simple node app to send some text message to coordinator. Below diagram will show you, how I connected Router XBee to my RPi. Here we use serial communication between RPi and XBee. RPi has only one set of serial communication pin and by default it’s configured for console I/O, there are so many tutorial out there to free it up and I use one from them.

connection_diagram_bb

image developed using Fritzing

I connected the XBee directly using jumper wires, the above diagram is just for illustration for that I use the breadboard.

Connect RPi 3.3 volt to XBee 3.3 volt pin, Ground to XBee ground, Rx to Xbee Tx (Data Out), Tx to XBee Rx (Data In).

Sending some data from Router Xbee to Coordinator

Now I wanted to send some data from Router XBee connected to my RPi  to the coordinator connected to my Computer.

I created a small app using node js, below is the code. To run the code we have to install two node modules.

  • xbee-api: npm install xbee-api
  • serialport: npm install serialport
var util = require('util');
var SerialPort = require('serialport').SerialPort;
var xbee_api = require('xbee-api');

var C = xbee_api.constants;

var xbeeAPI = new xbee_api.XBeeAPI({
    api_mode: 1
});

var serialport = new SerialPort("/dev/ttyAMA0", {
    baudrate: 9600,
    parser: xbeeAPI.rawParser()
});

serialport.on("open", function () {
    var frame_obj = {
        type: 0x10, 
        id: 0x01, 
        destination64: "0013A200407A25A7",
        broadcastRadius: 0x00,
        options: 0x00, 
        data: "Hello world" 
    };
    
    serialport.write(xbeeAPI.buildFrame(frame_obj));
    console.log('Sent to serial port.');
});

serialport.on('data', function (data) {
    console.log('data received: ' + data);
});


// All frames parsed by the XBee will be emitted here
xbeeAPI.on("frame_object", function (frame) {
    console.log(">>", frame);
});

 

When I run the above node app, I can see the data receiving in my Coordinator’s X-CTU app. I could also send a Remote AT (0x17) command to the router to one of the Digital pin and could turn On/Off a LED.

Seems like the communication is working fine. Let’s see what I can come up next.

 

download

Scan using your mobile phone and access/share the post from your phone.

Written by Sony Arouje

December 20, 2014 at 6:07 pm

Posted in Raspberry Pi

Tagged with , ,

Working of my very basic and crude Aeroponic System

with 3 comments

Here I will just show you a video of my Aeroponic system. As you can see its very basic, I didn’t want to spend much money to test whether my system works, so I used cost effective materials.

In one of my previous post I explained about how I used Rasberry pi to control the motor. If you haven’t read it, please check that out too.

 

Low Pressure Aeroponic System

 

What Next?

  • From this initial test run, I could see my system is a success. Now I will add more pillars and a high capacity tank.
  • Automate day to day activities. For e.g. I have to add nutrients to the reservoir once in two day. Using a Peristaltic pump and a motor driver I can automate the process with a click of a button from my mobile app. 
download

Scan using your mobile phone and access/share the post from your phone.

Written by Sony Arouje

December 11, 2014 at 2:22 pm

Posted in Raspberry Pi

Tagged with

Distributed Raspberry pi based Hydroponic Controller

leave a comment »

Last couple of weeks I was building a Hydroponic system controlled by Raspberry pi. As of yesterday night my system was based on a single Raspberry pi that control one or more water pumps. It was one of my design goal to add more Pi’s based controllers to the network with zero configuration.

Why more Controllers?

As I am living in an apartment and the hydroponic system is going to be installed in the balconies. Connecting the motors installed in different balconies to a single Raspberry controller will make things ugly, I don’t want wires hanging here and there. So one option is, add another Raspberry pi controller. It’s easily doable, just install the controller software I created and plug the water pump.

As I explained in my last post, this system is controlled via mobile devices. So when ever I add a controller to my hydroponic network I have to create an entry in each of the device in which my mobile app installed. Also I have to assign a static ip to each Raspberry controller or keep track of the host name. When I start thinking about it, I see a system with some complications. Yesterday night I modified my controller application, this is what I come up with.

Unifying server and Controllers with self advertisement

I created a Unifying server in node js. The controller system running in different Raspberry pi’s advertise about it when ever it joins to my wifi network. This Unifying server will get notification whenever a new controller joins. I use Node Discovery module for service discovery and publishing. In this scenario I don’t have to worry about any configuration of the controllers. Just install my controller software in each raspberry pi and plug it into my hydroponic system.

My mobile app connects to this unifying server instead of individual controller system. All the commands to the controllers will be routed via this unifying server to respective controller. Below is the routing function I come up with.

app.use('/', router);
router.use(function (req, res, next) {
    options.host = req.headers.hostid;
    options.path = req.originalUrl;
    options.method = req.method;
    


    var request = http.request(options, function (response) {
            response.on('data', function (data) {
                res.setHeader('content-type', 'application/json');
                res.send(data);
            });
        });
        if (req.method === 'POST') {
            request.setHeader('content-type', 'application/json');
            request.write(JSON.stringify(req.body));
        }
        request.end();
       
});

 

This unifying server is a very light weight system and can run in a Raspberry pi or in my computer. On of my design goal is that Controller should be self sufficient and should run in any circumstances even if there is no connection to unifying server.

The Unifying server and the Controller system is based on Node js. It’s a beautiful platform and I learned a lot about node js while building this system. Also become a huge fan of Javascript.

 

Next post I will go through the mobile app I created.

 

Happy coding…

download Scan using your mobile phone and access/share the post from your phone.

Written by Sony Arouje

November 22, 2014 at 5:37 pm

Posted in Raspberry Pi

Tagged with ,

Hydroponics system controlled by Raspberry Pi an overview

with 19 comments

Last couple of weeks I was spending my free time to understand and building a Hydroponic system to grow vegetables in my Apartment’s Balcony. I just don’t want to build a normal system that controlled by a timer, instead I want to build a system that I should be able to monitor even I am not at home, change watering schedule using my mobile device.

Before we jump into details, let me give you a brief about Hydroponic.

What is Hydroponics?

In simple terms, hydroponic is a system where you can grow vegetables without soil, mix the required nutrients in water and feed directly to plants. Advantage of this system is, we are feeding plants what they want, instead plant hunting for the nutrients from soil. Also less consumption of water as we reuse the water.

If you search in google you will get more details of Hydroponics. I am working on a subset of Hydroponic called Aeroponics, where plants grow vertically. I made the vertical growing tower based on the method described by Gunnar Shaffer.

Any Hydroponic system needs water circulation using a water pump, I used a submersible pump bought from Ebay for 225.00 INR. This pump should pump water in a periodical manner, say water for 15 mins then sleep for 60 mins and the cycle continues. We can use a timer to do that, it will cost from 1500 – 2500 INR. I decided to use one of the Raspberry pi lying in my table.

Why Raspberry pi?

As a programmer, this small brilliant device give me the flexibility of controlling the system with the programming language of my choice. For this system I used Node js platform to build the controller system. I spent a night to build the basic system that can turn on/off any device in a specific interval and some REST api’s through which mobile device can interact. Later I spent several nights to polish and enhancing my system.

For my testing I used a breadboard to turn off/on one LED. After I successfully controlled the LED, it’s the time to control the Electrical motor. I bought a 12v single channel Relay from ebay for 99.00 INR. It can control one electrical device, in my case the submersible water pump. This post will give you an idea about how to connect the Relay to your Raspberry pi.

Mobile Application

After I completed the system running in Raspberry pi, I decided to write the application for the mobile device. Through which I can interact with the system. As of now the application can

  • Turn off the pump, in case of maintenance.
  • Schedule watering interval.
  • Turn on motor to water immediately.

The mobile application is written using Cordova platform, so that app can run on my Windows or Android devices.

What Next?

  • The basic infrastructure is done, next important step is start growing veggies. It got delayed because I am waiting for two meters to measure the water content. The pH and TDS meter.
  • Suggestion system for nutrient quantity based on the previous data.
  • Distributed cluster of Pi based Aeroponics blocks controlled by a server.
  • Connect Water level monitor to Rasp pi and notify if water level of the tank goes down.

Update: see my hydroponic in action.

Thanks to

  • My wife, for her support and encouragement, for all the crazy stuffs that I am experimenting with.
  • My father who guides and clarifies all my question related to Electrical devices and suggestions to improve the system for better performance.
  • Gardenguru for providing me with key information like measuring and controlling ph and EC level. I also bought the necessary items from them like Net Cups, Hydrotons, Nutrients, etc. They have a shop near to my home, I go there and spent time talking with them. They are very enthusiastic and provide with any info about Hydroponic to a newbie like me.

 

download Scan using your mobile phone and access it from your phone.

Written by Sony Arouje

November 10, 2014 at 1:21 pm

Posted in Raspberry Pi

Tagged with ,

VS2013 Multi-Device Hybrid Apps and Network Error in Windows8

with 2 comments

Last couple of days I was working on Node js REST service running in one of my Raspberry Pi. The idea is to do certain stuffs remotely via mobile devices. Later I will write a post explaining the project in detail. I completed Phase 1 of the application running in Raspberry pi. So next task was creating a mobile app, I decided to use Cordova with VS 2013 Multi Device Hybrid app template.

Yesterday night I started working on the Hybrid app in VS 2013 for Windows 8. First thing I wanted to test was the connectivity to the REST service running in Raspberry pi. I used Angular js $http to connect to the REST service. To my surprise what ever I do, the app is throwing error while doing http post with status 0. The same code works successfully if I run as a web app.

I spend a hell lot of time to figure out the issue but no success. Then I decided to use fiddler to test the traffic, when fiddler is running the app could able to communicate with the REST service. I got a hint, when we run Fiddler in Win8, it adds apps to AppContainer Loopback exemption. If I exempt my windows 8 app then http request starts failing. This stage I realized that, the error is because of some app configuration issue. Also in VS Java Script console I could see the error as shown below.

XMLHttpRequest: Network Error 0x2efd, Could not complete the operation due to error 00002efd.

All my google search return nothing. After a long hours of desperate research I came to know that to access private network I need to add Private Network capability to windows 8 app. But I didn’t know how to add it for Hybrid app as there is no Capabilities section in the config.xml. Some more search leads me to the Faq page of Multi device hybrid app template. As per the FAQ page we can override the default AppManifest.xml as shown below.

1. Create a Package.appxmanifest file under res/cert/windows8. Create a windows8 solution folder if not exist.

2. Open the project folder and go to bld/windows-AnyCpu/Debug and open AppxManifest.xml in notepad, copy the content and paste it in the above Package.appxmanifest file.

3. Double click on Package.appxmanifest file then goto Capabilities tab and choose ‘Private Networks (Client & Server)’.

4. Save it and run the app again, this time it worked I could connect to my Node js REST api.

 

Hope this will help some one to solve the XMLHttpRequest issue.

 

Happy Coding…

Written by Sony Arouje

October 29, 2014 at 3:50 pm

Access Raspberry Pi via internet

with one comment

In this post I will explain how to access Raspberry pi via Internet. I am trying out a home automation system using Pi and I wanted to access a node.js service running in my Raspberry pi. Also I may wanted to SSH to the pi to restart or configure it while I am away from home.

Configuring the Router

In my home Raspberry Pi is connected to a Netgear R6300 router. The router is then connected to a DSL modem. In these kind of setup we might be dealing with four different IP’s

  1. External IP assigned to you by your ISP.
  2. IP Address of the modem
  3. IP Address of the Router assigned by the modem
  4. IP Address of the Raspberry Pi assigned by Router.

Prerequisite

  • Credentials to login to the Modem configuration.
  • Credentials to login to the router configuration.

External IP: you can get your external ip by visiting whatismyip.com

IP Address of the Modem and Router: As I am using Netgear modem, I login into Netgear genie app. And from the Internet section I could see the IP Address assigned  to my router as shown below.

image

As you could see  the IP address assigned to my router is 192.168.1.2. Also you can see the Gateway IP address 192.168.1.1, that IP will be the IP address of your modem.

IP address of the Raspberry pi: SSH to Raspberry PI and issue ‘ifconfig’ command and you can see some details and check wlan0 as shown below. Line in bold shows the ip address of the Pi.

wlan0     Link encap:Ethernet  HWaddr 04:a1:51:6a:fb:8d
              inet addr:10.0.0.10  Bcast:10.0.0.255  Mask:255.255.255.0
              UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
              RX packets:5543 errors:0 dropped:11 overruns:0 frame:0
              TX packets:1799 errors:0 dropped:0 overruns:0 carrier:0
              collisions:0 txqueuelen:1000
              RX bytes:1200798 (1.1 MiB)  TX bytes:192891 (188.3 KiB)

 

In my scenario I assigned a static IP to this Pi, other wise router’s DHCP server will assign ip and might change from time to time. So most router have configuration, to set static IP to the devices and will never change. At my house most of the devices like TV, Tabs and Raspberry PIs have static IP’s and the guest devices uses DHCP assigned IP’s.

Let’s configure SSH to the Pi from internet.

Router Port Forwarding

Excerpt from Genie help

Port forwarding is designed for FTP, Web server, or other server-based services. Once port forwarding is set up, requests from the Internet are forwarded to the proper server.

In the Genie app you can find Port forwarding in Advanced setup->Port forwarding/Port triggering, you might be able to find some thing similar in other modem’s configuration.

I clicked ‘Add Custom Service’ button and it will show the below screen to setup Port forwarding configuration. Here I am configuring SSH.

image

Here  22 is the port where SSH server in my PI is listening. Internal IP address is the IP address of the Raspberry Pi. Click apply and the changes will get saved.

We setup the port forwarding in the router. We need to do the similar configuration in Modem.

Modem Port Forwarding

Enter the IP address of the modem in the Chrome/IE, enter the user name and password if prompted.

Note: My DSL modem is pretty old one and may not be match with the interface of your modem configuration screen.

The port forwarding configuration in my Modem is located at Advanced Setup/NAT/Virtual servers. See the configuration below.

image

Here I setup the external port number as well as internal port number. You can have different external port number if you want, say for e.g. external port number 8090 can be mapped to internal port number 22. The server IP address should be the IP address of the router.

Check whether the port is opened by going to yougetsignal.com, if the port is still closed then you might need to do Port triggering in Modem as shown below.

image

 

We successfully configured SSH to Raspberry Pi from internet, you can check using a machine connected to a different network and connect to Pi using any SSH client like Putty. While connecting the IP address should be the external IP address and the port should be the one configured in Modem, here it’s 22.

Conclusion

The above approach will work, in case you want to open any port, I have a node.js service listening to 8090 in the same Raspberry pi. I did the above approach to access it via internet.

Leave your comments if you like this post or in case of any questions.

Written by Sony Arouje

June 25, 2014 at 3:33 pm

Pi Tracker–Code running in Raspberry Pi

with one comment

In my last post you can see the Tracker in action. This post I will explain the code running in Raspberry pi that controls the Tracker. I use Wiring Pi to control the  GPIO instead of the default RPI.GPIO. The intention of using Wiring pi is because Software PWM is easy to implement. Any way after the first run of the tracker I realized that my tracker is slow moving one and no need to control the speed, so I haven’t used Software PWM here.

Installing Wiring Pi for python

Command  prompt type the below commands

  1. sudo apt-get install python-dev python-pip
  2. sudo pip install wiringpi2

Let’s check whether wiringPi installed correctly

  1. sudo python
  2. import wiringpi2
  3. wiringpi2.piBoardRev()

if it returns a value then wiring Pi installed successfully.

Pi Tracker php code running in Raspberry pi

Motor.py

import wiringpi2 as io
from time import sleep
class Motor:
        def __init__(self, gpio_a, gpio_b):
                self.Gpio_a=gpio_a
                self.Gpio_b=gpio_b
                self.activeGpio=gpio_a
        def setup(self):
                io.wiringPiSetupGpio()
                io.pinMode(self.Gpio_a,1)
                io.pinMode(self.Gpio_b,1)
        def forward(self):
                self.stop()
                self.activeGpio=self.Gpio_a
        def reverse(self):
                self.stop()
                self.activeGpio=self.Gpio_b
    
        def acclerate(self,speed):
                io.digitalWrite(self.activeGpio,1)
                #speed param is not used here.
        def stop(self):
                io.digitalWrite(self.Gpio_a,0)
                io.digitalWrite(self.Gpio_b,0)

Engine.py

from Motor import Motor
class Engine:
        motor_a=Motor(17,27)
        motor_b=Motor(23,24)
        def __init__(self):
                Engine.motor_a.setup()
                Engine.motor_b.setup()
        def steer(self, command):
                direction,speed=command.split(",")
                if(direction=="CLOSE"):
                        self.stop()
                elif (direction=="U"):
                        self.forward()
                elif (direction=="L"):
                        self.left()
                elif(direction=="R"):
                        self.right()
                else:
                        self.reverse()
        def forward(self):
                Engine.motor_a.forward()
                Engine.motor_b.forward()
                self.acclerate()
        def reverse(self):
                Engine.motor_a.reverse()
                Engine.motor_b.reverse()
                self.acclerate()
        def right(self):
                Engine.motor_b.reverse()
                Engine.motor_a.forward()
                self.acclerate()
        def left(self):
                Engine.motor_a.reverse()
                Engine.motor_b.forward()
                self.acclerate()
        def acclerate(self):
                Engine.motor_a.acclerate(10)
                Engine.motor_b.acclerate(10)
        def stop(self):
                Engine.motor_a.stop()
                Engine.motor_b.stop()
                print "engine stopped"

trackerRemoteListener.py

import socket
from Engine import Engine
TCP_IP = '10.0.0.10'
TCP_PORT =5005
BUFFER_SIZE = 100
engine= Engine()
engine.stop()
s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
s.bind((TCP_IP, TCP_PORT))
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.listen(1)
conn, addr = s.accept()
print 'Connection address:', addr
while True:
        try:
                data = conn.recv(BUFFER_SIZE)
                print "received data: ",data
                engine.steer(data)
                if not data:
                        engine.stop()
                        conn,addr=s.accept()
        except KeyboardInterrupt:
                conn.close()
                engine.stop()
                print "connection closing"
        except Exception as err:
                conn.close()
                s.listen(1)
                conn,addr=s.accept()
                #s.listen(1)
                print "error occured"
                pass
conn.close()

How it works

Motor.py class represent a motor in the Tracker. It accepts two parameters and it should be a valid GPIO pin to which the motor is connected. For e.g Motor_a is connected to GPIO 17 and 27. If we give write 1 to 17 and 0 to 27 then Motor_a will run forward, write 1 to 27 and 0 to 17 Motor_a run reverse.

Pi Tracker uses two motors to drive, Engine.py controls these two motors. As you can see in the code Engine.py creates two Motor instance. It also has functions to steer the tracker in different directions.

trackerRemoteListener.py is the socket program that listens to the command from external device to control the tracker. To control this tracker I used an Android tab that sends the command to this listener.

Hope the code is self explanatory, if not post your questions in the comment section.

 

Happy coding…

Written by Sony Arouje

June 24, 2014 at 11:55 am

Posted in Raspberry Pi

Tagged with , , ,

PI Tracker in action–video

with one comment

In my last post I gave an overview of a toy I created using Raspberry Pi and the components used for it. After that some of my friends wanted to see the toy in action and here is the video.

PI Tracker

Video Streaming

A new feature added to the tracker after the last post is the video streaming to the controlling device. In the modified tracker a USB camera is attached to the front of the tracker and connected to the Raspberry Pi. The RaspPi host a mjpg streamer and the video can be streamed to any device connected to the same network, including the Android device that controls the tracker. This helps my son to sit anywhere in the house and control the tracker.

 

Stay tuned for the next post with source code and more…

Edit: A new post added explaining the Source code running in Raspberry pi

Written by Sony Arouje

June 12, 2014 at 6:22 pm

PI TRACKER – Raspberry Pi based WiFi controlled toy

with 2 comments

I was always fascinated about software and hardware interaction. But with my limited knowledge in electronics, I kept the hardware part aside and was working only in software. After having some hands on experience with my first Raspberry Pi, I decided to build a toy for my son. I purchased my second pi and some other components and this is what I built. Yes it looks ugly but worth playing with it :).

fotor_(283)

Last couple of days I was refreshing my basic electronic skills and virtually designing the software and  hardware for the device. You can find so many similar RaspPi based toys and I am adding one more to it.

Yesterday evening I got the last piece of the puzzle, the rechargeable battery.  After that I spent the next 5 hrs to code the application running in the vehicle and the Remote control app for my Android tab, remote control app is based on the Acclerometer of the device. To control the toy I decided to use WiFi and use my Android tab as a steering wheel. I will go more details into the software part in a different post.

Future addition

  • Obstacle detection and avoidance system
  • Video feed to the remote control device

Components

Rest of the post will go through the components used in the tracker and how to acquire it. If you are in Bangalore then you can get all these items from OM Electronics in SP road or you can buy online. I bought it from OM Electronics.

 

image Motor

Qty: 2

Features

  • 300RPM 12V DC motors with Gearbox
  • 6mm shaft diameter with internal hole
  • 125gm weight
  • Same size motor available in various rpm
  • 2kgcm torque
  • No-load current = 60 mA(Max), Load current = 300 mA(Max)
image Chasis

Qty: 1

Features

Powder coated Metal chasis for robots. Easy to mount the motors on place by using normal motor mount nut. It can either be used in skid steel configuration (4 motors) or differential configuration (2 rear wheels + 1 front castor wheel). The body contains perforated holes for easy mounting of various size circuit boards and other mechanical components.

Length : 190mm

Width : 105mm

Height : 40mm

image Track wheels

Qty: 4

Features

  • 6.1 mm hole.
  • Diameter 90 mm
  • Made from high quality virgin Nylon.
  • Hole on shank for screw
  • Comes with screw to lock on standard motor shaft of 6 mm.
image

Track and Ribbit

Qty: 60

Features

High quality Plastic Track  Belt and Ribbit

Specification :

  • 30mm X 20mm
  • 10mm Width
l293d-h-bridge-motor-driver-module L293D Motor Driver controller

Qty: 1

Features

H Bridge to control the motors individually

image Jumber Wires

male to male jumber wires – 10 or more  pcs

male to female jumber wires – 10 or more pcs

female to female jumber wires – 10 or more pcs

3cell_lion_battery 12V Lithium-Ion Rechargeable Battery

12v rechargable battery + charger

Url: http://www.robosoftsystems.co.in/roboshop/index.php/12v-lithium-ion-rechargeable-battery.html

Charger: http://www.robosoftsystems.co.in/roboshop/index.php/electronics-batteries/batteries-chargers/11-1v-1000mah-15-25c-lipo-battery.html

 

Next part I will go through the software part of the system. Stay tuned.

Written by Sony Arouje

June 10, 2014 at 12:28 pm

Posted in Raspberry Pi

Tagged with , ,

%d bloggers like this: