Sony Arouje

a programmer's log

Archive for the ‘Arduino’ Category

Arduino system in a breadboard

with 3 comments

After successfull completion of the first prototype of my Aeroponic controller, I decided to redesign the system with more functionalities. In the new design I need external EEPROM, WiFi and more but I am running out of extra pins in my Nano to support all the new functionalities in my mind. I cant go to Mega, as it will increase the size of my system and cost. So I decided to experiment with Atmega32a which has 32 I/O pins and can accommodate all my new requirements. But I have to run this chip standalone without all the luxury provided by Arduino board, like USB connection, Power regulation, etc.

I bought couple of Atmega32a from the market and boot loaded using the Arduino ISP Shield. Tested the chip using a blinky sketch and it worked well.

The next task is run it standalone from an external power source. Atmega32 can handle voltage upto 5.5v and my Aeroponic controller runs with an external power source of 12v. So I need to use a regulator to step down the voltage from 12 to 5v. One option could be to use LM7805 but in my experiments I could see this regulator produces a lot of heat. I come across this switching regulator called LM2575 and every one says it works really well and not produce much heat. I bought couple of these regulators with fixed 5v output.

The data sheet of LM2575 provides a schema to connect the regulator as shown below.

image

[Note: Above picture from the Datasheet of LM2575]

Yesterday night I decided to combine all the parts together to create a standalone board to run the blinky sketch.

I wired LM2575 as described in the above schema in a breadboard, checked the output voltage and it was 5v. I left the system for couple of hours to see any heat coming out. After the heat testing I decided to connect Atmega32a to the power source and make the standalone system.

 

Atmega32A

[Note: Above picture from the Datasheet of Atmega32]

Here is the wiring.

  • Atmega VCC to LM2575 5v output
  • Atmega GND to common GND
  • Atmega XTAL1 and XTAL2 to 16mghz crystal, and two 22pf ceramic capacitor from each leg of the crystal to GND.
  • Atmega RXD to FTDI USB’s TXD
  • Amega TXD to FTDI USB’s RXD
  • FTDI USB’s GND to common GND.

The FTDI adapter allows me to see the debug information I am writing to the serial port. The blinky sketch I uploaded also write ‘Hello world’ to serial port.

Let’s see how to looks in a breadboard. As you can see it’s very minimal.

IMG_1279

 

Now it’s a standalone board which can run Arduino sketch and can easily fit in my new board.

Next task will be to try programming the Atmega using the connected FTD USB to TTL adapter.

Advertisements

Written by Sony Arouje

May 18, 2016 at 10:37 am

Posted in Arduino

Tagged with , ,

Home made Arduino ISP Shield

with 4 comments

In recent days I started programming more on Atmega chips than Arduino boards. I use Arduino Uno as the ISP to bootload and program the Atmega chips. One of the difficulty I faced to use Arduino ISP is the wires running from Uno to bread board. If I misplace the breadboard slot while plugging a new chip, I might fry it and waste my money.

So I decided to make a shield for my Uno. It’s nothing special and not so beautiful but does it job well.

IMG_1277

 

This board is based on the Arduino ISP sketch from lydiard. I also kept a slot to plug FTDI USB to TTL adapter, which connects the Serial port of Atmega 32 plugged into the shield. Using the TTL adapter I can see the serial writes from the chip and easily debug my code.

With this board I can bootload several of my Atmega 16/32 chips and upload sketch very easily.

Written by Sony Arouje

May 16, 2016 at 11:35 pm

Control AC/DC devices using Arduino

leave a comment »

In forums I could see people asking how to switch on/off devices using Arduino. It’s a very simple approach using a relay module. In this post I will briefly explain how to do that.

 

Connecting Relay module to Arduino

RelayConnection_bb

 

Most of the relay module runs with 5 or 12v DC. Even if it’s 5v, never connect VCC of relay to Arduino. Always make sure Relay should powered from an external source. Most of the relay need more current (A) than Arduino can supply and might damage your Arduino. In the above diagram I used a battery (it should be a 12v battery, I couldn’t find 12v battery in fritzing) to as power source.

Here the Arduino and the Relay are powered from the battery. If you are powering Arduino separately via USB then remove the wire connecting to VIN of Arduino. Leave the GND connecting to Arduino as it is, all the connected devices needs common ground.

Relay need a trigger to switch on/off the connected device. If we supply high (5v) to INP pin of relay module the connected device will switch on, if we supply low then the device will get switched off. Here I connected D2 to INP pin of the relay. In code if we do digitalWrite to D2 with HIGH, the relay will get activated and LOW will deactivate the relay.

We can control AC or DC device using the relay. As you can see from the above diagram, the Relay is in series to the power supply going to the load. The wiring is very similar to a switch between a load and the power.

Written by Sony Arouje

April 19, 2016 at 4:12 pm

Posted in Arduino

Tagged with , , , , ,

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

%d bloggers like this: