Sony Arouje

a programmer's log

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

leave a comment »

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 6 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 6 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 ,

RS485 Communication Protocol with Micro Controllers and Raspberry pi

with 6 comments

We are in the age of connected devices, devices could talk each other either via RF or wired. In one of my post I explained about Radio Frequency communication using Xbee. In this post lets see how devices can talk each other via wired network. One of the advantage of Wired network is, it is cost effective compare to buying an XBee modules like Xbee pro. I personally prefer Wireless communication as it’s hassle free, just place the devices where ever we need.

In my previous post I explained how to Bootload Atmega16A and program it using Arduino. Next step is to establish the communication between the Micro controllers and Raspberry pi. In this case my Raspberry Pi is acting as the central hub that talk to other controllers and collect data or issue command to do some job.

RS 485 Protocol

I better leave it to Wikipedia to give a detailed explanation of the protocol. In brief using RS485, devices can communicate Full duplex or Half duplex. I used a Half duplex communication. So it’s a protocol, how do we implement the protocol in our hardware, there is a chip Max485 from Maxim. This chip can establish a half duplex communication.

Max485 Pin configuration

Max 485 is a 8 pin chip as shown below. It’s a DIP chip and SMD have different pin layout.

image

Image from Maxim site

Pin 1 – RO: It’s the Data-In pin, devices can read data from the bus using this pin. Rx pin of the Micro controllers should connect to this pin.

RE and DE: Set this pin to Logical High to transmit any data to the bus. Set this pin to Low to receive data from the bus.

Pin 4 DI: Devices can transmit data via this pin.  This pin should be connected to the Tx pin of the device.

Pin 8 and 5 – VCC and GND: To power the chip, VCC should be 5 volt.

Pin 7 and 6 – A and B: Here we connect the data line. A should connect to the A Pin of the next Max 485 and B with B.

 

Connection Diagram

The below picture will illustrate how to connect all the devices together.

RS485_SerialCommunication_bb 

Image created using Fritzing

As per the diagram, if RPi want to transmit any data. We should set a high voltage on GPIO 18 and issue a serial write. All other devices in the network will be in listening mode and can read data using serial read, if any other device wanted to transmit data, then issue a Logical High to RE DE pin and will get promoted as a master and transmit data via serial write.

Now it’s up to you to program it and do some cool things with it.

Written by Sony Arouje

April 23, 2015 at 11:05 pm

Bootloading Atmega16 with Arduino Uno

with one comment

Last two days I was experimenting with Microcontrollers and researching about how to write applications on it. I bought one Atmega16A and decided to use Arduino bootloader. So that I can write programs using Arduino IDE and syntax. This post explains about how to bootload Atmega16. I didn’t had any prior experience with Arduino, I have a uno sitting at my desk for quite a long time but never used it. Last three nights I was learning more about Arduino coding and learning about boards config and other stuffs.

Software Setup for Bootloading

I followed the steps posted by Sudar in his blog, please go through the post before reading further. Here I will write some points I had to do to do to complete the bootloading process.

Arduino IDE version: To run the core created by Sudar, we need the IDE version 1.0.x. I have the latest version 1.6.3. There are some differences in configuring boards.txt from 1.0 to 1.6. I tried to rewrite the boards.txt as per 1.6.* standard but it didn’t like it. So I downloaded the old version 1.0.6 from Arduino website. If you have 1.6.* already installed then better download the zip file and extract to a folder. That way you can use 1.6 and 1.0 in same machine.

Adding Boards and Variants: Adding boards to the sketch book folder didn’t work for me, may be I didn’t get it clearly. So I did the below steps.

  1. Go to the Arduino’s hardware folder, <<IDE install location of IDE>>/hardware/arduino/ and open boards.txt.
  2. Copy the contents of Atmega16 boards and pasted to the boards.txt opened in Step 1.
  3. Create a new folder named mega16 under <<IDE install location>>/hardware/arduino/variants and paste the “pins_arduino.h” created for Atmega16.
  4. Open Arduino IDE 1.0.* and goto Tools->Boards and you should see as shown belowarduino_ide_v1.0.6If if you can see the new board under Boards menu as shown above then we successfully setup the software environment for bootloading.
  5. Goto File->Examples->ArduinoISP, it will open a new window with ArduinoISP sketch. Before uploading the sketch make sure you have selected Arduino Uno in Tools->Boards->Arduino Uno. Now upload the sketch to your Uno. Now we setup our Uno as a programmer.

Hardware Setup for Bootloading

Here again I followed the pin connection detailed in Sudar’s post. Please follow exactly the way mentioned in the post. Also don’t forget to connect the capacitor between Reset and GND of Arduino.

Note: If you try to upload any sketch to Arduino Uno when the Capacitor is connected, IDE will throw errors. So before doing any thing with your Arduino remove the Capacitor.

Bootloading

Follow the below steps to burn the bootloader

  1. We have to set our Arduino Uno as an ISP. To do that go to Tools->Programmer and select “Arduino as ISP”
  2. Set the bootloader from Tools->Boards and select the newly added board, ie. Atmega16(internal 8mhz clock).
  3. Now burn the bootloader by selecting “Burn Bootloader” under Tools menu.

If every thing works fine, you could see a success message at the bottom portion of the IDE.

Uploading Sketches to Atmega16

Next we need to upload some sketches to newly bootloaded Atmega16. For this I used the new version of Arduino IDE 1.6.3, If you want you can use IDE 1.0.*. Some how the old IDE is very slow for me, so I decided to use the new version. Skip the below step if you decided to use the old 1.0.* version.

Follow the steps to use the Atmega16 board in new version

  1. Create a new folder under <<Installed location of IDE V1.6.*>>/hardware. You can name the folder anything, I named as Mega16.
  2. Under Mega16 folder create another folder called “avr”.
  3. Inside the avr folder copy the boards.txt and create another folder named variants and copy “pins_arduino.h” inside variants folder.
  4. Open boards.txt and add the line “atmega16-8.upload.tool=arduino:avrdude”

Follow the below steps to upload sketch(Common for all versions of IDE)

  1. Open up the IDE and load Blink from File->Examples->Basic.
  2. Edit the code so that you are writing to a pin of Atmega16, here I write to Digital 6, it’s physical pin 20.
  3. Before uploading the sketch Choose Atmega16(internal 8 Mhz) from Tools->Boards.
  4. Choose “Upload using Programmer” from File menu.

Just connect a LED with a Resistor to Physical pin 20 of Atmega16 and you can see the LED blinking.

 

Now I can write any thing to the Atmega16 and connect to sensors or any thing I wanted to do without Arduino.

Written by Sony Arouje

April 23, 2015 at 1:42 pm

Follow

Get every new post delivered to your Inbox.

Join 227 other followers

%d bloggers like this: