Showing posts with label Arduino Projects. Show all posts
Showing posts with label Arduino Projects. Show all posts

Wednesday, January 27, 2016

Programming the robot- part2 (giving life to little Franky)



In my last  post I have discussed several functions that I have used. From this post I would like to discuss the rest of the functions.

Functions associated with LCD Display

Write_LCD()

Write_LCD() handles displaying the current distance measurement the ultra sound sensor is taking. Since the sensor measures distance every 50ms that resolution is too fast for humans to be able grasp any information. Therefore the actual display doesn’t show the distance in real time. It has an interval about 200ms.
First challenge I faced was that variable x is an integer so I had to convert it to a string before I can send it to LCD display. By using following code I was able to convert x into a string (i.e.an array of characters).

Converting an integer into an array

Another problem I faced was since x varies from single digit to up to 3 digits the display showed meaningless characters when there are blanks. For example let’s at the beginning x was a 3 digit number. When it changes to a 3 digit number the leftmost digit will turn in to a meaningless character. My solution was to use if statements to split the case into 3 scenarios. So if x is between 0 and 9, 2 zeros will be displayed in front of x, if x is between 10 and 99, a zero will be displayed in front of x, if x is larger than 100 no zeros will be displayed in front of x. you will be able to understand my method clearly.



Writing into LCD Display


Functions associated with servo motor

Control_servo()

Servo motor is used when robot has stopped due to detection of an obstacle and needs to find an alternative path to go. I used a polar coordination system to identify the angle and distance to an obstacle. The following diagram will help you to understand my method.


In this picture r denotes the displacement to the obstacle and theta  denotes the angle from left side horizontal axis. When the sensor facing forward direction value of  theta  must be 90 degrees. But I found that the minimum value for theta was about 20 degrees and maximum was about 150 degrees. Therefore when initializing the servo it was fed with 70 degrees not 90 degrees. Servo library takes the angle difference from it’s current position to move to a new position.

When the robot got a x value which is less than 20cm it stops and main function calls control_servo() function . Control servo() function first moves sensor from 70 degrees to 140 degrees. While doing this it records the distance when angle is 90,110 and 130 degrees. Then again sensor moves from 130 degrees to 0 degrees. Sensor records the distance when angle is 50, 30, 15 and 0 degrees. One important thing to remember is to have a delay when changing angle. Since the actual servo takes some time to move to a new position from current position a delay is required. I have used a delay of 10ms for this. By accurately measuring the angular speed of the servo this time delay can be fine-tuned. Data array is used to record relevant angle and displacement. 



Function to control Servo motor


Now I think it’s ok to explain functionality of turn_robot() function. The purpose of this function is to turn the robot in to a suitable direction based on the values in data array. When turn robot is called, first it calls control_servo() function in order to collect distance and angle measurements. Then it calls sort() function to arrange obtained data from smallest distance value to highest distance value. After this data[6] element will have the highest distance measurement and corresponding angle.70 degrees is subtracted from this angle. If this value is a negative value it means this angle (i.e. the obstacle that is situated furthest from robot) is positioned from left side of the robot. If this value is positive it means this angle (i.e. the obstacle that is situated furthest from robot) is positioned from right side of the robot. Then this angle is used to turn the robot to that direction.
equation 2


According to equation 2  there is a time period which is proportional to a given angle theta. Assuming omega is a constant which is the angular velocity of the robot turning then t can be used to turn the robot. By calculating a time period which corresponds to theta and using that time period as a delay period I was able to achieve this. We only need the magnitude of theta since we already know the direction of the turn. The angular velocity of the vehicle had to be measured experimentally and also this constant value is valid only when the surface that robot moves is uniform. So this method is not very accurate method at the moment but I am planning to implement a control system to keep the speed of the motors at a constant rate. By that we omega value will stay the same. In here I have multiplied turn_time variable by 1000 in order to convert it in to milliseconds.


Function to turn robot 

  Now I have covered all the functions I have constructed to build my program. The main program or loop() doesn’t do much except coordinating the all these functionalities and making robot move forward. Inside loop() it checks  x value .If x is larger than 20cm(or any arbitrary value) robot will move forward and if x is less than that value it will stop robot and call turn_robot() function. After that turn_robot() function will turn the robot in a suitable direction and starts main program from beginning.
Main function loop()

This is my complete program for my robot. Although this program works it still need lots of debugging. There are some unexpected behaviours that need to be fixed.It might take some time and I hope to write my progress on my blog. But I’m glad finally I was able to make a working prototype of my robot. It may sound funny but building this robot was like raising a child for me. You need to be both knowledgeable and passionate at what you are doing. Sometimes you get frustrated when things are not going well or not giving the desired output but you won’t give up until you are satisfied. You will realised even the simplest things in life like going on a straight line is not simple as it seems for somebody as simple as a robot. It takes lot of time and patience to achieve what you want but at the end of the day you can see that little creature is actually wondering in your room and this will make you feel you achieved what you deserve.

I think if you read these articles it might be helpful to you in your own projects. I have posted a link to the source code at the end of this article. Please feel free to download it and use it if you need.
























Programming the robot -1(aka giving life to little Franky )





I was hoping to write about this earlier but due to many reasons I missed it and finally I got a chance to sit down continue on my post. In previous article I discussed how to connect a LCD display to Arduino board through a shift register. (74HC595N). I decided to have an LCD display in my robot for several reasons.
  •    It’s very useful to know the readings that robot is taking during testing.
  •    I can’t access serial monitor when my robot is not connected to PC. I  have to use a USB cable and it limits the robot’s movements.
  •   It’s cool to have an extra gadget on my robot. It makes it more interactive.

So with the implementation of LCD display the robot consists of 4 main sections.
  •    Motors and the IC that controls motors.
  •    LCD display and shift register.
  •    Distance sensor
  •    Servo motor

In order to control all these sections I had to write a program that controls each of this section. I have talked about the motor controls in details in a previous post and the basics of implementing the LCD display and Distance sensor were discussed in last post. Therefore I would like to talk about the rest of my program in details in upcoming posts.
In this version the robot was expected to go along a path until it detects an obstacle from a certain distance. The robot then stops and starts to scan the surrounding area using the detector attached to a servo motor. Servo motor turns the detector to left and right while the detector records 7 measurements (distance to a particular obstacle and the direction i.e. angle to it with respect to the initial position of the detector. ) then it’s chooses the most suitable direction to go (direction which the distance to an obstacle is maximum.).It may seems like an easy thing to do but implementing it was indeed a difficult task.
Since this is going to be a bit lengthy than a usual post I would like to split this into small sections where I explain the functions that I implemented in order to control my robot. Here is a list of functions that I have used in program.

Functions associated with movements of robot

  •   Go_right ()
  •    Go_left ()
  •    Go_backward()
  •    Go_forward()
  •     robot_stop()
  •     turn_robot()


Functions associated with distance sensor
  •  measure distance()
  •  sort()

Functions associated with LCD
  •  write_LCD()
d     Functions associated with servo motor
  •        control_servo()

            Then there are setup () and main () functions that are being used to initialise and run program. 
      
      Including required libraries and declaring variables 
             
Header files used in program
 In this version of robot I used timer 2 in AVR micro controller since timer 0 is allocated to delay () function and timer1 is allocated to servo motor. MsTimer2.h header file gives access to use timer 2. Servo.h is used in servo motor. SPI.h and LiquidCrystal.h are used in LCD display. SPI.h is the header file which is used in serial communication tasks.by using it we can use a modified version of LiquidCrystal.h file in programs.

       
     

variables used in program

     x is the variable that is being used to store the distance measurements by distance sensor. It updates value of x every 100ms or any other given time period using timer2 interrupts. It is declared as volatile since x gets updated outside of the program. Therefore it indicates to the program that value of x can be changed anytime.

direc is variable type that is constructed exclusively for this program using structures in C. structures allows programmer to construct user-defined data types that can be used to store various types of data. In here my requirement was to have a data type which is capable of storing both angle and distance to an obstacle from robot position. In other words I wanted to use polar coordinates to detect obstacles. My initial idea was to use two different arrays to store the angle and the distance separately but it didn’t sound good because these two parameters are actually related to each other. Therefore I decided to use a user-defined data type to store these two parameters. After constructing the data type you can use it to declare variables, just as you declare an integer or any other default data types.  

Structure used in program as a user-defined data type


          In here I have declared an array called data which has 7 elements in it. Each element can store both angle and direction since their data type is direc. Rest of the variables are conventional variables that are being used to store various parameters used by program.

The next step was to initialize the setup() function. Setup() function is used to assign pins in Arduino board to various inputs or outputs that are used in program. pinMode() function is used to assign an Arduino GPIO to an input (ex: echopin which is used to measure reflected ultra sound wave) or to an output (ex: trigpin which is used to initiate an ultra sound wave) . myservo.attach () does the same.In here myservo is an object that is declared as a Servo.
      New thing in setup () is the way that timer interrupt has been set up. Previously I was able to setup a timer interrupt from scratch but this time I used a function that was built by Arduino community to setup a timer interrupt. It made my life so easy and all I had to do was to give a value to the timer interrupt period and an ISR to be called when timer overflows. Flash() is the ISR and inside flash() I have called measure_distance() function. Therefore when ISR is called by timer interrupt every 100ms, it will call measure_distance() that will measure the distance to an obstacle. MsTimer2.h header file is responsible for handling timer 2. You can use this link to learn more about this.  
      
     
Setup() function

      Lcd_home() is used to initiate the lad display by clearing up the display and positioning the cursor on left upper corner.


Myservo.write (ini_angle) is used to make sure that sensor is facing forward direction when robot is turned on. The ini_angle varible value could be any value but my case it was around 70 degrees.
Now we’ll look at the functions I have used to in my program.    

Functions associated with robot movements

These functions will depend on the type of robot you are going to build. In my case it was a robot with wheels therefore it is expected that it should be able to move forward, turn left or right and backward. There are 4 connectors that need to be energised in order to rotate the motors. So I had to play with my robot a bit to identify what combination of these will make my robot go forward, backward, turn left and right. It’s something I had to do with trial and error. The most important thing to remember is to never set all motor connectors to high state since it will destroy the H bridge circuit in L293D IC.




functions that control movements of robots


     I’m not going to explain turn_robot() function here since it requires some other functions that yet to be explained. So I will present this function later in this post.

Functions associated with distance sensor

Measure_distance() is the function that measure the distance to an obstacle and store it in variable in every 100ms. It’s one of the most critical functions. It generates an ultrasound wave and listen to it’s reflection. Then it measures time delay between sending the signal and receiving it back. This value is then used to calculate x value. 
 

duration is the time delay measured and diving it by 58.2 this value is converted to a distance is cm.The speed of sound is 340 m/s or 29.1 microseconds per cm. duration is the time for wave to return to the sensor after reflection. Therefore duration value is halved when calculating distance. Since x is a global variable any other function can access this x value.
Function to measure displacement



Sort() function is used to arrange collected distance and angle data from smallest value to largest value. It takes the measured values that are stored in array called data and compare an element with it’s previous value. If the previous value is higher than the chosen element it will copy the previous value to another allocated memory place temporally. Then it moves the selected element to the position of previous element .Then copies the values in temporary memory into the next element. This process is done until all the values have been compared with it’s adjacent element. The following chart will explain it better.
The technique that I used in here is called nested for loop. It means a for loop inside another for loop. These types of loops are very useful when you are trying to manipulate things like 2dimentional arrays or matrices. In this case the inner most loop is the loop responsible of carrying out the comparison and copying elements. Outer most for loop controls the iterations occurred therefore the inner most loop.


Flow chart for sorting algorithm


Function used to arrange data in ascending order

I hope to explain the rest of the function from my next post.




























Thursday, December 17, 2015

Control LCD display using shift registers (74HC595N)

This post is pretty much a continuation of my post using shift registers in Arduino projects .Please have a look at it first if you haven’t read it since I assume you are already familiar with how shift registers work and how to use them in a project. Therefore I'm not going to explain how the shift register chip works in this post. As you might already know I was trying to build a robot during my last summer vacation. Unfortunately I had to postpone it  due to lack of technical knowledge and lack of time to learn them .but I'm having a long summer break after another successful year at university and hopefully this time I think I’ll be able to finish what I started. This project is also a side project of that project. My goal was to build an obstacle avoiding robot using Arduino platform. I wanted to use a LCD display to display the distance to an obstacle in real time since it helps a lot in debugging when your Arduino is not connected to the computer and you don’t have access to the serial input readings. But one major problem with that was the number of I/O pins the display required in order to do that. An LCD display wanted at least 6 I/O pins. I had other components like a servo motor (1 data pin) ultrasound distance (2 data pins) measuring unit and my motor controlling unit (4 data pins)  and I couldn't use 0th pin of Arduino board since it deals with the communications of the board . So I ran out of pins. Then this 74HC595N shift register IC came for the rescue. The advantage of using shift register was connecting LCD to Arduino through shift register cost me only 3 pins. That was a huge advantage when it comes to working with micro controllers. However it wasn’t straight forward since the Arduino LiquidCrystal library is not compatible with using shift registers. So I had to find a way to go through it. Fortunately I was able to find this article about how to achieve this.  This is done by using a technology called Serial Peripheral Interface (SPI) which uses a synchronous serial data protocol to communicate with 74HC595 IC. In here Arduino micro controller acts as the master device and shift register acts as the slave device. LCD display is connected to the outputs of the Shift register IC. Then SPI.h and a modified version of conventional LiquidCrystal.h header files can be used to write programs to use LCD display.

The following schematic shows the connection of the components and the connection required are listed below. You should keep in mind to use only compatible LCD displays (Such as Hitachi HD44780) with the LiquidCrystal.h header file.


                      IC Pins (1-8)
                  LCD Display pins
1(Q1)
4(RS)
2
-
3
6 (E)
4-7
11-14
8
GND


LCD Display  Pin
Connection
1
GND
2
+5v
3
10K trimpot variable leg
5
GND
7-10
-
15
+5V through 220 ohms resistor
16
GND

IC pins 9-16
Arduino I/O pins
9
-
10
+5V
11(Sh_CP/SPI clock signal)
13
12(ST_CP/Latch Pin)
9
13
GND
14 (DS/Serial Data input)
11
15
-
16
+5V

Remember to connect the fixed legs of the trimpot (Trimmer/variable potentiometer) to +5V and GND.
The following image is a schematic of the circuit.
Image retrieved from http://42bots.com

After connecting all the components We can replace the old LiqudCrystal.h file with new header file which supports use of shift register. Please go through the following steps to setup the necessary files.
  1. Download this new version of the LiquidCrystal.h from here.
  2. Close Arduino IDE if you are currently using it.
  3. Find the directory where the library folder is located. It should be inside the directory where you install Arduino IDE.
  4. Replace the older version of header file with the newer one.( keep of copy of the older one as a backup )
  5. Open Arduino IDE and Go to Files à Examples à LiquidCrystal and select Hello World SPI.
. If you can see an Arduino sketch it means the new SPI supporting header file has been recognised by the IDE and you are ready to go. Just connect your Arduino board and upload the sketch to board and run it. If you can see the output “Hello world” on your LCD all good (you can replace this to anything you like in the sketch). If it’s not working please check your connections first. Most people (including me) sometimes make wrong connections that causes malfunction or not working at all. Sometimes you might see some random characters on screen . Press reset button few times to get of this and run your code. Now you can use your LCD with Arduino just using 3 pins and saving 3 more precious pins for other components.


Please go to following links since those web pages have lots of useful details about this.

If you need my sketch you can have it from here.










Sunday, February 22, 2015

Using shift registers in Arduino projects

If  you are using an Arduino board(like Uno) you get about 12 digital pins for your projects .this number is fairly enough if your  project is a simple one that won’t consume no more than few pins but as the complexity of your projects increase soon you will run out of pins. There are few solutions for this.
  • You can buy a board like mega and expand your number of digital I/O pins.
  • You can use multiplexing/ demultiplexing chips to read and write to pins.
  • You can use shift register chips to expand the I/O pins.

It’s obvious that the first solution shouldn't be your first choice since it will cost you few bucks and it’s probably is not the best solution as well. Eventually you will run out the pins if your project needs more than 54 digital I/O pins .So keep that option ,optional!!!.

Today I’m going to discuss about the 3rd solution I mentioned. I will discuss the 2nd (mux and demux) solution in future when I get a chance. Shift registers are used to expand the I/O capabilities in an electronic circuit. In Arduino domain using only 3 pins of the board and a single chip you will be able to control up to 8 outputs. And by cascading the shift registers you will be able to control thousands of outputs only using 3 arduino pins. In order to do this I have used 74HC595N chip which has 8 outputs. For this instance I used 3 595 chips to control 24 LEDs.

Figure1 74HC595 chip


Figure2-Pin configuration














Q0-Q7   are the output pins that connected to LEDs anode.74HC595 is capable of sourcing current to               LEDs  but there are different chips that use sinking current(current is drawn into the chip)                  method to drive LED. So make sure you check the data sheet if you are not using this chip.

VCC/GND   +5v supply and ground.

DS   serial data input to the chip. This pin is connected to one of the digital output pins in Arduino              and if you cascade several of them, you have to connect the DS pin of the second chip to the                Q7’ pin of the first chip.

OE      output enable .the horizontal piece of line indicates that it’s active low. That means you                      have to make the pin low in order to make the output enabled. So connect that to the                           ground to make that pin low .

ST_CP   storage register clock input .this pin is also called latch pin since it’s the pin that is used to                  transfer the data stored in the chip to the output pins. The value loaded into the chip won’t                    get pass through unless this pin gets a LOW to HIGH transition.

SH_CP  shift register clock input. This pin is used to insert the serial data into the chip register.                         When the pin’s state gets a transition from LOW to HIGH it reads the value of the DS pin                  and sends the value to register.


MR         Master reset.(active low )this pin can reset the whole chip when activated. The values                         stored in the chip will be erased .So connect this pin to +5v supply to avoid resetting the                       chip.

Q7’         This pin is used to cascade several chips together and further expand the outputs.
               Please read the data sheet I provide carefully to understand the functionality and the                            autonomy of the chip better.   And also I have add some links to some youtube videos  that I               referred in order to learn about shift registers. I highly recommend you to watch them to get                 more understanding how this chip works.

Writing the program

There is a function called shiftOut() defined in Arduino to use in shift registers but I will present you another way of implementing the functionality and later I’ll give the code I wrote using shiftOut() function. As a first instance we’ll look how to implement a single shift register.  Use the above diagram to construct the circuit. If you want you may avoid the 1uF capacitor ,it is used to remove the flickering .

Figure3-Circuit Diagram 
















Now we’ll look at the code. I have attached the source file at the end of the post. So you  may have a  look at it or you can use it in your project.

Figure4-Initializing code












Initialising is done as usual in first place. In there I have assigned pins 8,9 and 10 to the serial data pin, clock pin and latch pin of the chip. And also I created an array consists of 24 elements in order to store the status of each LED. It’s type is Boolean ,therefore I can store a HIGH or  LOW  value in each element. time_const  is used to control the speed of the LED on and off. Writereg()  is a function which defined to shift the data into the chip.


Figure5-Writereg() function














At the beginning of the function the latch pin is set to low and at the end (when the data has been transferred to the chip) it is set to high. In that way we can give a LOW to HIGH transition and data has been sent to output pins. As I mentioned  above the clock pin is used to distinguish between data bits .First the clock pin set to low then the data bit is sent to a storage register in the chip .and again clock pin is set to high and this transition stores the bit in storage register this happens in all 3 chips. The first 8 bits stored in the chip which connected directly to the Arduino. When we moved the next  byte to the first chip the previous byte get shifted to the next shift register .Like that we can shift any amount of bytes as long as we have enough chips and the first byte that shifted will be stored in the last shift register that cascaded.  

Using shiftout() function in sketches 


Arduino community has provided a built in function to handle shift functions easily.

Syntax

Shiftout(Data pin,clock pin,bitorder,value)

Data pin -  serial data input  pin of the chip is assigned to this pin.
Clock pin – SHCP pin of the chip is assigned to the this pin.
Bitorder- For this you can assign two values. They are MSBFRIST or MSBLAST .

MSBFIRST 

setup the least significant bit of the value you pass to Q0 pin. For example if you send value 6       (110 in binary) to the shift register, it will be represented as follows,

Q0 – 0
Q1 – 1
Q2 –  1 

LSBFIRST 

This is the opposite of MSBFIRST ,it will assign the LSB bit to Q7 pin and  MSB bit to Q0.

 Most of the time we are only going to use MSBFIRST since it’s much convenient .So if something is not displayed as you wish when you are executing the code try replace MSB with LSB or LSB to MSB that might solve the problem. There is a tutorial in Arduino site that explains this function in more details. Please read that as well.
Shift registers are very useful way to expand the I/O capabilities of your microcontroller. I found about this technique when I was looking for a way to control a LCD display by Arduino without compromising 6 pins. I haven’t tried it yet but I hope to write another about that in some other time. Please use the links I provide below to get to know more about shift registers.

Links


following links are few tutorials I referred in order to learn Shift registers.