Sunteți pe pagina 1din 153

SISTEMAS BASADOS EN

MICROCONTROLADORES 1
SISTEMA DE ORDENADORES
Clasificacin segn su capacidad de
trabajo y tratamiento de datos

Mainframes

Miniordenadores

Microordenadores
DEFINICIN DE TRMINOS BSICOS

HARDWARE Circuitos y componentes fsicos

SOFTWARE Conjunto de instrucciones

Conjunto de instrucciones y
FIRMWARE
programas
CAMPOS DE APLICACIN
CAMPOS DE APLICACIN
CLASIFICACIN DE UN SISTEMA
MICROPROCESADO SEGN SU FUNCIONALIDAD

CISC (Complex
Juego complejo de ms de 80 instrucciones
Instruction Set Muchos ciclos de reloj
Computer)

RISC (Reduced
Juego reducido de instrucciones
Instruction Set Un ciclo de reloj
Computer)

SISC (Specific
Instruction Set Juego especfico de instrucciones
Computer)
CLASIFICACION DE UN SISTEMA
MICROPROCESADO SEGN SU ARQUITECTURA
INTERNA
Von Neumann
CLASIFICACION DE UN SISTEMA
MICROPROCESADO SEGN SU ARQUITECTURA
INTERNA
Harvard
EJEMPLO DE UN SISTEMA MICROPROCESADO
ARQUITECTURA
INTERNA 2
CONCEPTO DE UN MICROPROCESADOR
Circuito integrado o chip formado por millones de transistores construidos sobre
una oblea de silicio.

decodificar coordinar y
y ejecutar controlar
La unidad central de procesamiento (CPU) tambin se denomina
microprocesador o simplemente el procesador. Es un circuito integrado
compuesto por millones de transistores.

Qu es?

CPU

Qu hace?

Su principal funcin es interpretar y ejecutar las instrucciones


contenidas en los programas y procesar los datos.
Varios CORES que
procesan instrucciones
CPU
Memoria Cach de nivel
actual L2 propia de cada CORE

Memoria Cach de nivel


Integra L3 compartida por todos
los CORES

La controladora de
memoria (RAM)

Interface

Una GPU integrada


(IGP)*
Es SINCRONO. Por tanto hay un reloj Hoy en da, la mayora de los
digital que se encarga de marcar los procesadores, tienen una velocidad
momentos en los que operar. Su BASE y otra mayor en modo TURBO
velocidad se mide en MHz o GHz. (cuando ms carga de trabajo hay).

Funcionamiento CPU Frecuencias


ARQUITECTURA INTERNA
ACTUAL
BUSES DEL SISTEMA
ARQUITECTURA INTERNA
Con los nuevos procesadores multincleo aparecen nuevos elementos en el
procesador:

Controlador de Memoria Integrado (IMC)


Se sustituye el FSB por un bus de sistema de alta velocidad INTEL QPI
o AMD HT
CARACTERISTICAS
3
CARACTERISTICAS DEL MICROPROCESADOR
Las caractersticas principales que determinan lo bueno/malo que es un
microprocesador, es decir, sus prestaciones son las siguientes:

Anchura de los buses de datos y direcciones

Tamao de la memoria cach

Frecuencia de reloj a la que trabaja (velocidad interna)

Frecuencia a la que trabaja el bus de sistema (velocidad externa)

Densidad de integracin

Alimentacin (voltaje)
CARACTERISTICAS DEL MICROPROCESADOR

ANCHURA DE LOS BUSES

Bus de datos
Representa el dato ms grande que es capaz de manejar el microprocesador
en una sola operacin.
Adems, el tamao de este bus determina el ancho de palabra de la
memoria principal.

Bus de direcciones
El tamao de este bus determina la cantidad mxima de memoria que
podemos direccionar.
Con 32 bits de ancho de bus podremos direccionar hasta 4 GB (232).
Actualmente casi todos los microprocesadores disponen de buses de
direccionamiento de 64 bits por lo que podran direccionar 16 exabytes.
CARACTERISTICAS DEL MICROPROCESADOR

MEMORIA CACH

Se trata de memorias de tamao mucho ms pequeo y de velocidades


mucho mayores que la memoria RAM.
En ellas se almacenan las ltimas instrucciones procesadas o las futuras a
procesar junto con sus datos.
CARACTERISTICAS DEL MICROPROCESADOR
CARACTERISTICAS DEL MICROPROCESADOR
CARACTERISTICAS DEL MICROPROCESADOR

VELOCIDAD INTERNA DEL PROCESADOR

Se trata de la frecuencia de reloj interna a la que trabaja el


microprocesador.

En general, cuanto mayor sea la velocidad del procesador


mayor nmero de operaciones por unidad de tiempo realiza
mayor rendimiento.
CARACTERISTICAS DEL MICROPROCESADOR

La velocidad de un procesador se mide por la


cantidad de operaciones que realiza en un segundo.

La velocidad se mide en Hertzios (Hz):

1 Hz representa una operacin por segundo.

1 Mhz (MegaHertzio) es un milln de operaciones por segundo.

1 Ghz (GigaHertzio) son 1.000 millones de operaciones por segundo.


CARACTERISTICAS DEL MICROPROCESADOR
CARACTERISTICAS DEL MICROPROCESADOR
CARACTERISTICAS DEL MICROPROCESADOR

DENSIDAD DE INTEGRACIN

Indica la separacin que hay entre los transistores


que forman el microprocesador.
Tambin se conoce como tecnologa de fabricacin
y se mide en micras/micrmetros (mn) o
nanmetros (nm).
Mayor densidad de integracin mayor nmero
de componentes mayor rendimiento.
CARACTERISTICAS DEL MICROPROCESADOR

ALIMENTACIN O VOLTAJE

A mayor voltaje mayor frecuencia de


funcionamiento del procesador pero tambin
mayor calor disipado y mayor consumo de energa.
En la actualidad se utiliza un parmetro conocido
como Thermal Design Power (TDP) para
representar la mxima cantidad de calor que
necesitar disipar el microprocesador.
SEGMENTACION
4
SEGMENTACIN
SEGMENTACIN
Ejemplo 1
SEGMENTACIN
Ejemplo 1
SEGMENTACIN
Ejemplo 2
SEGMENTACIN
Ejemplo 2: Secuencial
SEGMENTACIN
Ejemplo 2. Con Segmentacin
SEGMENTACIN
SEGMENTACIN
CLCULO DE LA ACELERACIN
CLCULO DE LA ACELERACIN O SPEED UP
Ejercicio 1
SEGMENTACIN
SEGMENTACIN
SEGMENTACIN
Extraccin de la Instruccin
SEGMENTACIN
Decodificacin
SEGMENTACIN
Ejecucin
SEGMENTACIN
Memoria
SEGMENTACIN
Escritura
SEGMENTACIN
Ciclo de una Instruccin
SEGMENTACIN

Reducir el tiempo de ejecucin mejora el rendimiento.


Ejemplo: usar una versin ms rpida de un
procesador.

Mejorar el rendimiento mejora el tiempo de respuesta.


Ejemplo: aumentar el nmero de ncleos en un
procesadores

21
SEGMENTACIN
Tiempo de ciclo
Tiempo de ciclo debe permitir que una instruccin pase por todas las
etapas en un ciclo.

Tiempo de respuesta (latencia)


Tiempo entre el comienzo y la finalizacin de una instruccin.

Throughput
Rendimiento.
Nmero de instrucciones por unidad de tiempo.
1
=

22
SEGMENTACIN
EJERCICIO 1
Las 5 etapas del procesador tienen las siguientes latencias:

Instrucciones Fetch Decode Execute Memory Writeback

A 300ps 400ps 350ps 550ps 100ps


B 200ps 150ps 100ps 190ps 140ps

Cada etapa supone 20ps extra debido a los registros entre etapas en
procesadores segmentados.
Con un procesador no segmentado, calcular:
Cul es el tiempo de ciclo?
Cul es la latencia de cada instruccin?
Cul es el rendimiento?

23
SEGMENTACIN
EJERCICIO 2
Las 5 etapas del procesador tienen las siguientes latencias:

Instrucciones Fetch Decode Execute Memory Writeback

A 300ps 400ps 350ps 550ps 100ps


B 200ps 150ps 100ps 190ps 140ps

Cada etapa supone 20ps extra debido a los registros entre etapas en
procesadores segmentados.
Con un procesador segmentado, calcular:
Cul es el tiempo de ciclo?
Cul es la latencia de cada instruccin?
Cul es el rendimiento?

24
SEGMENTACIN
ETAPA 1 ETAPA 2 ETAPA 3 ETAPA

FRECUENCIA = CICLOS POR SEGUNDO


1 Hz = 1 cycle/sec
1 KHz = 103 cycles/sec
1 MHz = 106 cycles/sec
1 GHz = 109 cycles/sec
2 GHz clock has a cycle time = 2109 cycles/sec

1 .
= =

SEGMENTACIN

EJERCICIO 3

En un procesador segmentado con 4 etapas los tiempos


consumidos por las etapas son 1, 1.75, 1.5 y 1.25
nanosegundos. Adems, el tiempo de comunicacin de
datos de una etapa a otra es de 0.25 nanosegundos. Cul
ser la mxima frecuencia de reloj utilizable en el
procesador?
SEGMENTACIN
EJERCICIO 4

Un programa se ejecuta en 10 segundos en el


microprocesador X a 2 GHz
Cual es el nmero de ciclos de reloj?

Se desea que el microprocesador Y corra el mismo programa


en 6 segundos, pero Y necesita un 10% ms de ciclos
Cual debe ser la frecuencia de reloj de Y?
SEGMENTACIN

Un programa corre en 10 segundos en el microprocesador X a 2 GHz


Cual es el nmero de ciclos de reloj?
.
=

. =
= 10 2 109 = 20 109

Queremos que el microprocesador Y corra el mismo programa en 6


segundos, pero Y necesita un 10% ms de ciclos
Cual debe ser la frecuencia de reloj de Y?
= 1.1 20 109 = 22 109
. 22 109
= = = 3.67
6
SEGMENTACIN
CICLO POR INSTRUCCIN - CPI


= =

Ejemplo:


=

14
=
7
= 2
SEGMENTACIN
CICLO POR INSTRUCCIN CPI

EJERCICIO 5

Para un programa dado se ejecuta 10 instrucciones


El microprocesador A tiene un reloj con perodo 250 ps y CPI de 2.0
El microprocesador B tiene un reloj con perodo 500 ps y CPI de 1.2
Qu microprocesador es ms rpida y por cuanto?
SEGMENTACIN
CICLO POR INSTRUCCIN CPI
EJERCICIO 5
Para un programa dado se ejecuta 10 instrucciones
El microprocesador A tiene un reloj con perodo 250 ps y CPI de 2.0
El microprocesador B tiene un reloj con perodo 500 ps y CPI de 1.2
Qu microprocesador es ms rpida y por cuanto?

A: =
= 10 2 250 = 5000

B: =
= 10 1.2 500 = 6000
SEGMENTACIN
CICLO POR INSTRUCCIN - CPI

CPIi= ciclos por instruccin del tipo i


Ci= nmero de instrucciones del tipo i
SEGMENTACIN
CLCULO DEL CPI
EJERCICIO 6
Un diseador de cdigo decide entre dos secuencias de cdigo
para una microprocesador. Hay tres tipos de instrucciones
Clase A: requiere 1 ciclo/instr
Clase B: requiere 2 ciclo/instr
Clase C: requiere 3 ciclo/instr
El primer cdigo tiene 5 instrucciones: 2 de A, 1 de B, y 2 de C
El segundo cdigo tiene 6 instrucciones: 4 de A, 1 de B, y 1 de C

Calcular los ciclos de CPU para cada cdigo. Cul es ms rpido?


Cul es la CPI de cada programa?
SEGMENTACIN
CLCULO DEL CPI
EJERCICIO 6

A.
Ciclos CPU (1 programa) = (21) + (12) + (23) = 2+2+6 = 10 ciclos
Ciclos CPU (2 programa) = (41) + (12) + (13) = 4+2+3 = 9 ciclos

El segundo programa es ms rpido, an ejecutando una instruccin


ms.

B.
CPI (1r programa) = 10/5 = 2
CPI (2 programa) = 9/6 = 1.5
RELANTIZACIN DE LA SEGMENTACIN
RELANTIZACIN DE LA SEGMENTACIN
RELANTIZACIN DE LA SEGMENTACIN
RELANTIZACIN DE LA SEGMENTACIN
RELANTIZACIN DE LA SEGMENTACIN
Dependencia de datos
RELANTIZACIN DE LA SEGMENTACIN
Dependencia de datos
RELANTIZACIN DE LA SEGMENTACIN
Dependencia de datos
RELANTIZACIN DE LA SEGMENTACIN
Dependencia de datos
RELANTIZACIN DE LA SEGMENTACIN
Dependencia de datos
MEMORIA
4
MEMORIA
MEMORIA
MEMORIA
MEMORIA
MEMORIA

Ta = Tiempo de acceso
Tc = Tiempo de ciclo de memoria
MEMORIA
MEMORIA

Tamao de la palabra

Unidad direccionable

Unidad de transferencia
TIPOS DE MEMORIA

MEMORIAS DE SLO LECTURA

ROM

PROM
MEMORIA
MEMORIA DE SOBRE TODO LECTURA

EPROM

EEPROM

MEMORIA FLASH
MEMORIA

MEMORIA DE LECTURA Y ESCRITURA

RAM DINMICA (DRAM)

RAM ESTTICA (SRAM)


MEMORIA
MEMORIA
CHIP DE MEMORIA
MEMORIA
MEMORIA
MEMORIA
Agrupacin por longitud de celdas
MEMORIA
Agrupacin por direcciones

Sistema con memoria


16K x 8
MEMORIA
Agrupacin por direcciones
MEMORIA

PROCEDIMIENTO PARA EL DISEO DE UN MAPA DE MEMORIA EN UN


SISTEMA BASADO EN MICROPROCESADOR:

1. Detallar las necesidades del sistema en cuanto a direccionamiento,


tamao de palabra y tipo de memoria a utilizar (RAM/ROM).
2. Determinar los circuitos integrados de que se dispone, tanto en
longitud como en tamao de palabras y definir los que se necesitan.
3. Construir el mapa de memoria.
4. Disear la tabla de direcciones y ocupacin de cada circuito integrado.
5. Determinar la circuitera auxiliar necesaria para el control del circuito.
6. Dibujar el circuito completo de la memoria.
MEMORIA
MEMORIA
MEMORIA

Ejemplo 3:
Supngase una memoria RAM de 1024 palabras
16 bits/palabra construida empleando circuitos
integrados de memoria RAM de 128 palabras 8
bits/palabra. A fin de permitir el direccionamiento
de las palabras de la memoria, calcular:
a) El nmero de lneas del bus de direcciones
b) El nmero de lneas del bus de direcciones
comunes a todos los mdulos.
MEMORIA

Ejemplo 4:
Disear el mapa de memoria de un sistema basado
en microprocesador para el 8085 de INTEL
(A0..A15, D0..D7), suponiendo que se necesitan
8K8 de memoria ROM, 4K8 de memoria RAM.
Se disponen de circuitos integrados ROM de 2K8
y circuitos integrados RAM de 2K8 y que la
memoria est situada a partir de la direccin $0
empezando por la ROM y colocando a continuacin
la RAM
MICROPROCESADOR
8086
CARACTERSTICAS PRINCIPALES
ARQUITECTURA DEL 8086
PROGRAMACIN DEL 8086
PROGRAMACIN DEL 8086
REGISTRO DE DATOS O DE PROPSITO GENERAL
PROGRAMACIN DEL 8086
REGISTRO DE SEGMENTO
PROGRAMACIN DEL 8086
REGISTRO DE PILA
PROGRAMACIN DEL 8086
PUNTERO DE INTRUCCIONES O CONTADOR DEL PROGRAMA
PROGRAMACIN DEL 8086
REGISTROS NDICES
PROGRAMACIN DEL 8086
REGISTROS DE ESTADO O DE INDICADORES (FLAG)
Es un registro de 16 bits de los cuales 9 son utilizados para indicar
diversas situaciones durante la ejecucin de un programa.

Los bits 0, 2, 4, 6, 7 y 11 son indicadores de condicin, que reflejan los


resultados de operaciones del programa.

Los bits del 8 al 10 son indicadores de control y el resto no se utilizan.

Estos indicadores pueden ser comprobados por las instrucciones de


salto condicional, lo que permite variar el flujo secuencial del
programa segn el resultado de las operaciones.
PROGRAMACIN DEL 8086
REGISTROS DE ESTADO O DE INDICADORES (FLAG)
PROGRAMACIN DEL 8086
REGISTROS DE ESTADO O DE INDICADORES (FLAG)
PROGRAMACIN DEL 8086
ESPACIO DE MEMORIA
PROGRAMACIN DEL 8086
SEGMENTACIN
PROGRAMACIN DEL 8086
MODOS DE DIRECCIONAMIENTO
PROGRAMACIN DEL 8086
MODOS DE DIRECCIONAMIENTO
PROGRAMACIN DEL 8086
ESPACIO DE ENTRADA Y SALIDA
PROGRAMACIN
PROGRAMACIN DEL 8086

DEFINICIN DE VARIABLES
PROGRAMACIN DEL 8086

DEFINICIN DE VARIABLES
PROGRAMACIN DEL 8086
FORMATO DE LAS INSTRUCCIONES
INSTRUCCIONES DE MOVIMIENTO DE DATOS
INSTRUCCIONES ARITMTICAS
INSTRUCCIONES ARITMTICAS
INSTRUCCIONES ARITMTICAS
INSTRUCCIONES ARITMTICAS
INSTRUCCIONES LGICAS
INSTRUCCIONES LGICAS
INSTRUCCIONES LGICAS
INSTRUCCIONES LGICAS
INSTRUCCIONES LGICAS
INSTRUCCIONES DE SALTO
INSTRUCCIONES DE SALTO
INSTRUCCIONES DE SALTO
UNIVERSIDAD TCNICA DEL NORTE
FACULTAD DE INGENIERIA EN CIENCIAS APLICADAS
CARRERA DE MECATRNICA

PROGRAMACION EN LENGUAJE ENSAMBLADOR

INTERRUPCIONES

INT 21h
INT 10h/00h INT 21h/35h
INT 21h/01h
INT 10h/01h INT 10h/1003h INT 21h/39h
INT 21h/02h
INT 10h/02h INT 11h INT 21h/3Ah
INT 21h/05h
INT 10h/03h INT 12h INT 21h/3Bh
INT 21h/06h
INT 10h/05h INT 13h/00h INT 21h/3Ch
INT 21h/07h
INT 10h/06h INT 13h/02h INT 21h/3Dh INT 33h/0000h
INT 21h/09h
INT 10h/07h INT 13h/03h INT 21h/3Eh INT 33h/0001h
INT 21h/0Ah
INT 10h/08h INT 15h/86h INT 21h/3Fh INT 33h/0002h
INT 21h/0Bh
INT 10h/09h INT 16h/00h INT 21h/40h INT 33h/0003h
INT 21h/0Ch
INT 10h/0Ah INT 16h/01h INT 21h/41h
INT 21h/0Eh
INT 10h/0Ch INT 19h INT 21h/42h
INT 21h/19h
INT 10h/0Dh INT 1Ah/00h INT 21h/47h
INT 21h/25h
INT 10h/0Eh INT 20h INT 21h/4Ch
INT 21h/2Ah
INT 10h/13h INT 21h/56h
INT 21h/2Ch

INT 10h / AH = 0 - set video mode.


input:
AL = desired video mode.

these video modes are supported:

00h - text mode. 40x25. 16 colors. 8 pages.

03h - text mode. 80x25. 16 colors. 8 pages.

13h - graphical mode. 40x25. 256 colors. 320x200 pixels. 1 page.


example:

mov al, 13h


mov ah, 0
int 10h

INT 10h / AH = 01h - set text-mode cursor shape.


input:
CH = cursor start line (bits 0-4) and options (bits 5-7).
CL = bottom cursor line (bits 0-4).

when bit 5 of CH is set to 0, the cursor is visible. when bit 5 is 1, the cursor is not visible.

; hide blinking text cursor:


mov ch, 32
mov ah, 1
int 10h

; show standard blinking text cursor:


mov ch, 6
mov cl, 7
mov ah, 1
int 10h

; show box-shaped blinking text cursor:


mov ch, 0
mov cl, 7
mov ah, 1
int 10h

; note: some bioses required CL to be >=7,


; otherwise wrong cursor shapes are displayed.

INT 10h / AH = 2 - set cursor position.


input:
DH = row.
DL = column.
BH = page number (0..7).
example:

mov dh, 10
mov dl, 20
mov bh, 0
mov ah, 2
int 10h

INT 10h / AH = 03h - get cursor position and size.


input:
BH = page number.
return:
DH = row.
DL = column.
CH = cursor start line.
CL = cursor bottom line.

INT 10h / AH = 05h - select active video page.


input:
AL = new page number (0..7).
the activated page is displayed.

INT 10h / AH = 06h - scroll up window.


INT 10h / AH = 07h - scroll down window.
input:
AL = number of lines by which to scroll (00h = clear entire window).
BH = attribute used to write blank lines at bottom of window.
CH, CL = row, column of window's upper left corner.
DH, DL = row, column of window's lower right corner.

INT 10h / AH = 08h - read character and attribute at cursor position.

input:
BH = page number.
return:
AH = attribute.
AL = character.

INT 10h / AH = 09h - write character and attribute at cursor position.

input:
AL = character to display.
BH = page number.
BL = attribute.
CX = number of times to write character.

INT 10h / AH = 0Ah - write character only at cursor position.

input:
AL = character to display.
BH = page number.
CX = number of times to write character.

INT 10h / AH = 0Ch - change color for a single pixel.

input:
AL = pixel color
CX = column.
DX = row.
example:

mov al, 13h


mov ah, 0
int 10h ; set graphics video mode.
mov al, 1100b
mov cx, 10
mov dx, 20
mov ah, 0ch
int 10h ; set pixel.

INT 10h / AH = 0Dh - get color of a single pixel.

input:
CX = column.
DX = row.
output:
AL = pixel color

INT 10h / AH = 0Eh - teletype output.

input:
AL = character to write.
this functions displays a character on the screen, advancing the cursor and scrolling the screen as necessary. the
printing is always done to current active page.

example:

mov al, 'a'


mov ah, 0eh
int 10h

; note: on specific systems this


; function may not be supported in graphics mode.

INT 10h / AH = 13h - write string.

input:
AL = write mode:
bit 0: update cursor after writing;
bit 1: string contains attributes.
BH = page number.
BL = attribute if string contains only characters (bit 1 of AL is zero).
CX = number of characters in string (attributes are not counted).
DL,DH = column, row at which to start writing.
ES:BP points to string to be printed.
example:

mov al, 1
mov bh, 0
mov bl, 0011_1011b
mov cx, msg1end - offset msg1 ; calculate message size.
mov dl, 10
mov dh, 7
push cs
pop es
mov bp, offset msg1
mov ah, 13h
int 10h
jmp msg1end
msg1 db " hello, world! "
msg1end:

INT 10h / AX = 1003h - toggle intensity/blinking.

input:
BL = write mode:
0: enable intensive colors.
1: enable blinking (not supported by the emulator and windows command prompt).
BH = 0 (to avoid problems on some adapters).
example:

mov ax, 1003h


mov bx, 0
int 10h

bit color table:


character attribute is 8 bit value, low 4 bits set fore color, high 4 bits set background color.
note: the emulator and windows command line prompt do not support background blinking, however to make colors
look the same in dos and in full screen mode it is required to turn off the background blinking.

HEX BIN COLOR

0 0000 black
1 0001 blue
2 0010 green
3 0011 cyan
4 0100 red
5 0101 magenta
6 0110 brown
7 0111 light gray
8 1000 dark gray
9 1001 light blue
A 1010 light green
B 1011 light cyan
C 1100 light red
D 1101 light magenta
E 1110 yellow
F 1111 white
note:

; use this code for compatibility with dos/cmd prompt full screen mode:
mov ax, 1003h
mov bx, 0 ; disable blinking.
int 10h

INT 11h - get BIOS equipment list.


return:
AX = BIOS equipment list word, actually this call returns the contents of the word at 0040h:0010h.

Currently this function can be used to determine the number of installed number of floppy disk drives.

Bit fields for BIOS-detected installed hardware:


bit(s) Description
15-14 Number of parallel devices.
13 Reserved.
12 Game port installed.
11-9 Number of serial devices.
8 Reserved.
7-6 Number of floppy disk drives (minus 1):
00 single floppy disk;
01 two floppy disks;
10 three floppy disks;
11 four floppy disks.
5-4 Initial video mode:
00 EGA,VGA,PGA, or other with on-board video BIOS;
01 40x25 CGA color.
10 80x25 CGA color (emulator default).
11 80x25 mono text.
3 Reserved.
2 PS/2 mouse is installed.
1 Math coprocessor installed.
0 Set when booted from floppy.

INT 12h - get memory size.


return:
AX = kilobytes of contiguous memory starting at absolute address 00000h, this call returns the contents of the word
at 0040h:0013h.

Floppy drives are emulated using FLOPPY_0(..3) files.


INT 13h / AH = 00h - reset disk system.

INT 13h / AH = 02h - read disk sectors into memory.


INT 13h / AH = 03h - write disk sectors.
input:
AL = number of sectors to read/write (must be nonzero)
CH = cylinder number (0..79).
CL = sector number (1..18).
DH = head number (0..1).
DL = drive number (0..3 , for the emulator it depends on quantity of FLOPPY_ files).
ES:BX points to data buffer.
return:
CF set on error.
CF clear if successful.
AH = status (0 - if successful).
AL = number of sectors transferred.
Note: each sector has 512 bytes.

INT 15h / AH = 86h - BIOS wait function.


input:
CX:DX = interval in microseconds
return:
CF clear if successful (wait interval elapsed),
CF set on error or when wait function is already in progress.

Note:
the resolution of the wait period is 977 microseconds on many systems (1 million microseconds - 1 second).
Windows XP does not support this interrupt (always sets CF=1).

INT 16h / AH = 00h - get keystroke from keyboard (no echo).


return:
AH = BIOS scan code.
AL = ASCII character.
(if a keystroke is present, it is removed from the keyboard buffer).

INT 16h / AH = 01h - check for keystroke in the keyboard buffer.


return:
ZF = 1 if keystroke is not available.
ZF = 0 if keystroke available.
AH = BIOS scan code.
AL = ASCII character.
(if a keystroke is present, it is not removed from the keyboard buffer).
INT 19h - system reboot.
Usually, the BIOS will try to read sector 1, head 0, track 0 from drive A: to 0000h:7C00h. The emulator just stops the
execution, to boot from floppy drive select from the menu: 'virtual drive' -> 'boot from floppy'

INT 1Ah / AH = 00h - get system time.


return:
CX:DX = number of clock ticks since midnight.
AL = midnight counter, advanced each time midnight passes.
notes:
there are approximately 18.20648 clock ticks per second,
and 1800B0h per 24 hours.
AL is not set by the emulator.

INT 20h - exit to operating system.

The short list of emulated MS-DOS interrupts -- INT 21h

DOS file system is emulated in C:\emu8086\vdrive\x (x is a drive letter)

If no drive letter is specified and current directory is not set, then C:\emu8086\MyBuild\ path is used by default.
FLOPPY_0,1,2,3 files are emulated independently from DOS file system.

For the emulator physical drive A: is this file c:\emu8086\FLOPPY_0 (for BIOS interrupts: INT 13h and boot).

For DOS interrupts (INT 21h) drive A: is emulated in this subdirectory: C:\emu8086\vdrive\a\

Note: DOS file system limits the file and directory names to 8 characters, extension is limited to 3 characters;
example of a valid file name: myfile.txt (file name = 6 chars, extension - 3 chars). extension is written after the dot,
no other dots are allowed.

INT 21h / AH=1 - read character from standard input, with echo, result is stored in AL.
if there is no character in the keyboard buffer, the function waits until any key is pressed.

example:

mov ah, 1
int 21h

INT 21h / AH=2 - write character to standard output.


entry: DL = character to write, after execution AL = DL.

example:

mov ah, 2
mov dl, 'a'
int 21h

INT 21h / AH=5 - output character to printer.


entry: DL = character to print, after execution AL = DL.

example:

mov ah, 5
mov dl, 'a'
int 21h

INT 21h / AH=6 - direct console input or output.

parameters for output: DL = 0..254 (ascii code)


parameters for input: DL = 255

for output returns: AL = DL


for input returns: ZF set if no character available and AL = 00h, ZF clear if character available.
AL = character read; buffer is cleared.

example:

mov ah, 6
mov dl, 'a'
int 21h ; output character.

mov ah, 6
mov dl, 255
int 21h ; get character from keyboard buffer (if any) or set ZF=1.

INT 21h / AH=7 - character input without echo to AL.


if there is no character in the keyboard buffer, the function waits until any key is pressed.

example:

mov ah, 7
int 21h

INT 21h / AH=9 - output of a string at DS:DX. String must be terminated by '$'.

example:

org 100h
mov dx, offset msg
mov ah, 9
int 21h
ret
msg db "hello world $"

INT 21h / AH=0Ah - input of a string to DS:DX, fist byte is buffer size, second byte is number of chars actually read.
this function does not add '$' in the end of string. to print using INT 21h / AH=9 you must set dollar character at the
end of it and start printing from address DS:DX + 2.

example:

org 100h
mov dx, offset buffer
mov ah, 0ah
int 21h
jmp print
buffer db 10,?, 10 dup(' ')
print:
xor bx, bx
mov bl, buffer[1]
mov buffer[bx+2], '$'
mov dx, offset buffer + 2
mov ah, 9
int 21h
ret
the function does not allow to enter more characters than the specified buffer size.
see also int21.asm in c:\emu8086\examples

INT 21h / AH=0Bh - get input status;


returns: AL = 00h if no character available, AL = 0FFh if character is available.

INT 21h / AH=0Ch - flush keyboard buffer and read standard input.
entry: AL = number of input function to execute after flushing buffer (can be 01h,06h,07h,08h, or 0Ah - for other
values the buffer is flushed but no input is attempted); other registers as appropriate for the selected input function.

INT 21h / AH= 0Eh - select default drive.

Entry: DL = new default drive (0=A:, 1=B:, etc)

Return: AL = number of potentially valid drive letters

Notes: the return value is the highest drive present.

INT 21h / AH= 19h - get current default drive.


Return: AL = drive (0=A:, 1=B:, etc)

INT 21h / AH=25h - set interrupt vector;


input: AL = interrupt number. DS:DX -> new interrupt handler.

INT 21h / AH=2Ah - get system date;


return: CX = year (1980-2099). DH = month. DL = day. AL = day of week (00h=Sunday)

INT 21h / AH=2Ch - get system time;


return: CH = hour. CL = minute. DH = second. DL = 1/100 seconds.

INT 21h / AH=35h - get interrupt vector;


entry: AL = interrupt number;
return: ES:BX -> current interrupt handler.

INT 21h / AH= 39h - make directory.


entry: DS:DX -> ASCIZ pathname; zero terminated string, for example:

org 100h
mov dx, offset filepath
mov ah, 39h
int 21h

ret

filepath DB "C:\mydir", 0 ; path to be created.


end
the above code creates c:\emu8086\vdrive\C\mydir directory if run by the emulator.

Return: CF clear if successful AX destroyed. CF set on error AX = error code.


Note: all directories in the given path must exist except the last one.

INT 21h / AH= 3Ah - remove directory.

Entry: DS:DX -> ASCIZ pathname of directory to be removed.


Return:

CF is clear if successful, AX destroyed CF is set on error AX = error code.

Notes: directory must be empty (there should be no files inside of it).

INT 21h / AH= 3Bh - set current directory.

Entry: DS:DX -> ASCIZ pathname to become current directory (max 64 bytes).

Return:

Carry Flag is clear if successful, AX destroyed.


Carry Flag is set on error AX = error code.
Notes: even if new directory name includes a drive letter, the default drive is not changed,
only the current directory on that drive.

INT 21h / AH= 3Ch - create or truncate file.

entry:

CX = file attributes:

mov cx, 0 ; normal - no attributes.


mov cx, 1 ; read-only.
mov cx, 2 ; hidden.
mov cx, 4 ; system
mov cx, 7 ; hidden, system and read-only!
mov cx, 16 ; archive
DS:DX -> ASCIZ filename.

returns:

CF clear if successful, AX = file handle.


CF set on error AX = error code.

note: if specified file exists it is deleted without a warning.

example:

org 100h
mov ah, 3ch
mov cx, 0
mov dx, offset filename
mov ah, 3ch
int 21h
jc err
mov handle, ax
jmp k
filename db "myfile.txt", 0
handle dw ?
err:
; ....
k:
ret

INT 21h / AH= 3Dh - open existing file.

Entry:

AL = access and sharing modes:

mov al, 0 ; read


mov al, 1 ; write
mov al, 2 ; read/write

DS:DX -> ASCIZ filename.

Return:

CF clear if successful, AX = file handle.


CF set on error AX = error code.

note 1: file pointer is set to start of file.


note 2: file must exist.

example:

org 100h
mov al, 2
mov dx, offset filename
mov ah, 3dh
int 21h
jc err
mov handle, ax
jmp k
filename db "myfile.txt", 0
handle dw ?
err:
; ....
k:
ret

INT 21h / AH= 3Eh - close file.

Entry: BX = file handle

Return:

CF clear if successful, AX destroyed.


CF set on error, AX = error code (06h).
INT 21h / AH= 3Fh - read from file.

Entry:

BX = file handle.
CX = number of bytes to read.
DS:DX -> buffer for data.

Return:

CF is clear if successful - AX = number of bytes actually read; 0 if at EOF (end of file) before call.
CF is set on error AX = error code.

Note: data is read beginning at current file position, and the file position is updated after a successful read the
returned AX may be smaller than the request in CX if a partial read occurred.

INT 21h / AH= 40h - write to file.

entry:

BX = file handle.
CX = number of bytes to write.
DS:DX -> data to write.

return:

CF clear if successful; AX = number of bytes actually written.


CF set on error; AX = error code.

note: if CX is zero, no data is written, and the file is truncated or extended to the current position data is written
beginning at the current file position, and the file position is updated after a successful write the usual cause for AX <
CX on return is a full disk.

INT 21h / AH= 41h - delete file (unlink).

Entry:

DS:DX -> ASCIZ filename (no wildcards, but see notes).

return:

CF clear if successful, AX destroyed. AL is the drive of deleted file (undocumented).


CF set on error AX = error code.

Note: DOS does not erase the file's data; it merely becomes inaccessible because the FAT chain for the file is
cleared deleting a file which is currently open may lead to filesystem corruption.
INT 21h / AH= 42h - SEEK - set current file position.

Entry:

AL = origin of move: 0 - start of file. 1 - current file position. 2 - end of file.


BX = file handle.
CX:DX = offset from origin of new file position.

Return:

CF clear if successful, DX:AX = new file position in bytes from start of file.
CF set on error, AX = error code.

Notes:

for origins 1 and 2, the pointer may be positioned before the start of the file; no error is returned in that case, but
subsequent attempts to read or write the file will produce errors. If the new position is beyond the current end of file,
the file will be extended by the next write (see AH=40h).

example:

org 100h
mov ah, 3ch
mov cx, 0
mov dx, offset filename
mov ah, 3ch
int 21h ; create file...
mov handle, ax

mov bx, handle


mov dx, offset data
mov cx, data_size
mov ah, 40h
int 21h ; write to file...

mov al, 0
mov bx, handle
mov cx, 0
mov dx, 7
mov ah, 42h
int 21h ; seek...

mov bx, handle


mov dx, offset buffer
mov cx, 4
mov ah, 3fh
int 21h ; read from file...

mov bx, handle


mov ah, 3eh
int 21h ; close file...
ret

filename db "myfile.txt", 0
handle dw ?
data db " hello files! "
data_size=$-offset data
buffer db 4 dup(' ')
INT 21h / AH= 47h - get current directory.

Entry:

DL = drive number (00h = default, 01h = A:, etc)


DS:SI -> 64-byte buffer for ASCIZ pathname.

Return:

Carry is clear if successful


Carry is set on error, AX = error code (0Fh)

Notes:

the returned path does not include a drive and the initial backslash.

INT 21h / AH=4Ch - return control to the operating system (stop program).

INT 21h / AH= 56h - rename file / move file.

Entry:

DS:DX -> ASCIZ filename of existing file.


ES:DI -> ASCIZ new filename.

Return:

CF clear if successful.
CF set on error, AX = error code.

Note: allows move between directories on same logical drive only; open files should not be renamed!

mouse driver interrupts -- INT 33h

INT 33h / AX=0000 - mouse ininialization. any previous mouse pointer is hidden.

returns:
if successful: AX=0FFFFh and BX=number of mouse buttons.
if failed: AX=0
example:

mov ax, 0
int 33h
see also: mouse.asm in examples.

INT 33h / AX=0001 - show mouse pointer.

example:

mov ax, 1
int 33h

INT 33h / AX=0002 - hide visible mouse pointer.

example:

mov ax, 2
int 33h

INT 33h / AX=0003 - get mouse position and status of its buttons.

returns:
if left button is down: BX=1
if right button is down: BX=2
if both buttons are down: BX=3
CX = x
DX = y
example:

mov ax, 3
int 33h

; note: in graphical 320x200 mode the value of CX is doubled.


; see mouse2.asm in examples.
UNIVERSIDAD TCNICA DEL NORTE
FACULTAD DE INGENIERIA EN CIENCIAS APLICADAS
CARRERA DE MECATRNICA

PROGRAMACION EN LENGUAJE ENSAMBLADOR


MANEJO DE STRINGS

Los microprocesadores de la familia 8086, posee instrucciones diseadas para un rpido procesamiento de los string,
cuando se habla de string, se refiere a una secuencia de elementos uno despus del otro, estos elementos pueden
ser de bytes, words y para el caso de 80386 y superiores, doble word, la diferencia de estas instrucciones en particular
con respecto a las dems instrucciones estndar de Assembler, es que, con la suma de un prefijo se puede realizar
un determinado procesamiento a un conjunto de posiciones de memoria.

Instrucciones:

MOVS: Copia un string de una locacin a otra.

STOS: Graba el contenido de un acumulador a un string.

LODS: Carga el valor de un elemento del string a un acumulador.

CMPS: Compara un string con otro.

SCAS: Busca un valor especfico dentro de un string.

MOVS

El MOVS copia una string fuente a un string destino, esta funcin puede ser usada en conjunto con el prefijo REP. En
el ejemplo copiamos el contenido de un vector de 10 elementos a otro vector de posee tambin 10 elementos. name
"movs"

.model tiny
.stack 100h
.data
fuente db 1 DUP('0123456789')
destino db 10 DUP(?)
.code
cld
mov cx,10 ; cargar la longitud de la cadena en CX
mov si,offset fuente ; Cargar direccin fuente a SI
mov di,offset destino ; Cargar direccin destino a DI (al utilizar
rep movsb ; copiar 10 bytes
ret

Despus ejecutar el cdigo, se obtiene:


STOS

Copia el acumulador AL o AX a una cadena. Podemos utilizarlo de dos formas:

Sin prefijo: cuando deseamos cargar una cadena en la cual cada elemento necesita un procesamiento
individual, entonces podemos con un simple STOS guardar los elementos de a uno, con la ventaja que nos
provee de la funcin de incremento o decremento de la direccin destino evitando ser implementada por
nosotros.
Con prefijo: nos sirve para realizar un llenado de una cadena. Ingresamos el dato con que vamos a llenar
la cadena en AL o AX y luego mediante un prefijo REP realizamos CX loops.

En el ejemplo siguiente dada una cadena de 11 elementos, llenar con asteriscos mediante una STOS con prefijo
REP

.model tiny

.stack 100h

.data

destino db 11 DUP(?)

.code
cld ; trabajar en forma ascendente
mov cx,11 ; cargar long. de la cadena en CX
mov di,offset destino ; cargar direccin destino en DI
mov al,'*' ; byte a llenar el vector destino
rep stosb ; lleno con '*' la cadena
ret

Despus ejecutar el cdigo, se obtiene:


LODS

Carga desde una cadena un elemento a el acumulador AL o AX segn la longitud del elemento. Esta instruccin
no se usa con prefijos puesto que no tendra sentido ya que cada vez que carga un valor al acumulador borra el
anterior. LODS se utiliza cuando queremos procesar cada elemento de la cadena, entonces creamos un bucle
mediante una instruccin LOOP y dentro de este utilizamos la instruccin LODS.

En el ejemplo, utilizamos esta funcin en conjunto con STOSB para transformar una cadena de nmero a su
correspondiente cdigo ASCII.

.model tiny

.stack 100h

.data

fuente db 0,1,2,3,4,5,6,7,8,9
destino db 10 DUP(?)
longitud equ 10

.code
cld ; trabajar en forma ascendente
mov cx,longitud ; cargar la longitud de la cadena en CX
mov si,offset fuente ; cargar fuente para inst LODSB
mov di,offset destino ; cargar destino para inst STOSB
loop1:
lodsb
add al,'0'
stosb
loop loop1
ret

Despus ejecutar el cdigo, se obtiene:


CMPS

Compara dos cadenas, realiza una resta de cada elemento sin modificar ninguno de sus valores pero si actualizando
los flags, esta instruccin se puede utilizar en conjunto con el prefijo REPNZ o REPZ.

Utilizando REPNZ o REPNE: Compara mientras no sean iguales, saliendo del bucle cuando dos elementos
lo sean y dejando el flag de cero en 1, en caso de no encontrar elementos iguales, llegar a CX = 0, y
retornar el flag de cero en 0,
Utilizando REPZ o REPE: Compara mientras sean iguales, saliendo del bucle cuando encuentre dos
elementos que no lo sean y dejando el flag de cero en 0, en caso de no encontrar elementos distintos llegara
a CX = 0, y retornar el flag de cero en 1.

Luego de realizado el bucle de comparacin mediante un salto condicional como el JZ o JNZ se elige que hacer.

En el ejemplo se realiza la comparacin de dos cadenas para determinar si son iguales o no, para esto, luego de
comparar se verifica el estado de la bandera de cero.

.model tiny

.stack 100h

.data

cadena1 db "Cadena a comparar"


cadena2 db "Cadena a comparar"
longitud EQU 17

.code
mov cx,longitud ; cargar la longitud de la cadena en CX
cld ; trabajar en forma ascendente
mov si,offset cadena1 ; Cargar direccin fuente a SI
mov di,offset cadena2 ; Cargar direccin destino a DI
repe
cmpsb
je igual ; en caso que sean distintas ;
mov ah,0d
jmp final

igual: ; en caso que sean iguales


mov ah,1d

final:
ret

Despus ejecutar el cdigo, se obtiene:


SCAS

Compara el valor de un elemento de la cadena con el acumulador. La forma en que se usa es similar al CMPS, se
utilizara tambin en conjunto con los prefijos REPNE y REPE.

Prefijo REPNE o REPNZ: Sale del bucle y retorna el flag cero en 1 cuando encuentra un valor que coincide
con el acumulador en caso de no encontrar algn elemento igual que el acumulador llega a CX = 0
retornando el flag cero en 0.
Prefijo REPE o REPZ: Sale del bucle y retorna el flag cero en 0 cuando encuentra un valor que no coincide
con el acumulador en caso de no encontrar algn elemento distinto que el acumulador llega a CX = 0
retornando el flag cero en 1.

El ejemplo busca una letra en el alfabeto, guardando en AX su posicin.

.model tiny

.stack 100h

.data

cadena db "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
longitud EQU 26

.code
cld ; trabajar en forma ascendente
mov cx,longitud ; cargar la long.de la cadena en CX
mov di,OFFSET cadena ; cargar direccion de cadena en DI
mov al,'F' ; caracter a buscar
repne
jne noencontrado
mov ax,longitud
sub ax,cx ; calcular la posicion

noencontrado:
ret

Despus ejecutar el cdigo, se obtiene:

S-ar putea să vă placă și