Pages

Saturday, December 7, 2013

Dijkstra's algorithm : Grid Search implementation Arduino


This tutorial contains an implementation of Dijkstra's algorithm using an Arduino to search for the shortest path in a grid. Here I have used 4*4 grid to demonstrate the implementation


Step 1 : Write the grid nodes to the EEPROM of the Arduino


Sample grid


1     1     1     0

1     0     1     1

1     1     1     1

1     0     1     1

Note that is a square grid matrix where 1 indicates accessible nodes and 0 indicates nodes to be avoided. I wrote this to Arduino EEPROM by a slight modification to the EEPROMWrite in Arduino example set.

Code:


#include <EEPROM.h>
void setup()
{
 
   EEPROM.write(0,1);
   EEPROM.write(1,1);
   EEPROM.write(2,1);
   EEPROM.write(3,0);
   EEPROM.write(4,1);
   EEPROM.write(5,0);
   EEPROM.write(6,1);
   EEPROM.write(7,1);
   EEPROM.write(8,1);
  EEPROM.write(9,1);
  EEPROM.write(10,1);
  EEPROM.write(11,1);
  EEPROM.write(12,1);
 EEPROM.write(13,0);
 EEPROM.write(14,1);
 EEPROM.write(15,1);
}
void loop()
{
}


Thursday, July 11, 2013

Serial Communication using RxTx library in Java(Windows)

In this post I expect to explain how to use Java RxTx library to carry out a two way serial communication with an Arduino. On downloading and installing Java RxTx serial communication library please refer this link http://duvindu92.blogspot.com/2013/07/installing-java-rxtx-library-for-serial.html.

In this sample code first a string is sent by the Arduino requesting the name of the user. Once the user types in the name, it is sent back to the Arduino through the serial port and Arduino returns a welcome message, "Hello"+ <yourName>. So lets begin

The JAVA Code

import java.io.BufferedReader;                    //BufferedReader makes reading operation efficient
import java.io.InputStreamReader;         //InputStreamReader decodes a stream of bytes into a character set
import java.io.OutputStream;          //writes stream of bytes into serial port
import gnu.io.CommPortIdentifier;           
import gnu.io.SerialPort;
import gnu.io.SerialPortEvent;            //deals with possible events in serial port (eg: data received)
import gnu.io.SerialPortEventListener; //listens to the a possible event on serial port and notifies when it does
import java.util.Enumeration;
import gnu.io.PortInUseException;           //all the exceptions.Never mind them for now
import java.io.IOException;
import gnu.io.UnsupportedCommOperationException;
import java.util.TooManyListenersException;
import java.util.Scanner;                                   //to get user input of name

public class SerialTest implements SerialPortEventListener {        
   
    private SerialPort serialPort ;         //defining serial port object
    private CommPortIdentifier portId  = null;       //my COM port
    private static final int TIME_OUT = 2000;    //time in milliseconds
    private static final int BAUD_RATE = 9600; //baud rate to 9600bps
    private BufferedReader input;               //declaring my input buffer
    private OutputStream output;                //declaring output stream
    private String name;        //user input name string
    Scanner inputName;          //user input name

    //method initialize
    private void initialize(){
        CommPortIdentifier ports = null;      //to browse through each port identified
        Enumeration portEnum = CommPortIdentifier.getPortIdentifiers(); //store all available ports
        while(portEnum.hasMoreElements()){  //browse through available ports
                ports = (CommPortIdentifier)portEnum.nextElement();
             //following line checks whether there is the port i am looking for and whether it is serial
               if(ports.getPortType() == CommPortIdentifier.PORT_SERIAL&&ports.getName().equals("COM6")){ 

                System.out.println("COM port found:COM6");
                portId = ports;                  //initialize my port
                break;                                                                                     }
           
            }
       //if serial port am looking for is not found
        if(portId==null){
            System.out.println("COM port not found");
            System.exit(1);
        }
        
                            }
    
    //end of initialize method
    
    //connect method
   
    private void portConnect(){
        //connect to port
        try{
         serialPort = (SerialPort)portId.open(this.getClass().getName(),TIME_OUT);   //down cast the comm port to serial port
                                                                                     //give the name of the application
                                                                                     //time to wait
        System.out.println("Port open succesful: COM6"); 
        
        //set serial port parameters
serialPort.setSerialPortParams(BAUD_RATE,SerialPort.DATABITS_8,SerialPort.STOPBITS_1,SerialPort.PARITY_NONE);
        
        

        }
        catch(PortInUseException e){
            System.out.println("Port already in use");
            System.exit(1);
        }
        catch(NullPointerException e2){
            System.out.println("COM port maybe disconnected");
        }
        catch(UnsupportedCommOperationException e3){
            System.out.println(e3.toString());
        }
       
        //input and output channels
        try{
      //defining reader and output stream
       input = new BufferedReader(new InputStreamReader(serialPort.getInputStream()));
        output =  serialPort.getOutputStream();
        //adding listeners to input and output streams
        serialPort.addEventListener(this);
        serialPort.notifyOnDataAvailable(true);
        serialPort.notifyOnOutputEmpty(true);
        }
        catch(Exception e){
            System.out.println(e.toString());
                            }
        
    }
    //end of portConncet method
    
    //readWrite method
   
    public void serialEvent(SerialPortEvent evt) { 
   
       if (evt.getEventType() == SerialPortEvent.DATA_AVAILABLE) { //if data available on serial port
try {
String inputLine=input.readLine();
System.out.println(inputLine);
                                inputName = new Scanner(System.in); //get user name
                                name = inputName.nextLine();
                                name = name + '\n';
                                System.out.printf("%s",name);
                                output.write(name.getBytes());     //sends the user name
} catch (Exception e) {
System.err.println(e.toString());
}
}
       
    }
    //end of serialEvent method
    
    //closePort method
    private void close(){
        if(serialPort!=null){
            serialPort.close(); //close serial port
        }
        input = null;        //close input and output streams
        output = null;
    }
    //main method
    public static void main(String[] args) {
        SerialTest myTest = new SerialTest();  //creates an object of the class
        myTest.initialize();
        myTest.portConnect();
       System.out.println("Started");
       while(1>0);       //wait till any activity
        
       
                                            }
//end of main method
// end of  SerialTest class
}
Arduino Code

boolean stringComplete = false;
String inputString = "";

int led=13;

void setup(){
Serial.begin(9600);
pinMode(led,OUTPUT);
Serial.println("Hi, What's Your Name");
                  }

void serialEvent() {
  while (Serial.available()) {
    
    char inChar = (char)Serial.read(); 
    inputString += inChar;
    if (inChar == '\n') {
      stringComplete = true;
                                    }
   Serial.flush();
    //end of while()
                                     }
    //end of serialEvent
                    }

void loop(){
       if(stringComplete){
             digitalWrite(led,HIGH);
             String name = "Hello "+ inputString; 
             inputString = "";
             Serial.println(name);
             stringComplete = false;
                                 }
             }

Installing Java RxTx library for serial communication

I was in the middle of an electronic project which required sending data from the computer to an external circuit driven by an Arduino. After playing around with the Arduino Serial Monitor for a while I wanted to write a piece of software using java, that could get the job done. So, as usual google was the page to turn to. After hours of searching I could rarely find an complete description in a single place that would guide a beginner like me :P. So after all the struggles I decided to write this post down

This post will guide you through on how to do serial communication through the RXTX library on java. Well of course first you will have to download the library, install before anything.

Download page : http://rxtx.qbang.org/wiki/index.php/Download
Instructions on installation: http://rxtx.qbang.org/wiki/index.php/Installation_for_Windows
(Windows)

Now you are good to go. In order to start coding you will have to import gnu.io.* to your program. I will follow this post with one explaining a sample code

Monday, July 8, 2013

DRIVING BIPOLAR STEPPER MOTOR WITH ARDUINO + L298N


Ever removed removing stepper motors from old printers. Well, most of the stepper tors you find in the old printers are bipolar stepper motors. Bipolar stepper motors have a permanent magnet rotor and two coils in a stator at 90 degrees to each other. 


Simple bipolar stepper


Above is a simple diagram of one. In driving bipolar stepper motors equal currents are applied to both the coils. The motor is stepped by varying the direction of current in each coil. The below diagram shows the full stepping sequence of the above stepper motor by doing so

Full step sequence of a bipolar stepper motor



The above motor has a full step angle of 45 degrees. This step angle or resolution can be improve by increasing the poles on the motor. Typical step value of a bipolar motor may either be 1.8 degrees(200 steps per revolution) or 7.5 degree steps(48 steps per revolution). These could be halved by using a half- step sequence where between each step indicated above current in the coil whose current is reversed, is switched off before reversing. Hence steps can be reduced to 0.9 degree steps or 3.75.

Enough on the details, let's get onto the driving one. The motor I used was one with full step of 7.5 degree step angle. A voltage of 9v were applied to the motor while it drew a current of about 100mA during operation. I used Arduino mega 2560 which was interfaced with L298N motor controller circuit for the purpose

L298N motor driver ciruit

Diodes were used for protection from inductive load of the motor. Datasheet of L298N recommends fast diodes, so 1N4148 were used. Input pins of the L298N were connected to Digital pins of the Arduino which I have mentioned in my code below. Logic supply voltage of L298N (pin4 - Vs) was connected to +5v pin of Arduino while the ground of the circuit was connected to ground pin of Arduino in order to supply common ground for logic operations.

The next step was to program the arduino. The following code was written to drive the motor continuously in one direction

//defining connections to L298N
int input1 = 22;
int input2 = 23;
int input3 = 28;
int input4 = 29;

void setup()
{
  pinMode(input1,OUTPUT);
  pinMode(input2,OUTPUT);
  pinMode(input3,OUTPUT);
  pinMode(input4,OUTPUT);
}

void loop()
{
//1st step
digitalWrite(input1,HIGH);
digitalWrite(input2,LOW);
digitalWrite(input3,LOW);
digitalWrite(input4,HIGH);
delay(10);  //small delay between each step of 10ms

//2nd step
digitalWrite(input1,LOW);
digitalWrite(input2,HIGH);
digitalWrite(input3,LOW);
digitalWrite(input4,HIGH);
delay(10);

//3rd step
digitalWrite(input1,LOW);
digitalWrite(input2,HIGH);
digitalWrite(input3,HIGH);
digitalWrite(input4,LOW);
delay(10);

//4th step

digitalWrite(input1,HIGH);
digitalWrite(input2,LOW);
digitalWrite(input3,HIGH);
digitalWrite(input4,LOW);
delay(10);
}

Arduino was given 9v and the circuit was powered up. Ta - Dah. Here you go. Your application may vary from driving the motor continuously in one direction. Now, its all up to you to make-break this code to tune into your application. Cheers :)

Saturday, March 2, 2013

              GUI programming with PYGTK #1 - Getting started





What is PYGTK?

PYGTK is a tool that lets you create programs with graphical interface using Python programming language. It contains GTK+ library which has wide range of visual elements that can be used to develop full featured applications which can be run on various platforms viz, windows, Linux, MacOS X unmodifies.

Why PYGTK?

It's easy to learn, easy to use and most importantly it's FREE. You can even use, modify, distribute and study it.

How to install PYGTK?

For LINUX platforms:

Python and PYGTK are already installed in the system if you are a LINUX user. However if you are unable to locate PYGTK follow the below steps

1) Connect to the Internet
2) Open up a new 'Terminal' window ( /Applications/Utilities/Terminal)
3) Type the following commands in the terminal window

            $ sudo apt-get update
            $ sudo apt-get install python-gtk2-doc
4) Done. Now you have PYGTK in you system



      
For Windows platforms

If you do not have python in your system firstly you will have to download it online using the following link (python version 2.7.3)

        http://www.python.org/download/releases/2.7.3/

To get the PYGTK, GTK+ library and other useful modules namely PyCairo, PyGObject go to the following link and download the relevent items. When downloading the above modules keep in mind to download the versions compatible with the version of Python installed in your system.
       
       http://www.pygtk.org/downloads.html
            
That's it for now. It's time to have fun using PYGTK :). Cheers :)

Tuesday, February 19, 2013

Using Electronic Components #1 - 555 timer

 NE555 - Let's Emit a pulse
What is 555 timer?

   555 timer IC could be regarded as one of the most successful chips ever made. Statistics show that 555 timer IC is the world's mostly manufactured IC with over 1billion IC's still being produced each year. From hobby electronics to engineering, 555 comes in handy in enormous range of applications. If you are a starter this is probably the best IC to start with, given its simplicity and capability.


So what can 555 do? let's get started. First application will be emitting a pulse.


pinout of 555 timer
Before beginning with our experiment i will introduce each pin of 555

Vcc - positive supply pin
ground - ground pin
pin 2 - trigger pin. output triggers when voltage on pin falls below 1/3rd of supply voltage
pin 6 - threshold pin. 555 output goes low when voltage on the pin goes above     2/3rd of supply voltage
pin 4 - reset pin
pin 5 - control pin. As of now do not pay much attention to this pin as i will go through its uses in the next tutorials



Components needed:

R4: 100K
R1: 4.7K
R3: 470
R2: 10K linear potentiometer
C1: 47 μF electrolytic
C2: 0.1 μF ceramic
IC1: 555 timer
D1: 5mm LED










If you are unable to find some parts feel free to replace them with close substitutes. At this point what matters is seeing what is happening.

First make the connections as shown in the schematic above. Begin by turning the potentiometer(R8) to its maximum resistance. Then gradually reduce the resistance of R8. At some point you will observe LED light up, stays on for 5 seconds and go off. So that is it, you emitted the pulse, but what exactly went through? how can  you customize this? let me take you through it

555 output triggered when the voltage on the pin 2 of the IC fell below 1/3 of the supply voltage(in this case below 3v). It then emits a pulse whose time length depends on R4, C1 and triggers off again. 555 in this mode is called monostable mode

So what do all the resistors, capacitors around 555 do?

R1, R2 - acts as a voltage divider to change voltage on pin2

R3 - limit the current through LED

R4, C1 - controls the duration of the pulse. If you are aware of the time  constant concept you will understand duration of pulse is roughly equal to R4*C4 (time constant). Of course you will need to have a little idea of insides of 555, which is available on data sheet. And if you are unfamiliar with time constant concept just remember the result i derived

C2 - it's used to prevent any voltage fluctuations from affecting our proceedings. However it's not critical as for now

Note: You can add an electrolytic capacitor of 100uf between positive and negative supply to prevent any effect from supply voltage fluctuations

So we are done for now. You are free to customize this according to your need. Cheers :)