Home
now
Contents
1. 3 2 AVR Architecture A schematic of the AVR architecture is shown in figure 3 1 The 32 General Purpose Registers R1 to R31 8 bit wide are also called the Register File Data is moved be tween the Registers and the memory Addressing memory locations above 255 is done by combining two 8bit registers to form a 16 bit register R26 and R27 combined is the X register R28 with R29 is the Y register and R30 with R31 is the Z register Different types of addressing modes are defined for transferring data between the Registers and the memory locations mostly the SRAM In the AVR data memory space figure 3 2 locations 0 to 31 0x1F are occupied by the Register File Generally the assembler refers to them by names R1 to R31 not by the adresses Location 0x20 to Ox5F 32 to 95 are occupied by the Special Function Registers SFR like the Status Register the Stack Pointer and the control status registers of the peripherals The Special Function Registers can also be accessed using the I O address space ranging from 0 to Ox3F using IN and OUT insructions Some of the special function registers are shown in figure 3 3 b refer to the Atmega32 data sheet for a complete list Use the address given inside the parantheses to access them as memory locations CHAPTER 3 CODING IN ASSEMBLY LANGUAGE 32 The first Register is SREG the status register that holds the flags resulting from the last executed arithmetic or logical instruction There are seve
2. 11 31 DDRD DDD7 pops opps DDD4 DDD2 DDDi DoDo PIND4 P2 PD PNDO 10 30 PIND PIND7 PIND6 Figure 3 3 AVR Special Function Registers CHAPTER 3 CODING IN ASSEMBLY LANGUAGE 34 MOV R2 R5 content of R5 is copied to R2 ADD R1 R2 r1 r2 stored to ri 3 4 3 I O Direct These type of instructions are to transfer data between the Registers r1 to r31 and the Special Function Registers that can also be accessed as I O ports The following example demonstrates this At this point we are writing a complete example program io direct s Section text denotes code section global main main clr ri inc r R1 now contains 1 out 0x17 r1 using I O address DDRB and out 0x18 r1 PORTB LED should glow end Executing this program should switch ON the LED connected to the LSB of Port B Modify the program to remove the INC instruction assemble and upload it again the LED should go off 3 4 4 Immediate In this mode data to be transferred from to any of the Registers is part of the instruction itself Registers below r16 cannot be used under this mode immed s demonstrate Load Immediate mode Section text denotes code section global main main ldi ri6 255 load ri6 with 255 out 0x17 r16 Display content of R16 out 0x18 ri6 using LEDs on port B end Assembling and running immed s listed above makes all port B bits HIGH can be viewed using the LED boa
3. CHAPTER 2 GETTING STARTED 26 2 6 4 Controlling the uC from Python This section demonstrates a simple method to read write the Input Output ports and other registers of the micro controller from the PC using Python A program called pymicro c runs on the micro controller It listens over the serial port for two commands READB or WRITEB The first one should be followed by the address of the register to be read The WRITE command is followed by the register address and the data to be written On the PC side pymicro py handles the communication to the micro controller It defines class named atm32 that contains the communication routines The example program listed below demonstrates a blinking LED code in Python import time from pymicro import u atm32 while 1 u outb PORTB 1 time sleep 0 5 u outb PORTB 0 time sleep 0 5 To run this program compile and upload pymicro c remove the PCRST jumper and then run blink py It is very easy to implement some programs for example a stepper motor controller in Python using this method 2 7 Motor Control H bridge The H bridge accessory is useful for controlling DC and stepper motors The circuit schematic is shown in figure2 5 One can use the pymicro c program to test the H bridge After uploading pymicro you can control the motor control outputs from Python interpreter For example connect the board to port A and a DC motor with series resistor for current limiting b
4. Choosing File gt Open from the menubar will display all the C files inside the microhope directory You can open any of the examples do not modify the files starting with mh compile assemble and upload from the IDE We will start by programming the digital Input Output ports of Atmega32 and them proceed to the peripheral devices 2 1 Testing the Hardware Connect MicroHOPE hardware to a USB port and start the microHOPE IDE from the menu Click on Detect MH to get a popup menu of the available USB to Serial devices It will contain entries like dev ttyACMO dev tty ACM etc If you are running expEYES find out the device descriptor used by it from the expEYES GUI titlebar and avoid using the same Using File gt Open from the menubar load blink c from the microhope directory Compile and Upload the program by clicking on the menubar In case of error check the USB connections first If problem persists try pressing and releasing the microHOPE resent button at the same time when you click on Upload Make sure that the PCRST jumper is closed Once the program is uploaded the LED connected to PBO should blink at 1 Hz rate If not press the reset button on the board 2 2 Input Output ports of Atmega32 The pinout diagram of Atmega32 is shown in figure 2 1 There are 32 pins organized as four ports named A B C and D each 8 bit wide Each pin can be configured as an input or output The data direction and transfer are done
5. To generate the HEX file e avrdude To upload the Hex file These packages are available under GNU Linux For Debian Ubuntu distributions they can be installed from the repository using the commands apt get install avr libc apt get install avrdude chmod u s avrdude Insatlling avr libc automatically installs gcc avr and other required packages The last command will enable non root users to use avrdude The installed programs can be invoked from the command line Use a text editor to create your source program for example blink c and compile it using avr gcc Wall 02 mmcu atmega32 o blink blink c We have asked the compiler to print all the warnings optimize to level 2 generate code for atmega32 The executable output stored in blink and input taken from blink c The executable file is converted into Intel Hex format using the following command avr objcopy j text j data 0 ihex blink blink hex The Hex file is now ready for upload This can be done using the command avrdude b 19200 P dev ttyACMO pm32 c stk500vi U flash w blink hex We have specified a baudrate of 19200 the output device is dev tty ACMO m32 processor and the transfer protocol stk500v1 44 CHAPTER 4 PROGRAMMING DETAILS 45 CDC ACM Device The PC is connected to the uC through the USB to Serial Converter IC MCP2200 This chip implements the Communication Device Class CDC protocol of USB and is classified as an Abstract Co
6. 0x37 memory mapped addresses equ PORTB 0x38 of DDRB and PORTB Section data the data section vari byte 15 global variable vari Section text The code section global __do_copy_data initialize variables global __do_clear_bss and setup stack global main declare label main as global main lds work vari load vari to R1 sts DDRB work PBO as output sts PORTB work set PBO HIGH end 1 The Working registers R1 to R31 and the SFRs can be assigned different names as shown in the beginning 2 data starts a data section initialized RAM variables 3 text starts a text section code and ROM constants CHAPTER 3 CODING IN ASSEMBLY LANGUAGE 31 Register File Data Address Space l O Registers 900 ae 902 s 3D 9E PSF Application Flash Section 3D SF 3FFF Figure 3 2 AVR memory maps a Data memory b Program memory 4 byte allocates single byte constants 5 ascii allocates a non terminated string 6 asciz allocates a 0 terminated string 7 set declares a symbol as a constant expression identical to equ 8 global declares a public symbol that is visible to the linker 9 end singifies the end of the program The lines global do copy data and global do clear bss will tell the compiler to insert code for initializing variables which is a must for programs having initialized data Assembling and uploading first s will set the 4 LSBs of port B
7. 1c Oc 94 34 00 jmp 0x68 0x68 bad interrupt 20 Oc 94 34 00 jmp 0x68 0x68 bad interrupt 24 Oc 94 34 00 jmp 0x68 0x68 bad interrupt 28 Oc 94 34 00 jmp 0x68 0x68 lt __bad_interrupt gt 2c Oc 94 34 00 jmp 0x68 0x68 lt __bad_interrupt gt 30 Oc 94 34 00 jmp 0x68 0x68 lt __bad_interrupt gt 34 Oc 94 34 00 jmp 0x68 0x68 lt __bad_interrupt gt 38 Oc 94 34 00 jmp 0x68 0x68 lt __bad_interrupt gt 3c Oc 94 34 00 jmp 0x68 0x68 lt __bad_interrupt gt 40 0c 94 34 00 jmp 0x68 0x68 lt __bad_interrupt gt 44 Oc 94 34 00 jmp 0x68 0x68 lt __bad_interrupt gt 48 Oc 94 34 00 jmp 0x68 0x68 lt __bad_interrupt gt 4c Oc 94 34 00 jmp 0x68 0x68 lt __bad_interrupt gt 50 Oc 94 34 00 jmp 0x68 0x68 lt __bad_interrupt gt 00000054 lt __ctors_end gt 54 11 24 eor ri rl 56 1f be out Ox3f r1 63 58 cf eb ldi r28 Ox5F 95 ba d8 eO ldi r29 0x08 8 bc de bf out Ox3e r29 62 be cd bf out Ox3d r28 61 60 Oe 94 36 00 call Ox6c Ox6c main 64 Oc 94 3e 00 jmp Ox7c Ox c lt _exit gt 00000068 lt __bad_interrupt gt 68 Oc 94 00 00 jmp 0 0x0 lt __vectors gt 0000006c lt main gt 6c 88 27 eor r16 r16 0000006e lt _exit gt 6e f8 94 cli 00000070 lt __stop_program gt TO ff cf rjmp 2 0x70 lt __stop_program gt 3 8 Using Pre processor s and S The examples described so far used the s extension for the filenames The program square wave tc0 s listed below
8. ADCSRA 1 lt lt ADEN 7 Enable ADC set clock pre scaler ADMUX 1 lt lt REFSO AVCC reference channel 0 ADCSRA 1 ADSO Start ADC while ADCSRA amp 1 ADIF wait for ADC conversion data ADCH 8 ADCL make 10 bit data from ADCL and ADCH lcd put int data 2 4 8 Reading in a Loop The example program adc loop c reads an ADC input in a loop and display the result on the LCD If the input is left unconnected the displayed value could be anywhere between 0 an 1023 Connecting PAO to 5V will display 1023 the maximum output include mh lcd c include mh adc c include mh utils c main uinti6 t data lcd init O adc enable fot 1 data read adc 0 lcd_clear lcd put int data delay ms 100 Modify the code for reading other ADC channels 2 4 4 Temperature Control The program adc loop c can be easily modified to make a temperature monitor controller using the LM35 temperature sensor Connect LM35 output to PAO At 100 C the CHAPTER 2 GETTING STARTED 15 TCCRn TOVn gt Int Req Control Logic Clock Select Edge Detector TOP i From Prescaler DATABUS Figure 2 2 8 bit Timer Counter0 Schematic output of LM35 will be 1 volt With the internal 2 56 volts as reference the ADC output will be around 400 1 0 2 56 1023 Drive the relay contact contr
9. Serial Converter IC User programs also can use this path to communicate to the PC via the USB port The following functions are available for handling the UART 1 uart init baud 38400 is the maximum baudrate supported You can use any submultiple of that We use 1 Stop Bit and the parity is Even 2 uart recv byte Waits on the UART receiver for a character and returns it 3 uart send byte c Sends one character over the UART transmitter On the PC side we use a simple Python program to communicate to the micro controller The USB to Serial interface will appear as a virtual COM port on the PC on GNU Linux http www robot electronics co uk htm srf05tech htm CHAPTER 2 GETTING STARTED 22 systems it can be accessed as dev ttyACM0 You need to install Python interpreter and the python serial module on the PC for this to work These Python programs should be terminated before using MicroHOPE again to upload programs 2 6 1 Send receive Characters The program echo c waits for data from the PC vis the USB to serial converter increment it by one and sends it back The received data is also displayed on the local LCD display include mh lcd c include mh uart c int main void uint8_t data lcd_init uart init 38400 for data uart_recv_byte lcd_put_char data uart send byte data After uploading this program open a terminal window change to the directory named microhope and run
10. cso1 csoo w R W R W R W R W R W R W R W Let us start using Timer Counter0 with the help of the following functions sqwave tcO csb ocrval This function generates a square wave on OCO whose frequency is decided by the clock select bits csb and ocrval Example sqwave tc0 c listed below demonstrates the usage of this function example sqwave tc0 c include mh timer c csb 2 Clock select bits ocrval 99 Output Compare register vaule int main 1 sqwave tcO csb ocrval The 8MHz system clock is divided by 8 csb 2 refer to table below to get a 1MHz input to the counter The OCRO register is set to 99 The mode bits are set such that the when the counter value reaches the OCRO the output is toggled and counter is cleared This will result in the waveform generator output toggles after every 100 clock cycles giving a 5kHz sqaurewave on pin OCO PB3 You may view this on an oscilloscope If you do not have one connect a loudspeaker with a 100Q series resistor from PB3 to ground We have used expEYES for viewing and characterizing the waveforms generated by microHOPE Changing ocrval to 199 will give output 2 5kHz on the output The output frequency is given by the relation f m felock 2 N 14 OC RO where felock is the system clock and N is the clock division factor as shown below cso2 CS01 CS00 Description 0 0 0 No clock source Timer Counter stopped clkyo No prescaling
11. tmp16 lt NS tmp16 I TCNT1 1 counter for TG ADCSRA 1 lt lt ADSC 1 Start ADC while ADCSRA amp 1 lt lt ADIF Done dbuffer tmp16 ADCH Collect Data ADCSRA ADIF reset ADC DONE flag while TCNT1L lt TG Wait TG usecs while UCSRA amp 1 UDRE Wait Tx empty UDR D Send a D first for tmpi6 0 tmpi6 lt NS tmp16 Send to the PC f while UCSRA amp 1 UDRE UDR dbuffer tmp16 The Python program cro py import serial struct time import numpy as np CHAPTER 2 GETTING STARTED 25 im NP TG fd fd fi pl pl pl 0 10 20 30 40 50 0 0 i Figure 2 4 Oscilloscope screen shot port matplotlib pyplot as plt 500 100 serial Serial dev ttyACM0O 38400 stopbits 1 timeout 1 0 flush g plt figure t axis 0 NP TG 1000 0 5 t ion t show va ta range NP li ne plt plot ta va while 1 fd write chr 1 command for the uC print fd read This must be a D data fd read NP raw struct unpack B NP data convert to byte array ta va for i in range NP ta append 0 001 i TG micro to milliseconds va append raw i 5 0 255 line set xdata ta line set_ydata va plt draw time sleep 0 05 Modifed versions cro2 c and cro2 py that allows changing NS and TG from the Python program are also provided
12. called subroutine pops the stored PC to resume execution from the called point Program sub routine s listed below demonstrates this feature sub routine s CALL instruction IO_DDRB 0x17 IO_PORTB 0x18 Section text code section starts disp Subroutine inc rl out 0x18 r1 PORTB ret global main main ldi r16 255 out 0x17 r16 DDRB clr ri rcall disp relative call call disp direct call end The LED connected to PBO will light up Uncomment the CALL DISP and find out the difference in the generated code from the lst file Functionally both are same but relative jump is possible only if the offset is less than 256 3 6 2 Jump instructions The program counter can be modified to change the flow of execution of the code section data data section starts here Section text denotes code section global main main ldi r16 255 out 0x17 r16 DDRB jmp labi ldi r16 15 load 15 ro r16 labi out 0x18 r16 r16 to PortB end Running this code jump s will put on all the LEDs Comment the JMP instruction and execute the code again to figure out the difference it is making Jumps can be conditional also like CHAPTER 3 CODING IN ASSEMBLY LANGUAGE 38 Program Vector No Address Source Interrupt Definition 1 000 RESET External Pin Power on Reset Brown out Reset Watchdog Reset and JTAG AVR Reset 2 002 INTO External Interrupt Request 0 3 004 INT1 External Interrupt Req
13. e enable uart 9600 baudrates 2400 4800 9600 amp 19200 only e uart read returns one byte from the receiver buffer call only when variable ubcount is nonzero e uart write uint8 t writes a byte to the transmitter e disable uart disable the interrupts The Soft Serial code is tested by connecting PD2 soft Rx and PD3 soft Tx to a computer through the USB to Serial converter MCP2200 by using another microHOPE board with the uC removed The Transmit output from MCP2200 that appears on pin 14 of the uC socket is connected to PD2 Receive input on pin15 is connected to PD3 The program soft echo c listed below waits for data from the PC and the received data is send to the LCD display and also to the PC via PD3 include mh soft uart c include mh lcd c int main uint8_t x 0 lcd_init enable_uart 9600 2400 4800 9600 amp 19200 allowed for CHAPTER 2 GETTING STARTED 28 Figure 2 6 Connection to PC via soft serial port while ubcount wait for Rx data x uart read lcd put char x uart write x The Python echo py is used on the PC side The device name is shown as dev tty ACMI assuming that dev tty ACMO is already taken by the microhope board used for program development import serial fd serial Serial dev ttyACM1 9600 stopbits 1 timeout 1 0 while 1 c raw_input Enter the character to send fd write c print Receiced fd read E
14. 0bit resolution The value of ocra should be from 0 to 1023 to set the duty cycle example pwm tc1 c include mh timer c uint8_t csb 1 1 gt 8MHz clock in uinti6 t ocra 1024 3 Duty cycle arounf 33 int main pwm10_tc1 csb ocra J 2 5 3 8 bit Timer Counter2 This one is similar to Timer Counter0 CHAPTER 2 GETTING STARTED 19 sqwave tc2 uint32 t freq This function generates a square wave on OC2 The clock selction bits and the OCR2 value are calculated It is not possible to set all frequency values using this method The actual frequency set is returned and displayed on the LCD Example sqwave tc2 c include mh timer c include mh lcd c int main t uint32 t f lcd init O f set sqr tc2 1500 lcd put long f PWM by programming the registers The example given below demonstrates the usage of T C2 as a PWM waveform generator by setting the control register bits The duty cycle is set to 25 by setting the OCR2 to one fourth of the maximum example pwm tc2 c include lt avr io h gt uint8_t csb 2 Clock select bits uint8_t ocrval 255 4 Output Compare register vaule int main Set TCCR2 in the Fast PWM mode TCCR2 1 lt lt WGM21 1 lt lt WGM20 1 lt lt COM21 csb OCR2 ocrval TCNTO 0 DDRD 1 lt lt PD7 Set PD7 0C2 as output 2 5 4 More applications of Timer Counter Timer Counter can be used for timing
15. 28 48 OCRIBL TimerCounteri Output Compare Register B Low Byte 27 47 ICR1H Timer Counter Input Capture Register High Byte 26 46 ICR1L Timer Counter Input Capture Register Low Byte 25 45 TCCR2 roca wew2o cowz cow wema cs csn cs 24 44 TCNT2 Timer Counter 8 Bits 23 43 OCR2 Timer Counter2 Output Compare Register 22 42 asR as rcwu ocmue Tcr 21 S41 worcR J were wo wo woe woo 203 s40 UBRRH wsL UBRR 11 8 UCSRC URSEL SIF S3F earn S eme kem S1E S3E EEARL EEPROM Address Register Low Byte S1D 3D EEDR EEPROM Data Register ieme rue eost rote Potts porta reena rome rente rota 1B 3B PORTA PORTAT PORTAS PORTA4 PORTA3 PORTA2 PORTA PORTAO DDA2 DDA DDAO B 1A S3A DD DDA7 DDA6 DDA4 DA3 DB4 19 539 PINA PINA7 PAG Pas Pinas PINA3 PINA2 PA Piao 18 38 PO PORTB7 PORTB6 PORTB5 PORTB4 PORTB3 PORTB2 PORTB1 PORTBO 17 37 DDRB DDB7 DDB6 D DB3 DDB2 DDB1 DDBO RT RA RT 16 36 PINB PINB7 PiNB6 Pas _PINB4 PINB3 PINB2 PN amp Piso 15 35 PORTC PORTC7 PORTCE PORTCS PORTC4 PORTC3 PORTC2 PORTC1 PORTCO 14 34 DDRC DDC Doce Docs DDc4 DC pocz Doci Doco 13 33 PINC PINC7 PINC6 PINC5 PINC4 PINC2 PINCI PINCO RTD 7 12 32 PO PORTD7 PORTD6 PORTDS PORTD4 PORTD2 PORTD1
16. 4bit mode using pins 11 to 14 connected to PC4 PC5 PC6 and PCT The LCD should be connected to port C socket to use the C library functions to access the display 1 2 3 Motor Control Board The motor control board consists of 2 H bridges IC L293D Board can be powered from outside or from the MicroHOPE socket An INT EXT jumper is provided to select the power option The voltage level at the for outputs of L293 is decided by the four LSBs of the port on which it is connected The outputs A B C amp D can be used for controlling 2 DC motors or one stepper motor For details refer to http en wikipedia org wiki Hitachi HD44780 LCD controller CHAPTER 1 INTRODUCTION 6 uhope Device dev ttyACMO DIEM Compile Assemble Upload Detect MH Help About include avr io h Include file for I O operations int main void DDRA 0 Port Aas Input PORTA 1 Enable pullup on PAO DDRB 1 Configure PBO as output For iF PINA amp 1 IF PAOis set PORTB 1 SetPBO by ORing with 00000001b else otherwise clear PBO PORTB amp 1 by ANDing with 11111110b 00000001b home ajith microhope copy3 c Line 14 Col 0 Figure 1 7 MicroHOPE User Interface 1 2 4 USBASP Programmer board This is an open sourced ISP In System Programming programmer available from http www fischl This is provided as an accessory to MicroHOPE due to several reasons If you want to develop programs that uses the
17. MicroHOPE O o Lo ri 9 o we UO MicroHQPE sre ope org expeyes in 35912 Yai Yo OINDIA aaaaa User s Manual Micro controllers or Hobby Projects and Education Inter University Accelerator Centre A Research Centre of UGC New Delhi 110 067 Visit http expeyes in microhope for updates Chapter 1 Introduction Most of computer systems in use today are embedded in other machinery such as auto mobiles telephones appliances and peripherals for computer systems Tasks requiring smaller amounts of processing power and memory are generally implemented using micro controllers uC A micro controller is a small computer on a single integrated circuit consisting of a CPU combined with program and data memory peripherals like analog to digital converters timer counters serial communication ports and general purpose Input Output ports Intel 8051 Atmel AVR PIC etc are popular micro controllers available in the market To design the MicroHOPE hardware we have chosen ATmega32 micro controller from Atmel AVR series after considering the hardware resources avail able on it and the support of Free Software tools like GNU assembler and C compiler Why microHOPE Many people who write programs that run on a PC find it difficult to get started on coding for a microcontroller mainly due to 1 Programming a uC requires some knowledge about the target hardware 2 Transferring the program from t
18. UART of Atmega32 you need to upload code using ISP It can be used for programming other AVR micro controllers also It can be used for burning the boot loader The LED on the board indicates power It goes off while uploding code giving an additional indication More details are given in chapter 4 1 3 MicroHOPE Software MicroHOPE s software requirements are a text editor a cross compiler and assembler avr C library a code uploader and other associated programs We have written a minimal text editor that is our IDE that can invoke the compiler uploader etc and also detect the MicroHOPE hardware It can edit compile assemble and upload programs It is available for both GNU Linux and MS Windows platforms On MSwindows you need to install the Winavr package and the driver for MCP2200 IC from Microchip 1 3 4 All GNU Linux Systems Download and install avr gcc avrlib and avrdude from the repositories of your GNU Linux distribution Download the source file uhope c and the Makefile from MicroHOPE web site The command make Download from http expeyes in microhope CHAPTER 1 INTRODUCTION T will compile and create the executable uhope you need to install gtk library Copy it to usr bin uhope will start the program 1 3 1 1 Debian and derivatives like Ubuntu Debian package is available on the website After installing the package run create microhope env from a terminal to copy the example programs t
19. _t adcval lcd initO uart init 38400 adc enableO for data uart_recv_byte if chan lt 7 adcval read adc chan lcd_clear lcd put int low low adcval amp 255 hi adcval gt gt 8 uart_send_byte low send LOW byte uart send byte hi send HI byte 2 6 3 A simple Oscilloscope The program cro c can waits for a command byte from the PC On receiving a l it digitizes the input at PAO 500 times with 100 microseconds in between samples and CHAPTER 2 GETTING STARTED 24 sends the data to the PC The program cro py sends the necessary command receives the data and displays it as shown in the figure2 4 While running cro py the PCRST jumper should be open The C program running on the micro controller is listed below include lt avr io h gt define READBLOCK 1 code for readblock is 1 define NS 500 upto1800 for ATmega32 define TG 100 100 usec between samples uint8 t tmp8 dbuffer NS uinti6 t tmpi6 int main void t UART at 38400 baud 8 istop No parity UCSRB 1 lt lt RXEN 1 lt lt TXEN UBRRH 0 UBRRL 12 UCSRC 1 lt lt URSEL 41 lt lt UCSZ1 1 lt lt UCSZO ADCSRA 1 lt lt ADEN Enable ADC for 3 while UCSRA amp 1 lt lt RXC wait for the PC if UDR 1 1 is our command TCCR1B 1 lt lt CS11 ADMUX 1 lt lt REFSO 1 lt lt ADLAR 0 ADCSRA ADIF for tmp16 0
20. an ISP called the USBASP that is open hardware The microHOPE IDE can upload programs using the USBASP programmer CHAPTER 4 PROGRAMMING DETAILS AT 4 2 1 Software The program avrdude can be used for programming the micro controller by using Parallal port or the USBASP programmer The commands to use as root user are avrdude c dapa patmega32 U flash w blink hex avrdude c usbasp patmega32 U flash w blink hex The c option is used for specifying the programmer to be used The commands should be given from a terminal after changing to the directory microhope where all the data files are kept Setting up the Boot Loader We can use one of these methods for uploading the bootloader program of microHOPE The commands for uploading the hex file and setting the fuses using the parallel port cable are avrdude c dapa patmega32 U flash w ATmegaBOOT 168 atmega32 hex avrdude c dapa patmega32 U lfuse w 0xef m U hfuse w 0xda m If you are using USBASP use avrdude B10 c usbasp patmega32 U flash w ATmegaBOOT 168 atmega32 hex avrdude B10 c usbasp patmega32 U lfuse w 0xef m U hfuse w 0xda m For more details refer to the microhope section of the website expeyes in CHAPTER 4 PROGRAMMING DETAILS 48 Latest version of this document can be downloaded from expeyes in microhope This product is from the PHOENIX project of IUAC New Delhi with contributions from the academic community People involved in de
21. applications like measuring the time elapsed be tween two events or counting the number of pulse inputs during a specified time interval measure frequency This function counts the number of pulses received on the external input of Timer Counterl PB1 during 500 milliseconds to calculates the frequency of the input pulse Example freq counter c include mh utils c include mh timer c include mh lcd c CHAPTER 2 GETTING STARTED 20 int main uint32_t f set_sqr_tc2 1500 Set a square wave on TC2 output PD7 lcd_init while 1 f measure freqO lcd_clear lcd put long f delay ms 200 return 0 Connect PD7 to PB1 and upload the program freq counter c to read the frequency on the LCD display You can also connect PB1 to an external pulse source to measure its frequency The maximum frequency that can be measured is limited by the size of the counter that is 63535 means we it can handle upto around 126 kHz Time Interval Measurement The T C units can be programmed to keep track of time interval between two events The program r2ftime c measures the rising edge to falling edge time on PB1 Example r2ftime c include mh utils c include mh timer c include mh lcd c int main lcd_init set sqr tc2 500 Test signal on PD7 while 1 1 lcd clear lcd put long r2ftime PB1 delay ms 100 The function r2ftime uses two other functions called start_t
22. ave not initialized the global variable varl inside the program The example global init s listed below demonstrates this feature global init s variable initialization DDRB 0x37 PORTB 0x38 Section data vari byte Oxee Section text denotes code section global main global do copy data initialize global variables global do clear bss and setup stack pointer main lds r16 vari content of RAM at vari to r16 sts DDRB r16 store R16 to DDRB amp PORTB sts PORTB r16 using their memory addresses end The lines global do copy data initialize global variables global do clear bss and setup stack pointer are for initializing variables and setting up the stack essential for programs with initialized data 3 6 Program Flow Control The programs written so far has an execution flow from beginning to end without any branching or subroutine calls generally required in all practical programs The execution flow can be controlled by CALL and JMP CHAPTER 3 CODING IN ASSEMBLY LANGUAGE 3T 3 6 1 Calling a Subroutine The subroutine call can be relative or direct For a direct call the content of the Program Counter is replaced by the operand of the CALL instruction For an indirect call the operand is added to the current value of the Program Counter In both cases the current value of the PC is pushed into the memory location pointed by the Stack Pointer register The RET instruction inside the
23. by writing to the registers DDRX PORTX and PINX where X stands for A B C or D The avr gcc compiler allows us to program the registers and their individual bits using the same names given in the Atmega32 manual The C compiler allows you to access them just like normal variables For example the statement PORTB 15 writes the number 15 to Port B The individual pins are referred using names like PAO means BIT 0 of Port A For complete details of Atmega32 refer to http www atmel in Images doc2503 pdf For old model of microHOPE using FT232 it will be ttyUSB CHAPTER 2 GETTING STARTED 9 XCK TO PBO 1 PAO ADCO T1 PB1 2 PA1 ADC1 INT2 AINO PB2 3 PA2 ADC2 OCO AIN1 PB3 4 PA3 ADC3 SS PB4 5 PA4 ADC4 MOSI PB5 6 PA5 ADC5 MISO PB6 7 PA6 ADC6 SCK PB7 8 PA7 ADC7 RESET 9 AREF vec GND GND AVCC XTAL2 PC7 TOSC2 XTAL1 PC6 TOSC1 RXD PDO PC5 TDI TXD PD1 PC4 TDO INTO PD2 PC3 TMS INT1 PD3 PC2 TCK OC1B PD4 PC1 SDA OC1A PD5 PCO SCL ICP1 PD6 PD7 OC2 Figure 2 1 Atmega32 Pinout e DDRX Direction of every pin of an I O port is decided by the state of corresponding bit in the Data Direction registers DDRX To configure a pin as output make the bit 1 and to make it as input make it zero For example DDRA 1 will configure BIT 0 of Port A PAO as output and all other pins as input e PORTX For pins that are configured as ouput assigning a value to PORTX
24. clkyo 8 From prescaler Clk o 64 From prescaler Clk 5 256 From prescaler Clk o 1024 From prescaler External clock source on TO pin Clock on falling edge iki mac om ry 0 1 0 1 1 alolalo a jo a External clock source on TO pin Clock on rising edge CHAPTER 2 GETTING STARTED 17 pwm tcO csb ocrval This function generates a Pulse Width Modulated waveform on OCO whose frequency is decided by the clock select bits csb and the duty cycle by the ocrval The output OCO is cleared when the counter reaches the OCRO value the counter proceeds upto 255 and then sets OCO The program pwm tc0 c generates a 3 9 kHz PWM with 25 dutycycle example pwm tcO c include mh timer c uint8 t csb 2 Clock select bits uint8 t ocrval 63 Output Compare register vaule int main pwm_tc0 csb ocrval PWM waveforms are often used for generating analog DC voltages in 0 to 5 volts range by filtering it using an RC circuit It is better to set a higher frequency so that the filter RC value could be small The frequency can be made 31 25kHz by setting csb 1 The DC level is decided by the value of OCRO ranging from 0 to 255 Once you learn howto manipulate the control registers the same thing can be done without calling the library function as shown below example pwm tc0 v2 c include lt avr io h gt uint8 t csb 1 Clock select bits uint8
25. e loaded boot loader code on the uC To load a new program the PC asserts the RTS signal of MCP2200 gen erating a pulse that resets ATmega32 On reset the boot loader code will start waiting for new code from the PC If new code is available it is loaded and control is transferred to it otherwise the existing code will start running Atmega32 has 32 Input Output pins organized as 4 ports each 8 bit wide The IC is available in DIP package that can be socket mounted The ATmega32 has 32 kB of Flash memory 512 bytes EEPROM and 2 kB Static RAM Three Timer Counters a serial interface USART a byte oriented Two wire Serial Interface an 8 channel 10 bit CHAPTER 1 INTRODUCTION 4 t Fer a Fer l O HiH CONN 40 on i ee petals ha x a3 A xO 88 ia 1 2 m i d d A i ke no uw E aN P TELLE peel P5 Pa CONN_10 CONN 10 Figure 1 3 Circuit schematic of microHOPE e o Z f o Figure 1 4 The digital output Board ADC and an SPI serial port are some of the peripheral devices on the chip The processor on the microHOPE board runs at 8MHz using the external crystal All the I O pins except the two bits of port D that are used by the UART R
26. ect the reference where ref is REF EXT is an external volt age is applied to the AVREF pin REF INT to use the internal 2 56 V reference and REF AVCC to connect the AVCC supply internally to AVREF 4 read adc ch Converts the voltage on channel ch and returns it in a 16 bit number 2 4 1 Reading an Analog Voltage The example program adc c reads an ADC input and display the result on the LCD include mh lcd c include mh adc c main uinti6 t data lcd init O adc enable data read adc 0 lcd put int data 2 4 2 Programmig ADC registers The operation of the ADC is controlled mainly by the registers ADCSRA and ADMUX Setting ADEN will enable the ADC and setting ADSC will start a conversion The bit ADIF is set after a conversion and this bit can be cleared by writing a 1 to it The ADSP bits decide the speed of operation of the ADC by pre scaling the clock input The channel number is selected by the MUXO to MUXA bits in the ADMUX rregister The reference input is selected by the REFSO and REFS1 bits 7 6 5 4 3 2 1 0 ADEN T ADSC ADATE ADI ADE ADPS2_ ADPSI_ APSO R W RW R W RW R W RW R W R W 0 0 0 0 0 0 0 0 CHAPTER 2 GETTING STARTED 14 7 6 5 4 3 2 1 0 R W R W R W R W R W R W R W R W 0 0 0 0 0 0 0 0 The program adc v2 c demonstrates the usage of these registers include lt avr io h gt include mh lcd c convert channel 0 set pre scaler to 7 main uint16_t data lcd_init
27. erstanding them from a generic point of view makes switching from one type of device to another easier To program in assembly language we need to have some understanding about the Instruction Set the Registers and the memory configuration of the micro controller We also need to know the syntax supported by the assembler we use there is usually small differences between various assemblers Since we are using Atmega32 belonging to the AVR family and the GNU assember for AVR further discussions will be restricted to them 3 1 Format of an Assembler Program A single line of code may have a e Label always terminated by a colon e The instruction e The operands could be 0 1 or 2 of them e A comment starting with a semicolon http sourceware org binutils docs as 29 CHAPTER 3 CODING IN ASSEMBLY LANGUAGE Data Bus 8 bit Status and Control 32x8 Instruction General Register Purpose Registrers Instruction Decoder Y Control Lines Flash Program Memory Program Counter Interrupt Unit Direct Addressing Indirect Addressing Figure 3 1 A block diagram of Micro controller labi INC R1 increment the content of Register r1 30 The instruction and operand is not case sensitive but the labels are case sensitive Lab1 is not the same as labl A complete program is shown below first s example assembler program for avr gcc work 1 equ DDRB
28. etween the H bridge output pins A and B The following Python code will rotate the motor from pymicro import p atm32 p outb DDRA 15 p outb PORTA 1 2 8 Infrared Receiver The program ir recv c can receive data using the TSOP1738 IR receiver The output of the chip is connected to bit 2 of PORTD The received byte is displayed on the LCD display The receiver tested using TV remote controls To test ir recv c make the connections as shown below PD2 of microHOPE TSOP1738 5V I GND CHAPTER 2 GETTING STARTED 27 EN1 2 VCC 1A 4h 14 1 1Y AY x cup 12952 eno 13 3 JE z GND ya GND 2 8 2Y 3y 4 2A 3 vcc EN3 4 R O zn 2 ES e zw NV Figure 2 5 H bridge schematic Press some buttons on the remote control panel The received number will be displayed on the LCD display of microHOPE The code ir recv c is available on the website It can be modified to work with the single byte IR transmitted from expEYES 2 9 Alternate Serial Port The Atmega32 controller has only one Serial Port UART that is already connected to the USB to Serial converter In order to communicate to other devices that supports serial communication we have a simple library that will convert PD2 to a Transmit pin and PD3 a Receive pin The functions available are
29. f microHOPE IDE Click on Compile and then Upload from the menubar The LED on PBO should start glowing after uploading the program LED will be off when you connect PAO to ground You may rewrite the program so that the LED may be controlled by some other bit configured as input The simple program given above has certain drawbacks It changes PORTB as a whole instead of acting on PBO alone Suppose we have something else connected to the other pins of Port B they also will be affected by the action of PORTB PINA To avoid such problems we should manipulate individual bits The include file mh digital c contains macros for setting and clearing bits by specifying their position 2 2 2 Bit manipulation macros These macros can be used on variables defined in the program and also on registers like DDRX PORTX etc BITVAL bit position The value of bit position could be 0 to 7 in the case of 8 bit integers and 0 to 15 for 16 bit integers This macro returns 1 lt lt bit position For example BITVAL 3 will give 8 that is binary 1000 obtained by left shifting of 1 thrice SETBIT variable bit position This macro SETS the specified bit in the given variable without affecting the other bits For example SETBIT DDRB 7 will make the last bit of DDRB high CLRBIT variable bit position This macro clears the specified bit of the given variable For example CLRBIT val 0 clears the least significant bit of val that is a
30. generates a 15 93 kHz square wave on PB3 TCCRO WGMO1 3 COMOO 4 OCRO Ox5C DDRB 0x37 PB3 3 Section text code section global main main ldi ri6 1 lt lt WGMO1 1 lt lt COMOO 1 CTC mode 0x53 CHAPTER 3 CODING IN ASSEMBLY LANGUAGE 41 sts TCCRO r16 ldi r16 100 sts OCRO r16 ldi r16 1 lt lt PB3 sts DDRB r16 end The addresses of the Special Function Registers and the various bits inside them are defined inside the program first 6 lines Instead of entering them like this we can use the corresponding include file We need to use the S file extension to tell avr gcc to call the assembler with the suitable pre processor options The same program re written with extension square wave tc0 S is listed below include lt avr io h gt Section text global main main ldi ri16 1 lt lt WGMO1 1 lt lt COMOO 1 CTC mode sts TCCRO r16 ldi r16 250 sts OCRO r16 ldi r16 1 lt lt PB3 sts DDRB r16 end The second method is advisable if you plan to develop larger assembler programs for practical applications 3 0 Example Programs The programs described below performs better than their C counterparts 3 9 1 R2R DAC on Port B A R2R network as shown in figure 3 5 a is connected to port B The program writes the content of R1 to port B in an infinite loop R1 ia incremented every time and after reaching 255 it will become 0 resulting in a ramp at the output
31. he PC to the target device requires some special hardware and software There are plenty of micro controller development kits in the market but most of them focus on explaining the hardware and software of the development kit rather than the micro controller They teach programming the I O pins of the development board using the library functions provided and the user can get things done without understanding anything about the micro controller The objective of this work is to help learning uC architecture and programming not the MicroHOPE hardware or software The focus will be on the features of the micro controller without hiding its details from the user A simple Graphical User Interface is provided to Edit Compile or Assemble and upload the program We start by programming the Input Output ports of Atmega32 which require some basic knowledge of binary number system and C language with its bit manipulation operators After that we will proceed to the programming of the peripherals like ADC Timer Counter etc Since they are more complex we will start with a software library in the form of C source files that can be included in your program Once you I We are very much aware of the drawback of this method When you include a file all the functions in that will get added to your executable increasing its size Once the code is working copy the necessary functions to your source file instead of including the whole file to get rid of
32. imer and read_timer that are explained below e void start_timer Start the counter with a 1 MHz clock input An interrupt service routine is activated when the count reached 50000 that increments another interger e uint32 t read timer Stops the counter and returns the microseconds elapsed after calling start timer There will be an error of 2 to 3 microseconds that is due to the overhead of the function calls CHAPTER 2 GETTING STARTED 21 2 5 4 1 Distance Measurement This technique is used for measuring distance using an ultrasound echo module HY SRFO05 using ultra sound echo c The trigger is connected to PBO and the echo is connected to PB1 The distance is measured by Example ultra sound echo c include mh utils c include mh timer c include mh lcd c int vsby2 17 velocity of sound in air 34 mS cm int main t uint32 t x DDRB 1 lt lt PBO set PBO as output DDRB amp 1 lt lt PB1 and PB1 as inpt lcd init O while 1 PORTB 1 lt lt PBO set PBO HIGH delay_100us 1 PORTB amp 1 lt lt PBO set PBO LOW delay_100us 5 Wait for a while to avoid false triggering start_timer while PINB amp 22 0 Wait for LOW on PB1 x read timer 400 lcd_clear lcd_put_long x vsby2 1000 distance in cm delay_ms 500 2 6 Talking to the PC via USB On the microHOPE board the Rx Tx pins of ATmega32 are connected to the USB to
33. irect Single Register The contents of the register is read specified operation is performed on it and the result is written back to the same register For example Labi INC R2 increments Register 2 The line above shows the format a line of code in assembly language The label field is required only if the program needs to jump to that line Everything after the semicolon is comment only 3 4 2 Register Direct Two Registers The contents of the source and destination registers are read specified operation is per formed and the result is written back to the destination register The format is to specify the destination first For example CHAPTER 3 CODING IN ASSEMBLY LANGUAGE Address S3F S5F S3D 5D S3C 5C 3B 5B INT2 3A 5A INTF2 39 59 TICIE1 38 58 37 57 36 56 35 55 34 54 33 53 WGM00 32 52 Timer Counter 8 Bits 1 n Oscillator Calibration Register 31 sn On Chip Debug Register 30 550 ADTS2 Ans aoo acme Pu Psr Psmo S2F S4F COMiA com1ao_ comi cowtgo rocia roc wcwt wemo S2E S4E ICNC1 cesi wews wom cs2 css cst S2D 4D Timer Counter Counter Register High Byte 2C 4C Timer Counter Counter Register Low Byte 2B S4B Timer Counter1 Output Compare Register A High Byte 2A S4A TimeriCounter Output Compare Register A Low Byte 29 49 OCR1BH Timer Counter1 Output Compare Register B High Byte
34. n text global main main clr ri end gt gt The generated machine language output can be examined by looking at the lst output shown below generated by the objdump program It can be seen that the assembler generates some code that is required for the proper operation of the uC In the Atmega32 Program memory the first 80 50hex bytes are supposed to be filled with the addresses of the 20 interrupt vectors It can be seen that the program jumps to location ctors end 54hex The porcessor status register 0x3F is cleared and the Stack Pointer is initialized to 0x085F the last RAM location before calling our main section After returning from the main it jumps to _ exit 0x6e clears the interrupt flag and then enters an infinite loop That means we need to end the main section with an infinite loop if our program uses interrupts home ajith microhope ASM test Disassembly of section text 00000000 lt __vectors gt 0 4 8 C 10 14 Oc 94 2a Oc 94 34 Oc 94 34 Oc 94 34 Oc 94 34 Oc 94 34 00 00 00 00 00 00 jmp 0x54 jmp 0x68 jmp 0x68 jmp 0x68 jmp 0x68 jmp 0x68 0x54 0x68 0x68 0x68 0x68 0x68 file format elf32 avr lt __ctors_end gt lt __bad_interrupt gt lt __bad_interrupt gt lt __bad_interrupt gt lt __bad_interrupt gt lt __bad_interrupt gt CHAPTER 3 CODING IN ASSEMBLY LANGUAGE 40 18 0c 94 34 00 jmp 0x68 0x68 lt __bad_interrupt gt
35. n integer type variable GETBIT variable bit position This macro returns the value the specified bit if the specified bit of the variable is 1 else it returns zero For example if x 3 GETBIT x 1 will return 2 and GETBIT x 3 will return zero Let us rewrite the previous program as copy2 c using these macros as include lt avr io h gt int main void 3The macros are implemented using define BITVAL bit 1 lt lt bit define CLRBIT sfr bit SFR BYTE sfr amp BITVAL bit define SETBIT sfr bit SFR BYTE sfr BITVAL bit Ji define GETBIT sfr bit SFR BYTE sfr amp BITVAL bit CHAPTER 2 GETTING STARTED 11 uint8_t val DDRA 0 Port as Input PORTA 1 Enable pullup on PORTA bit 0 DDRB 1 Pin 0 of Port B as output forts 3 val GETBIT PORTA 0 if val 0 SETBIT PORTB 0 else CLRBIT PORTB 0 The same can be done without using the bit manipulation macros as shown in copy3 c include lt avr io h gt Include file for I O operations int main void 1 uint8_t val 8 bit unsigned word DDRA 0 Port A as Input PORTA 1 Enable pullup on PAO DDRB 1 Configure PBO as output for if PINA amp 1 If PAO is set PORTB 1 Set PBO by ORing with 00000001b else otherwise clear PBO PORTB amp 1 by ANDing with 11111110b 00000001b j The code fragment shown above uses the Bitwise AND OR and NOT opera
36. n pointed to by the Stack Pointer and jumps to the corresponding interrupt vector location as shown in figure For example the processor will jump to location 0x0002 0x0004 if you count them as bytes if external interrupt pin INTO is activated provided the interrupt is enabled by the processor beforehand The interrupt vector location is filled with the address of the subroutine handling the interrupt For the interrupts that are not used by the program the assembler fills some default values After executing the Interrupt Service Routine the program execution resumes at the point where it was interrupted The program interrpt s listed below shows the usage of interrupts Connect 8 LEDs to Port B and run the code Connect PD2 to ground momentarily and watch the LEDs Section data data section starts here Section text denotes code section global __vector_1 INTO vect vector 1 inc ri CHAPTER 3 CODING IN ASSEMBLY LANGUAGE out Ox18 r1 reti global main main ldi r16 255 out 0x17 r16 out 0x12 r16 ldi r16 0x40 out Ox3b r16 clr ri sei loop rjmp loop end gt DDRB Port D pullup gt enable INTO 3 7 Output of the Assembler 39 We have learned howto write assemble and execute simple assembler programs Let us assemble a program with a single instruction as shown below test s an single line program data section starts here denotes code section Section data Sectio
37. ntrol Model ACM device It apprears as a virtual COM port to the application program They get the device names dev ttyACMO dev ttyACM1 etc in the order in which they are plugged in Remember to close the application programs before disconnecting the device otherwise it will get higher numbers when connected again 4 1 1 Batch files Since a lot of command line arguments are required to specify the compiler linker and loader options it is convenient to put them in small batch files or shell scripts These files can be found inside the microhope directory once the package is installed The compilation of C code and generation of Intel Hex format file for uploading is done by compile mega32 sh listed below avr gcc Wall O2 mmcu atmega32 Wl Map 1 map o 1 1 c avr objcopy j text j data O ihex 1 1 hex avr objdump S 1 gt 1 lst For example to compile a program named hello c it should be invoked from the com mand line as compile mega32 sh hello The c extension should not be specified The script also generates the linker MAP file and a listing file that may be used for examining the generated output Under GNU Linux microhope on the USB port will appear as file dev ttyACMO and program uploading is done by mh upload sh listed below avrdude b 19200 P dev ttyACMO pm32 c stk500v1 U flash w 1 hex To upload hello hex use the command mh upload hello Running from DOS prompt Use a
38. o a directory named microhope inside your home directory The MicroHOPE program can be started from the applications menu A screen shot of the microhope IDE is shown in figure 1 7 By default it looks for files inside a subdirectory named microhope inside your home directory The IDE allows you to load save files detect the hardware compile assemble the code and upload the output The examples given in this document will appear inside the directory named micro hope All files starting with mh are the files containing library functions to access the various peripherals of Atmega32 To make the source code visible to the user they are not compiled as a library file Do not modify the files starting with mh You can select any of the example programs compile assemble and upload them using the menu Correct all the errors before doing Upload You also need to detect the hardware once before uploading For assembly language programs the file name extension should be s or S The pre processor is invoked if S is used 1 3 2 MS Windows Download and install the software from http www expeyes herobo com microhope php The requirements are the USB to Serial IC drivers winavr package from sourceforge net and the microHOPE installer Chapter 2 Getting Started After installing the required software packages you must have copied the examples to a directory named microhope inside your home directory Start the microHOPE IDE
39. of the R 2R network figure 3 5 b The frequency of the ramp generated is around 8 kHz program ramp on R2RDAC S generates ramp on Port B include lt avr io h gt Section text global main main ldi r16 255 sts DDRB r16 all bits of DDRB set loop inc rl sts PORTB ri R1 to PORTB LEDs CHAPTER 3 CODING IN ASSEMBLY LANGUAGE 42 DAC output 5 i a A 4 e Nol ar f 4 So 0 1 0 2 0 3 0 4 0 5 0 6 0 7 0 8 72 o Pi CONN 2 port X o o ral ae Figure 3 5 R2R DAC on port B a schematic b output waveform rjmp loop end 3 9 2 Sine wave Generator The program sine wave S listed below uses Timer Counter 0 to trigger an interrupt when the counter reaches the set point register OCRO Register X is pointed to a sine table stored in SRAM On an interrupt the value from sine table pointed to by X is written to Port B where the R 2R DAC is connected Register R22 is used for reseting the pointer after 32 increments The R 2R DAC on port B generates the DC values that makes the sine wave include lt avr io h gt Section data global stab Stab sine table byte 128 150 171 191 209 223 234 240 242 240 234 223 209 191 171 150 128 105 84 64 46 32 21 15 13 15 21 32 46 64 84 105 127 Section text code section global do copy data global __do_clear_bss global TIMERO COMP vect TIMERO_COMP_vect ISR ld
40. olling the heater from PBO via a transistor Insert the following line in the beginning DDRB 1 and within the loop if data 400 switch off heater PORTB 0 else if data lt 395 switch on heater PORTB 1 The heater will be switched OFF when the ADC output is greater than 400 It will be switched ON only when the output goes below 395 The window of 6 is given to avoid the relay chattering 2 5 Timer Counters ATmegal6 has three counter timer units Two of them are of 8 bit size and one is 16 bit The counter input could be derived from the internal clock or from an external source The output of the counter is compared with setpoint registers and different types of actions are taken on compare match The mode of operation of Counter Timer is programmed by setting the bits in the control registers These circuits are useful for time interval measurements and generating different kinds of waveforms CHAPTER 2 GETTING STARTED 16 2 5 1 8 bit Timer CounterO A block diagram of Timer Counter0 is shown in figure2 2 The counter TCNTO gets its input and control signals from the control logic circuit The counter output is compared with a Output Compare Register OCRO and a compare match can trigger different types of actions like generating a waveform on OCO pin 4 of Atmega32 same as PB3 The mode of operation is decided by the register TCCRO shown below 7 6 5 4 3 2 1 0 FOCO wamoo COMO comoo WGMo CS02
41. omplete code including the sections added by the assembler Moving data from R16 to DDRB and PORTB is done using both the I O space address and the memory space address The generated code is smaller in the case of I O space addressing using the OUT instruction 0000006c lt main gt 6c 10 ef ldi r17 OxFO 6e 10 93 60 00 sts 0x0060 r17 72 00 91 60 00 lds r16 0x0060 76 O7 bb out 0x17 r16 78 08 bb out 0x18 r16 Ta 00 93 37 00 sts 0x0037 r16 Te 00 93 38 00 sts 0x0038 r16 3 4 6 Data Indirect In the previous mode the address of the memory location is part of the instruction word In Data Indirect mode the address of the memory location is taken from the contents of the X Y or Z registers This mode has several variations like pre and post incrementing of the register or adding an offset to it data indirect s addressing using pointer section data data section starts here vari Section text denotes code section global main main ldi r17 0b10101010 set r17 to 10101010b sts vari ri store it to RAM at vari CHAPTER 3 CODING IN ASSEMBLY LANGUAGE 36 ldi r26 lo8 vari lower byte and ldi r27 hi8 vari higher byte of the address ld ri6 X data from where X is pointing to out 0x17 r16 out 0x18 r16 end The operators lo8 and hi8 are provided by the assembler to extract the high and low bytes of the 16bit memory address 3 5 Variable Initialization In the previous examples we h
42. r24 X load from table increment sts PORTB r24 write it to PORTB inc r22 increment r22 CPSE r20 r22 reached the end reti Skip if equal clr r22 ready for next round subi r26 32 set X to table start reti global main main CHAPTER 3 CODING IN ASSEMBLY LANGUAGE 43 ldi r16 255 sts DDRB r16 ldi r16 1 lt lt WGMO1 1 TCCRO to CTC mode sts TCCRO r16 ldi r16 50 Set point reg to 50 sts OCRO r16 ldi r16 1 lt lt OCIEO set TCO compare interrupt enable sts TIMSK r16 ldi r16 1 lt lt OCFO interrupt enable bit sts TIFR r16 ldi XL lo8 stab point X to the sine table ldi XH hi8 stab clr r22 R22 will keep track of the location in table ldi r20 32 Store size of the table in R20 sei loop rjmp loop infinite loop end Chapter 4 Programming details MicroHOPE does program loading through the Rx Tx pins of the UART with the help of the pre loaded boot loader program The boot loader code is first loaded using the In System Programming ISP feature of the uC implemented using the Serial Peripheral Interface SPI interface of the micro controller Both the methods are explained below 4 1 Compile and Upload using bootloader Even though the IDE does the job it is a good idea to learn about the programs used behind the seen to compile and upload the code The software packages used are e avr gcc To compile the C program also require the C library avr libc e avr objcopy
43. ral instructions whose results depend on the status of the bits inside SREG Availability of SREG as a special function register allows us to examine the status of various flags after arithmetic and logical operations Stack Pointer is used as a pointer to the data address space PUSH and POP instructions are used for moving data between the register file and location specified by the stack pointer All the peripherals and the general purpose I O ports are operated by accessing the corresponding SFRs We will be using ports A and B to view data written to them using 8 LEDs The SFRs used often in the example programs are listed below Name I O Addr Mem Addr Function DDRA OxlA 0x3A Data Direction of Port A PORTA 0x1B 0x3B Output to Port A PINA 0x19 0x39 Input from Port A DDRB 0x17 0x37 Data Direction of Port B PORTB 0x18 0x38 Output to Port B PINB 0x16 0x36 Input from Port B SREG Ox3F Ox5F Status Register 3 2 1 The Program Memory Space 3 3 Atmega32 Instruction Set For a complete list of instructions supported by Atmega32 refer to the data sheet We will only examine some of them to demonstrate different types of memory addressing and the arithmetic and logical operations 3 4 Addressing Modes The micro controller spends most of the time transferring data between the Register File SFRs and the RAM Let us examine the different modes of addressing the Registers and Memory 3 4 1 Register D
44. rd 3 4 5 Data Direct In this mode the address of the memory location containing the data is specified instead of the data itself Data could be transferred from the specified location to a register LDS or from a register to the memory location STS The instruction mnemonics are LDS for moving data from RAM to Register and STS for storing Register content to RAM The example data direct s demonstrates the usage of LDS and STS instructions First we use the immediate mode to initialize R17 with some value CHAPTER 3 CODING IN ASSEMBLY LANGUAGE 35 data direct s demonstrate data direct mode DDRB 0x37 PORTB 0x38 Section data vari Section text denotes code section global main main ldi R17 OxfO set r17 to 11110000b sts vari r17 store ri7 to location vari lds r16 vari content of RAM at vari to r16 sts DDRB r16 Store R16 to DDRB amp PORTB sts PORTB r16 using their memory addresses end The actual address of the memory location is not known to us it is decided by the linker The label var1 defined inside the data section is used inside the code The actual value can be seen from the lst file generated by the avr objdumb program Generated machine language code for the section main is shown below It can be seen that the label varl is given the RAM address of 0x0060 Also note that the main is at address 0x0000006c in the program address space Examine the lst file to have a look at the c
45. t ocrval 254 4 Output Compare register vaule int main Set TCCRO in the Fast PWM mode TCCRO 1 lt lt WGMO1 1 lt lt WGMOO 1 lt lt COMO1 csb OCRO ocrval TCNTO 0 DDRB 1 lt lt PB3 Set PB3 0CO as output Connect a 1k resistor and 100uF capacitor in series from PB3 to ground as shown below and measure the voltage across the capacitor using a voltmeter pas pH 2 5 2 16 bit Timer Counter1 The Timer Counterl has more features like two Output Compare Registers Input Cap ture unit etc as shown in figure2 3 The frequency and duty cycle of the waveforms can be controlled better due to the 16 bit size of the counters Some C functions to use the T C1 are given below CHAPTER 2 GETTING STARTED 18 Control Logic TOP BOTTOM Direction Y Timer Counter OCnA H E Req l Waveform OCnA Generation Fixed TOP Int Req Values Waveform OCnB Generation From Analog Comparator Ouput In 1 Edge Detector n r ICPn TCCRnA TCCRnB DATABUS Figure 2 3 16 bit Timer Counterl schematic sqwave tcl csb OCRA example sqwave tcl c include mh timer c uint8 t csb 2 2 is divide by 8 option 1MHz clock in uinti6 t ocra 50000 Output Compare register A int main sqwave tci csb ocra pwm10_tci csb OCRA This function generates a PWM waveform with 1
46. t be called once in the beginning e lcd clear Clears the display e lcd put char char ch Outputs a single character to the LCD display e lcd put string char s Displays a string to the LCD e lcd put byte uint8 t i Diplays an 8 bit unsigned integer e lcd put int uintl6 ti Displays a 16 bit unsigned integer e lcd put long uint32 t i Displays a 32 bit unsigned integer The file mh lcd float c provides led put float float val uint8 t ndec where ndec is the number of decimal places restricted to 3 Defining float type data increases the program size a lot CHAPTER 2 GETTING STARTED 13 2 4 Analog to Digital Converter Most of the I O PORT pins of Atmega32 have alternate functions PAO to PA7 can be used as ADC inputs by enabling the built in ADC All the pins configured as inputs in the DDRA will become ADC inputs but the ones configured as outputs will remain as digital output pins The ADC converts the analog input voltage in to a 10 bit number The minimum value represents GND and the maximum value represents the ADC reference voltage The reference inputs could be AVCC an internal 2 56V or a voltage connected tothe AREF pin The selection is done in software The ADC operation is controlled via the registers ADMUX and ADCSRA The data is read from ADCH and ADCL The include file mh adc c provides the following functions 1 adc enable Enables the ADC 2 adc disable Disables the ADC 3 adc set ref ref Sel
47. text editor like notepad to edit the source program and save it with a c extension The commands for compilation and uploading are C gt avr gcc Wall 02 mmcu atmega32 o blink blink c C gt avr objcopy j text j data 0 ihex blink blink hex C gt avrdude b 19200 P COMxx pm32 c stk500v1 U flash w blink hex Where COMXxx is the virtual com port number assigned by Windows We have found it very difficult due to the arbitrary numbering of the COM ports 1For the old model of microhope using FT232 IC this will be dev tty USBO CHAPTER 4 PROGRAMMING DETAILS 46 11 16 18 PC Parallel Port PC USB PORT mso Target Programmar MOST AVR IC Figure 4 2 USBASP programmer a block diagram b with MicroHOPE 4 2 Serial Loading of Program memory Most of the uCs have the In System Programming ISP feature implemented using three pins Serial ClocK SCK Master In Slave Out MISO and Master Out Slave n MOSI All types of memory on the micro controller can be accessed using the SCK MISO and MOSI pins while holding the RESET pin LOW These pins along with ground are available on the 5 pin header J7 on the microHOPE board For details refer to the circuit schematic shown in figure 1 3 The SPI pins can be accessed by connecting to the Parallel port of the PC using a cable as shown is figure 4 1 We can also use In System Programmers that can be connected to the USB port of the PC We are using
48. the python program echo py listed below using the commands cd microhope python echo py import serial fd serial Serial dev ttyACMO 38400 stopbits 1 timeout 1 0 while 1 c raw_input Enter the character to send fd write c print Receiced fd read We can rewrite echo c without using the library functions The program echo v2 c listed below id functionally identical to echo c include mh lcd c int main void uint8_t data lcd_init 38400 baudrate 8 databit 1 stopbit No parity UCSRB 1 lt lt RXEN 1 lt lt TXEN 5If you are using old microHOPE with FT232 IC edit echo py to replace ttyACMO with ttyUSBO The same thing applies to programs like cro py pymicro py etc CHAPTER 2 GETTING STARTED 23 UBRRH 0 UBRRL 12 At 8MHz 12 gt 38400 UCSRC 1 lt lt URSEL 1 UCSZ1 1 lt lt UCSZO for 1 while UCSRA amp 1 lt lt RXC wait on Rx data UDR read a byte lcd put char data while UCSRA amp 1 lt lt UDRE Rx Empty UDR data 2 6 2 Sending ADC data The program remote adc c listed below on receiving a channel number in 0 to 7 range reads the corresponding channel and send the data to the PC using the UART via the USB to Serial converter Use the Python program remote adc py on the PC side include mh lcd c include mh uart c include mh adc c int main void uint8_t chan low hi uinti6
49. this difficulty CHAPTER 1 INTRODUCTION 3 PORTD ports Jep USB USBto ATMegase Pc PI 9 Serial AVR A 8 MHz emory CPU Peripherals ta Crystal RT S Converter VZZZA 7 ST Jumper Reset g Button PORTC PORTA Jl I A portion of the Flash memory is occupied by the Boot Loader Code Figure 1 1 a MicroHOPE Block diagram Figure 1 2 MicroHOPE board learn how to program the peripherals using the Special Function Registers there is no need to use these library functions MicroHOPE allows you to code in assembly language This feature is included mainly to get a better idea about the architechture of the uC by playing with the registers and assembly instructions directly The content of registers can be displayed using LEDs connected to the I O ports of the micro controller Since microHOPE comes with a bootloader pre installed inside the program memory of Atmega32 you can upload code using the USB interface with a single click from the GUI provided At the same time executing the compile and upload programs from a text terminal are also explained For compiling the C program we use the avr gcc compiler and avrdude for uploading it to the target 1 1 MicroHOPE Hardware A block diagram of microHOPE hardware is shown in figure 1 1 Programs can be up loaded from the PC through the USB port with the help of the pr
50. tors 2 2 3 Blinking LED Making pin PBO HIGH and LOW in a closed loop result in the blinking of the LED conencted to it We need to slow down the rate of blinking so that it can be perceived by our eyes This can be done by making the processor wait for a while between writing to PORTB There are some delay functions provided for this The file mh utils c contains the following functions delay 100us int n This function will make the CPU idle for n x100 microseconds For example to insert a 200 microsecond delay call delay 100us 2 CHAPTER 2 GETTING STARTED 12 delay ms int n This function will make the CPU idle for n milliseconds For example to insert a 500 millisecond delay call delay i ms 500 The program blink c lis listed below include mh utils c int main void DDRB 1 configure PBO as output for 1 PORTB 1 delay ms 500 PORTB 0 delay ms 500 I If everything goes fine you should see the LED blinking You can remove the delay statements and watch the high frequency pulses on PBO using an oscilloscope 2 3 The LCD Display The file mh Icd c contains functions to access the display connected to port C The example program hello c listed below demonstrates the usage of the LCD display include mh lcd c int main lcd_init lcd put string Hello World The file mh lcd c provides the following functions e lcd init Initializes the LCD display mus
51. uest 1 4 006 INT2 External Interrupt Request 2 5 008 TIMER2 COMP Timer Counter2 Compare Match 6 00A TIMER2 OVF Timer Counter2 Overflow 7 00C TIMER1 CAPT Timer Counter1 Capture Event 8 00E TIMER1 COMPA Timer Counter1 Compare Match A 9 010 TIMER1 COMPB Timer Counter1 Compare Match B 10 012 TIMER1 OVF Timer Counter1 Overflow 11 014 TIMERO COMP Timer Counter0 Compare Match 12 016 TIMERO OVF Timer Counter0 Overflow 13 018 SPI STC Serial Transfer Complete 14 01A USART RXC USART Rx Complete 15 01C USART UDRE USART Data Register Empty 16 01E USART TXC USART Tx Complete 17 020 ADC ADC Conversion Complete 18 022 EE_RDY EEPROM Ready 19 024 ANA COMP Analog Comparator 20 026 TWI Two wire Serial Interface 21 028 SPM_RDY Store Program Memory Ready Figure 3 4 Interrupt vectors of Atmega32 Addresses according to a 2byte word arrange ment CPI R16 100 BREQ loopt The branching will happen only if R16 is equal to 100 3 6 3 Interrupt Call from anywhere So far we have seen that the execution flow is decided by the program instructions There are situations where the uC should respond to external events stopping the current program temporarily This is done using Interrupts that are external signals either from the I O pins or from from some of the peripheral devices On receiving an interrupt signal the processor stores the current Program Counter to the memory locatio
52. velopment and testing Ajith Kumar B P V V V Satyanarayana Ambar Chatterjee Jithin B P Georges Khaznadar Jeffrey Antony Kishore T Pramode C E Arun Jayan Akshay M
53. ven though this code has been tested it seems to be having severe limitations Receiver cannot handle data coming a high rates require at least 2 to 3 milliseconds gap between bytes Chapter 3 Coding in Assembly Language Main objective of this chapter is to learn the architecture of the micro controller rather than developing large programs Some examples justifying coding in assembly for better performance will be demonstrated One concern with assembly or machine language cod ing is that the work is specific to the architecture of the selected device The approach will be to examine the architecture in a generic manner and provide some example programs that are more or less common to any kind of processors Major components of a micro controller are shown in figure3 1 After powering up or Reset the Program Counter in initialized to zero so that it points to the beginning of the Program Memory The instruction stored at that location is brought to the Instruction Decoder and executed This could be operations like moving data between the Working Registers and RAM performing some arithmetic and logical operations changing the content of the program counter etc Writing to the Special Function Registers control the Input Output pins and also the operation of peripheral devices like ADC Timer Counter etc The popular family of micro controllers like 8051 AVR and PIC follows the same architechture even though the details may differ Und
54. will set that data on them For example PORTA 1 will make PAO high that can be measured on the pin number 40 of the IC e PINX For the pins configured as inputs PINX will read the status of the external voltage level connected to the pins For pins that are configured as outputs PINX will return the data written to PORTX If the pins configured as inputs are left unconnected there could be unwanted level changes due to electrical noise this can be prevented by enabling the internal pull up resistor For pins that are configured as inputs setting clearing the bits in PORTX will enable disable the corresponding internal pullup resistor The operations described above can be understood easily with some examples For a quick test MicroHOPE hardware has an LED connected to PBO with a series resistor for current limiting 2 2 1 Reading and Writing Ports The program copy c reads the voltage level at PAO Pin 0 of Port A and sets the same on PBO where we have the LED We will enable the internal pullup resistor on PAO so that and it will go LOW only when it is connected to ground using a piece of wire include lt avr io h gt Include file for I O operations int main void DDRA 0 Port A as Input PORTA 1 Enable pullup on PAO DDRB 1 Configure PBO as output fori CHAPTER 2 GETTING STARTED 10 PORTB PINA Read Port A and write it to Port B To test this example open copy c from the File menu o
55. x Tx pins are available to the user on the four I O connectors An LED is connected to Bit 0 of Port B for quick testing of the board A reset button is also provided The 5V USB power via a fuse is connected to both VCC and AVCC inputs A jumper is provided to disable the reset option from the PC required when the board is running programs that need to communicate with a PC like a data logger or oscilloscope The circuit schematic is shown in figure 1 3 1 2 Accessories There are several accessory boards that can be plugged in to the I O sockets Some of them are explained below Visit the website to know about new additions 1 2 1 Digital Output Board 8 LEDs This can be plugged into any of the four ports to monitor the output useful for debugging code CHAPTER 1 INTRODUCTION 5 PORTC P2 OOCOOOCO Figure 1 6 H Bridge board 1 2 2 Alphanumeric LCD For some applications it is necessary to have a local display The HD44780 controller or compatible IC based LCD displays are widely available They come with a 16 pin connector and the transfer protocol is well documented The connections between microHOPE and the LCD display are shown in figure 1 5 a Pins 4 5 and 7 of the LCD display are control lines connected to PC1 PC2 and PC4 The ASCII codes are transferred in the
Download Pdf Manuals
Related Search
now now.gg nowthatstv nowgoal now portal now tv now you see me 3 now.gg roblox now you see me 2 now stock now foods nowadays now hiring now hiring near me nowthatstv login now learning now playing now wifi pass now gg talkie now habersham now xfinity now we are free now gg roblox online now gg free fire
Related Contents
ABOUT THIS MANUAL ParSec Data Display & Entry Panel (DDE) INSTALLATION & USER Philips AUDIO-AFSPILLER SA4125 User's Manual GE JES0734PMRR User's Manual RCIM UNIT - Hitachi Air Conditioning Recetas que impulsan la vida y extraen nutritivos layman. - TeXdoc.net La CGT dans les TPE Enjeux des élections et de notre représentativité カタログ Copyright © All rights reserved.
Failed to retrieve file