Вы находитесь на странице: 1из 43

Curso Prtico

de Programao
em Linguagem C
para 8051


Parte 1

















Prof. Salomo Choueri Junior

Sumrio

1. Introduo ...................................................................................................................................................................... 1
1.1. Linguagem C ........................................................................................................................................................... 1
1.2. Hardware Base ........................................................................................................................................................ 1
1.3. Estrutura de um Software de Aplicao ................................................................................................................. 2
2. Estrutura Bsica de um programa em C ......................................................................................................................... 3
2.1. PROG1.C Software de Testes ............................................................................................................................. 3
2.2. Comentrios ............................................................................................................................................................ 4
2.3. Diretivas de Pr-Processamento .............................................................................................................................. 4
2.4. Funo Principal void main ( ) ............................................................................................................................. 5
2.5. Atribuies .............................................................................................................................................................. 5
2.6. Loop Infinito while (1) ......................................................................................................................................... 5
2.7. A Linguagem C case sensitive .............................................................................................................................. 5
3. Compilao, Simulao e Programao ......................................................................................................................... 6
3.1. Compilao ............................................................................................................................................................. 6
3.1.1. Arquivos .HEX ................................................................................................................................................. 6
3.2. Simulao ............................................................................................................................................................... 7
3.3. Programao na Placa de Testes ............................................................................................................................. 7
4. Operadores Lgicos e Aritmticos ................................................................................................................................. 9
4.1. Operadores Lgicos ................................................................................................................................................ 9
4.2. Operadores Aritmticos .......................................................................................................................................... 9
4.3. Exerccios Resolvidos ............................................................................................................................................ 9
4.3.1. EXR1.C ............................................................................................................................................................ 9
4.3.2. EXR2.C ...........................................................................................................................................................10
4.3.3. EXR3.C ...........................................................................................................................................................11
4.3.4. EXR4.C ...........................................................................................................................................................11
4.4. Exerccios Propostos: .............................................................................................................................................12
4.5. Projeto Proposto: ....................................................................................................................................................12
5. Variveis e Funes ......................................................................................................................................................13
5.1. Variveis.................................................................................................................................................................13
5.1.1 Nome ................................................................................................................................................................13
5.1.2 Tipo e Valores ..................................................................................................................................................13
5.2. Funes ..................................................................................................................................................................14
5.2.1 Sintaxe das Funes .........................................................................................................................................14
5.3. PROG2.C Pisca Leds ..........................................................................................................................................15
5.4. PROG3.C Pisca Leds com tempo controlado pela DIPS .....................................................................................15
5.5. Exerccios Resolvidos ...........................................................................................................................................17
5.5.1. EXR5.C ...........................................................................................................................................................17
5.6. Exerccios Propostos: .............................................................................................................................................17

5.7. Projeto Proposto: ................................................................................................................................................... 18
6. Operadores Relacionais e Estruturas de Deciso .......................................................................................................... 19
6.1. Operadores Relacionais ......................................................................................................................................... 19
6.2. Estrutura if-else ...................................................................................................................................................... 19
6.3. PROG4.C Sequencial de LEDS .......................................................................................................................... 21
6.4. Estrutura switch-case ............................................................................................................................................. 23
6. 5. Comandos break e continue .................................................................................................................................. 23
6.6. PROG5.C Sequencial de LEDS com switch ....................................................................................................... 24
6.7. Exerccios Propostos .............................................................................................................................................. 24
6.8. Projetos Propostos ................................................................................................................................................. 24
7. Estruturas de Loop - Laos ........................................................................................................................................... 25
7.1. Estrutura while ....................................................................................................................................................... 25
7.2. Estrutura do while .................................................................................................................................................. 25
7.3. PROG6.C Alarme Residencial ............................................................................................................................ 26
7.4. Estrutura for ........................................................................................................................................................... 29
7.5. PROG7.C Contador de Eventos .......................................................................................................................... 29
7.5. Exerccios Resolvidos ........................................................................................................................................... 32
7.5.1. EXR6.C ........................................................................................................................................................... 32
7.7. Exerccios Propostos .............................................................................................................................................. 32
7.8. Projeto proposto ..................................................................................................................................................... 32
8. Atividades no presenciais............................................................................................................................................ 33
Apndice A Reviso ...................................................................................................................................................... 34
Apndice B at89x52.h ................................................................................................................................................... 35





1
P2
LED2
LED3
LED4
LED5
LED6
LED7
DIP8
DIP7
DIP6
DIP5
DIP4
DIP3
DIP2
DIP1
LED8
BZ
PB
P0_0
P0_1
P0_2
P0_3
P0_4
P0_5
P0_6
P0_7
P2_7
P2_6
P2_5
P2_4
P2_3
P2_2
P2_1
P2_0
P3_0
P3_1
P3_2
P3_3
P3_4
P3_5
P3_6
P3_7
P1_0
P1_1
P1_2
P1_3
P1_4
P1_5
P1_6
P1_7



LEDS
DIPS
P0
P1
LED1
P3
Introduo

1.1. Linguagem C

A Linguagem C foi criada para gerar o menor nmero de cdigos quanto possvel. Seu conjunto de
comandos bem reduzido, porm bastante flexvel.
Para microcontroladores utiliza-se o SDCC (Small Device C Compiler) que um compilador ANSI
C otimizado. Trata-se de um projeto open source (cdigo fonte aberto) sob licena GLP (General
Public License) da GNU.

1.2. Hardware Base

O hardware utilizado no curso a Placa de Testes EDT-044 que utiliza o microcontrolador
AT89S52.
Este microntrolador possui 32 pinos de I/O divididos em 4 ports de 8 bits Estes ports so bit/byte
endereveis, ou seja, podemos acessar o port (P0, P1, P2, P3) ou cada bit individualmente (P0_0,
P0_1, P0_2, P0_3, P0_4, P0_5, P0_6, P0_7, P1_0 ... P1_7, P2_0 ...P2_7, P3_0 ... P3_7).

Na Placa de Testes so utilizadas 9 entradas e 9 sadas, a saber:

Entradas:
P2 Dip-switch com 8 chaves (ON = nvel lgico 0)
P3_2 Push-Bottom (acionada = nvel lgico 0)

Sadas:
P0 8 Leds (ativos em nvel lgico 1)
P3_7 Buzzer (ativo em nvel lgico 0)











2
1.3. Estrutura de um Software de Aplicao

Para aplicaes em microcontroladores tem-se, geralmente, a estrutura apresentada a seguir:


























INICIO
Declarar e definir
contedos iniciais
das variveis

Processo
INICIALIZAO
LOOP INFINITO

Inicializar
perifricos
programveis
Colocar contedos
iniciais nas sadas


3


2. Estrutura Bsica de um programa em C


Para apresentarmos a estrutura bsica de um programa em Linguagem C, faremos um software para
testar a Placa de Testes.

2.1. PROG1.C Software de Testes

Este programa utilizar o seguinte fluxograma:





Abra o editor JFE (C:\8051\Editor_C\JFE), Carregue o software PROG1.C que est na pasta
C:\8051\CursoC.

A figura a seguir mostra o programa aberto no JFE.

PROG1
Apaga LEDS
Desliga BZ
LEDS DIPS
BZ PB

INICIALIZAO
LOOP INFINITO


4


2.2. Comentrios

Os comentrios aparecem em verde e podem iniciados com /* e encerrados com */ quando utiliza-
se vrias linhas ou coloca-se // quando forem colocados em apenas uma linha.


2.3. Diretivas de Pr-Processamento

O comando #include inclui um arquivo header (cabealho) que contm as definies do
microcontrolador utilizado (at89x52.h) assim como bibliotecas com funes em C.

No arquivo at89x52.h tem-se as definies dos ports e registradores de funes especiais do
AT89S52. No momento, utilizaremos somente os ports que aparecem em azul:
P0, P1, P2, P3, P0_0 ... P0_7, P1_0 ... P1_7, P2_0 ...P2_7, P3_0 ... P3_7

Podemos utilizar tambm, os nomes das entradas e sadas da Placa de testes:

As entradas aparecem em marrom:
DIPS, DIP1 ... DIP8 e PB

As sadas aparecem em vermelho:
LEDS, LED1 ... LED8 e BZ

O Apndice B apresenta o arquivo at89x52,h





5
2.4. Funo Principal void main ( )

Trata-se do bloco principal do programa que estar entre chaves { }. No nosso caso, a funo
principal nunca retornar nada (void vazio) e tambm, nunca recebe nenhum parmetro, ou seja,
sempre ser void main ( ).
Maiores informaes no tpico 5.2 Funes.

2.5. Atribuies

Note que as atribuies so encerradas com ponto e vrgula ( ; ) e os valores em hexadecimal devem
ser precedidos de 0x.

2.6. Loop Infinito while (1)

Todas as atribuies, comandos e estruturas que estiverem entre as chaves { } da estrutura while (1)
sero repetidas em loop infinito. Maiores informaes no tpico 7.1 Estrutura - while.

2.7. A Linguagem C case sensitive

Isto significa que o compilador diferencia letras maisculas e minsculas. Todos os comandos em C
so com letras minsculas e os ports e entradas e sadas da placa so escritos com letras maisculas.














6
3. Compilao, Simulao e Programao

3.1. Compilao

Para compilar o programa basta clicar em Compilar. Caso no tenha erros de sintaxe no programa
digitado, um arquivo com extenso .HEX ser criado no mesmo diretrio do arquivo fonte.



3.1.1. Arquivos .HEX

O formato Intel Hex compreende um arquivo texto (ASCII) , com a seguinte codificao:

:040000000200443284
:01000B0032C2
:0100130032BA
:01001B0032B2
:0100230032AA
:01002B0032A2
:100044007581CF120040E582600302002C7900E93B
:100054004400601B7A0090008C780075A000E49343
:10006400F2A308B8000205A0D9F4DAF275A0FF786B
:1000740000E84400600C7900900000E4F0A3D8FC90
:08008400D9FAF6D8FD02002CA8
:10002C0012003180FE758000D2B785A080A2B292FA
:08003C00B780F7227582002253
:00000001FF

: - Delimitador de incio da linha
04 - Nmero de bytes da linha
0000 - Endereo inicial dos bytes
00 - Tipo de registro: 00 = dados, 01 fim de registro
02004432 - Dados/instrues
84 - Checksum complemento da soma de todos os bytes





7

3.2. Simulao

a) Abrir o programa Pinnacle52 ( Iniciar Programas Pinnacle Pinnacle52 register later)
b) Abrir Code Memory ( View - Code Memory) otimizar janela.
c) Abrir Ports ( View Ports) otimizar janela.
d) Abrir o Programa ( File open Arquivos do tipo: INTEL HEX PROG1.HEX)
e) Executar programa (seta verde - run)
f) Simular entradas (DIPS e PB) e verificar sadas (LEDS e BZ)






3.3. Programao na Placa de Testes

a) Abrir o Gravador USB ( C:\8051\Gravadores\Gravador USB)
b) Conectar o cabo USB do Kit Programador
c) Carregar o Arquivo .HEX ( LOAD FLASH)
d) Gravar o programa (AUTO)
e) Simular o programa alterando o estado da Dips-Switch e PB e verificando os LEDS e BZ.






8































9
4. Operadores Lgicos e Aritmticos
4.1. Operadores Lgicos

OPERADORES LGICOS
! NOT
& AND
| OR
^ XOR
<< n Desloca n bits esquerda
>> n Desloca n bits direita

4.2. Operadores Aritmticos

OPERADORES ARITMTICOS
+ SOMA
- SUBTRAO
/ DIVISO
% RESTO DA DIVISO
* MULTIPLICAO
++ INCREMENTO ( SOMAR 1 )
-- DECREMENTO ( SUBTRAIR 1 )

4.3. Exerccios Resolvidos

4.3.1. EXR1.C

D um programa que realize as seguintes operaes lgicas:
LED1 = DIP1 + DIP2
LED2 = DIP1 . DIP2
LED3 = DIP1 + DIP2


LED4 = DIP1 + DIP2 . DIP1



Tabela de Verificao

DIP1 DIP2 LED8 LED7 LED6 LED5 LED4 LED3 LED2 LED1
0 0 0 0 0 0 0 1 0 0
0 1 0 0 0 0 1 0 0 1
1 0 0 0 0 0 1 0 0 1
1 1 0 0 0 0 1 0 1 1











10

Programa EXR1.C

/*
EXR1.C
Exerccio Resolvido 1
Operaes Lgicas
*/
#include <at89x52.h>

void main ()
{
LEDS = 0x00;
BZ = 1;
while (1)
{
LED1 = DIP1 | DIP2;
LED2 = DIP1 & DIP2;
LED3 = !(DIP1 | DIP2);
LED4 = DIP1 | (DIP2 & !DIP1);
}
}



4.3.2. EXR2.C

D uma rotina que apresente nos LEDS o contedo das DIPS multiplicado por 4.
Exemplos de testes:
DIPS DIP8 DIP7 DIP6 DIP5 DIP4 DIP3 DIP2 DIP1 LEDS LED8 LED7 LED6 LED5 LED4 LED3 LED2 LED1
0x01 0 0 0 0 0 0 0 1 0x04 0 0 0 0 0 1 0 0
0x05 0 0 0 0 0 1 0 1 0x14 0 0 0 1 0 1 0 0
0x0C 0 0 0 0 1 1 0 0 0x30 0 0 1 1 0 0 0 0
0x3F 0 0 1 1 1 1 1 1 0xFC 1 1 1 1 1 1 0 0


Programa EXR2.C

/*
EXR2.C
Exerccio Resolvido 2
Operaes Aritmticas
LEDS = DIPS x 4
*/
#include <at89x52.h>

void main ()
{
LEDS = 0x00;
BZ = 1;
while (1)
{
LEDS = DIPS *4;
}
}




11

4.3.3. EXR3.C

D uma rotina que apresente nos LEDS o contedo das DIPS multiplicado por 4 utilizando
instruo de deslocamento.

Programa EXR3.C

/*
EXR2.C
Exerccio Resolvido 2
LEDS = DIPS x 4
Com instruo de deslocamento
*/
#include <at89x52.h>

void main ()
{
LEDS = 0x00;
BZ = 1;
while (1)
{
LEDS = DIPS << 2;
}
}

4.3.4. EXR4.C

D uma rotina que apresente nos LEDS a soma do nibble mais significativo das DIPS com o nibble
menos significativo.

Algoritmo:
Soma-se o contedo da DIPS deslocado 4 bits direita com o contedo da DIPS com o nibble mais
significativo zerado.

Exemplo: 0x0F + 0x02 = 0x11

DIPS DIP8 DIP7 DIP6 DIP5 DIP4 DIP3 DIP2 DIP1 DIPS DIP8 DIP7 DIP6 DIP5 DIP4 DIP3 DIP2 DIP1
0xF2 1 1 1 1 0 0 1 0 0x07 0 0 0 0 1 1 1 1
0x02 0 0 0 0 0 0 1 0
LEDS LED8 LED7 LED6 LED5 LED4 LED3 LED2 LED1
0x11 0 0 0 1 0 0 0 1















12
Programa EXR4.C

/*
EXR4.C
Exerccio Resolvido 4
LEDS = soma do nibble mais significativo com o nibble menos significativo da DIPS
*/
#include <at89x52.h>

void main ()
{
LEDS = 0x00;
BZ = 1;
while (1)
{
LEDS = (DIPS >>4) + (DIPS & 0x0F);
}
}


4.4. Exerccios Propostos:

EX1.C D uma rotina que apresente nos LEDS o contedo das DIPS dividido por 4.
EX2.C D uma rotina que apresente nos LEDS o resto da diviso das DIPS por 4.
EX3.C D uma rotina que acione o BZ (ativo em nvel lgico 0) quando a DIP1 = 1.

4.5. Projeto Proposto:

PROJ1.C Controle de uma Bomba para caixa dgua e alarme do reservatrio.

Entradas:
DIP1 Sensor de nvel de gua mnimo do reservatrio
DIP2 Sensor de nvel de gua mximo do reservatrio
DIP3 Sensor de nvel de gua mnimo da caixa dgua
DIP4 Sensor de nvel de gua mximo da caixa dgua
OBS: Sensores = 1 na presena de gua

Sidas:
LED1 Bomba dgua ativo em nvel lgico 1
BZ Alarme - ativo em nvel lgico 0

A bomba dgua deve ligar sempre que a caixa dgua no estiver cheia e tiver gua no reservatrio
e o Alarme deve ativar se no tiver gua no reservatrio.








13
5. Variveis e Funes


5.1. Variveis

Uma varivel uma posio de memria na qual o programa pode armazenar valores. Assim, uma
varivel possui 3 atributos: um nome, o tipo de dado e o valor armazenado.

5.1.1 Nome

Algumas regras bsicas para estabelecer o nome da varivel:
a) Deve sempre comear com letra ou sublinhado (_);
b) No pode conter caracteres especiais, somente letras, nmeros e sublinhado;
c) Deve lembrar o que guarda;
d) O compilar C case sensitive;
e) Existem nomes reservados.

Nomes Reservados pelo Padro ANSI-C

auto break case char const continue default do double
else enum extern float for goto if int long
register return short signed sizeof static struct switch typedef
union unsigned void volatile while main

Outros nomes reservados pelo SDCC: bit, interrupt, using, sfr

5.1.2 Tipo e Valores

Tipo de Dado bits bytes Valores
bit 1 0 ou 1
char 8 1 -128 a +127
unsigned char 8 1 0 a 255
int 16 2 -32768 a +32767
unsigned int 16 2 0 a 65355
long 32 4 -2147483648 a +2147483647
unsigned long 32 4 0 a 4294967295
float 32 4 1,17549
E-38
a 3,402823
E+38















14
5.2. Funes

Funes so blocos de programas que so executados como uma sub-rotina.

5.2.1 Sintaxe das Funes

As funes possuem um cabealho e o bloco de instrues que ela realiza como mostra a estrutura
abaixo:

tipo_do_dado_de_retorno nome (declarao_do_parmetro_de_entrada)
{
Instrues;
}

Na declarao da funo, quando ela no retorna nenhum dado coloca-se void (vazio) e, quando no
h nenhum parmetro de entrada no coloca-se nada dentro dos parnteses.

Exemplo1: Funo teste
#include <at89x52.h>

void teste ( )
{
LEDS = DIPS;
BZ = PB;
}
void main ( )
{
LEDS = 0x00;
BZ = 1;
while (1)
{
teste ( );
}
}


Exemplo 2: Funo somar
#include <at89x52.h>

char somar (char a, char b)
{
unsigned char c;
c = a + b;
return (c);
}
void main ( )
{
LEDS = 0x00;
BZ = 1;
while (1)
{
LEDS = somar (0x07,0x20);
}
}


15
5.3. PROG2.C Pisca Leds

O programa a seguir apresenta uma rotina que faz os LEDS piscarem utilizando a funo
atraso_ ms(tempo_em_ms).

/*
PROG2.C
PISCA LEDS
*/
// Diretivas de Pr-Processamento
#include <at89x52.h>
#include <atraso.h>

void main ()
{ // Inicio do programa principal
LEDS = 0x00; // Apaga LEDS
BZ = 1; // Desliga BZ
while (1)
{ // Inicio do Loop Infinito
LEDS = 0xFF; // Acende todos os LEDS
atraso_ms(500); // Atraso de 500ms (0,5s)
LEDS = 0x00; // Apaga todos os LEDS
atraso_ms(500); // Atraso de 500ms (0,5s)
} // Fim do Loop Infinito
} // Fim do Programa Principal

5.4. PROG3.C Pisca Leds com tempo controlado pela DIPS

O programa a seguir faz os LEDS acenderem e apagarem com velocidade controlada pela DIPS
segundo tabela dada a seguir

DIP3 DIP2 DIP1 VALOR T (s) T (ms)
0 0 0 0 0,1 100
0 0 1 1 0,2 200
0 1 0 2 0,3 300
0 1 1 3 0,4 400
1 0 0 4 0,5 500
1 0 1 5 0,6 600
1 1 0 6 0,7 700
1 1 1 7 0,8 800


O clculo do tempo dado pela seguinte expresso:
Tempo = ((DIPS & 0x07) + 1) * 100

Para zerar o contedo de DIP8 a DIP4, executa-se a operao AND com 0x07, como mostrado a
seguir:

DIPS DIP8 DIP7 DIP6 DIP5 DIP4 DIP3 DIP2 DIP1
0xXY X X X X X Y Y Y
0x07 0 0 0 0 0 1 1 1
0x0Y 0 0 0 0 0 Y Y Y



16
Como os valores da DIPS variam de 0 a 7 e os tempos de 100ms a 800ms, soma-se 1 ao valor da
DIPS e multiplica-se por 100.

A varivel com o tempo de atraso (MS) deve ser declarada como varivel global, pois utilizada
tanto na funo main quanto na funo atraso_ms.

/*
PROG3.C
PISCA LEDS COM TEMPO DADO PELA DIPS
*/
// Diretivas de Pr-Processamento
#include <at89x52.h>
#include <atraso.h>

// Declarao das variveis globais
unsigned int MS;

void main ()
{ // Inicio do programa principal
LEDS = 0x00; // Apaga LEDS
BZ = 1; // Desliga BZ
while (1)
{ // Inicio do Loop Infinito
MS = ((DIPS & 0x07) + 1) * 100; // MS = tempo de atraso
LEDS = 0xFF; // Acende todos os LEDS
atraso_ms(MS); // Atraso
LEDS = 0x00; // Apaga todos os LEDS
atraso_ms(MS); // Atraso
} // Fim do Loop Infinito
} // Fim do Programa Principal


























17
5.5. Exerccios Resolvidos

5.5.1. EXR5.C

Utilize a programa PROG3.C e transforme a rotina que faz piscar os LEDS na funo SEQ1 ( ).

/*
EXR5.C
PISCA LEDS COM TEMPO DADO PELA DIPS
*/
// Diretivas de Pr-Processamento
#include <at89x52.h>
#include <atraso.h>

// Declarao das variveis globais
unsigned int MS;

// Declarao das funes
void SEQ1 ();

// PROGRAMA PRINCIPAL
void main ()
{ // Inicio do programa principal
LEDS = 0x00; // Apaga LEDS
BZ = 1; // Desliga BZ
while (1)
{ // Inicio do Loop Infinito
MS = ((DIPS & 0x07) + 1) * 100; // MS = tempo de atraso
SEQ1 (); // Chama funo SEQ1 ()
} // Fim do Loop Infinito
} // Fim do Programa Principal

// FUNES
void SEQ1 ( )
{
LEDS = 0xFF; // Acende todos os LEDS
atraso_ms(MS); // Atraso
LEDS = 0x00; // Apaga todos os LEDS
atraso_ms(MS); // Atraso
}




5.6. Exerccios Propostos:

EX4.C Baseado no PROG3.C, d um programa que realize atraso de 100ms a 1,6s com base em
DIP4, DIP3,DIP2 e DIP1.

EX5.C Baseado no PROG3.C, d um programa que faa o BZ tocar quando os LEDS estiverem
acesos.






18

5.7. Projeto Proposto:

PROJ2.C Apresente nos LEDS a sequncia da super mquina.

LED8 LED7 LED6 LED5 LED4 LED3 LED2 LED1 LEDS
1 0 0 0 0 0 0 1 0x81
0 1 0 0 0 0 1 0 0x42
0 0 1 0 0 1 0 0 0x24
0 0 0 1 1 0 0 0 0x18
0 0 1 0 0 1 0 0 0x24
0 1 0 0 0 0 1 0 0x42













































19
6. Operadores Relacionais e Estruturas de Deciso

6.1. Operadores Relacionais

OPERADORES RELACIONAIS
= = IGUAL A
!= DIFERENTE DE
< MENOR QUE
> MAIOR QUE
<= MENOR OU IGUAL A
>= MAIOR OU IGUAL A

6.2. Estrutura: if - else

Sintaxe:

if (condio)
{
instruo 1;
instruo 2;
...
}
else
{
instruo 1;
instruo 2;
...
}
Forma simplicada:

if (condio) instruo 1;
else instruo 2;


























20



Exemplo1:


if ( DIPS = = 0xFF)
{
LEDS = 0xFF;
}
else
{
LEDS = 0x00;
}

if ( DIPS = = 0x80)
{
BZ = 0;
}
else
{
BZ = 1;
}
OU

if ( DIPS = = 0xFF) LEDS = 0xFF;
else LEDS = 0x00;
if ( DIPS = = 0x80) BZ = 0;
else BZ = 1;


Exemplo 2:


if ( PB = = 0 )
{
LED1 = 0;
}
else
{
if ( DIP1 = = 1)
{
LED1 = 1;
}

if ( DIP2 = = 1)
{
LED1 = 1;
}
}

OU

if ( !PB ) LED1 =0;
else
{
if ( DIP1) LED1 = 1;
if ( DIP2) LED1 = 1;
}
Exemplo1
DIPS = 0xFF

Apaga LEDS

Acende LEDS
DIPS = 0x80


Desliga BZ

Aciona BZ
S

S

Exemplo2
DIP1 = 1

Acende LED1
S

DIP2 = 1


Acende LED1
S

PB = 0


Apaga LED1
S




21

6.3. PROG4.C Sequencial de LEDS

O programa a seguir apresenta uma rotina que realiza 4 sequncias diferentes nos LEDS
selecionadas pela DIP1 e DIP2 segundo a tabela:

DIP2 DIP1 Sequncias nos LEDS
0 0 Sequncia 1
0 1 Sequncia 2
1 0 Sequncia 3
1 1 Sequncia 4


PROG4

Apaga LEDS
MS (global)
Teste (local)
Apaga LEDS
Desliga BZ
teste= nibble
signif. da DIPS
teste = 0x00

S

teste = 0x01

S

teste = 0x02

S

teste = 0x03

S


SEQ4( )


SEQ3( )


SEQ2( )


SEQ1( )


22

/*
PROG4.C
SEQUENCIAL DE LEDS
*/
// Diretivas de Pr-Processamento
#include <at89x52.h>
#include <atraso.h>

// Declarao das variveis globais
unsigned int MS = 200;

// Declarao das funes
void SEQ1 ();
void SEQ2 ();
void SEQ3 ();
void SEQ4 ();

// FUNO PRINCIPAL
void main ()
{ // Inicio do programa principal
unsigned char teste; // Declarao de varivel local
LEDS = 0x00; // Apaga LEDS
BZ = 1; // Desliga BZ
while (1)
{ // Inicio do Loop Infinito
teste = DIPS & 0x0F;
if (teste==0x00) SEQ1();
else
{
if (teste == 0x01) SEQ2();
else
{
if (teste == 0x02) SEQ3();
else
{
if (teste == 0x03) SEQ4();
else LEDS = 0X00;
}
}
}
} // Fim do Loop Infinito
} // Fim do Programa Principal
// FUNES

void SEQ1 ()
{
LEDS = 0xFF;
atraso_ms (MS);
LEDS = 0x00;
atraso_ms (MS);
}
void SEQ2 ()
{
LEDS = 0x55;
atraso_ms (MS);
LEDS = 0xAA;
atraso_ms (MS);
}
void SEQ3 ()
{
LEDS = 0x0F;
atraso_ms (MS);
LEDS = 0xF0;
atraso_ms (MS);
}
void SEQ4 ()
{
LEDS = 0xC0;
atraso_ms (MS);
LEDS = 0x03;
atraso_ms (MS);
LEDS = 0x30;
atraso_ms (MS);
LEDS = 0x0C;
atraso_ms (MS);
}
















23
6.4. Estrutura switch-case

Sintaxe:
switch (varivel)
{
case valor1: instruo 1;
instruo 2;
...
break;
case valor2: instruo 1;
instruo 2;
...
break;
case valorn: instruo 1;
instruo 2;
...
break;
default: instruo 1;
instruo 2;
...
break;
}
6. 5. Comandos break e continue

break :Fora uma interrupo abrupta do bloco de uma estrutura switch, for, while e do while.

continue: Ignora o resto das instrues do bloco e retorna ao incio do bloco.






















24
6.6. PROG5.C Sequencial de LEDS com switch
/*
PROG5.C
SEQUENCIAL DE LEDS COM SWITCH
*/
// Diretivas de Pr-Processamento
#include <at89x52.h>
#include <atraso.h>
// Declarao das variveis globais
unsigned int MS = 200;
// Declarao das funes
void SEQ1 ();
void SEQ2 ();
void SEQ3 ();
void SEQ4 ();

// FUNO PRINCIPAL
void main ()
{ // Inicio do programa principal
unsigned char teste; // Declarao de varivel local
LEDS = 0x00; // Apaga LEDS
BZ = 1; // Desliga BZ
while (1)
{ // Inicio do Loop Infinito
teste = DIPS & 0x0F;
switch (teste)
{
case 0x00: SEQ1();
break;
case 0x01: SEQ2();
break;
case 0x02: SEQ3();
break;
case 0x03: SEQ4();
break;
default: LEDS = 0X00;
break;
}
} // Fim do Loop Infinito
} // Fim do Programa Principal
// FUNES (idem PROG4.C)

6.7. Exerccios Propostos

EX6.C D um programa que acenda todos os LEDS se DIP1=1 e DIP2=1. Os LEDS devem
apagar se DIP8=1. Dar prioridade DIP8.
EX7.C D um programa que verifique a DIPS e acenda os LEDS de acordo com a faixa de
valores dadas a seguir:
LED1 = 1 para DIPS <= 0x20
LED2 = 1 para 0x20 < DIPS < 0x30
LED3 = 1 para DIPS >= 0x30
6.8. Projetos Propostos

PROJ3.C D um sequencial de LEDS com 8 sequncias controladas pela DIP3, DIP2 e DIP1 e 8
velocidades controladas pela DIP7, DIP6 e DIP5.


25
7. Estruturas de Loop - Laos

7.1. Estrutura: while

Sintaxe:

while (condio)
{
instruo 1;
instruo 2;
...
}

Forma simplicada:

while (condio) instruo 1;


Na estrutura while o bloco de instrues realizado enquanto a condio for verdadeira formando
assim um loop de repetio







while ( PB = = 0)
{
BZ = 0;
Atraso_ms(500);
BZ = 1;
Atraso_ms(500);
}
LEDS = 0xFF;


7.2. Estrutura: do while

Sintaxe:

do
{
instruo 1;
instruo 2;
...
}
while (condio);

Exemplo
PB = 0

Acende os LEDS
S


Aciona BZ


Atraso 0,5s

Desliga BZ


Atraso 0,5s


26
Na estrutura do while, realiza-se o bloco de instrues antes de verificar a condio para realizar o
loop de repetio.










do
{
BZ = 0;
Atraso_ms(500);
BZ = 1;
Atraso_ms(500);
}
while ( PB = = 0);
LEDS = 0xFF;



7.3. PROG6.C Alarme Residencial

Entradas:
DIP1 = Liga/Desliga Alarme
DIP5 a DIP8 = Sensores

Sadas:
LED1 = Temporizao
LED8 = Sensor ativo

Descrio:

Enquanto o alarme no estiver ligado o LED8 deve acender se pelo menos um sensor estiver ativo.
Ao ligar o alarme deve-se realizar um atraso de 5s para o usurio sair de sua casa (durante este
tempo o LED1 deve acender).
Ao trmino deste tempo inicia-se a verificao dos sensores. Quando um sensor for acionado deve-
se realizar um atraso de 5s para que o usurio chegue at a central de alarme para deslig-lo. Caso o
alarme no seja desligado o buzzer deve ser acionado. O buzzer s ser desativado quando o alarme
for desligado.
Exemplo
PB = 0

Acende os LEDS
S


Aciona BZ


Atraso 0,5s

Desliga BZ


Atraso 0,5s


27

PROG6

unsigned char teste
Apaga LEDS
Desliga BZ
teste= nibble +
signif. da DIPS
DIP1 = 1

S

teste 0x00

S

Atraso 5s

Acende LED8

Apaga LED8

Apaga LED1

Acende LED1
Teste = nibble +
signif. da DIPS
teste 0x00

S



Atraso 5s

Apaga LED1

Acende LED1
DIP1 = 1

S


Liga BZ

Desliga BZ


28


/*
PROG6.C
ALARME RESIDENCIAL
Entradas:
DIP1 = Liga/Desliga Alarme
DIP5 a DIP8 = Sensores

Sadas:
LED1 = Temporizao
LED8 = Sensor ativo

*/
// Diretivas de Pr-Processamento
#include <at89x52.h>
#include <atraso.h>

// FUNO PRINCIPAL
void main ()
{ // Inicio do programa principal
unsigned char teste; // Declarao de varivel local
LEDS = 0x00; // Apaga LEDS
BZ = 1; // Desliga BZ
while (1)
{ // Inicio do Loop Infinito
while (!DIP1) // Espera ligar Alarme
{
teste = DIPS & 0xF0; // Separa sensores
if (teste != 0x00) LED8=1; // Acende LED8 se sensores <>0
else LED8=0; // Apaga LED8 se sensores = 0
}
LED1=1; // Acende LED1
atraso_ms (5000); // Atraso 5s
LED1=0; // Apaga LED1
do
{
teste = DIPS & 0xF0; // Separa sensores
}
while (teste == 0x00); // Aguarda sensores <> 0
LED1=1; // Acende LED1
atraso_ms (5000); // Atraso 5s
LED1=0; // Apaga LED1
while (DIP1) BZ = 0; // Aciona BZ enquanto DIP1=1
BZ = 1; // Desliga BZ
atraso_ms (100); // Atraso debouncing chave
} // Fim do Loop Infinito
} // Fim do Programa Principal










29
7.4. Estrutura for

Sintaxe:

for (inicializao;condio;incremento)
{
instruo 1;
instruo 2;
...
}

Forma simplicada:

for (inicializao;condio;incremento)
instruo 1;


7.5. PROG7.C Contador de Eventos

Entradas:

PB = Clock do Contador
DIPS = Programao da Contagem mxima

Sadas:

LEDS = Indicao da Contagem
BZ = Indicao sonora do trmino de Contagem

Descrio:

A cada pulso em PB ( 1 0 1 ) deve-se incrementar a contagem e atualizar os LEDS. A cada
incremento deve-se comparar a contagem atual com a contagem mxima programada pela DIPS.
Caso a contagem atingir o nmero programado deve-se dar 5 bips no buzzer (com o valor da
contagem piscando concomitantemente), zerar a contagem e voltar peas.
















30

PROG7
unsigned char CONT=0
insigned char i
Apaga LEDS
Desliga BZ
PB = 1

S


Atraso 20ms

CONT +1

LEDS = CONT

DIPS=CONT

S

LEDS=CONT
Aciona BZ
PB = 0

S



Atraso 20ms
I=0;i<5;i++



Atraso 0,5s
LEDS=0x00
Desliga BZ


Atraso 0,5s

CONT +1


31


/*
PROG7.C
CONTADOR DE EVENTOS
Entradas:
PB = Clock do Contador
DIPS = Programao da Contagem mxima

Sadas:
LEDS = Indicao da Contagem
BZ = Indicao sonora do trmino de Contagem

*/
// Diretivas de Pr-Processamento
#include <at89x52.h>
#include <atraso.h>

// FUNO PRINCIPAL
void main ()
{ // Inicio do programa principal
unsigned char i,CONT =0x00; // Declarao de varivel local
LEDS = 0x00; // Apaga LEDS
BZ = 1; // Desliga BZ
while (1)
{ // Inicio do Loop Infinito
while (PB) {} // Aguarda PB ir para zero
atraso_ms (20); // Deboucing
while (!PB) {} // Aguarda PB ir para um
atraso_ms (20); // Deboucing
CONT++; // Incrementa contagem
LEDS = CONT; // Atualiza LEDS
if (CONT == DIPS) // Verifica final de contagem
{
for (i=0;i<5;i++) // Faz 5 bips no BZ
{
LEDS = CONT;
BZ = 0;
atraso_ms (500);
LEDS - 0x00;
BZ = 1;
atraso_ms (500);
}
CONT = 0x00; // Zera CONT
LEDS = 0x00; // Zera LEDS
}
} // Fim do Loop Infinito
} // Fim do Programa Principal











32
7.5. Exerccios Resolvidos

7.5.1. EXR6.C

Mudar a instruo que incrementa a contagem no PROG7 (com realce em amarelo) para incremento
em decimal.
- Para fazer o incremento em decimal, segue-se o seguinte algoritmo:
. Antes de incrementar a contagem, testa-se o nibble menos significativo de CONT;
. Se o nibble menos significativo for igual a 9, soma-se 7 CONT ( 0x09+7=0x10 ;
0x19+7=0x20 ; 0x29+7=0x30...)
. Se o nibble menos significativo for diferente de 9, some-se 1 a CONT.

Este trecho de programa ficaria assim:

teste = CONT & 0xF0;
if (teste = = 0x09) CONT = CONT+7
else CONT++;

OBS: O algoritmo utilizado tem uma situao de erro: quando o valor de CONT for 0x99, ao
somar-se 7 o resultado ficaria 0xA0 ao invs de 0x00. Uma das solues possveis dada a seguir

if (CONT != 0x99)
{
teste = CONT & 0x0F;
if (teste = = 0x09) CONT = CONT+7
else CONT++;
}
else CONT = 0x00

7.7. Exerccios Propostos

EX8.C D um programa que realize uma contagem de tempo em segundos nos LEDS ( de 0x00 a
0x99). Esta contagem deve estar condicionada DIP1. Se DIP1=0 o contador deve estar parado,
caso contrrio o contador segue contando em segundos.
EX9.C De um programa que aguarde o acionamento da PB. Quando PB for acionada, realizar
uma contagem regressiva nos LEDS de 0x09 a 0x00 (em segundos). Ao chegar a 0x00 o buzzer
deve disparar. Um pulso na DIP1 deve desligar o buzzer e retornar ao incio do programa.


7.8. Projeto proposto

PROJ4.C Projeto de aplicao de livre escolha. Sugestes: Controle de motor de passo, Controle
de Temperatura de uma estufa, Controle de velocidade de um motor por PWM, etc.







33
8. Atividades no presenciais

a) Digitar, compilar e testar os exerccios resolvidos: EXR1.C a EXR6.C
b) Resolver os exerccios propostos: EX1.C a EX9.C
c) Elaborar os projetos propostos: PROJ1.C a PROJ4.C
d) Compactar todos os programas fonte (*.C) e enviar para o professor Salomo
(salomaocj@jorgestreet.com.br) at 03/07/2013 .



















































34

Apndice A Reviso



Funo OR Funo AND Funo XOR Funo NOT
S = A | B S = A & B S = A ^ B S = !A
A B S A B S A B S A S
0 0 0 0 0 0 0 0 0 0 1
0 1 1 0 1 0 0 1 1 1 0
1 0 1 1 0 0 1 0 0
1 1 1 1 1 1 1 1 1



Tabela de Converso

Binrio Hexa Decimal
0 0 0 0 0 0
0 0 0 1 1 1
0 0 1 0 2 2
0 0 1 1 3 3
0 1 0 0 4 4
0 1 0 1 5 5
0 1 1 0 6 6
0 1 1 1 7 7
1 0 0 0 8 8
1 0 0 1 9 9
1 0 1 0 A 10
1 0 1 1 B 11
1 1 0 0 C 12
1 1 0 1 D 13
1 1 1 0 E 14
1 1 1 1 F 15
























35
Apndice B at89x52.h


/*-------------------------------------------------------------------------
Register Declarations for ATMEL 89x52 Processors

Written By - Bernd Bartmann
Bernd.Bartmann@picard.isdn.cs.tu-berlin.de (1999)
based on reg51.h by Sandeep Dutta sandeep.dutta@usa.net
KEIL C compatible definitions are included

This program is free software; you can redistribute it and/or modify it
under the terms of the GNU General Public License as published by the
Free Software Foundation; either version 2, or (at your option) any
later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.

In other words, you are welcome to use, share and improve this program.
You are forbidden to forbid anyone else to use, share and improve
what you give them. Help stamp out software-hoarding!
-------------------------------------------------------------------------*/

#ifndef AT89x52_H
#define AT89x52_H

/* BYTE addressable registers */
sfr at 0x80 P0 ;
sfr at 0x80 LEDS ;
sfr at 0x81 SP ;
sfr at 0x82 DPL ;
sfr at 0x83 DPH ;
sfr at 0x87 PCON ;
sfr at 0x88 TCON ;
sfr at 0x89 TMOD ;
sfr at 0x8A TL0 ;
sfr at 0x8B TL1 ;
sfr at 0x8C TH0 ;
sfr at 0x8D TH1 ;
sfr at 0x90 P1 ;
sfr at 0x98 SCON ;
sfr at 0x99 SBUF ;
sfr at 0xA0 P2 ;
sfr at 0xA0 DIPS ;
sfr at 0xA8 IE ;
sfr at 0xB0 P3 ;
sfr at 0xB8 IP ;
sfr at 0xC8 T2CON ;
sfr at 0xC9 T2MOD ;
sfr at 0xCA RCAP2L ;


36
sfr at 0xCB RCAP2H ;
sfr at 0xCC TL2 ;
sfr at 0xCD TH2 ;
sfr at 0xD0 PSW ;
sfr at 0xE0 ACC ;
sfr at 0xE0 A ;
sfr at 0xF0 B ;


/* BIT addressable registers */
/* P0 */
sbit at 0x80 P0_0 ;
sbit at 0x81 P0_1 ;
sbit at 0x82 P0_2 ;
sbit at 0x83 P0_3 ;
sbit at 0x84 P0_4 ;
sbit at 0x85 P0_5 ;
sbit at 0x86 P0_6 ;
sbit at 0x87 P0_7 ;
sbit at 0x80 LED1 ;
sbit at 0x81 LED2 ;
sbit at 0x82 LED3 ;
sbit at 0x83 LED4 ;
sbit at 0x84 LED5 ;
sbit at 0x85 LED6 ;
sbit at 0x86 LED7 ;
sbit at 0x87 LED8 ;

/* TCON */
sbit at 0x88 IT0 ;
sbit at 0x89 IE0 ;
sbit at 0x8A IT1 ;
sbit at 0x8B IE1 ;
sbit at 0x8C TR0 ;
sbit at 0x8D TF0 ;
sbit at 0x8E TR1 ;
sbit at 0x8F TF1 ;

/* P1 */
sbit at 0x90 P1_0 ;
sbit at 0x91 P1_1 ;
sbit at 0x92 P1_2 ;
sbit at 0x93 P1_3 ;
sbit at 0x94 P1_4 ;
sbit at 0x95 P1_5 ;
sbit at 0x96 P1_6 ;
sbit at 0x97 P1_7 ;

sbit at 0x90 T2 ;
sbit at 0x91 T2EX ;

/* SCON */
sbit at 0x98 RI ;
sbit at 0x99 TI ;
sbit at 0x9A RB8 ;
sbit at 0x9B TB8 ;
sbit at 0x9C REN ;


37
sbit at 0x9D SM2 ;
sbit at 0x9E SM1 ;
sbit at 0x9F SM0 ;

/* P2 */
sbit at 0xA0 P2_0 ;
sbit at 0xA1 P2_1 ;
sbit at 0xA2 P2_2 ;
sbit at 0xA3 P2_3 ;
sbit at 0xA4 P2_4 ;
sbit at 0xA5 P2_5 ;
sbit at 0xA6 P2_6 ;
sbit at 0xA7 P2_7 ;
sbit at 0xA0 DIP1 ;
sbit at 0xA1 DIP2 ;
sbit at 0xA2 DIP3 ;
sbit at 0xA3 DIP4 ;
sbit at 0xA4 DIP5 ;
sbit at 0xA5 DIP6 ;
sbit at 0xA6 DIP7 ;
sbit at 0xA7 DIP8 ;

/* IE */
sbit at 0xA8 EX0 ;
sbit at 0xA9 ET0 ;
sbit at 0xAA EX1 ;
sbit at 0xAB ET1 ;
sbit at 0xAC ES ;
sbit at 0xAD ET2 ;
sbit at 0xAF EA ;

/* P3 */
sbit at 0xB0 P3_0 ;
sbit at 0xB1 P3_1 ;
sbit at 0xB2 P3_2 ;
sbit at 0xB2 PB ;
sbit at 0xB3 P3_3 ;
sbit at 0xB4 P3_4 ;
sbit at 0xB5 P3_5 ;
sbit at 0xB6 P3_6 ;
sbit at 0xB7 P3_7 ;
sbit at 0xB7 BZ ;

sbit at 0xB0 RXD ;
sbit at 0xB1 TXD ;
sbit at 0xB2 INT0 ;
sbit at 0xB3 INT1 ;
sbit at 0xB4 T0 ;
sbit at 0xB5 T1 ;
sbit at 0xB6 WR ;
sbit at 0xB7 RD ;

/* IP */
sbit at 0xB8 PX0 ;
sbit at 0xB9 PT0 ;
sbit at 0xBA PX1 ;
sbit at 0xBB PT1 ;


38
sbit at 0xBC PS ;
sbit at 0xBD PT2 ;

/* T2CON */
sbit at 0xC8 T2CON_0 ;
sbit at 0xC9 T2CON_1 ;
sbit at 0xCA T2CON_2 ;
sbit at 0xCB T2CON_3 ;
sbit at 0xCC T2CON_4 ;
sbit at 0xCD T2CON_5 ;
sbit at 0xCE T2CON_6 ;
sbit at 0xCF T2CON_7 ;

sbit at 0xC8 CP_RL2 ;
sbit at 0xC9 C_T2 ;
sbit at 0xCA TR2 ;
sbit at 0xCB EXEN2 ;
sbit at 0xCC TCLK ;
sbit at 0xCD RCLK ;
sbit at 0xCE EXF2 ;
sbit at 0xCF TF2 ;

/* PSW */
sbit at 0xD0 P ;
sbit at 0xD1 FL ;
sbit at 0xD2 OV ;
sbit at 0xD3 RS0 ;
sbit at 0xD4 RS1 ;
sbit at 0xD5 F0 ;
sbit at 0xD6 AC ;
sbit at 0xD7 CY ;


/* BIT definitions for bits that are not directly accessible */
/* PCON bits */
#define IDL 0x01
#define PD 0x02
#define GF0 0x04
#define GF1 0x08
#define SMOD 0x80

#define IDL_ 0x01
#define PD_ 0x02
#define GF0_ 0x04
#define GF1_ 0x08
#define SMOD_ 0x80

/* TMOD bits */
#define M0_0 0x01
#define M1_0 0x02
#define C_T0 0x04
#define GATE0 0x08
#define M0_1 0x10
#define M1_1 0x20
#define C_T1 0x40
#define GATE1 0x80



39
#define M0_0_ 0x01
#define M1_0_ 0x02
#define C_T0_ 0x04
#define GATE0_ 0x08
#define M0_1_ 0x10
#define M1_1_ 0x20
#define C_T1_ 0x40
#define GATE1_ 0x80

#define T0_M0 0x01
#define T0_M1 0x02
#define T0_CT 0x04
#define T0_GATE 0x08
#define T1_M0 0x10
#define T1_M1 0x20
#define T1_CT 0x40
#define T1_GATE 0x80

#define T0_M0_ 0x01
#define T0_M1_ 0x02
#define T0_CT_ 0x04
#define T0_GATE_ 0x08
#define T1_M0_ 0x10
#define T1_M1_ 0x20
#define T1_CT_ 0x40
#define T1_GATE_ 0x80

#define T0_MASK 0x0F
#define T1_MASK 0xF0

#define T0_MASK_ 0x0F
#define T1_MASK_ 0xF0

/* T2MOD bits */
#define DCEN 0x01
#define T2OE 0x02

#define DCEN_ 0x01
#define T2OE_ 0x02


/* Interrupt numbers: address = (number * 8) + 3 */
#define IE0_VECTOR 0 /* 0x03 external interrupt 0 */
#define TF0_VECTOR 1 /* 0x0b timer 0 */
#define IE1_VECTOR 2 /* 0x13 external interrupt 1 */
#define TF1_VECTOR 3 /* 0x1b timer 1 */
#define SI0_VECTOR 4 /* 0x23 serial port 0 */
#define TF2_VECTOR 5 /* 0x2B timer 2 */
#define EX2_VECTOR 5 /* 0x2B external interrupt 2 */

#endif

Вам также может понравиться