Sony Arouje

a programmer's log

Connect Arduino to external EEPROM

leave a comment »

Arduino has a tiny built in hard drive called EEPROM, in this area we can write data that should be available after power cycles. Unfortunately the size of this built in EEPROM is 512 byte for Atmega168 and 1kb for Atmega328. If our application is dealing with very small amount of data to persist then built in EEPROM is a good choice.

In some scenarios we might need to keep some logging info or any kind of data that needs more than 1kb then we need to go for external EEPROM. For this post I am using 24LC256, it can store 256kb of data. We can connect upto 8 ICs to a single Arduino by changing the voltage in A0, A1 and A2 pins.

clip_image001

 

Connection to Arduino

connection_bb

 

Here I connect A0 to A2 to GND and that gives me an address of 0x57.

VSS to GND, VCC to 5v, WP to GND, SCL to A5, SDA to A4

High on WP will disable writing, in my scenario I need to write, so I connect to GND.

 

Source Code

To deal with EEPROM reading and writing, I used a library called Extended Database Library (EDB). I also used the samples provided along with EDB but with some modifications.

 

#include <EDB.h> #include <Wire.h> #define disk 0x50 #define TABLE_SIZE 131072 // 1 device struct LogEvent { int id; int temperature; } logEvent; void writer(unsigned long address, byte data) { Wire.beginTransmission(disk); Wire.write((int)(address>>8)); Wire.write((int)(address & 0xFF)); Wire.write(data); Wire.endTransmission(); delay(5); } byte reader(unsigned long address) { byte rdata = 0xFF; Wire.beginTransmission(disk); Wire.write((int)(address>>8)); Wire.write((int)(address & 0xFF)); Wire.endTransmission(); Wire.requestFrom(disk,1); if(Wire.available()) rdata = Wire.read(); return rdata; } EDB db(&writer, &reader); void setup() { Serial.begin(9600); Wire.begin(); randomSeed(analogRead(0)); Serial.println("Creating db..."); EDB_Status result = db.create(2, TABLE_SIZE, (unsigned int)sizeof(logEvent)); if (result != EDB_OK) printError(result); Serial.println("Created db..."); createRecord(1); selectAll(); } void loop() { // put your main code here, to run repeatedly: } void createRecord(int recno) { Serial.println("Creating Records..."); logEvent.id = 1; logEvent.temperature = random(1, 125); EDB_Status result = db.insertRec(recno, EDB_REC logEvent); if (result != EDB_OK) printError(result); Serial.println("DONE"); } void selectAll() { for (int recno = 1; recno <= db.count(); recno++) { EDB_Status result = db.readRec(recno, EDB_REC logEvent); if (result == EDB_OK) { Serial.print("Recno: "); Serial.print(recno); Serial.print(" ID: "); Serial.print(logEvent.id); Serial.print(" Temp: "); Serial.println(logEvent.temperature); } else printError(result); } } void deleteAll() { Serial.print("Truncating table..."); db.clear(); Serial.println("DONE"); } void printError(EDB_Status err) { Serial.print("ERROR: "); switch (err) { case EDB_OUT_OF_RANGE: Serial.println("Recno out of range"); break; case EDB_TABLE_FULL: Serial.println("Table full"); break; case EDB_OK: default: Serial.println("OK"); break; } }

 

 

Happy coding…

Written by Sony Arouje

April 14, 2016 at 1:39 am

Posted in Arduino

Tagged with ,

MQTT Communication with Arduino using ESP8266 ESP-01

with 100 comments

I was doing some experiments with Arduino connected to WiFi using ESP8266 module. The priority of my experiment was to establish MQTT communication with my local MQTT server and Arduino. I tried so many Arduino libraries for ESP8266 but none of them are compatible with PubSubClient, a good MQTT library for Arduino. Today I come across a library called WiFiEsp, it has similar footprints of Arduino WiFi library, and it can work with PubSubClient. This post deals with how to utilize both PubSubClient and WifiEsp libraries to establish MQTT communication with an MQTT server.

Connecting ESP8266 to Arduino

  • I powered ESP8266 directly from my Arduino’s 5V. You shouldn’t do that, it may damage the wifi module as it deals with 3.3v. This wifi module need more current than Arduino’s 3.3v pin can provide, so connecting Arduino 3.3v to Wifi module will not work. A good option is to connect Arduino 5v to a 3.3v voltage regulator like LM1117/LD117 and power the wifi module from LM*. Connect both VCC and CH_PD pin of ESP to 3.3v power.
  • ESP8266 GND to Arduino GND. If powering ESP externally then Arduino and ESP should have a common GND.
  • ESP8266 TXD to Arduino RXD, in the below sketch I used Softserial and connected to D2.
  • ESP8266 RXD to Arduino TXD. Arduino Pin supply 5v and can damage the wifi module. So I used two resistors to create a voltage divider (Google search and you will get it). In the below sketch I used Softserial and connected to D3.

 

Arduino Sketch

I decided to write a sketch to see the MQTT in action. Below sketch is just a combination of samples provided in WifiEsp and Pubsubclient. I just combined both sample codes to verify the communication, so nothing special. The end result is, Arduino could establish MQTT connection to my MQTT server and send and receive messages for subscribed topics.

 

#include <WiFiEsp.h> #include <WiFiEspClient.h> #include <WiFiEspUdp.h> #include "SoftwareSerial.h" #include <PubSubClient.h> IPAddress server(10, 0, 0, 2); char ssid[] = "XYZ"; // your network SSID (name) char pass[] = "pwd"; // your network password int status = WL_IDLE_STATUS; // the Wifi radio's status // Initialize the Ethernet client object WiFiEspClient espClient; PubSubClient client(espClient); SoftwareSerial soft(2,3); // RX, TX void setup() { // initialize serial for debugging Serial.begin(9600); // initialize serial for ESP module soft.begin(9600); // initialize ESP module WiFi.init(&soft); // check for the presence of the shield if (WiFi.status() == WL_NO_SHIELD) { Serial.println("WiFi shield not present"); // don't continue while (true); } // attempt to connect to WiFi network while ( status != WL_CONNECTED) { Serial.print("Attempting to connect to WPA SSID: "); Serial.println(ssid); // Connect to WPA/WPA2 network status = WiFi.begin(ssid, pass); } // you're connected now, so print out the data Serial.println("You're connected to the network"); //connect to MQTT server client.setServer(server, 1883); client.setCallback(callback); } //print any message received for subscribed topic void callback(char* topic, byte* payload, unsigned int length) { Serial.print("Message arrived ["); Serial.print(topic); Serial.print("] "); for (int i=0;i<length;i++) { Serial.print((char)payload[i]); } Serial.println(); } void loop() { // put your main code here, to run repeatedly: if (!client.connected()) { reconnect(); } client.loop(); } void reconnect() { // Loop until we're reconnected while (!client.connected()) { Serial.print("Attempting MQTT connection..."); // Attempt to connect, just a name to identify the client if (client.connect("arduinoClient")) { Serial.println("connected"); // Once connected, publish an announcement... client.publish("command","hello world"); // ... and resubscribe client.subscribe("presence"); } else { Serial.print("failed, rc="); Serial.print(client.state()); Serial.println(" try again in 5 seconds"); // Wait 5 seconds before retrying delay(5000); } } }

 

 

For testing MQTT communication, I wrote a Server and a Client couple of months ago, both are node js apps and can run in my development machine. Server uses Mosca and Client uses MQTT module.

Below is the code for Server and Client.

 

Server

var mosca = require('mosca'); var ascoltatore = { //using ascoltatore type: 'mongo', url: 'mongodb://localhost:27017/mqtt', pubsubCollection: 'ascoltatori', mongo: {} }; var moscaSettings = { port: 1883, backend: ascoltatore, persistence: { factory: mosca.persistence.Mongo, url: 'mongodb://localhost:27017/mqtt' } }; var server = new mosca.Server(moscaSettings); server.on('ready', setup); server.on('clientConnected', function (client) { console.log('client connected', client.id); }); // fired when a message is received server.on('published', function (packet, client) { console.log('Published', packet.payload); }); // fired when the mqtt server is ready function setup() { console.log('Mosca server is up and running'); }

As you can see, server uses Mongodb to persist the client connection, run a mongodb instance before running MQTT server.

Client

var mqtt = require('mqtt'); var client = mqtt.connect('mqtt://10.0.0.2', {clientId:'nodeapp'}); client.on('connect', function () { client.subscribe('command'); client.publish('presence', 'Hello mqtt'); }); client.on('message', function (topic, message) { console.log('from mqtt ' + message.toString()); });

Happy coding…

Written by Sony Arouje

March 15, 2016 at 5:35 pm

Posted in Arduino

Tagged with , ,

Bluetooth Communication with Arduino

leave a comment »

I am in the process of redesigning my Raspberry Pi based Aeroponic controller, in my new system I am using Arduino. This time I decided to use Bluetooth instead of WiFi to communicate between my mobile app and Arduino controller. Later I will write a different post explaining about the new design. In this post I will explain how to communicate to Arduino via Bluetooth.

 

Arduino Bluetooth connection

I bought a HC-05 Bluetooth module from Ebay, it’s a very low cost module. The connection is pretty simple. See the connection below. I am using Arduno Nano in my new design.

connection_v2_bb

 

Connection Details

  • Nano VCC to BT VCC
  • Nano GND to BT GND
  • Nano RXD to BT TXD
  • Nano TXD to BT RXD

In my sketch I used Softserial and I assign D2 and D3 as RXD and TXD respectively.

I haven’t used the EN and KEY pin in the Bluetooth module. You might want to use EN pin, if you want to enter into AT mode to issue any commands to BT module.

Arduino Sketch

#include <SoftwareSerial.h> SoftwareSerial soft(2,3);// RX, TX void setup() { soft.begin(9600); Serial.begin(9600); } void loop() { if(soft.available()){ String serialData = soft.readString(); Serial.println(serialData); //echo bluetooth data to serial writeAck(); } } void writeAck(){ uint8_t payload[]="ACK|0|\n"; soft.write(payload,sizeof(payload)); }

 

It’s a very simple sketch to receive the data from Bluetooth module and echo to Serial, also send and Acknowledgment back to the caller.

You can test the program by issuing some text from Hyperterminal or any other similar app. I wrote an Android app to issue command via Mobile bluetooth.

 

Happy coding…

Written by Sony Arouje

March 4, 2016 at 1:26 pm

Posted in Arduino

Tagged with , ,

Farm Automation system based on Arduino and Raspberrypi

with 3 comments

Last two weeks, in my free time, I was working on a system to automate  Green house or an open field. The system designed using Arduino Nano and Raspberry Pi. The Arduino is used to read sensors and control devices and the Raspberry pi is the brain that decides what to do when an event detected by Arduino. All the systems communicates wirelessly via XBee.

In normal scenario in a farm we have to

  • Switch on the drip irrigation pump when the soil humidity is low.
  • Switch off when the soil is wet.
  • Switch on the Main motor that connects to a water source when the reservoir level goes down.
  • Switch off the main motor when the reservoir is full.
  • If it’s a Green house then monitor the humidity and control devices to increase or decrease the humidity. Also need to control temperature.

 

Below is a very ugly drawing I could come up : ), to explain the system.

image

 

Arduino based nodes

The nodes are connected to different Sensors like Soil Humidity, Temperature, Air Humidity, etc. Also the nodes can also switch on/Off drip irrigation motor, switch on/off Reservoir’s Solenoid valves, or control any hardware needed in the field.

Raspberry pi Brain

I developed this central/brain system in Nodejs. The system is very much generic and run based on configurations. So nothing is hardcoded. The XBee connected to the pi act as the coordinator and receive periodic sensor inputs from Ardunio connected in the field. This system can issue command to control devices based on the sensor inputs.

 

Let’s go through some of the scenarios to see how the system works.

Watering the plants: From the above picture you can see, there are 5 Arduino’s in the field sensing different parameters. For now lets think that they all reads the soil humidity. Say soil humidity value range from 0 to 100, where 0 is dry and 100 is fully wet. We need to switch on the drip irrigation motor when any of the sensor value is less than 20. Once all the sensor give a humidity value greater than 90 we need to switch off the motor.

As you can see the system need to take action based on the values coming from the sensor. Depending upon the crops these values can be changed. That’s where the Central Node js system comes into play.

In the central system, we can group the Sensor nodes and configure the triggering points. Also we can configure what to do when the triggering points reach. For e.g. in the above case we can say when the soil humidity of any sensor goes below 20, then send the Motor switch on command to the node sitting next to the Reservoir motor. To switch off the motor, the system needs approval from all the sensors, that means the motor will get switched off if all the nodes reported value is greater than 90.

Failover: What happens when a sensor node dies without sending soil humidity greater than 90 value, will the motor run whole day? No, the central system can be configured for that too, while configuring we can set up a timeout period. If the central system is not receiving high water level after a configured time, it automatically sends a Switch off command to the desired Arduino node to switch off the motor.

Filling Reservoir: From the above diagram, we can see there are two reservoirs and one Main motor. The main motor need to switch on to fill the Reservoir. Each reservoir is equipped with sensors to detect the High and Low water level. Also each water input is equipped with a solenoid valve. If the reservoir is high then the solenoid valve will close the input thus protect the reservoir from overflowing. Once all the reservoir get filled the system will switch off the Main motor before closing the last solenoid, other wise the pressure increase and can damage the Main motor.

The Arduino node will send a Water low when the water go down below a desired level. Then the central system will open the Solenoid before switching on the Main motor. The valve will open only for the reservoir where the water is low, rest all the valves will be closed.

If more than one Reservoir’s water is low then those valves will be open and the main pump will work until all the reservoir’s are filled. For e.g. say Reservoir A and B’s water level is low then both the valves will be open and switch on the main pump. A get filled and B is still not full then A’s valve will get closed. Once B is full the system will send Main pump switch off command then sends the command to close B’s valve.

 

System design

All the above scenarios are based on certain rules and all these rules are configurable. The central system is not aware of any rules. Based on the fields condition we need to configure it.

 

User can also see the activities in the farm via a dashboard. I haven’t designed any Dashboard UI yet.

 

Happy farming…

Written by Sony Arouje

February 17, 2016 at 6:16 pm

My IoT Experimental desk

leave a comment »

Snapseed (30)

Written by Sony Arouje

February 13, 2016 at 5:33 pm

Posted in .NET

Arduino Scheduler: sleep x time then run for y time

leave a comment »

Recent days I was playing with my Arduino uno to perform several tasks. One task is something like, say sleep for 10 mins and switch on a pin for 3 mins then sleep for 10 mins, and the cycle continues. I evaluated several libraries but most of them run a task based on an interval. For e.g. toggle pin 13 every 1 minute, it’s more like a delay. But what I wanted was, delay for 2 minutes then give a HIGH voltage to pin 13 for 1 minute then write LOW to pin 13 and again sleep for 10mins.

My search leads nothing, so I decided to write a quick and dirty Scheduler for me. I came up with a library after spending 3 hours yesterday night. I didn’t had much programming experience in C++, so I had to spend some time to understand how things work in C++ world. I also use the Timer library as a reference.

Let’s see the sketch that use my library.

#include "TaskScheduler.h" TaskScheduler t1; TaskScheduler t2; TaskScheduler t3; void setup() { Serial.begin(9600); pinMode(13, OUTPUT); pinMode(12, OUTPUT); t1.sleepThenToggle(4000,1000,13,HIGH); t2.every(2000,readSensor); t3.write(12,HIGH,4000); } void readSensor(){ Serial.println("Reading sensors..."); } void loop() { t1.update(); t2.update(); t3.update(); }

Here I declared three tasks, t1, t2 and t3.

Task t1 is a toggle pin task with sleep, in the sample code above, Arduino sleeps for 4000ms then switch on pin 13 for 1000ms and the cycle continues.

  • sleepThenToggle(<sleep time>,<keep the pin state for x ms>,<pin number>,<starting state of the pin>);

Task t2 is a callback task, in the above case, the function readSensor will get called every 2000ms.

  • every(<sleeptime>,<callback>);

Task t3 is a digitalWrite with timeout. One scenario we can use that functionality is, say the switching on/off of a pin is based on an external command, it might be coming from a Raspberry pi. In a situation if the Pi went down with some reason after issuing a switch on command then Arduino will keep the Pin on till a reset. These scenarios, we can use write, in the above code, the pin 12 will be HIGH for 4000ms, after that it will get switched off automatically.

  • t3.write(<pin number>,<starting state of the pin>,<timeout period>);

Make sure to call the ‘update()’ in the loop, other wise no action will be taken.

For the curious minds visit my Gitrepo to see the code.

 

Happy coding…

Written by Sony Arouje

January 28, 2016 at 1:25 pm

Posted in Arduino

Tagged with ,

Communication between Raspberry Pi and Arduino using XBee

with 17 comments

Recently I was doing some experiments to establish a wireless communication between a Raspberry pi and Arduino. To establish wireless communication I used XBee Pro Series 2 from Digi International. The idea behind this test setup is to test, whether I can control devices like motor or read different sensors remotely.

One of the biggest advantage of using XBee is, you can find a lot of tutorials and libraries for any kind of system and programming languages. For this test app, I used Node js in RPi and C in Arduino.

Test Setup

XBee: I configured two xbee, one as Coordinator and another as Router. Both in API mode 2 (AP =2). I used XCTU to configure both the device. Only reason to choose API 2 is because the Arduino library I used only support API mode 2.

Raspberry pi: connected Coordinator XBee to one of my RPi. You can see more about the connection in one of my earlier post.

Arduino Uno: connected the Router xbee to one of my Arduino. The connection is pretty simple as below.

  • XBee Rx –> Arduino Tx
  • XBee Tx -> Arduino Rx
  • XBee 3.3v-> Arduino 3.3v
  • XBee Gnd –>Arduino Gnd

 

Raspberry Pi Node js code

Modules used

  • 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: 2 }); var serialport = new SerialPort("/dev/ttyAMA0", { baudrate: 9600, parser: xbeeAPI.rawParser() }); var frame_obj = { type: 0x10, id: 0x01, destination64: "0013A200407A25AB", broadcastRadius: 0x00, options: 0x00, data: "MTON" }; serialport.on("open", function () { serialport.write(xbeeAPI.buildFrame(frame_obj)); console.log('Sent to serial port.'); }); // All frames parsed by the XBee will be emitted here xbeeAPI.on("frame_object", function (frame) { console.log(">>", frame); if(frame.data!== undefined) console.log(frame.data.toString('utf8')); });

 

 

Arduino Sketch

This sketch uses a XBee library, to add the library, goto Sketch->Include Library->Manage Libraries. From the window search for XBee and install the library. I am using Arduino IDE 1.6.7.

I use SoftwareSerial to establish serial communication with XBee, Pin 2 is Arduino Rx and Pin 3 is Arduino Tx.

 

#include <Printers.h> #include <XBee.h> #include <SoftwareSerial.h> unsigned long previousMillis = 0; const long interval = 4000; // the interval in mS XBee xbee = XBee(); // XBee's DOUT (TX) is connected to pin 2 (Arduino's Software RX) // XBee's DIN (RX) is connected to pin 3 (Arduino's Software TX) SoftwareSerial soft(2,3);// RX, TX Rx16Response rx16 = Rx16Response(); ZBRxResponse rx = ZBRxResponse(); XBeeAddress64 addr64 = XBeeAddress64(0x0013a200,0x407a25b5); char Buffer[128]; char RecBuffer[200]; void setup() { // put your setup code here, to run once: soft.begin(9600); Serial.begin(9600); xbee.setSerial(soft); } void print8Bits(byte c){ uint8_t nibble = (c >> 4); if (nibble <= 9) Serial.write(nibble + 0x30); else Serial.write(nibble + 0x37); nibble = (uint8_t) (c & 0x0F); if (nibble <= 9) Serial.write(nibble + 0x30); else Serial.write(nibble + 0x37); } void print32Bits(uint32_t dw){ print16Bits(dw >> 16); print16Bits(dw & 0xFFFF); } void print16Bits(uint16_t w){ print8Bits(w >> 8); print8Bits(w & 0x00FF); } void loop() { // put your main code here, to run repeatedly: xbee.readPacket(); if (xbee.getResponse().isAvailable()) { if (xbee.getResponse().getApiId() == ZB_RX_RESPONSE) { xbee.getResponse().getZBRxResponse(rx); if (rx.getOption() == ZB_PACKET_ACKNOWLEDGED) { // the sender got an ACK Serial.println("got ACK"); } else { // we got it (obviously) but sender didn't get an ACK Serial.println("not got ACK"); } Serial.print("Got an rx packet from: "); XBeeAddress64 senderLongAddress = rx.getRemoteAddress64(); print32Bits(senderLongAddress.getMsb()); Serial.print(" "); print32Bits(senderLongAddress.getLsb()); Serial.println(' '); // this is the actual data you sent Serial.println("Received Data: "); for (int i = 0; i < rx.getDataLength(); i++) { print8Bits(rx.getData()[i]); Serial.print(' '); } //Received data as string to serial Serial.println(' '); Serial.println("In string format"); for (int i = 0; i < rx.getDataLength(); i++) { if (iscntrl(rx.getData()[i])) RecBuffer[i] =' '; else RecBuffer[i]=rx.getData()[i]; } Serial.println(RecBuffer); String myString = String((char *)RecBuffer); if(myString=="MTON"){ Serial.println("Switching on Motor"); } else if(myString=="MTOFF"){ Serial.println("Switching off Motor"); } } //clear the char array, other wise data remains in the //buffer and creates unwanted results. memset(&RecBuffer[0], 0, sizeof(RecBuffer)); memset(&Buffer[0], 0, sizeof(Buffer)); } //Send a packet every 4 sec. unsigned long currentMillis = millis(); if (currentMillis - previousMillis >= interval) { // save the last time you blinked the LED previousMillis = currentMillis; strcpy(Buffer,"RSLOW"); uint8_t payload[20]= "RSLOW"; // ZBTxRequest zbtx = ZBTxRequest(addr64,(uint8_t *)Buffer,sizeof(Buffer)); ZBTxRequest zbtx = ZBTxRequest(addr64,payload,sizeof(payload)); xbee.send(zbtx); } }

 

Burn the sketch to Arduino.

Testing

Run node js code in RPi and you start receiving the frames from Arduino.

 

 

Happy coding….

Written by Sony Arouje

January 21, 2016 at 12:06 am

Raspberry Pi as a Development Server

leave a comment »

In my searches, I came across a very elaborate blog about Raspberry pi and how to utilize this small computer for development purpose. Also the post touches topic about how to configure Port forwarding to access the Pi from Internet.

Worth reading the blog: How to Turn Your Raspberry Pi Into a Development Server

 

Happy coding…

Written by Sony Arouje

October 30, 2015 at 10:55 am

Posted in Raspberry Pi

My modified Royal Enfield Electra 5s

with 31 comments

Last couple of months my Royal Enfield was in Kerala with my friend Shibin, a highly creative Mechanic. I better call him an Artist, his eye for details is highly remarkable. Also he is very passionate about his job.

The restoration was a lengthy process. Almost all the parts has been replaced. The major modifications are.

 

bulle1_copyright

Crank Weight: Added 6kg more, now the crank weight is around 11.7kg. The increased crank weight allow me to ride slow speed in higher gear without knocking. Now the riding is smooth without much gear shifting. Also the kind of beat the machine produce is awesome. I need to get accustomed to a new riding habit. Increased weight also need a good bearing, I used SKF bearing. The cost of the bearing is higher but I don’t want to sacrifice quality over cost.

Matte Black Paint: I am a hardcore fan of Black. So I decided to paint my RE with Black. I loved the Matte colors of Harley, so asked Shibin to use the same kind of Black in my RE. He did an awesome job.

Buffing: This is the idea of Shibin to buff the Engine section. I asked to paint Engine as well, he advised me not to. So he went ahead and buffed it, after seeing the result, I realized that my idea of painting was not good.

Delco: My RE was fitted with Electronics timing system (CDI). Shibin decided to replace it with old mechanical Delco. The Engine has slot to fit it but he had to drill some holes and customize the engine to suit the Delco.

Front Suspension: From the beginning I didn’t like the design of the Suspension in my Electra. I always admire the look of old RE. So I asked Shibin to replace the front suspension with the Classic one.

Mudguards: I didn’t like Electra’s mudguards either. The mudguards are replaced with the Standard model.

Fixed some other major Issues:

I was complaining about the burning color in my silencer but no service centers could fix it. Shibin had a look and said it’s the issue with the timing system. When he dismantled the engine, he told me that Carburetor was irrecoverably damaged. I assumed this should have been captured in the prior service 3 months before that. Also a lot of issues with the timing system.

One of the Oil pump holes where closed with some Engine sealer. From the beginning I had these Engine leakage, I complained it several times as well. So they might have added the sealer more and some how it went into the oil pump. Some say that it’s not leakage, it’s marking the territory but for me it’s a mess, also I am social being no need to mark the territory :).

A Word to Eicher motors: Royal Enfield is a great machine but the major issues are with the Authorized service centers. The service persons are not at all experienced. Because of high demand service centers are employing very less skilled persons. These guys are learning from the mistakes, but unfortunately our bullets are bearing their mistakes. Every one is jumping to buy an Enfield but they are not realizing the trouble they have to face in the future from these so called Authorized centers. I am pretty sure none of the issues in your Enfield could be fixed in any Authorized service centers. Try and find a good mechanic in your area or pack your RE to Shibin :).

 

Happy riding…

Written by Sony Arouje

September 16, 2015 at 6:09 pm

Posted in Misc

Tagged with , ,

MQTT Protocol for Internet of Things (IoT)

with 8 comments

I was thinking about how to control my Aeroponic system remotely via internet. The Raspberry Pi controlling the system is connected to internet via a router. I could access RaspberryPi by Port forwarding and stuff like that but it’s complicated. Next option could be using Websockets but I felt it’s an overkill for the applications running in Pi.

Recently I received a Refcard from Dzone regarding a protocol called MQTT. I was not aware of this Protocol before. So thought of doing some experiment with it. I am not going much deeper into the protocol, Dzone refcard did a great job of explaining it well.

In a nutshell, MQTT consist of three parts.

  • Broker
  • Subscribers
  • Publishers

image

 

Publisher, publish message to a specific topic and any Subscriber subscribes for that topic receives the message. Broker is the central hub, both Publishers and Subscribers are connected to the Broker and it take care of delivering the message to all the subscribers subscribed for the topic.

Brokers

We can implement our own broker using RabitMQ or Mosca plugin for Node js or any other MQTT brokers available in the market. To experiment it, I used CloudMQTT addon in Heroku. I used Heroku just to manage every thing from one central place.

Dev Environment

I created two set off Node js application, one running in my computer as a publisher and another running in my RaspberryPi as a subscriber. Both have no direct connection instead they are connected to CoudMQTT broker. Below is a test code and nothing related to my Aeroponic system.

Publisher Code

var mqtt = require('mqtt');
var client = mqtt.createClient('<<PortNumber>>', 'm11.cloudmqtt.com', {
    username: '<<UserName>>',
    password: '<<Password>>'
});

client.on('connect', function () { // When connected
    
    // subscribe to a topic
    client.subscribe('TEMPERATURE_READING', function () {
        // when a message arrives, do something with it
        client.on('message', function (topic, message, packet) {
            console.log("Received '" + message + "' on '" + topic + "'");
        });
    });
    
    // publish a message to a topic
    client.publish('SET_TEMPERATURE', '24', function () {
        console.log("Message is published");
      });
});

 

The above code act as a Publisher as well as a Subscriber. For e.g. the above code can be a piece running in Internet and the Pi’s can Publish the Temperature readings in a periodic interval and logged in a central db. We can see the readings via a webapp or which ever the way we need. Also if required we can set a temperature to all the connected RPi’s by publishing a message to topic ‘SET_TEMPERATURE’.

Subscriber Code

var mqtt = require('mqtt'), url = require('url');
var client = mqtt.createClient('<<Portnumber>>', 'm11.cloudmqtt.com', {
    username: '<<UserName>>',
    password: '<<Password>>'
});

client.on('connect', function () { // When connected
    
    // subscribe to a topic
    client.subscribe('SET_TEMPERATURE', function () {
        // when a message arrives, do something with it
        client.on('message', function (topic, message, packet) {
            console.log("Received '" + message + "' on '" + topic + "'");
           // set the temperature. 
        });
    });
    
});

 

The code is very minimal and we could achieve an easy communication to all the connected devices. In the above scenario clients are always connected. If you want to end the connection then call ‘client.end()’.

Later I implemented a Broker using Mosca, both scenarios the system worked really well.

Written by Sony Arouje

September 3, 2015 at 5:29 pm

Posted in Raspberry Pi

Tagged with ,

<span>%d</span> bloggers like this: