Está en la página 1de 39

Ensamblador del AVR

San Luis Potosí, México Prof. Carlos E. Canto Quintal


Ensamblador del AVR

Lenguajes de alto Nivel


Pascal
C++
Visual C
etc

Ensamblador

Lenguajes de bajo Nivel


Lenguaje de máquina

1000110101

San Luis Potosí, México Carlos Canto Quintal


Ensamblador del AVR

San Luis Potosí, México Prof. Carlos E. Canto Quintal


Ensamblador del AVR

San Luis Potosí, México Prof. Carlos E. Canto Quintal


Ensamblador del AVR

• Corto y fácil
• Rápido
• Fácil de aprender (¿será?)
• Los AVRs son ideales para aprender
ensamblador

San Luis Potosí, México Prof. Carlos E. Canto Quintal


Ensamblador del AVR

Archivo
objeto • Es un programa que corre
Fuente en la PC ( generealmente),

Ensamblador Archivo • “Traduce” el código fuente


hex
(escrito por el usaurio) a
lenguaje de Máquina para
include el microcontrolador
files
Archivo
Archivo map
list

San Luis Potosí, México Prof. Carlos E. Canto Quintal


Ensamblador del AVR

• Es generalmente un archivo que contiene las


sentencias en lenguaje ensamblador
• Las directivas Include se usan para insertar
texto de otros archivos como parte del fuente.

San Luis Potosí, México Prof. Carlos E. Canto Quintal


Ensamblador del AVR

• Contiene el programa en máquina e


información de depurado usada por el AVR
studio

San Luis Potosí, México Prof. Carlos E. Canto Quintal


Ensamblador del AVR

• Contiene datos para la memoria flash del


procesador AVR
• Este es usado por la utilería del programador
para descargar a la memoria del AVR

San Luis Potosí, México Prof. Carlos E. Canto Quintal


Ensamblador del AVR

• Un listado de etiquetas y símbolos usados en el


programa
• Sirve como referencia para localizar datos en la
memoria

San Luis Potosí, México Prof. Carlos E. Canto Quintal


Ensamblador del AVR

• Un reporte completo del proceso de


ensamblado
– Incluye mensajes de error, información de
direcciones, bytes generados y estadísticas

San Luis Potosí, México Prof. Carlos E. Canto Quintal


Ensamblador del AVR

Cada línea de programa es una de las siguientes posibles:


 Una directiva de ensamblador (o pseudo-instrucción)
 Una instrucción
 Un Comentario
 Una etiqueta
Los espacios en blanco entre símbolos son ignorados
Los comentarios también son ignorados (comienzan con “;” Cualquier línea
puede tener un comentario)
Una instrucción tiene el siguiente formato:
LABEL : OPCODE OPERANDS ; COMMENTS

Obligatorio

Opcional
San Luis Potosí, México Prof. Carlos E. Canto Quintal
Ensamblador del AVR

 Las líneas de código no debe exceder 120 caracteres


 Cada línea de entrada puede ser precedida por una etiqueta
, la cual es una cadena alfanumérica terminada con dos
puntos
 Las etiquetas se usan como objetivo en instrucciones JUMP y
Branch y como nombre de variables en memoria de
programa y RAM
 Una línea de entrada puede tomar una de las siguientes
formas:
1. [Etiqueta:] directiva[operandos] [Comment]
2. [Etiqueta:] instrucción [operandos] [Comentario]
3. Comentario
4. Línea vacía

San Luis Potosí, México Prof. Carlos E. Canto Quintal


Ensamblador del AVR

• Comentario de una sola línea


– Comienza con un punto y coma (;) o doble
diagonal (//) y extendido hasta el final de la línea
• Bloque de comentarios
– Comienza con /*, termina */, y puede abarcar
varias líneas

San Luis Potosí, México Prof. Carlos E. Canto Quintal


Ensamblador del AVR

• El ensamblador soporta un número de


directivas
• Las directivas no son traducidas directamente
a códigos de operación.
• Son usadas para ajustar localidades del
programa en la memoria , definen macros,
etc.

San Luis Potosí, México Prof. Carlos E. Canto Quintal


Ensamblador del AVR

Las Pseudo instrucciones comienzan con un punto. Algunas


importantes son:

.def simbolo = registro le asigna un nombre a un


registro
.equ simbolo = expresion le asigna un simbolo a una expresión
.set simbolo = expresion como .equ pero puede ser
reasignado
.include “nombre de archivo" incluye un archivo en el
directorio del proyecto o en el
conjunto de archivos provistos
por el ensamblador, como
“m328pdef.inc”
.org direccion Ensambla en una dirección

San Luis Potosí, México Prof. Carlos E. Canto Quintal


Ensamblador del AVR

Ejemplos:

label: .EQU var1=100 ; hace var1 igual a 100 (Directive)


.EQU var2=200 ; hace var2 igual a200
test: rjmp test ; loop Infinito (Instrucción)
; línea de solo comentario
; otra línea de comentario

San Luis Potosí, México Prof. Carlos E. Canto Quintal


Ensamblador del AVR

label: .db expresion, expresion... ……Define bytes constantes


label: .dw expression, expression......Define plabras constantantes
label: .byte numero ………………………..Reserva bytes

San Luis Potosí, México Prof. Carlos E. Canto Quintal


Ensamblador del AVR

• El ensamblador genera bytes para la flash y la


EEPROM y reserva las direcciones de la
SRAM
• Las directivas de segmento ponen la memoria
activa para comandos subsecuentes
– .cseg – code segment (flash)
• Este es el segmento por “default” que toma el
ensamblador si no se especifica ninguno.
– .eseg – EEPROM
– .dseg – data segment (SRAM)

San Luis Potosí, México Prof. Carlos E. Canto Quintal


Ensamblador del AVR

• El ensamblador mantiene un contador de


localización para cada segmento.
.org valor
– Pone al contador de localización del segmento en
cuestión al “valor” especificado.
• El origen por default para el segmento de código y
EEPROM es 0x0000
• El contador de localización para el segmento de datos
es la primera dirección que sigue a los registros de E/S
(0x0060).

San Luis Potosí, México Prof. Carlos E. Canto Quintal


Ensamblador del AVR

Una macro permite la utilización repetida de secuencias de instrucciones. Por


ejemplo:
.MACRO Delay
nop
nop
nop
nop
.ENDMACRO
; instrucciones
Delay
; más instrucciones
Una macro no ahorra espacio de memoria puesto que al compilar la etiqueta
de la macro es reemplazada por el conjunto de instrucciones
correspondientes. Para el caso de querer ahorrar espacio se emplean las
subrutinas.
San Luis Potosí, México Prof. Carlos E. Canto Quintal
Ensamblador del AVR

Includes,
Defines,
Equates, .include “m328pdef.inc”
Etc. .def temp=r16

Definición del ldi temp,high(RAMEND)


STACk OUT SPH,temp
Ldi temp,low(RAMEND)
OUT SPL,temp
Configuraciones
PORTs,
TIMERS, ldi temp,0XFF
USART, OUT DDRD,temp
ADC, etc

ldi temp,0xff
OUT POTRD,temp
Programa Call delay
………..
………
San Luis Potosí, México Prof. Carlos E. Canto Quintal
Ensamblador del AVR

Ensamblado del programa


• Después de crear un proyecto nuevo , el
programa fuente es ensamblado usando el
comando”Build “.
– La opción de crear un archivo de listado debe ser
seleccionado bajo las opciones del ensamblador
bajo el menú de “Project”
• Si ocurren errores, corregir y re-ensamblar.

San Luis Potosí, México Prof. Carlos E. Canto Quintal


Ensamblador del AVR

Programa LEDs Flasher


/* * leds_flasher.asm
* Created: 16/09/2015 10:10:04 a. m.
* Author: Carlos Canto */
;un ejemplo simple de programa para el AVR mega328Ppara ilustrar la salida a un puerto.
;Diseñado para ser ejecutado en un simulador bajo el control del debug
;este programa cuenta de 0 a 255 (y repite) sacando al puerto
;el valor actual del contador al PUERTO B.

.include "m328pdef.inc"
.def cuenta= r16 ;el registro 16 contendrá el valor del contador
.def temp= r17 ;registro usado como temporal
ldi temp,0xFF ;configuración del PORTB como salida
out DDRB,temp
ldi cuenta,0x0 ;Inicializar conteo a 0
sigue: out PORTB,cuenta ;Put counter value on PORT B
inc cuenta ;incrementa contador
jmp sigue ;repetir (por siempre)

San Luis Potosí, México Prof. Carlos E. Canto Quintal


Simulating the Program
• Start debugging (Debug menu)
• Select the I/O View and be sure
that Register 16, the Processor,
and PORT B are visible
• Single step, observing changes
in the I/O View
– Use Auto-step to run the
simulator while observing
changes at each step

Dr. Tim Margush - Assembly Language


2/27/2016 25
Programming
Program Flash from HEX
• On the Program Tab, you
can accept defaults for
everything but the input file
under Flash
– Use the browse (…) button to
locate the HEX file with the
same name as your project
– It will be in the project folder
• Click Program when ready

Dr. Tim Margush - Assembly Language


2/27/2016 26
Programming
Internal Clock Speed
• This program runs too fast
under the default processor
settings (4MHz internal
oscillator)
– The LEDs appear to all stay
illuminated
• Under the Fuses tab, select
the Ext. Clock
– Click Program to send the
options to the processor
External Clock
• Under the Board tab, set
the STK500 Osc to 1024Hz
and click Write
– The processor should run
slow enough to observe the
leading bit cycling once per
second
– Note that the dialog indicates
the clock will be set to the
attainable frequency of 1019
Hz
• Not all frequencies can be
produced exactly
Backwards Counter
• You should notice that the counter appears to
run backwards
• The circuit used to control the LEDs causes the
LED to emit light when the port output is 0
– 00000000
– 00000001
– etc… appears to be counting backwards
External Oscillator
• Be sure to set the STK500 Osc back to a larger value (4 MHz is
fine) before downloading other programs
– You must click Write to send the setting to the processor

• If this value is too slow, the programmer cannot download


code to flash
Tools for AVR assembly programing
Four programs are necessary for this. These
tools are:
• the editor,
• the assembler program,
• the chip programing interface, and
• the simulator.
Developing software and hardware for
microcontroller based systems involves the use of
a range of tools that can include
• editors
• assemblers, compilers,
• debuggers
• simulators
• emulators
• and Flash/OTP programmers.
The typical microcontrollers firmware development cycle,
which involves:
• Writing the code
• Translating the code
• Debugging the code with the help of debugging tools,
including emulators
• Programming a Flash or OTP version of the
microcontroller to built up a first functional prototype of
your system
1. Writing Microcontroller Code

• Software Code for a microcontroller is written in a


programming language of choice (often Assembler or C).
This source code is written with a standard ASCII text
editor and saved as an ASCII text file. Programming in
assembler involves learning a microcontroller's specific
instruction set (assembler mnemonics), but results in the
most compact and fastest code. A higher level language like
C is for the most part independent of a microcontroller's
specific architecture, but still requires some controller
specific extensions of the standard language to be able to
control all of a chip's peripherals and functionality. The
penalty for more portable code and faster program
development is a larger code size (20%...40% compared to
assembler).
2. Translating the Code
• Next the source code needs to be translated into
instructions the microcontroller can actually execute. A
microcontrollers instruction set is represented by "op
codes". Op codes are a unique sequence of bits ("0"
and "1") that are decoded by the controller's
instruction decode logic and then executed. Instead of
writing opcodes in bits, they are commonly
represented as hexadecimal numbers, whereby one
hex number represents 4 bits within a byte, so it takes
two hex numbers to represent 8 bits or 1 byte. For that
reason a microcontroller's firmware in machine
readable form is also called Hex-Code and the file that
stores that code Hex-File.
• Assemblers, Compilers, Linkers and Librarians
• Assemblers or (C-) Compilers translate the human readable source code
into "hex code" that represents the machine instructions (op codes). To
support modular code and reusable libraries of code, most assemblers and
compilers today come with Linkers and Librarians.
• Linkers, link code modules saved in different files together into a single
final program. At the same time they take care of a chip's memory
allocation by assigning each instruction to a microcontroller memory
addresses in such a way that different modules do not overlap.
• Librarians help you to manage, organize and revision control a library of
re-usable code modules.
• Once the ASCII source code text file has been assembled (with an
Assembler) or compiled (with a Compiler) and the files have been linked
(with the Linker), the output results in a number of files that can be used
for debugging the software and programming the actual microcontroller's
memory.
• An Integrated Development Environment puts all of the previously
discussed software components under one common unified user
interface, so that it becomes possible to make a code change and
get the modified code loaded into the emulator with a few mouse
clicks, instead of dozens. A good IDE allows you for example to click
on a syntax error message produced by the compiler and have the
source code with the highlighted offending instruction pop up for
editing in the text editor. One click of a button and the modified
code gets retranslated, linked and downloaded to the emulator. An
IDE allows you to store the configuration settings for a project - like
compiler switches, or what flavor of chip to emulate - so you can
easily recreate a project later on. Some IDEs are flexible enough to
allow you to incorporate different choices of third party tools (like
compilers and debuggers), others only work with a manufacturer's
own tool chain.
3. Depurado del código (Debugging)
• Un debugger es una pieza de software que corre en la PC, el cual tiene
que estar fuertemente integrado con el emulador que se use para
validar el código. Por esa razón todos los fabricantes de emuladores
sacan su propio software debugger junto con sus herramientas, pero
también los fabricantes de compiladores fercuentemente incluyen
debuggers, el cual trabaja con ciertos emuladores, dentro de sus
paquetes de desarrollo.
• Un debugger permite descargar nuestro código a la memoria del
emulador y para así controlar todas las funciones del emulador desde
la PC. Tareas comunes de los debuggers incluyen la capacidad de
examinar y modificar los registros en chip del microcontrolador, datos -y
memoria de programa; pausar o parar la ejecución del programa en
localidads definidas de memoria configurando puntos de ruptura
(breakpoints); ejecución del código una instrucción a la vez (single
stepping) ; y observanado la historia del código ejecutado (trace) .
• Simulators
• Simulators try to model the behavior of the complete microcontroller in
software. Some simulators go even a step further and include the whole
system (simulation of peripherals outside of the microcontroller). No
matter how fast your PC, there is no simulator on the market that can
actually simulate a microcontroller's behavior in real-time. Simulating
external events can become a time-consuming exercise, as you have to
manually create "stimulus" files that tell the simulator what external
waveforms to expect on which microcontroller pin. A simulator can also
not talk to your target system, so functions that rely on external
components are difficult to verify. For that reason simulators are best
suited to test algorithms that run completely within the microcontroller
(like a math routine for example). They are the perfect tool to complement
expensive emulators for large development teams, where buying an
emulator for each developer is financially not feasible.

También podría gustarte