Knowledge Base > General Gyaan >
Tutorials
ADC on the ATMEGA
ADC stands for Analog to Digital Converter. What do we need it for ? Well a lot of sensors that are used in Electronics(and Robotics) give output voltages in the form of potential differences. Doesn't make sense ? Simply speaking, a sensor will give out its readings in the form of voltages. So what do we do with it ?? Well, we convert it to a number which will help us determine the actual implications of that reading. We fix a maximum reading as the reference number (255 in our case,since we will be ignoring the last 2 bits) and calculate the corresponding value of our reading on the new scale. So, moving on, the ADC feature is available on PORTA of the ATMEGA16/32. Features :1. The reference (maximum) value can be taken from the AREF pin or an internal reference level of 2.56V is provided which can be accessed by the software. The AVCC may also be used as AREF by simply decoupling it(connecting to ground through a capacitor).2. 10-bit is available. This means that you can distinguish between two readings which have a difference of (Reference Value/210) . This means that the max value is broken up into 210-1 = 1023 parts and if you have a reference of say 5V, you can distinguish between readings 4.88mV apart (yeah, that's right !!) 3. The ADC can be used in free running mode(which means it will keep on converting continuously) or single conversion mode. 4. An interrupt may be generated once a conversion is complete, so that the MCU need not keep on checking for completion of conversion. 5. There is a ADC Noise Cancelling mode, which allows the user to switch off the other digital circuitry which might affect the conversion. 6. Since the result is 10 bit, the result is stored in 2 registers : ADCH and ADCL. If the ADLAR bit is not set, the result is right aligned. In that case, the 2 MSBs of the result are the 2 LSBs of the ADCH register and the remaining 8 LSBs of the result are in the ADCL. In this case, it is necessary to read the ADCL first and the ADCH second, only then will the ADC registers be updated with the next result. 7. Accuracy is best between 50 and 200 Khz clock frequency. Running at 16 Mhz,we select the prescaler as 128, which gives a clock frequency of 8/128, which is 125 Khz. Code :Now, we set up the registers.ADC RegistersNext, we write the functions to initialise ADC and call a conversion.ADC CodeResources :1. ATMEGA16 Datasheet Pages 204 - 2212. ADC Tutorial on AVRFreaks 3. Sample code 4. Registers Contributed by : Ankit Daftery ankitdaf [at] gmail [dot] com |
Ball detection using Matlab
BALL DETECTION USING MATLAB Category: IMAGE PROCESSING Description: Detecting a ball involves image processing. The best way to do so can be writing your algorithms on MATLAB or openCV, where we can load our image on the data base and do required math’s on the image. This project involves detecting a ball in real time and continuously noting the ball coordinates. The coordinates obtained can be used to control motors to follow the ball (ball follower) or to control your camera to move along its 2 axis with the moving ball. Thus the input to the algorithm is image and output is x and y coordinates of the ball. Requirements: MATLAB, WEBCAM. Coding: The code is written in MATLAB. To understand the code one must go through GETTING STARTED of matlab help. CODE: imaqhwinfo info = imaqhwinfo('winvideo') dev_info = imaqhwinfo('winvideo',1) vid = videoinput('winvideo'); set(vid,'TriggerRepeat',Inf); vid.FrameGrabInterval = 1; vid.FramesPerTrigger=20; figure; % Ensure smooth display set(gcf,'doublebuffer','on'); start(vid) while(vid.FramesAcquired<=1000) I = getdata(vid,1); fR=I(:,:,1); MY=fR >180; MY = bwareaopen(MY,5); se = strel('disk',4); MY = imclose(MY,se); MY = imfill(MY,'holes'); J=rgb2hsi(I); H=J(:,:,1); MY1=H < 0.5; F=MY & MY1; F = bwareaopen(F,5); se = strel('disk',4); F = imclose(F,se); F = imfill(F,'holes'); imshow(F) [B,L] = bwboundaries(F,'noholes'); s = regionprops(L, 'centroid'); cor = cat(1, s.Centroid); disp(cor); %pause(0.05); flushdata(vid); end stop(vid) Author: ANIKET .A . TATIPAMULA Mobile : 9969982534. Video links: http://www.youtube.com/watch?v=_FIU2rLs2mA |
Fuse Bits : Changing your MCU speed and JTAG
Interfacing a PS/2 keyboard to the ATMEGA16
There are a lot of devices which would be great if we could use them to communicate with a micro-controller and a keyboard is one of them. Adding a keyboard interface opens up a whole world of varying your input to the MCU and controlling it. A lot many tutorials about this are already available on the internet, but I found that patching ready made code to your MCU is most often problematic. Its best to understand the protocol and write code yourself. THE PS/2 PROTOCOL : This is how a male PS/2 connector (on the keyboard) looks like : 1 - Data 2 - Not Implemented 3 - Ground 4 - Vcc (+5V) 5 - Clock 6 - Not Implemented Communication : Each key press on the keyboard corresponds to a fixed hex code which is communicated by the keyboard controller to the MCU. This code is known as the scan code. This is followed by a "break code", which indicates that the key was released and consists of two "words". The first "word" is the same for all keys (generally F0), and the second "word" is generally the scan code repeated again. Now let's deal with only communication from the keyboard to the MCU. The data format is as below : 1 start bit 8 data bits, least significant bit first 1 parity bit (odd parity) 1 stop bit (always 1) One word therefore consists of 11 bits, and three words make a package. One package corresponds to one key press. Timing : The data and clock lines are open-collector. They are always high in the idle state. The keyboard pulls the clock line low and generates a clock signal to begin sending data on the data line, when a key is pressed. Note that the keyboard won't send any data if the clock line has been held low by the micro-controller, even if a key is pressed. ![]() The Interface : Data acquisition Data acquisition can be done in different ways, including SPI , or by continuously polling the data and clock lines to see when they go low etc. However, shall be using the interrupt method here. The clock signal generated by the keyboard is fed to the INT2 line of the ATMEGA16. The reason for selecting INT2 is that it is an edge triggered interrupt and can be used to detect a rising and falling edge asynchronously i.e. independent of the MCU clock. The data line is sampled at every interrupt trigger and the needed bits are stored and shifted to obtain the scan code.Since we already know the data packet format, we can safely afford to neglect the remaining bits. Here, we shall not be reading the break codes. However, they may be used if special functionality is needed. Code :Click here to view the Keyboard Data Acquisition CodeThis code is very basic and will help you obtain the key scan codes. You can further add the look-up tables for these scan codes to identify the keys pressed. You could also try out key combinations and implement extra functions, password features etc. Issues : Reliability issue : The above code works just fine. One scan code can be detected additionally as well. However, if code to read the two scan codes that follow is added, all the data i.e. all three words get messed up. Reason yet to be detected and fixed. References and additional reading : 1. Science Prog website 2. ComputerEngineering.org 3. Interrupt based Code Images courtesy computerengineering.org P.S : Code will be improved and added soon. Keep visiting !! :D Contributed by: Ankit Daftery ankitdaf [at] gmail [dot] com |
Exernal Interrupts on the ATMEGA
So, now you know how to use the ADC and the UART features present on the ATMEGA. The ATMEGA16/32 has one more feature of great importance to us : external interrupts.Click here to read a brief introduction on Interrupts Okay, now why are they of importance to us ? A lot of stuff generates signals in the form of voltages or voltage changes to indicate decided events. For example, a device might have one line which goes low for a few clock cycles and then high again to indicate that it has completed its task.We can therefore use this line as an external interrupt line to schedule further tasks. The ATMEGA16/32 has 3 external interrupt lines : INTO,INT1 and INT2, on pins PD2,PD3 and PB2. Interrupts on INT0 and INT1 can be 1. level-triggered(meaning that the interrupt is triggered when the signal goes low i.e. 0V for some time OR 2. edge-triggered(meaning that the interrupt is triggered when the signal changes from high to low or low to high) ====> INT2 can only be used as an edge-triggered interrupt. Setting up the interrupts :: Control Registers MCUCR : MCU Control Register ![]() Bits 3,2,1,0 are the ones which are of importance to us. Bits 3,2 are used for sensing an external interrupt on line INT1. Bits 1,0 are used for sensing an external interrupt on line INT0. The table for setting up these bits is as follows : ![]() The table for INT0 is similar to the one above. It is to be noted that if an edge triggered interrupt is selected, the edge (change) must last for at least one cycle for it to be detected. Similarly, if a low level triggered interrupt is selected, the low signal level must be held till the instruction being executed currently by the MCU is completed. MCUCSR : MCU Control and Status Register ![]() Bit 6 is the only one of importance here, and controls the INT2 line. If this bit is set to 1, a rising edge generates an interrupt and if it is set to 0, a falling edge generates an interrupt. The pulses here also must be longer than one clock cycle. Also, the ISC2 bit must be set following a specific method,since an interrupt can occur even while changing the ISC2 bit. The procedure is something like this : 1.Disable INT2 by clearing its Interrupt Enable bit in the GICR Register. 2.The ISC2 bit can be changed. 3.The INT2 Interrupt Flag should be cleared by writing a logical one to its Interrupt Flag bit (INTF2) in the GIFR Register before the interrupt is re-enabled. GICR : General Interrupt Control Register ![]() Bit 7,6,5 enable the INT1, INT0 and INT2 lines respectively if set to one. GIFR : General Interrupt Flag Register ![]() Bit 7,6,5 manage the status of the Interrupt requests. The flag is set for each of these when the respective line is triggered, and cleared when the corresponding interrupt service routine is executed.Alternatively, we can clear the flags manually by writing it to 1.Click here to view Sample Code to setup the interrupts <---------------------------------------------------------------------------------------------> Resources : 1. ATMEGA 16 Datasheet 2. Introduction to interrupts 3. Sample Code Contributed by : Ankit Daftery ankitdaf [at] gmail [dot] com |
Interfacing a 16 X 2 LCD to your ATMEGA
Often, when you are working with micro-controllers, you might feel the need to see what conditions are being executed or what input the micro-controllers are taking. For that, you can always use LEDs, but then LEDs are a very clumsy and confusing way of going about it. So, what should you use that shows me what's going on ?? An LCD, of course !! Here's how. 1. Read the datasheet of your LCD. 2. Understand your LCD. 3. Write the code. 4. Burn the code. 5. Make the connections and voila !! For the purpose of modularizing work ( and for fear of this post becoming too long and boring), I have posted the detailed discussions section-wise as text files. All links are at the bottom of the post. Step 1 : Requirements : I am using a HITACHI JHD162A LCD Display, with a HD44780 LCD Controller, which comes for roundabout Rs. 110. The datasheet of the controller is much more important than that of the module, since its the controller which is going to take in input and print the screen. You need not bother with the datasheet of the LCD itself. Of course, you will also need a micro-controller with at least 11 usable pins and lots of connectors. Step 2: Understand your LCD : Read the datasheet.HD44780 LCD Datasheet Explained Step 3: Write the code: Easier said than done, eh ? Well, do the next best thing. Find code on the internet, understand it and tweak it, based on your configuration. I read Bibin John's code and modified it a bit. I have also been recommended Peter Fleury's library as being easy to use, but I haven't gone through it as yet.JHD162A LCD Code I have used the delay function provided by WinAVR in my code, since Bibin has written his own delay loop in assembly language and it was giving me faulty delays,making the wait too long. Step 4: Burn the code: The easiest part by far. Just make sure your code is syntactically and logically correct ( you need to know the datasheet well for that) and burn it using WinAVR. Step 5: Connect : Quite an important step. Even if the code is correct, your screen will display junk at the most and black boxes usually if the connections are improper. Here's the checklist. Here's a picture of the output I get : Shortcomings,problems, general precautions etc There are lots of things that can go wrong, implying there are lots of things you must be careful about.LCD Interfacing Checklist Problems :ProblemsHappy Printing !! P.S. Many thanks to Shashank S. for his help. --------------------------------------------------------------------------------------------- Links : 1. Datasheets : a. HITACHI JHD162A LCD Display b. HD44780 LCD Controller (Courtesy : Sparkfun) 2. Reading : a. Bibin John's Books b. Robotics India c. AVR-Beginners d. Meteosat's Tutorial 3. Files : a. Datasheet summary b. Code c. Checklist d. Problems e. Peter Fleury's library Contributed by : Ankit Daftery ankitdaf [at] gmail [dot] com |
Making your own AVR ATMEGA programmer
SPI : Serial Peripheral Interface
The serial peripheral interface provided in the ATMEGA16/32 allows a high-speed synchronous data communication channel with other devices.The relevant pins on the ATMEGA are : 1. MOSI : Master Out,Slave In : Pin B,5 This line is used by the master to send out data to the slave.The Master always initiates any communication. 2. MISO : Master In,Slave Out : Pin B,6 This line is used by the slave to send data to the master. 3. SCK : Serial Clock : Pin B,7 This is the serial clock generator. Communication takes place only when the clock is working.The clock starts a cycle when the master initiates communication. 4. (~SS): Slave Select : Pin B,4 The slave will respond only if the Slave Select line is pulled low.If not pulled low,the chip will not read data even if keeps on receiving clock pulses.The Master pulls the Slave select line high again at the end of the data transfer to synchronise the slave. Connections :Master ------------------------------------------> SlaveMOSI ------------------------------------------> MOSI SCK ------------------------------------------> SCK ~SS -------------------------------------------> ~SS MISO <------------------------------------------ MISO Data Flow :The SPI supports a full duplex operation, which means communication can take place both ways simultaneously, i.e. data can be sent on one line and received on another line simultaneously.When two-way communication is desired, it is best to follow the following method. 1. Write Data to the SPDR (SPI Data Register) 2. Wait till the transmission is complete. You can do this either by polling a flag or by using interrupts. 3. Read the SPSR (SPI Status Register) and then the SPDR immediately after that, in that order, if you are using the polling method. Just reading the SPDR is enough if you are using the interrupt example.This will prevent any accidental loss of data. This can be done safely even with the slave, since the data which has been queued up in the SPDR will not be transmitted unless the Master initializes communication. However, iteration-based loops cannot be used in the case of the slave to send data, since it is unsure when the Master will initiate communication and so the data would keep on updating in the SPDR without being sent. It is thus advisable to use the interrupt method in case a transmission by the slave is desired. Modes of Operation :Click here to view the SPI Modes of operationControl registers :![]() Bit 7 – SPIE : SPI Interrupt Enable This bit causes the SPI interrupt to be executed if SPIF bit in the SPSR Register is set and if the global interrupt is enabled. Bit 6 – SPE : SPI Enable 1 ----> SPI Enabled 0 ----> SPI Disabled Bit 5 – DORD : Data Order If DORD = 1 , the LSB of the data word is transmitted first. If DORD = 0 , the MSB of the data word is transmitted first. Bit 4 – MSTR : Master/Slave Select MSTR = 0 ----> Slave Mode MSTR = 1 ----> Master Mode If SS is configured as an input and is driven low while MSTR is set, MSTR will be cleared, and SPIF in SPSR will become set. MSTR will then have to be set again manually to re-enable SPI Master mode. Bit 3 – CPOL : Clock Polarity CPOL = 1 ----> SCK is high when idle CPOL = 0 ----> SCK is low when idle ![]() Bit 2 – CPHA : Clock Phase The settings of the Clock Phase bit (CPHA) determine if data is sampled on the leading (first) or trailing (last) edge of SCK. ![]() Bits 1, 0 – SPR1, SPR0 : SPI Clock Rate Select 1 and 0 These control the SCK rate of the Master device and have no effect on the Slave. The relationship between SCK and the Oscillator Clock frequency (fosc) is shown in the following table: ![]() Status Register :![]() Bit 7 – SPIF : SPI Interrupt Flag This flag is set when a serial transfer is complete. An interrupt is generated if SPIE in SPCR is set and global interrupts are enabled. If ~SS is an input and is driven low when the SPI is in Master mode, this will also set the SPIF Flag. SPIF is cleared by hardware when executing the corresponding interrupt routine or it can be manually cleared by first reading the SPI Status Register with SPIF set, then accessing the SPI Data Register (SPDR). Bit 6 – WCOL : Write COLlision Flag The WCOL bit is set if the SPI Data Register (SPDR) is written during a data transfer. The WCOL bit (and the SPIF bit) are cleared by first reading the SPI Status Register with WCOL set, and then accessing the SPI Data Register. Bit 5..1 – Res : Reserved Bits Bit 0 – SPI2X : Double SPI Speed Bit When this bit is written to one the SPI speed (SCK Frequency) will be doubled when the SPI is in Master mode . This means that the minimum SCK period will be two CPU clock periods, as opposed to the minimum of 4 in normal mode. When the SPI is configured as Slave, the SPI is only guaranteed to work at fosc/4 or lower. The SPI interface on the ATmega16 is also used for program memory and EEPROM download- ing or uploading. Sample code:Click here to view sample SPI CodeThe code to setup the slave is pretty simple and can be found in the ATMEGA16 Datasheet on Page No. 139Resources :1. ATMEGA16 Datasheet2. Modes of Operation 3. Sample Code Contributed by : Ankit Daftery ankitdaf [at] gmail [dot] com |
UART : Making your own Module
If you are done with UART between two micro-controllers, I am sure you would like to move on and try and communicate with a computer. Communication with the serial port of a computer, however is not so straight-forward, since the logic system of the serial communication line differs from that of the micro-controller. The difference is basically in voltage levels. RS-232 is a method for porting the micro-controller logic to serial port logic. Read up on the background of RS-232 for understanding properly. So, for this, you need a module which will connect the micro-controller and the PC and regulate data communication.A Max-232 chip is the one which converts the logic levels. Lots of circuits are available for it on the internet. You just need to run an image search for "max 232 circuit" or "rs 232" or similar.Here's the image: ![]() For making this module, use the following : 1. Right-angled DB9 female connector 2. A millimeter board made especially for the above connector 3. A Max-232 chip and mount 4. Miscellaneous connectors and wires. All the above are easily available in the market. Try to use them for convenience,especially the first two. Here's how my finished module looks like : Note the two holes on the board and the wire coming out. I purposely looped the wire once like this, because I have seen soldered connections break off due to pulling while use. The loop and the tight wires help to prevent that. Also, try to keep the wire a bit long, so it is convenient to connect it with your MCU. Well,this is all you need.
Contributed by : Ankit Daftery ankitdaf [at] gmail [dot] com |
1-10 of 21