HD44780U - SENAI
Transcription
HD44780U - SENAI
ESCOLA SENAI NAMI JAFET LUCAS TADEU M. G. F. SALOMÃO BRAÇO ROBÓTICO MICROCONTROLADO Mogi das cruzes 2010 ESCOLA SENAI NAMI JAFET LUCAS TADEU M. G. F. SALOMÃO BRAÇO ROBÓTICO MICROCONTROLADO Trabalho de Conclusão de Curso apresentado ao curso de Técnico em Eletroeletrônica da Escola Senai Nami Jafet como parte dos requisitos para a conclusão do curso. Profº Orientador: Alexandre Rodrigues de Almeida Profº Co-Orientador: José Antônio Barros de Oliveira Mogi das cruzes 2010 LUCAS TADEU M. G. F. SALOMÃO BRAÇO ROBÓTICO MICROCONTROLADO Trabalho de Conclusão de Curso apresentado ao curso de Técnico em Eletroeletrônica da Escola Senai Nami Jafet como parte dos requisitos para a conclusão do curso. Aprovado em ____________________________________ BANCA EXAMINADORA _______________________________________ Profº Carlos Alberto de Farias _______________________________________ Profº Carlos Ferreira de Souza _______________________________________ Profº Faustino Hiroshi Nakagawa _______________________________________ Profº José Álvaro Celidônio Gomes dos Reis _______________________________________ Profº Ignácio Antônio da Cunha Filho Dedico este trabalho a Deus acima de tudo que me deu sabedoria para conduzir esta empreitada e a aos meus pais por acreditarem em mim e me apoiarem. AGRADECIMENTOS Ao Profº Alexandre que me orientou neste projeto e me incentivou a cada dia a buscar o melhor. Ao Profº José Antônio que teve paciência de me ensinar e me orientar no ramo desconhecido que é a mecânica para mim. Aos alunos Rafael Roberto e Thaynan Nominato pela ajuda na usinagem das peças mecânicas. RESUMO Este trabalho tem como objetivo a construção de um braço robótico que será controlado através do microcontrolador AT89S52. Através de um display de cristal líquido (LCD) será mostrada uma pequena apresentação do trabalho e o estado que o braço robótico se encontra. O protocolo de comunicação serial RS232 foi implementado ao projeto para a transmissão de uma mensagem ao computador. Os movimentos do braço robótico serão feitos por motores de corrente contínua, controlados por drives de acionamento, utilizando o circuito integrado L298. Além disso, foi instalado na placa de controle um gravador para o microcontrolador. O programa do microcontrolador foi escrito em Assembly, que é uma linguagem de baixo nível. O circuito eletrônico foi projetado no ambiente de simulação Proteus, utilizando o programa ISIS. O projeto mecânico foi desenvolvido com a ajuda do software Inventor Professional 2008. Palavra-chave: Braço Robótico, microcontrolador. ABSTRACT This paper aims to build a robotic arm that will be controlled through the microcontroller AT89S52. Through a liquid crystal display (LCD) will be shown a short presentation of the work and state that the robotic arm is. The RS232 serial communication protocol was implemented for the project to transmit a message to the computer. The movements of the robotic arm will be made by DC motors, drivecontrolled drives, using the L298 chip. Furthermore, it was installed in a burner control board to the microcontroller. The microcontroller program was written in Assembler, which is a low-level language. The electronic circuit was designed in the simulation environment Proteus, use it if the ISIS program. The mechanical design was developed with the help of Inventor Professional 2008 software. Keyword: Robotic Arm, microcontroller. SUMÁRIO 1. INTRODUÇÃO ___________________________________________________________13 2. MICROPROCESSADORES ____________________________________________14 2.1 A CPU ____________________________________________________________________15 2.2 DIFERENÇA ENTRE MICROPROCESSADOR E MICROCONTROLADOR __16 2.3 MICROCONTROLADORES 8051 __________________________________________17 2.4 O MICROCONTROLADOR AT89S52 _______________________________________19 2.4.1 PINAGEM DO AT89S52 ____________________________________________________21 2.4.1.1 PORT 0 _________________________________________________________________21 2.4.1.2 PORT 1 _________________________________________________________________22 2.4.1.3 PORT 2 _________________________________________________________________22 2.4.1.4 PORT 3 _________________________________________________________________23 2.4.1.5 RST ____________________________________________________________________24 2.4.1.6 ALE/PROG ______________________________________________________________24 2.4.1.7 PSEN ___________________________________________________________________25 2.4.1.8 EA/VPP _________________________________________________________________25 2.4.1.9 XTAL 1 _________________________________________________________________25 2.4.1.10 XTAL 2 ________________________________________________________________25 2.4.1.11 Vcc ___________________________________________________________________25 2.4.1.12 GND ____________________________________________________________26 2.4.2 ORGANIZAÇÃO DA MEMÓRIA _____________________________________________26 3. DISPLAY LCD ___________________________________________________________28 3.1 PINAGEM DO MÓDULO LCD ______________________________________________29 3.2 INTERFACE COM A CPU __________________________________________________30 3.3 INSTRUÇÕES _____________________________________________________________32 3.4 INICIALIZAÇÃO ___________________________________________________________34 4. COMUNICAÇÃO SERIAL ______________________________________________36 4.1 CANAIS DE COMUNICAÇÃO ______________________________________________37 4.2 A COMUNICAÇÃO SERIAL ________________________________________________37 4.2.1 TAXA DE TRANSFERÊNCIA (BAUD RATE) __________________________________38 4.2.2 TRANSMISSÃO ASSÍNCRONA X TRANSMISSÃO SÍNCRONA _________________39 4.2.3 CHECKSUM E PARIDADE _________________________________________________41 4.3 CARACTERES ASCII _____________________________________________________42 4.3.1 TABELA ASCII ____________________________________________________________43 4.3.1.1 CARACTERES NÃO IMPRIMÍVEIS ________________________________________43 4.3.1.2 CARACTERES IMPRIMÍVEIS _____________________________________________44 4.3.1.3 TABELA ASCII ESTENDIDA ______________________________________________48 4.4 INTERFACE SERIAL RS232 _______________________________________________48 4.4.1 DEFINIÇÃO DE SINAIS ____________________________________________________49 4.4.2 PINAGEM ________________________________________________________________53 4.4.3 CARACTERISTICAS DOS SINAIS ___________________________________________56 4.4.4 TEMPORIZAÇÃO DOS SINAIS ______________________________________________57 4.4.5 CONVERSORES DE NÍVEL TTL – RS232 ____________________________________58 4.4.6 CABO NULL MODEM ______________________________________________________59 4.4.7 CONTROLE DO FLUXO DE DADOS _________________________________________61 5. O HYPERTERMINAL ___________________________________________________62 5.1 CONFIGURANDO O HYPERTERMINAL PARA A COMUNICAÇÃO COM O MICROCONTROLADOR ______________________________________________________62 6. O CIRCUITO INTEGRADO L298 ______________________________________66 7. O BRAÇO ROBÓTICO _________________________________________________69 7.1 ESTRUTURA MECÂNICA _________________________________________________69 7.2 CIRCUITO ELETRÔNICO __________________________________________________72 7.2.1 FUNCIONAMENTO ________________________________________________________72 7.2.2 DIAGRAMA ELÉTRICO _______________________________________________73 7.2.2.1 LISTA DE COMPONENTES ELETRÔNICOS ________________________________75 7.2.3 CÓDIGO FONTE __________________________________________________________76 7.2.4 FLUXOGRAMA DE FUNCIONAMENTO ______________________________________83 7.3 GRAVADOR ISP __________________________________________________________86 7.3.1 UTILIZAÇÃO DO SOFTWARE ISP FLASH PROGRAMMER VERSION 3.0a ______87 7.3.2 CABO DE TRANSFERÊNCIA DE DADOS ____________________________________88 8. RESULTADOS __________________________________________________________89 9. CONCLUSÃO ___________________________________________________________90 REFERÊNCIAS ____________________________________________________________91 ANEXOS ____________________________________________________________________92 LISTA DE ILUSTRAÇÕES Figura 2.1 – Arquitetura básica do Microprocessador Figura 2.2 – Ilustração da CPU em um ciclo de busca de instrução (na ROM) Figura 2.3 – Diferença entre um microprocessador e um microcontrolador Figura 2.4 – Diagrama de blocos do 8048 Figura 2.5 – Diagrama de blocos do 8051 Figura 2.6 – Pinagem do AT89S52 Figura 2.7 – Diagrama de blocos do AT89S52 Figura 2.8 – Estrutura de memórias Figura 2.9 – RAM interna Figura 2.10 – Registradores da RAM interna Figura 3.1 – Circuito de controle de contraste Figura 3.2 – Ciclo de escrita de memória externa do microcontrolador Figura 3.3 – Ciclo de escrita do módulo LCD Figura 3.4 – Ciclo de leitura do módulo LCD Figura 4.1 – Transmissão a uma taxa de 9600 bps Figura 4.2 – Canal de dados e de sincronismo Figura 4.3 – Transmissão assíncrona Figura 4.4 – Tipos de paridade Figura 4.5 – Cálculo do checksum Figura 4.6 – DTE e DCE Figura 4.7 – Dois DTE interligados através de um modem Figura 4.8 – Pinagem do conector do DTE Figura 4.9 – Pinagem do conector do DCE Figura 4.10 – Sinais mais comuns Figura 4.11 – Circuito elétrico equivalente do RS232 Figura 4.12 – Sinal típico do RS232 Figura 4.13 – O CI MAX232 Figura 4.14 – Configuração do cabo Null Modem Figura 5.1 – Inserindo um nome para a conexão Figura 5.2 – Nome da conexão e ícone escolhido Figura 5.3 – Escolhendo a porta de comunicação Figura 5.4 – Configurando a porta de comunicação Figura 5.5 – Alterando o Controle de Fluxo Figura 5.6 – HyperTerminal configurado e já conectado à porta COM1 Figura 6.1 - Digrama interno do L298 Figura 6.2 - Pinagem do L298 Figura 6.3 - Controle de motor DC Figura 6.4 - Conexão em paralelo de duas pontes Figura 7.1 - Esquematização de forças Figura 7.2 – Sistema de polias e correia Figura 7.3 - O Braço Robótico Figura 7.4 - Unidade Processamento e Drive de Controle dos motores Figura 7.5 - Tela inicial do programa Figura 7.6 - Configuração do cabo para gravação LISTA DE TABELAS Tabela 2.1 – Funções especiais do PORT 1 Tabela 2.2 - Funções especiais do PORT 3 Tabela 3.1 – LCD disponíveis Tabela 3.2 – Pinagem do módulo LDC Tabela 3.3 – Principais instruções dos módulos LCD Tabela 3.4 – Instruções do controlador e tempo de execução Tabela 4.1 – Caracteres de Controle Tabela 4.2 – Caracteres imprimíveis Tabela 4.3 – Tabela ASCII estendida Tabela 4.4 – Sinais de referência Tabela 4.5 – Canal de comunicação primário Tabela 4.6 – Canal de comunicação secundário Tabela 4.7 – Sinais de controle e status Tabela 4.8 – Sinais de transmissão e recepção Tabela 4.9 – Sinais de teste Tabela 7.1 – Lista de componentes eletrônicos LISTA DE ABREVEATURA E SIGLAS PC Personal Computer LCD Liquid Crystal Display ISP In-Systen Programming ROM Read Only Memory RAM Random Access Memory CPU Central Processing Unit I/O Input / Output ALU Arithmetic Logic Unit EPROM Erasable Programmable Read-Only Memory TTL Transistor-Transistor Logic CRT Cathode Ray Tube LED Light-Emitting Diode EIA Electronic Industries Alliance ASCII American Standard Code for Information Interchange DTE Data Terminal Equipment DCE Data Circuit-terminating Equipment BBS Bulletin Board System DC Direct Current PWM Pulse-Width Modulation CI Circuito Integrado ABNT Associação Brasileira de Normas Técnicas P2 Polia Motora P3 Polia Movida Dp Diâmetro primitivo EPP Enhanced Parallel Port DLL Dynamic-link library 13 1. INTRODUÇÃO Atualmente, com o avanço da tecnologia e o aumento da competitividade entre as indústrias, viu-se necessário a substituição de alguns processos realizados manualmente. Nesse contexto de que “tempo é dinheiro”, surgiram os primeiros robôs com a finalidade de realizar as tarefas humanas com maior precisão e repetibilidade. O braço robótico está presente nas indústrias dos mais variados segmentos, sejam para a movimentação de peças, até a soldagem de chassis inteiros de carros. Este trabalho tem como objetivo a construção de um braço robótico para efeito didático, controlado por um microcontrolador da família 8051, mais especificamente o AT89S52 da Atmel. O microcontrolador irá se comunicar com o PC através da porta serial, utilizando o protocolo RS232. Na tela do computador será mostrada uma apresentação básica do projeto. Além disso, será mostrado em um display de LCD o estado do robô. Todo o controle será feito na placa principal, a qual é munida de um gravador ISP (In-Systen Programming) com a finalidade de realizar a gravação sem a necessidade de um gravador externo. 14 2. MICROPROCESSADORES Um microprocessador é um elemento eletrônico, desenvolvido para executar tarefas específicas, com linguagem de comando específica. Ele utiliza uma Memória de Programa (Code Memory – ROM) para ler as instruções que deve executar e se utiliza de uma Memória de Dados (Data Memory – RAM) para armazenar temporariamente informações de uso próprio das instruções, enquanto essas informações devem ser armazenadas. Na figura 2.1, vemos a ilustração simplificada de um microprocessador com CPU (Central Processing Unit) e seus elementos básicos associados: RAM, ROM, periféricos e fonte de alimentação. Figura 2.1 – Arquitetura básica do Microprocessador. No microprocessador há vias (Bus = Barramento) de controle, endereço, de comunicação de dados, de controle auxiliar e de entrada e saídas (I/O – Input/Output). As vias de controle de endereço servem para a CPU selecionar com qual posição de memória ou periféricos deseja se comunicar. As vias de controle auxiliar são sinais auxiliares que permitem ao microprocessador acionar, por exemplo, em certo tempo, a ROM e não a RAM, e vice-versa. Os dados 15 e endereços trafegam pela mesma via; por isso as vias de controle servem para escolher um endereço ou ler/escrever um dado no barramento. As vias de I/O são as vias que permitem a conexão com o mundo externo, a fim de a CPU trocar informações com ele. Nela pode ser conectado qualquer periférico, como teclados, displays, lâmpadas, motores entre outros. A CPU é o cérebro do sistema, e tem a função de comandar todos os barramentos, de acordo com as informações gravadas na ROM. O oscilador é o elemento que gera o “marca passo” da CPU, que permite que o microprocessador realize as tarefas internas e externas de maneira sincronizada e com velocidade predeterminada. O reset é o elemento que faz a CPU iniciar suas rotinas internas e realizar também a primeira leitura de instrução no endereço 0000h. As interrupções são pinos de acesso externo que permitem interromper o microprocessador, que então interrompe suas tarefas atuais e atende aquelas planejadas pela interrupção solicitada. 2.1 A CPU A seguir, na figura 2.2, vemos o ciclo de leitura de uma instrução na ROM. Figura 2.2 – Ilustração da CPU em um ciclo de busca de instrução (na ROM). 16 Os registradores são equivalentes a uma RAM, só que interna à CPU. Servem para armazenamento temporário de informações de utilidade interna ou externa à CPU. O contador de programa (Program Couter – PC) é o indicador de endereço de memória. Ele serve para endereçar a próxima instrução a ser lida pelo microprocessador. O registrador de instrução (Instruction Register – IR) é o local para onde se dirige o código da instrução que foi lida na ROM por meio do endereço do PC no ciclo de busca. O IR é necessário para que se possa mandar a instrução para o decodificador. A unidade de decodificação é o local onde a instrução é decodificada, e também são gerados os controles que, junto com a unidade de controle, permitem executar a instrução na ALU. A unidade lógica e aritmética (Arithmetic Logic Unit – ALU) é o local em que são realizadas as operações de lógica, aritmética e decisão/comparação. É o cérebro da máquina. O acumulador (Accumulator) é um registrador principal, e várias instruções se referem a ele para ele operar. A unidade de controle (Control Unit) é o local em que se processa o controle de fluxo das informações a fim de realizar a instrução recebida. 2.2 DIFERENÇA ENTRE MICROPROCESSADOR E MICROCONTROLADOR A principal diferença entre um microprocessador e um microcontrolador é o hardware interno. A maioria das aplicações que utilizam um microprocessador necessita de memória ROM, RAM e de chips auxiliares como temporizadores/contadores, interfaces seriais, entre outros. No microcontrolador esses periféricos já se encontram dentro de um único chip. Veja na figura 2.3 a diferença entre os dois. 17 Figura 2.3 – Diferença entre um microprocessador e um microcontrolador. 2.3 MICROCONTROLADORES 8051 A família 8051 originou-se a partir da família 8048. Esta foi a primeira família de controladores lançada no mercado pela INTEL. As limitações tecnológicas da época (1976) impuseram uma série de restrições, mas, para a época, foi um grande produto. Uma de suas maiores aplicações foram os teclados dos computadores de 16 bits, IBM PC (lançados em 1981). 18 Figura 2.4 – Diagrama de blocos do 8048. O 8048 oferece os seguintes recursos: • Interrupções (em 1 nível somente), • Single Step, • 1K de ROM interna (8748 tinha uma EPROM de 1K), • Memória de Programa Externa de até 4 KB (PC=12 bits com o bit mais significativo, alterado pela instrução SEL, chaveando os 2 bancos de 2K), • Aceita outros periféricos (8155,8255,8355,8243,8279), • 96 instruções, 90% de 1 byte. O êxito da família MCS-48 e os avanços da tecnologia dos circuitos integrados levaram a INTEL a lançar no mercado a família MCS-51 em 1980. O microcontrolador 8051 é o membro original da família e também o núcleo para toda a MCS-51. 19 Figura 2.5 – Diagrama de blocos do 8051. O 8051 oferece os seguintes recursos: • 5 Interrupções (2 externas, 2 dos timers/counters e 1 da porta serial), • 64 KB de Memória de Programa (PC=16 bits), • 64 KB de Memória de Dados, • 111 Instruções: o 1 ciclo " 64 " 58% o 2 ciclos " 45 " 40% o 4 ciclos " 2 " 2% o 1 byte " 49 " 44% o 2 bytes " 46 " 41% o 3 bytes " 16 " 15% • 98% de 1 ou 2 ciclos " velocidade • 85% de 1 ou 2 bytes " compacto 2.4 O MICROCONTROLADOR AT89S52 O microcontrolador AT89S52, da Atmel, pertence à família MCS-51 e é o mais utilizado por suas características e pelo baixo custo e fácil aquisição no mercado. Suas principais características são: 20 • Compatível com a família MCS-51; • 8K Bytes de memória Flash ISP, com 10.000 ciclos de gravação e apagamento; • Faixa de operação de 4,0V à 5,5V; • Operação totalmente estática de 0Hz à 33MHz • Proteção de programa em três níveis (Lock Bits) • RAM interna de 256 bytes • 32 estradas/saídas programáveis • Três contadores/temporizadores de 16 bits • Oito fonts de interrupção • Canal serial programável Full Duplex • Modo de economia de energia • Reseta a CPU através da interrupção de economia de energia • Temporizador Watchdog • Data Pointer duplo • Tempo de programação rápido • Programação ISP (bytes e página) Figura 2.6 – Pinagem do AT89S52. 21 Figura 2.7 – Diagrama de blocos do AT89S52. 2.4.1 PINAGEM DO AT89S52 2.4.1.1 PORT 0 O PORT 0 é uma porta bidirecional de I/O de 8 bits de dreno aberto. Como porta de saída cada pino pode ser interligado a até oito cargas TTL diretamente. Quando se encontra em nível lógico 1, os pinos funcionam como entrada em alta impedância. É também utilizado como via multiplexada da parte baixa dos endereços ou dados, quando se utiliza memória externa. Nesse modo, P0 possui pull-ups internso. 22 Para utilizá-lo como saída é necessário utilizar resistores de pull-up, garantindo assim, nível lógico 1. O PORT 0 também recebe os dados no processo de gravação interna da memória Flash de programa, e é usado como saída no processo de verificação da gravação. Pull-ups externos são necessários durante o processo de verificação. 2.4.1.2 PORT 1 O PORT 1 é uma porta bidirecional de I/O de 8 bits com pull-ups internos. Seu buffer pode suportar até quatro cargas TTL diretamente. Quando se encontra em nível lógico 1, pode ser utilizado com entrada devido aos resistores de pull-up interno, podendo ser colocado em nível lógico 0, fornecendo corrente através dos resistores de pull-up internos. Em adição, os pinos P0.0 e P0.1 podem ser configurados para entradas externas para o contador do TIMER2 (P1.0/T2) e como entrada de habilitação externa do TIMER2 (P1.1/T2EX). O PORT 1 também recebe a parte baixa dos endereços durante o processo de gravação/verificação do chip. Tabela 2.1 – Funções especiais do PORT 1. 2.4.1.3 PORT 2 O PORT 2 é uma porta bidirecional de I/O de 8 bits com pull-ups internos. Seu buffer pode suportar até quatro cargas TTL diretamente. Quando se encontra em nível 23 lógico 1, pode ser utilizado com entrada devido aos resistores de pull-up interno, podendo ser colocado em nível lógico 0, fornecendo corrente através dos resistores de pull-up internos. O PORT 2 envia a parte alta dos endereços em operações de busca de instruções quando o sistema é configurado para utilizar memória de programa externa, e também quando acessa a memória RAM externa que contenha endereços de 16 bits (MOVX @DPTR). Nessa aplicação, o PORT 2 usa fortes pull-ups internos quando seus pinos são levados a nível alto. Durante o acesso à memória externa que usa endereços de 8 bits (MOVX @RI), P2 reflete o conteúdo do registrador especial de funções interno P2. O PORT 2 recebe os bits de alta ordem do endereço e vários sinais de controle durante o processo de gravação/verificação. 2.4.1.4 PORT 3 O PORT 3 é uma porta bidirecional de I/O de 8 bits com pull-ups internos. Seu buffer pode suportar até quatro cargas TTL diretamente. Quando se encontra em nível lógico 1, pode ser utilizado com entrada devido aos resistores de pull-up interno, podendo ser colocado em nível lógico 0, fornecendo corrente através dos resistores de pull-up internos. O PORT 3 recebe vários sinais de controle durante o processo de gravação/verificação. O PORT 3 serve também para várias características especiais do AT89S52, como indica a tabela a seguir. 24 Tabela 2.2 - Funções especiais do PORT 3. 2.4.1.5 RST Entrada de reset. Nível alto nesse pino por dois ciclos de máquina enquanto o oscilador estiver funcionando, reseta o sistema, fazendo com que o microcontrolador reinicie o seu ciclo de busca de instruções na memória de programa localizada no endereço 0000h. 2.4.1.6 ALE/PROG Address Latch Enable (ALE). É um pulso de saída para travar a parte baixa do endereço durante o acesso à memória externa. Esse pino é também opino de entrada do pulso de programação (PROG) durante a operação de gravação da Flash interna. Em operação normal, sem o uso de memória externa, ALE é pulsado em um valor constante de 1/6 da freqüência do oscilador, e pode ser usado como gerador de clock externo em alguns casos. Note que somente um pulso é emitido durante o processo de acesso à memória externa. Se desejado, a operação do pino ALE pode ser inibida alternado o BIT0 do registrador AUXR (8EH). Com esse bit em 1 (nível alto) o pino ALE só é ativado durante operações de escritas/leitura de memória externa (durante as instruções 25 MOVX ou MOVC). Desligando essa função durante o processo de leitura/escrita da memória externa, não causa nenhum efeito no microcontrolador. 2.4.1.7 PSEN Program Store Enable (PSEN) é o pulso de habilitação de leitura para memória de programa externa. 2.4.1.8 EA/VPP External Access Enable (EA). Habilitação de memória de programa externa. EA deve ser ligado ao GND quando se utilizam programas gravados em memória externa. Quando se utilizam programas gravados na memória Flash interna, EA deve ser conectado ao Vcc. Esse pino também recebe a tensão de 12V quando se programaa memora Flash interna. 2.4.1.9 XTAL 1 Pino de entrada inversora do amplificador oscilador interno uo pino de entrada para o circuito oscilador de clock externo. 2.4.1.10 XTAL 2 Pino de saída inversora do amplificador oscilador interno. 2.4.1.11 Vcc Pino de alimentação positiva de 5V. 26 2.4.1.12 GND Pino de alimentação de referência GND. 2.4.2 ORGANIZAÇÃO DA MEMÓRIA Este microcontrolador tem um espaço separado para memória de programa e para memória de dados. É possível também, ele gerenciar memória RAM e ROM externas. Figura 2.8 – Estrutura de memórias. 27 Figura 2.9 – RAM interna. Figura 2.10 – Registradores da RAM interna. 28 3. DISPLAY LCD Os módulos LCD (Liquid Crystal Display) são interfaces de saída muito útil em sistemas microprocessados. Estes módulos podem ser gráficos e a caracter. Com ele é possível escrever mensagens de interação com o mundo externo. Os LCD comuns (tipo caracter) são especificados em número de linhas por colunas e são encontrados nas configurações previstas na tabela 3.1. Tabela 3.1 – LCD disponíveis. Um LCD consiste de um líquido polarizador da luz, eletricamente controlado, que se encontra comprimido dentro de celas entre duas lâminas transparentes polarizadoras. Os eixos polarizadores das duas lâminas estão alinhados perpendicularmente entre si. Cada cela é provida de contatos elétricos que permitem que um campo elétrico possa ser aplicado ao líquido no interior. Entre as suas principais características está a sua leveza, sua portabilidade, e sua capacidade de ser produzido em quantidades muito maiores do que os tubos de raios catódicos (CRT). Seu baixo consumo de energia elétrica lhe permite ser utilizado em equipamentos portáteis, alimentados por bateria eletrônica. É um 29 dispositivo eletrônico-óptico modulado, composto por um determinado número de pixels, preenchidos com cristais líquidos e dispostos em frente a uma fonte de luz para produzir imagens em cores ou preto e branco. 3.1 PINAGEM DO MÓDULO LCD Os módulos podem ser encontrados com LED backlight (com uma iluminação de fundo) para facilitar as leituras durante a noite. Neste caso, a alimentação deste led faz-se normalmente pelos pinos 15 e 16 para os módulos comuns e 19 e 20 para os módulos gráficos, sendo os pinos 15 e 19 para ligação ao anodo e os pinos 16 e 20 para o catodo. A corrente de alimentação deste led varia de 100 a 200mA, dependendo do modelo. Estes módulos utilizam um controlador próprio, permitindo sua interligação com outras placas através de seus pinos, onde deve ser alimentado o módulo e interligado o barramento de dados e controle do módulo com a placa do usuário. Naturalmente que além de alimentar e conectar os pinos do módulo com a placa do usuário deverá haver um protocolo de comunicação entre as partes, que envolve o envio de bytes de instruções e bytes de dados pelo sistema do usuário. A tabela 3.2 descreve cada pino do módulo para conexão deste a outra placa. Tabela 3.2 – Pinagem do módulo LDC. 30 Figura 3.1 – Circuito de controle de contraste. 3.2 INTERFACE COM A CPU Os módulos LCD são projetados para conectar-se com a maioria das CPU’s disponíveis no mercado, bastando para isso que esta CPU atenda as temporizações de leitura e escrita de instruções e dados, fornecido pelo fabricante do módulo. As figuras a seguir mostram um exemplo de diagrama de tempos típico requeridos para operação de escrita e leitura no módulo LCD e, o diagrama de tempo do microcontrolador AT89S52 no ciclo de escrita de memória externa, já que o microcontrolador pode enxergar os periféricos externos como uma memória externa. Figura 3.2 – Ciclo de escrita de memória externa do microcontrolador. 31 Figura 3.3 – Ciclo de escrita do módulo LCD. Figura 3.4 – Ciclo de leitura do módulo LCD. O módulo LCD pode se comunicar com a CPU com um barramento de 4 ou 8 bits dependendo das configurações de inicialização do módulo. 32 3.3 INSTRUÇÕES A seguir segue uma tabela com as principais instruções dos módulos LCD. Tabela 3.3 – Principais instruções dos módulos LCD. A tabela a seguir mostra todas as instruções disponíveis e o tempo médio de execução para os principais módulo LCD existente no mercado. 33 Tabela 3.4 – Instruções do controlador e tempo de execução. 34 3.4 INICIALIZAÇÃO Para utilizar o módulo LCD deve-se inicializá-lo corretamente, de acordo com os procedimentos abaixo: • Energizar o módulo; • Setar o pino Enable, para habilitar o módulo • Resetar o pino R/W, para habilitar a escrita • Resetar o pino RS, para habilitar o envio de uma instrução. • Fixar o modo de utilização, no caso, 2 linhas com via de 8 bits; • Permanecer nessa instrução pelo menos por 37µs; • Resetar o pino Enable; • Setar o pino Enable; • Fixar o controle do display, no caso, display acesso sem cursor; • Permanecer nessa instrução pelo menos por 37µs; • Resetar o pino Enable; • Setar o pino Enable; • Fixar o modo de operação, no caso, deslocando o cursor para a direita; • Permanecer nessa instrução pelo menos por 37µs; • Resetar o pino Enable; • Setar o pino Enable; • Limpar o display e retornar como cursor para o início; Permanecer nessa instrução pelo menos por 1,52ms; • Resetar o pino Enable. A partir desses comandos o módulo LCD está pronto para receber os caracteres, bastando seguir os procedimentos abaixo: • Setar o pino Enable; • Setar o pino RS, para habilitar o envio de dados; • Escrever os dados do caracter no barramento; • Permanecer nessa condição pelo menos por 37µs; • Resetar o pino Enable; • Resetar o pino RS. 35 Este procedimento deve ser feito para cada caracter que se deseja enviar ao display. O tempo de execução mínimo descrito nos procedimentos acima se refere ao módulo LCD que utiliza o controlador HD44780, da Hitachi. 36 4. COMUNICAÇÃO SERIAL A distância que um dado sinal percorre em um computador varia de alguns milímetros, como no caso de conexões de um simples CI, até vários centímetros quando a conexão de sinais envolve, por exemplo, uma placa mãe com conectores para diversos circuitos. Para estas distâncias, o dado digital pode ser transmitido diretamente. Exceto em computadores muito rápidos, os projetistas não se preocupam com o formato e espessura dos condutores, ou com as características analógicas dos sinais de transmissão. Freqüentemente, no entanto, os dados devem ser enviados para fora dos circuitos que constituem o computador. Nesses casos, as distâncias envolvidas podem ser enormes. Infelizmente, com o aumento das distâncias entre a fonte e o destino aumenta também a dificuldade de estabelecer uma transmissão de dados precisa. Isso é resultado de distorções elétricas dos sinais que trafegam através de condutores longos, e de ruídos adicionados ao sinal que se propagam através do meio de transmissão. Embora alguns cuidados devam ser tomados na troca de dados dentro de um computador, o grande problema ocorre quando dados são transferidos para dispositivos fora dos circuitos do computador. Nesse caso a distorção e o ruído podem tornar-se tão severos que a informação é perdida. A Comunicação de Dados estuda os meios de transmissão de mensagens digitais para dispositivos externos ao circuito originador da mensagem. Dispositivos Externos são geralmente circuitos com fonte de alimentação independente dos circuitos relativos a um computador ou outra fonte de mensagens digitais. Como regra, a taxa de transmissão máxima permissível de uma mensagem é diretamente proporcional a potência do sinal, e inversamente proporcional ao ruído. A função de qualquer sistema de comunicação é fornecer a maior taxa de transmissão possível, com a menor potência e com o menor ruído possível. 37 4.1 CANAIS DE COMUNICAÇÃO Um canal de comunicação é um caminho sobre o qual a informação pode trafegar. Ela pode ser definida por uma linha física (fio) que conecta dispositivos de comunicação, ou por um rádio, laser, ou outra fonte de energia radiante. Em comunicação digital, a informação é representada por bits de dados individuais, que podem ser encapsulados em mensagens de vários bits. Um byte (conjunto de 8 bits) é um exemplo de uma unidade de mensagem que pode trafegar através de um canal digital de comunicações. Uma coleção de bytes pode ser agrupada em um “frame” ou outra unidade de mensagem de maior nível. Esses múltiplos níveis de encapsulamento facilitam o reconhecimento de mensagens e interconexões de dados complexos. Um canal no qual a direção de transmissão é inalterada é referido como canal simplex. Por exemplo, uma estação de rádio é um canal simplex porque ela sempre transmite o sinal para os ouvintes e nunca é permitida a transmissão inversa. Um canal half-duplex é um canal físico simples no qual a direção pode ser revertida. As mensagens podem fluir nas duas direções, mas nunca ao mesmo tempo. Em uma chamada telefônica, uma parte fala enquanto a outra escuta. Depois de uma pausa, a outra parte fala e a primeira escuta. Falar simultaneamente resulta em sons que não podem ser compreendidos. Um canal full-duplex permite que mensagens sejam trocadas simultaneamente em ambas as direções. Ele pode ser visto como dois canais simplex, um canal direto e um canal reverso, conectados nos mesmos pontos. 4.2 A COMUNICAÇÃO SERIAL A maioria das mensagens digitais são mais longas que alguns poucos bits. Por não ser prático nem econômico transferir todos os bits de uma mensagem simultaneamente, a mensagem é quebrada em partes menores e transmitida seqüencialmente. A transmissão bit-serial converte a mensagem em um bit por vez através de um canal. Cada bit representa uma parte da mensagem. Os bits 38 individuais são então rearranjados no destino para compor a mensagem original. Em geral, um canal irá passar apenas um bit por vez. A transmissão bit-serial é normalmente chamada de transmissão serial, e é o método de comunicação escolhido por diversos periféricos de computadores. A transmissão byte-serial converte 8 bits por vez através de 8 canais paralelos. Embora a taxa de transferência seja 8 vezes mais rápida que na transmissão bit serial, são necessários 8 canais, e o custo poderá ser maior do que 8 vezes para transmitir a mensagem. Quando as distâncias são curtas, é factível e econômico usar canais paralelos como justificativa para as altas taxas de transmissão. A interface Centronics de impressoras é um caso típico de transmissão byte-serial. 4.2.1 TAXA DE TRANSFERÊNCIA (BAUD RATE) A taxa de transferência refere-se a velocidade com que os dados são enviados através de um canal e é medido em transições elétricas por segundo. Na norma EIA232, ocorre uma transição de sinal por bit, e a taxa de transferência e a taxa de bit (bit rate) são idênticas. Nesse caso, uma taxa de 9600 bauds corresponde a uma transferência de 9600 dados por segundo, ou um período de aproximadamente, 104µs (1/9600 s). Outro conceito é a eficiência do canal de comunicação que é definido como o número de bits de informação utilizável (dados) enviados através do canal por segundo. Ele não inclui bits de sincronismo, formatação, e detecção de erro que podem ser adicionados a informação antes da mensagem ser transmitida, e sempre será no máximo igual a um. Figura 4.1 – Transmissão a uma taxa de 9600 bps. 39 4.2.2 TRANSMISSÃO ASSÍNCRONA X TRANSMISSÃO SÍNCRONA Geralmente, dados serializados não são enviados de maneira uniforme através de um canal. Ao invés disso, pacotes com informação regulares são enviados seguidos de uma pausa. Os pacotes de dados binários são enviados dessa maneira, possivelmente com comprimentos de pausa variável entre pacotes, até que a mensagem tenha sido totalmente transmitida. O circuito receptor dos dados deve saber o momento apropriado para ler os bits individuais desse canal, saber exatamente quando um pacote começa e quanto tempo decorre entre bits. Quando essa temporização for conhecida, o receptor é dito estar sincronizado com o transmissor, e a transferência de dados precisa torna-se possível. Falhas na manutenção do sincronismo durante a transmissão irão causar a corrupção ou perda de dados. Duas técnicas básicas são empregadas para garantir a sincronização correta. Em sistemas síncronos, canais separados são usados para transmitir dados e informação de tempo. O canal de temporização transmite pulsos de clock para o receptor. Através da recepção de um pulso de clock, o receptor lê o canal de dado e armazena o valor do bit encontrado naquele momento. O canal de dados não é lido novamente até que o próximo pulso de clock chegue. Como o transmissor é responsável pelos pulsos de dados e de temporização, o receptor irá ler o canal de dados apenas quando comandado pelo transmissor, e portanto a sincronização é garantida. Figura 4.2 – Canal de dados e de sincronismo. Existem técnicas que compõem o sinal de clock e de dados em um único canal. Isso é usual quando transmissões síncronas são enviadas através de um modem. Dois métodos no qual os sinais de dados contêm informação de tempo são: codificação NRZ (Non-Return-to-Zero) e a codificação Manchester. 40 Em sistemas assíncronos, a informação trafega por um canal único. O transmissor e o receptor devem ser configurados antecipadamente para que a comunicação se estabeleça a contento. Um oscilador preciso no receptor irá gerar um sinal de clock interno que é igual (ou muito próximo) ao do transmissor. Para o protocolo serial mais comum, os dados são enviados em pequenos pacotes de 10 ou 11 bits, dos quais 8 constituem a mensagem. Quando o canal está em repouso, o sinal correspondente no canal tem um nível lógico ‘1’. Um pacote de dados sempre começa com um nível lógico ‘0’ (start bit) para sinalizar ao receptor que uma transmissão foi iniciada. O “start bit” inicializa um temporizador interno no receptor avisando que a transmissão começou e que serão necessários pulsos de clock. Seguido do start bit, 8 bits de dados de mensagem são enviados na taxa de transmissão especificada. O pacote é concluído com os bits de paridade e de parada (“stop bit”). Figura 4.3 – Transmissão assíncrona. O comprimento do pacote de dados é pequeno em sistemas assíncronos para minimizar o risco do oscilador do transmissor e do receptor variar. Quando osciladores a cristal são utilizados, a sincronização pode ser garantida sobre os 11 bits de período. A cada novo pacote enviado, o “start bit” reseta a sincronização, portanto a pausa entre pacotes pode ser longa. 41 4.2.3 CHECKSUM E PARIDADE Ruídos e distúrbios elétricos momentâneos podem causar mudanças nos dados quando estão trafegando pelos canais de comunicação. Se o receptor falhar ao detectar isso, a mensagem recebida será incorreta, resultando em conseqüências possivelmente sérias. Como uma primeira linha de defesa contra erros de dados, eles devem ser detectados. Se um erro pode ser sinalizado, pode ser possível pedir que o pacote com erro seja reenviado, ou no mínimo prevenir que os dados sejam tomados como corretos. Se uma redundância na informação for enviada, 1 ou 2 bits de erros podem ser corrigidos pelo hardware no receptor antes que o dado chegue ao seu destino. O bit de paridade é adicionado ao pacote de dados com o propósito de detecção de erro. Na convenção de paridade-par (“even-parity”), o valor do bit de paridade é escolhido de tal forma que o número total de dígitos ‘1’ dos dados adicionado ao bit de paridade do pacote seja sempre um número par. Na recepção do pacote, a paridade do dado precisa ser recomputada pelo hardware local e comparada com o bit de paridade recebido com os dados. Se qualquer bit mudar de estado, a paridade não irá coincidir, e um erro será detectado. Se um número para de bits for trocado, a paridade coincidirá e o dado com erro será validado. Contudo, uma análise estatística dos erros de comunicação de dados tem mostrado que um erro com bit simples é muito mais provável que erros em múltiplos bits na presença de ruído randômico. Portanto, a paridade é um método confiável de detecção de erro. Figura 4.4 – Tipos de paridade. Outro método de detecção de erro envolve o cálculo de um “checksum” quando mensagens com mais de um byte são transmitidas pelo canal de comunicação. Nesse caso, os pacotes que constituem uma mensagem são adicionados 42 aritmeticamente. Um número de checksum é adicionado a seqüência do pacote de dados de tal forma que a soma dos dados mais o checksum é zero. Quando recebido, os dados devem ser adicionados pelo processador local. Se a soma do pacote der resultado diferente de zero, ocorreu um erro. Na ocorrência de erros é improvável (mas não impossível) que qualquer corrupção de dados resultem em checksum igual a zero. Figura 4.5 – Cálculo do checksum. Podem ocorrer erros que não sejam apenas detectados, mas também sejam corrigidos se código adicional for adicionado a seqüência de dados do pacote. A correção de erros em uma transmissão, contudo, abaixa a eficiência do canal, e o resultado é uma queda na transmissão. 4.3 CARACTERES ASCII ASCII (acrônimo para American Standard Code for Information Interchange, que em português significa "Código Padrão Americano para o Intercâmbio de Informação") é uma codificação de caracteres de oito bits baseada no alfabeto inglês. Os códigos ASCII representam texto em computadores, equipamentos de comunicação, entre outros dispositivos que trabalham com texto. Desenvolvida a partir de 1960, grande parte das codificações de caracteres modernas a herdaram como base. 43 A codificação define 128 caracteres, preenchendo completamente os sete bits disponíveis. Desses, 33 não são imprimíveis, como caracteres de controle atualmente não utilizáveis para edição de texto porem amplamente utilizado em dispositivos de comunicação, que afetam o processamento do texto. Exceto pelo caractere de espaço, o restante é composto por caracteres imprimíveis. Existe uma tabela entendida para 8 bits que inclui os caracteres acentuados. 4.3.1 TABELA ASCII 4.3.1.1 CARACTERES NÃO IMPRIMÍVEIS Representados como a parte não imprimível da tabela ASCII, os caracteres de controle tiveram sua origem nos primórdios da computação, quando se usavam máquinas teletipo e fitas de papel perfurado. Caracter Decimal Hexadecimal Binário Comentário NUL 00 00 0000 0000 Caracter Nulo SOH 01 01 0000 0001 Começo de cabeçalho de transmissão STX 02 02 0000 0010 Começo de texto ETX 03 03 0000 0011 Fim de texto EOT 04 04 0000 0100 Fim de transmissão ENQ 05 05 0000 0101 Interroga ACK 06 06 0000 0110 Confirmação BEL 07 07 0000 0111 Sinal sonoro BS 08 08 0000 0100 Volta um caracter HT 09 09 0000 1001 Tabulação Horizontal LF 10 0A 0000 1010 Próxima linha VT 11 0B 0000 1011 Tabulação Vertical FF 12 0C 0000 1100 Próxima Página CR 13 0D 0000 1101 Início da Linha SO 14 0E 0000 1110 Shift-out SI 15 0F 0000 1111 Shift-in DLE 16 10 0001 0000 Data link escape D1 17 11 0001 0001 Controle de dispositivo 44 D2 18 12 0001 0010 Controle de dispositivo D3 19 13 0001 0011 Controle de dispositivo D4 20 14 0001 0100 Controle de dispositivo NAK 21 15 0001 0101 Negativa de Confirmação SYN 22 16 0001 0110 Synchronous idle ETB 23 17 0001 0111 Fim de transmissão de bloco CAN 24 18 0001 1000 Cancela EM 25 19 0001 1001 Fim de meio de transmissão SUB 26 1A 0001 1010 Substitui ESC 27 1B 0001 1011 Escape FS 28 1C 0001 1100 Separador de Arquivo GS 29 1D 0001 1101 Separador de Grupo RS 30 1E 0001 1110 Separador de registro US 31 1F 0001 1111 Separador de Unidade Tabela 4.1 – Caracteres de Controle. 4.3.1.2 CARACTERES IMPRIMÍVEIS Caracter Decimal Hexadecimal Binário Espaço 32 20 0010 0000 ! 33 21 0010 0001 “ 34 22 0010 0010 # 35 23 0010 0011 $ 36 24 0010 0100 % 37 25 0010 0101 & 38 26 0010 0110 ‘ 39 27 0010 0111 ( 40 28 0010 1000 ) 41 29 0010 1001 * 42 2A 0010 1010 + 43 2B 0010 1011 , 44 2C 0010 1100 45 - 45 2D 0010 1101 . 46 2E 0010 1110 / 47 2F 0010 FFFF 0 48 30 0011 0000 1 49 31 0011 0001 2 50 32 0011 0010 3 51 33 0011 0011 4 52 34 0011 0100 5 53 35 0011 0101 6 54 36 0011 0110 7 55 37 0011 0111 8 56 38 0011 1000 9 57 39 0011 1001 : 58 3A 0011 1010 ; 59 3B 0011 1011 < 60 3C 0011 1100 = 61 3D 0011 1101 > 62 3E 0011 1110 ? 63 3F 0011 1111 @ 64 40 0100 0000 A 65 41 0100 0001 B 66 42 0100 0010 C 67 43 0100 0011 D 68 44 0100 0100 E 69 45 0100 0101 F 70 46 0100 0110 G 71 47 0100 0111 H 72 48 0100 1000 I 73 49 0100 1001 J 74 4A 0100 1010 K 75 4B 0100 1011 L 76 4C 0100 1100 M 77 4D 0100 1101 46 N 78 4E 0100 1110 O 79 4F 0100 1111 P 80 50 0101 0000 Q 81 51 0101 0001 R 82 52 0101 0010 S 83 53 0101 0011 T 84 54 0101 0100 U 85 55 0101 0101 V 86 56 0101 0110 W 87 57 0101 0111 X 88 58 0101 1000 Y 89 59 0101 1001 Z 90 5A 0101 1010 [ 91 5B 0101 1011 \ 92 5C 0101 1100 ] 93 5D 0101 1101 ^ 94 5E 0101 1110 _ 95 5F 0101 1111 ` 96 60 0110 0000 a 97 61 0110 0001 b 98 62 0110 0010 c 99 63 0110 0011 d 100 64 0110 0100 e 101 65 0110 0101 f 102 66 0110 0110 g 103 67 0110 0111 h 104 68 0110 1000 i 105 69 0110 1001 j 106 6A 0110 1010 k 107 6B 0110 1011 l 108 6C 0110 1100 m 109 6D 0110 1101 n 110 6E 0110 1110 47 o 111 6F 0110 1111 p 112 70 0111 0000 q 113 71 0111 0001 r 114 72 0111 0010 s 115 73 0111 0011 t 116 74 0111 0100 u 117 75 0111 0101 v 118 76 0111 0110 w 119 77 0111 0111 x 120 78 0111 1000 y 121 79 0111 1001 z 122 7A 0111 1010 { 123 7B 0111 1011 | 124 7C 0111 1100 } 125 7D 0111 1101 ~ 126 7E 0111 1110 DELETE 127 7F 0111 1111 Tabela 4.2 – Caracteres imprimíveis. 48 4.3.1.3 TABELA ASCII ESTENDIDA Tabela 4.3 – Tabela ASCII estendida. 4.4 INTERFACE SERIAL RS232 RS é uma abreviação de “Recommended Standard”. Ela relata uma padronização de uma interface comum para comunicação de dados entre equipamentos, criada no início dos anos 60, por um comitê conhecido atualmente como “Electronic Industries Association” (EIA). Naquele tempo, a comunicação de dados compreendia a troca de dados digitais entre um computador central (mainframe) e terminais de computador remotos, ou entre dois terminais sem o envolvimento do computador. Estes dispositivos poderiam ser conectados através de linha telefônica, e conseqüentemente necessitavam um modem em cada lado para fazer a 49 decodificação dos sinais. Dessas idéias nasceu o padrão RS232. Ele especifica as tensões, temporizações e funções dos sinais, um protocolo para troca de informações, e as conexões mecânicas. A mais de 30 anos desde que essa padronização foi desenvolvida, a EIA publicou três modificações. A mais recente, EIA232E, foi introduzida em 1991. Ao lado da mudança de nome de RS232 para EIA232, algumas linhas de sinais foram renomeadas e várias linhas novas foram definidas. Embora tenha sofrido poucas alterações, muitos fabricantes adotaram diversas soluções mais simplificadas que tornaram impossível a simplificação da padronização proposta. As maiores dificuldades encontradas pelos usuários na utilização da interface RS232 incluem pelo menos um dos seguintes fatores: • A ausência ou conexão errada de sinais de controle resultam em estouro do buffer (“overflow”) ou travamento da comunicação. • Função incorreta de comunicação para o cabo em uso resultam em inversão das linhas de Transmissão e Recepção, bem como a inversão de uma ou mais linhas de controle (“handshaking”). 4.4.1 DEFINIÇÃO DE SINAIS Se a norma EIA232 completa for implementada, o equipamento que faz o processamento dos sinais é chamado DTE (Data Terminal Equipment – usualmente um computador ou terminal), tem um conector DB25 macho, e utiliza 22 dos 25 pinos disponíveis para sinais ou terra. O equipamento que faz a conexão (normalmente uma interface com a linha telefônica) é denominado de DCE (Data Circuit-terminating Equipment – usualmente um modem), tem um conector DB25 fêmea, e utiliza os mesmos 22 pinos disponíveis para sinais e terra. Um cabo de conexão entre dispositivos DTE e DCE contém ligações em paralelo, não necessitando mudanças na conexão de pinos. Se todos os dispositivos seguissem essa norma, todos os cabos seriam idênticos, e não haveria chances de haver conexões incorretas. 50 Figura 4.6 – DTE e DCE. Figura 4.7 – Dois DTE interligados através de um modem. 51 Figura 4.8 – Pinagem do conector do DTE. Os sinais em negritos são os mais comuns. 52 Figura 4.9 – Pinagem do conector do DCE. Os sinais em negritos são os mais comuns. 53 Diversos sinais são necessários para conexões onde o dispositivo DCE é um modem, e eles são utilizados apenas quando o protocolo de software os emprega. Para dispositivos DCE que não são modem, ou quando dois dispositivos DTE são conectados diretamente, poucos sinais são necessários. Deve-se notar que nas figuras apresentadas existe um segundo canal que inclui um conjunto de sinais de controle duplicados. Este canal secundário fornece sinais de gerenciamento do modem remoto, habilitando a mudança de taxa de transmissão durante a comunicação, efetuando um pedido de retransmissão se erros de paridade forem detectados, e outras funções de controle. Os sinais de temporização de transmissão e recepção são utilizados somente quando o protocolo de transmissão utilizado for síncrono. Para protocolos assíncronos, padrão 8 bits, os sinais de temporização externos são desnecessários. Os nomes dos sinais que implicam em um direção como “Transmit Data” e “Receive Data”, são nomeados do ponto de vista dos dispositivos DTE. Se a norma EIA232 for seguida a risca, estes sinais terão o mesmo nome e o mesmo número de pino do lado do DCE. Infelizmente, isto não é feito na prática pela maioria dos engenheiros, provavelmente porque em alguns casos torna-se difícil definir quem é o DTE e quem é o DCE. A figura a seguir apresenta a convenção utilizada para os sinais mais comuns. Figura 4.10 – Sinais mais comuns. 4.4.2 PINAGEM As funções dos sinais da norma EIA232 podem ser subdivididos em 6 categorias, apresentados nas tabelas a seguir. 54 Tabela 4.4 – Sinais de referência. Tabela 4.5 – Canal de comunicação primário. Tabela 4.6 – Canal de comunicação secundário. 55 Tabela 4.7 – Sinais de controle e status. Tabela 4.8 – Sinais de transmissão e recepção. 56 Tabela 4.9 – Sinais de teste. 4.4.3 CARACTERISTICAS DOS SINAIS Todas as linhas, sejam elas de informações de dados, temporização ou controle, podem ser representadas pelo mesmo circuito elétrico equivalente da figura a seguir. Figura 4.11 – Circuito elétrico equivalente do RS232. Este circuito equivalente aplica-se aos sinais originados tanto no DTE quanto no DCE. A capacitância “Co” não é especificada na norma, mas deve assumida como pequena e consistir apenas de elementos parasitas. “Ro” e “Vo” são escolhidos de forma tal que a corrente de curto-circuito não exceda a 500 mA. 57 Sinais com tensão entre –3 volts e –25 volts com relação ao terra (pino 7) são considerados nível lógico “1” ( condição marca), e tensões entre +3 volts e +25 volts são considerados nível lógico “0” (condição espaço). A faixa de tensões entre –3 volts e +3 volts é considerada uma região de transição para o qual o estado do sinal é indefinido. Figura 4.12 – Sinal típico do RS232. Os sinais de saída foram projetados para funcionar em aberto, ou com curto-circuito com outros sinais do condutor, incluindo o sinal de terra, sem danificar o outro circuito associado. Os sinais de entrada também foram projetados para aceitar qualquer tensão entre ±25 volts sem danificar. Quatro sinais foram implementados com segurança à falhas (“fail-safe design”) no qual durante a desenergização ou desconexão do cabo, seus sinais estarão desabilitados (nível lógico “0”). São eles: • Sinal RTS – desabilitado • Sinal SRTS – desabilitado • Sinal DTR – DTE não pronto • Sinal DSR – DCE não pronto 4.4.4 TEMPORIZAÇÃO DOS SINAIS A norma EIA232 especifica uma taxa máxima de transferência de dados de 20.000 bits por segundo (o limite usual é 19200 bps). Baud rates fixos não são fornecidos 58 pela norma. Contudo, os valores comumente usados são 300, 1200, 2400, 4800, 9600 e 19200 bps. Mudanças no estado dos sinais de nível lógico “1” para “0” ou vice-versa devem seguir diversas características, dadas a seguir: • Sinais que entram na zona de transição durante uma mudança de estado devem atravessar essa região com direção ao estado oposto sem reverter a direção ou reentrar; • Para os sinais de controle, o tempo na zona de transição deve ser menor do que 1ms; Para sinais de temporização, o tempo para atravessar a zona de transição deve ser: • Menor do que 1 ms para períodos de bits maiores que 25 ms; • 4% do período de um bit para períodos entre 25 ms e 125 µs; • Menor do que 5 µs para períodos menores que 125 µs. As rampas de subida e de descida de uma transição não devem exceder 30 V/ms. Taxas maiores do que esta pode induzir sinais em condutores adjacentes de um cabo. 4.4.5 CONVERSORES DE NÍVEL TTL – RS232 A maioria dos equipamentos digitais utiliza níveis TTL ou CMOS. Portanto, o primeiro passo para conectar um equipamento digital a uma interface RS232 é transformar níveis TTL (0 a 5 volts) em RS232 e vice-versa. Isto é feito por conversores de nível. Existe uma variedade grande de equipamentos digitais que utilizam o driver 1488 (TTL => RS232) e o receiver 1489 (RS232 => TTL). Estes CIs contém 4 inversores de um mesmo tipo, sejam drivers ou receivers. O driver necessita duas fontes de alimentação +7,5 volts a +15 volts e –7,5 volts a –15 volts. Isto é um problema onde somente uma fonte de +5 volts é utilizada. Outro CI que está sendo largamente utilizado é o MAX232 (da Maxim). Ele inclui um circuito de “charge pump” capaz de gerar tensões de +10 volts e –10 volts a partir de uma fonte de alimentação simples de +5 volts, bastando para isso alguns capacitores externos, conforme pode-se observar na figura a seguir. Este CI também 59 tem 2 receivers e 2 drivers no mesmo encapsulamento. Nos casos onde serão implementados somente as linhas de transmissão e de recepção de dados, não seria necessário 2 chips e fontes de alimentação extras. Figura 4.13 – O CI MAX232. 4.4.6 CABO NULL MODEM Um cabo Null Modem é utilizado para conectar dois DTE juntos. Isto é comumente usado como um meio barato para transferir arquivos entre computadores utilizando protocolos Zmodem, Xmodem, etc. Ele também pode ser utilizado em diversos sistemas de desenvolvimento. 60 Na figura abaixo é apresentado um método de conexão de um cabo “null modem”. Apenas 3 fios são necessários (TxD, RxD e GND). A teoria de operação é razoavelmente simples. O princípio é fazer o DTE pensar que está falando com um modem. Qualquer dado transmitido do DTE deve ser recebido no outro extremo e vice-versa. O sinal de terra (SG) também deve ser conectados ao terra comum dos dois DTE. Figura 4.14 – Configuração do cabo Null Modem. O sinal DTR é conectado com os sinais DSR e CD nos dois extremos. Quando o sinal DTR for ativado (indicando que o canal de comunicação está aberto), imediatamente os sinais DSR e CD são ativados. Nessa hora o DTE pensa que o Modem Virtual ao qual está conectado está pronto e que foi detectada uma portadora no outro modem. O DTE precisa se preocupar agora com os sinais RTS e CTS. Como os 2 DTE se comunicam à mesma velocidade, o fluxo de controle não é necessário e conseqüentemente essas 2 linhas são conectadas juntas em cada DTE. Quando o computador quer transmitir um dado, ele ativa a linha RTS como estão conectadas juntas, imediatamente recebe a resposta que o outro DTE está pronto pela linha CTS. Note que o sinal RI não está conectado em nenhum extremo. Esta linha é utilizada apenas para informar ao DTE que existe um sinal de chamada telefônica presente. Como não existe modem conectado a linha telefônica ela pode permanecer desconectada. 61 4.4.7 CONTROLE DO FLUXO DE DADOS Se a conexão entre um DTE e um DCE for diversas vezes mais rápida do que a velocidade entre os DCE, cedo ou tarde dados transmitidos do DTE serão perdidos, nesse caso o controle de fluxo de dados é utilizado. O controle de fluxo tem pode ser feito por hardware ou por software. O controle do fluxo de dados por software, também conhecido como XON/XOFF utiliza 2 caracteres ASCII; XON representado pelo caracter ASCII 17 e XOFF representado pelo caracter ASCII 19. O modem tem normalmente um buffer pequeno e quando completado envia o caracter XOFF para avisar o DTE parar de enviar dados. Uma vez que o modem estiver pronto para receber mais dados ele envia o caracter XON e o DTE enviará mais dados. Este tipo de controle de fluxo tem a vantagem de não necessitar linhas adicionais, às linhas TxD e RxD. A desvantagem está no protocolo de comunicação que não poderá utilizar os caracteres ASCII 17 e 19 em suas mensagens. O controle do fluxo de dados por hardware, também conhecido como RTS/CTS utiliza 2 linhas extras em seu cabo serial além das 2 linhas para transmissão de dados. Quando o DTE quer enviar dados ele ativa a linha RTS. Se o modem tem espaço para receber esse dado, ele irá responder ativando a linha CTS e o DTE começará a enviar dados. Se o modem não tem espaço para receber dados ele não ativa a linha CTS. 62 5. O HYPERTERMINAL O HyperTerminal é um programa que pode ser utilizado para conectar um computador a outros computadores, sites de Telnet, BBSs, serviços on-line e computadores host, usando um modem, um cabo Null Modem ou uma conexão Ethernet. Apesar do uso do HyperTerminal com BBS para acessar informações sobre computadores remotos constituir uma prática que se tornou menos comum com a disponibilidade da World Wide Web, o HyperTerminal ainda é uma forma útil de configurar e testar o modem ou examinar a conexão com outros sites. O HyperTerminal grava as mensagens que entram ou saem do computador ou do serviço na outra extremidade da conexão. Portanto, pode servir como uma ferramenta valiosa para a solução de problemas durante a configuração e uso do modem. Para certificar-se de que o modem está conectado corretamente ou para exibir suas configurações, pode-se enviar comandos através do HyperTerminal e verificar os resultados. O HyperTerminal apresenta funcionalidade de rolagem que permite exibir um texto recebido que tenha sido rolado para fora da tela. É possível utilizar o HyperTerminal para transferir grandes arquivos de um computador para seu computador portátil usando uma porta serial, em vez de passar pelo processo de configurar o computador portátil em uma rede. O HyperTerminal pode ser usado para ajudar a depurar código fonte de um terminal remoto. Também é possível usá-lo para estabelecer comunicações com computadores mais antigos, baseados em caracteres. O HyperTerminal foi criado para ser uma ferramenta de fácil utilização e não para substituir outras ferramentas avançadas disponíveis no mercado. 5.1 CONFIGURANDO O HYPERTERMINAL PARA A COMUNICAÇÃO COM O MICROCONTROLADOR Para se utilizar o HyperTerminal para a comunicação com o microcontrolador via porta serial, é necessário configurá-lo. 63 No sistema operacional Windows XP Professional Edition, geralmente o programa se encontra na pasta no seguinte diretório: C:\Documents and Settings\All Users\Menu Iniciar\Programas\Acessórios\Comunicações . Ao executar o programa, será exibida a seguinte tela: Figura 5.1 – Inserindo um nome para a conexão. Devemos digitar um nome para a conexão, por exemplo 8051; escolher um ícone e clicar no botão OK. Figura 5.2 – Nome da conexão e ícone escolhido. 64 A próxima janela que aparece diz respeito à porta de comunicação que será utilizada, neste caso deixa-se selecionada a porta COM1 e pressiona-se o botão OK. Figura 5.3 – Escolhendo a porta de comunicação. Escolhida a porta de comunicação devemos configurá-la conforme de acordo com a próxima janela que irá aparecer. Figura 5.4 – Configurando a porta de comunicação. 65 Nessa janela a única que deve-se alterar é o campo Controle de Fluxo. Deve-se alterá-lo para Xon / Xoff. Depois basta clicar no botão OK. Figura 5.5 – Alterando o Controle de Fluxo. Após configurada a porta COM1, o HyperTerminal está pronto para o uso e já está conectado à porta, esperando um dado ser recebido. Nesse momento basta conectar o cabo de comunicação na placa do microcontrolador e no computador, para ser efetuada a transmissão de dados do microcontrolador para o PC. Figura 5.6 – HyperTerminal configurado e já conectado à porta COM1. 66 6. O CIRCUITO INTEGRADO L298 O circuito integrado L298 é uma ponte H dupla com transitores, com 15W de potência, capaz de controlar o acionamento de relés, solenóides, motores de passo e motores DC, como no caso deste trabalho. Possui duas entrada de alimentação, uma TTL de 5V necessária para o controle da lógica interna, e outra de 0 a 50 V para a alimentação da carga. Com esse CI é possível controlar a velocidade de um motor DC usando o PWM (Pulse Width Modulation) e o sentido de rotação. Cada ponte H possui um pino de controle chamado Enable e mais dois pinos, chamados Input, para o controle da polaridade de saída da ponte, que no caso de um motor DC (Direct Current) serve para mudar o sentido de rotação. Além disso é possível monitorar a corrente consumida pela carga através do pino Sense que serve para colocarmos um resistor shunt e medirmos a tensão sobre ele, fazendo uma relação entre a tensão e a corrente. Caso não seja usado, deve-se ligá-lo diretamente à referência negativa do circuito. Figura 6.1 - Digrama interno do L298. 67 Figura 6.2 - Pinagem do L298. Figura 6.3 - Controle de motor DC. Caso o motor usado tenha uma corrente maior que 2A, pode-se conectar as pontes em paralelo, aumentando assim a corrente total para até 4A. 68 Figura 6.4 - Conexão em paralelo de duas pontes. Os diodos que se encontram na figura 6.3 são diodos rápidos, ou seja, tem uma freqüência de chaveamento elevada. Eles são necessários devido à corrente reversa que surge devido à energização e desernegização de uma carga indutiva. Como a corrente do motor utilizado é de 200mA, pode-se utilizar o diodo 1N4148, que tem uma velocidade de chaveamento de 4ns. 69 7. O BRAÇO ROBÓTICO 7.1 ESTRUTURA MECÂNICA O Braço Robótico do trabalho foi construído a partir de uma estrutura de chapas de alumínio e os eixos das articulações foram usinados em aço ABNT 1010/1020. O alumínio foi escolhido para ser utilizado na maioria das peças pois apresenta baixa densidade e por ser um material resistente à corrosão, além de ser fácil de se trabalhar devido sua maleabilidade. Para a transmissão de movimento foi utilizado polias e correias sincronizadas. O uso de polias foi necessário devido ao baixo torque do motor DC utilizado para fazer a movimentação do robô, entre 40Ncm e 60 Ncm, e para não haver falhas na transmissão como por exemplo a correia patinar devido à alta carga, composta praticamente dos pesos do eixo e motores. Abaixo segue um diagrama de esquematização das forças para o cálculo do torque necessário dos motores. Considerou-se o momento mais crítico quando o braço e antebraço estão totalmente alinhados e paralelos à base e não foi considerado o peso das chapas, somente dos eixos e do motor do antebraço. 1,715N 1,235N Mmotor antebraço Mmotor braço 40 150 1,911N 1,8424N 70 200 Figura 7.1 - Esquematização de forças. 25 70 ç 0,98 150 1,8424 220 1,911 420 1208 120,8 ç 1,911 200 382,2 38,22 Para aumentar o torque dos motores foi utilizado polias de diâmetros diferentes para aumentar a relação de transmissão. Abaixo segue o cálculo do comprimento da correia e da relação de transmissão. P2 = 12XL037 Dp = 19,41mm P3 = 28XL037 Dp = 45,29mm 45,29 2,34 19,41 Figura 7.2 – Sistema de polias e correia. Onde: • r2 é o raio da polia P2 • r3 é o raio da polia P3 • α2 é o ângulo de contato da polia P2 • α3 é o ângulo de contato da polia P3 • c é a distancia entre centros O comprimento da correia vale a soma dos dois trechos retos e dos dois arcos sobre as polias: 2. . ! " . #$% $& ' !. #$% ( $& ' 2 71 com β em radianos na última parcela. O ângulo β vale: ! )* +, $& ( $% 2. Através dos cálculos obtém-se o comprimento da correia a ser utilizada de 244,0289mm. Através da tabela do fabricante encontramos a correia 96XL037 com 243,84mm de comprimento, a qual atende à necessidade. Todo projeto mecânico foi desenvolvido no software Autodesk Inventor Professional 2008, que oferece um ambiente de simulação do protótipo e de animação. Abaixo segue uma figura do braço robótico projetado em três dimensões. Figura 7.3 - O Braço Robótico. 72 7.2 CIRCUITO ELETRÔNICO O circuito eletrônico foi totalmente projetado em função do microcontrolador AT89S52. O circuito é constituído pela unidade de processamento, interface de entrada, interface gráfica de saída, interface de comunicação com o computador e os drives de controle dos motores. Para a gravação dos programas no microcontrolador foi inserido na placa de processamento um gravador ISP, conforme catálogo do fabricante. Foram montadas duas placas: uma da unidade de processamento e interfaces e outra para os drives de acionamento dos motores DC. Figura 7.4 - Unidade Processamento e Drive de Controle dos motores. 7.2.1 FUNCIONAMENTO Quando o sistema for energizado, o microcontrolador enviará uma mensagem pelo canal serial do computador, que receberá essa mensagem através do programa HyperTerminal, nativo dos sistemas operacionais baseado no Windows. 73 Após o envio da mensagem, será mostrada no display LCD uma pequena apresentação do trabalho e em seguida o status do braço robótico: manual ou automático. Inicialmente ele se encontra em modo manual. Em modo manual, o microcontrolador fica esperando alguma chave ser acionada para em seguida ser tomada a decisão de qual motor será acionado e qual o sentido de rotação deverá ser escolhido. Se desacionado a chave, o braço robótico para de se movimentar e o microcontrolador fica esperando novamente alguma chave ser acionada. Em modo automático, o microcontrolador realizará alguns movimentos prédeterminados via software. Esses movimentos serão realizados até que o microcontrolador receba um sinal para voltar ao modo manual novamente. 7.2.2 DIAGRAMA ELÉTRICO O diagrama elétrico do circuito eletrônico foi desenvolvido no ambiente de simulação e criação de projetos eletrônicos Proteus 7 Professional. Com o programa ISIS Schematic Capture é possível desenvolver todo o circuito eletrônico e realizar sua simulação, mesmo com o uso de microcontroladores, como é o caso deste trabalho, pois ele possui algoritmos precisos de simulação garantindo os resultados esperados na fase de testes. A seguir, diagrama elétrico do controlador do braço robótico. 74 75 7.2.2.1 LISTA DE COMPONENTES ELETRÔNICOS 2 Resistores Quantidade 1 1 2 Referência R1 R3 Valor 1k 4k7 220R Descrição Resistor de filme metálico Resistor de filme metálico Resistor de filme metálico Referência C1,C2 C3 C4 C5,C6,C7,C8 Valor 33p 10u 100n 1u Descrição Capacitor eletrolítico polarizado de 16V Capacitor eletrolítico polarizado de 16V Capacitor eletrolítico polarizado de 16V Capacitor eletrolítico polarizado de 16V Referência U1,U3 U2 U4 Valor L298 AT89S52 MAX232 LM7805 Descrição Ponte H dupla Microcontrolador Drive RS232/TTL Regulador de Tensão D1-D12 1N4148 1N4007 Diodo de sinal Diodo retificador 8 Capacitores Quantidade 2 1 1 4 4 Circuitos Integrados Quantidade 2 1 1 1 17 Diodos 12 1 26 Diversos Quantidade 3 1 6 1 1 1 1 1 1 1 1 3 3 1 1 44 1 1 Referência Valor ANTEBRAÇO 12V BRAÇO BASE AUTOMATICO/MANUAL DMOT1 EMOT1 DMOT2 EMOT2 DMOT3 EMOT3 LCD1 LM016L RP2 1k RV1 1k P1 X1 12MHz Descrição Motor DC Botão Pulsador Chave alavanca 2 posições Display de LCD rede resitiva com 8 resistores Potenciômetro de carbono Conector fêmea DB9 Cristal oscilador Conector macho DB25 Conector KK molex macho 6 vias Conector KK molex fêmea 6 vias Conector KK molex macho 8 vias Conector KK molex fêmea 8 vias Conector KK molex macho 14 vias Conector KK molex fêmea 14 vias Terminal para alojamento KK molex Led difuso vermelho 3mm Led alto brilho azul 5mm Tabela 7.1 – Lista de componentes eletrônicos. 76 7.2.3 CÓDIGO FONTE O programa do microcontrolador foi escrito em Assembly, uma linguagem de baixo nível. O código fonte foi escrito no próprio ambiente de simulação do software Proteus. Abaixo segue o código fonte do programa gravado no microcontrolador. $mod51 ;*****************BRAÇO MECÂNICO MICROCONTROLADO****************** ; ; ;####################ESCOLA SENAI NAMI JAFET########################### ; ; ;###############TRABALHO DE CONCLUSÃO DE CURSO#################### ; ;#################TÉCNICO EM ELETROELETRÔNICA####################### ; ;LUCAS TADEU MONTEIRO GUEDES FERNANDES SALOMÃO ; ;######################PROFESSOR ORIENTADOR###################### ; ;ALEXANDRE RODRIGUES DE ALMEIDA ; ;##########################CÓDIGO FONTE########################## ; ;DECLARAÇÃO DAS VARIÁVEIS FMOT1 RMOT1 FMOT2 RMOT2 FMOT3 RMOT3 EQU EQU EQU EQU EQU EQU P1.0 P1.1 P1.2 P1.3 P1.4 P1.5 ENA1 ENB1 ENA2 EQU EQU EQU P3.2 P2.5 P2.4 IN1_1 IN2_1 IN3_1 IN4_1 IN1_2 IN2_2 EQU EQU EQU EQU EQU EQU P2.0 P2.1 P2.2 P2.3 P3.4 P3.5 RS EN EQU EQU P2.6 P2.7 AUTO EQU B.0 ORG 00H JMP MAIN ;ENDEREÇO DA INTERRUPÇÃO RESET ;SALTA PARA A ROTINA PRINCIPAL ORG 13H CPL B.0 CALL DELAYAUTO RETI ;ENDEREÇO DA INTERRUPÇÃO INT1 ;COMPLEMENTA O BIT 0 DO REGISTRADOR B ;CHAMA SUBROTINA DE TEMPO ;RETORNO DA INTERRUPÇÃO DELAYAUTO: DELAYAUTO1: MOV R4,#250D MOV R5,#200D MOV R6,#5D DJNZ R4,$ DJNZ R5,DELAYAUTO1 DJNZ R6,DELAYAUTO1 RET ;MOVE PARA R4 O VALOR 250 EM DECIMAL ;MOVE PARA R5 O VALOR 200 EM DECIMAL ;MOVE PARA R6 O VALOR 5 EM DECIMAL ;DECREMENTA E VERIFICA SE R4 É IGUAL A ZERO, SE NÃO FOR RETORNA PARA DELAYAUTO1 ;IDEM PARA R5 ;IDEM PARA R6 ;RETORNO DE SUBROTINA 77 MAIN: ORG 100H MOV P0,#00H MOV P1,#0FFH MOV P2,#00000000B MOV P3,#00001011B MOV R0,#00H MOV R1,#00H MOV R2,#00H MOV R3,#00H MOV R4,#00H MOV R5,#00H MOV R6,#00H MOV R7,#00H MOV A,#00H MOV B,#00H ;ENDEREÇO DA MEMÓRIA DE PROGRAMA DE INÍCIO DO PROGRAMA PRINCIPAL ;ZERANDO OS PORTS E REGISTRADORES MOV IE,#10000100B SETB PX1 MOV TCON,#04H ;HABILITA A INTERRUPÇÃO INT1 ;DEFINE A INTERRUPÇÃO INT1 COMO PRIMEIRA PRIORIDADE ;DEFINE QUE A INTERRUPÇÃO SERÁ ATIVADA POR BORDA DE DESCIDA CALL INITLCD ;CHAMA ROTINA DE INICIALIZAÇÃODO LCD CALL CONFIG_SERIAL CALL APRESENTACAO JMP RETORNA ;CHAMA ROTINA DE CONFIGURAÇÃO DA INTERFACE SERIAL ;CHAMA ROTINA DE ENVIO DA APRESENTACAO PARA A PORTA SERIAL DO PC CONFIG_SERIAL: MOV SCON,#40H; MOV TMOD,#21H; MOV PCON,#80H; MOV TH1,#0E6H; SETB TR1; SETB TI; RET UART COM 8 BITS E BAUD RATE VARIÁVEL TIMER 1 NO MODO 2, COM AUTO-RELOAD, TIMER SMOD=0, MULTIPLICA O CLOCK POR 32 CAREGA TH1 COM O VALOR 230, PARA UM BAUD RATE DE 2400 LIGA O TEMPORIZADOR SETA O FLAG DE INTERRUPÇÃO POR TRANSMISSÃO APRESENTACAO: MOV DPTR,#MSG4 CALL MSG3 RET MSG4: DB ' *****************BRACO ROBOTICO DE 3 EIXOS MICROCONTROLADO******************' DB 0AH,0DH ;COMANDO PARA MUDAR DE LINHA ESCREVER NO INÍCIO DA LINHA DB 0AH,0DH DB '####################ESCOLA SENAI NAMI JAFET###########################' DB 0AH,0DH DB 0AH,0DH DB '###############TRABALHO DE CONCLUSAO DE CURSO####################' DB 0AH,0DH DB 0AH,0DH DB '#################TECNICO EM ELETROELETRONICA#######################' DB 0AH,0DH DB 0AH,0DH DB 'LUCAS TADEU MONTEIRO GUEDES FERNANDES SALOMAO' DB 0AH,0DH DB 0AH,0DH DB '######################PROFESSOR ORIENTADOR######################' DB 0AH,0DH DB 0AH,0DH DB 'ALEXANDRE RODRIGUES DE ALMEIDA' DB 0AH,0DH DB 0AH,0DH DB 00H MSG3: CLR A MOV A,#00H MOVC A,@A+DPTR CJNE A,#00H,ENVIA RET ENVIA: LOOP: MOV SBUF, A JNB TI, LOOP CLR TI INC DPTR JMP MSG3 RETORNA: CALL CARREGANDO CALL DELAY CALL CLRLCD ;CHAMA SUBROTINA QUE ESCREVE "CARREGANDO" NO DISPLAY ;CHAMA SUBROTINA DE TEMPO ;CHAMA SUBROTINA QUE LIMPA O DISPLAY 78 CALL INTRODUCAO CALL DELAY CALL CLRLCD CALL INTRODUCAO1 ;CHAMA ROTINA DAS MENSAGENS DE INTRODUÇÃO DO TRABALHO ;CHAMA SUBROTINA DE TEMPO ;CHAMA SUBROTINA QUE LIMPA O DISPLAY ;CHAMA ROTINA DAS MENSAGENS DE INTRODUÇÃO DO TRABALHO ;######################MODO MANUAL###################### MODOMANUAL: MANU: MOV DPTR,#MANU MOV A,#0C0H LCALL CMDLCD LCALL MSG LJMP MANUAL DB ' MODO MANUAL ' DB 00H MANUAL: MOV P3,#00001010B ANL P2,#11000000B MANUAL1: JNB FMOT1,DMOT1 JNB RMOT1,EMOT1 JNB FMOT2,DMOT2 JNB RMOT2,EMOT2 JNB FMOT3,DMOT3 JNB RMOT3,EMOT3 JB AUTO,AUTOMATICO JMP MANUAL1 DMOT1: SETB IN1_1 CLR IN2_1 SETB ENA1 JNB FMOT1,DMOT1 CLR ENA1 CLR IN1_1 CLR IN2_1 JMP MANUAL EMOT1: SETB IN2_1 CLR IN1_1 SETB ENA1 JNB RMOT1,EMOT1 CLR ENA1 CLR IN1_1 CLR IN2_1 JMP MANUAL DMOT2: SETB IN3_1 CLR IN4_1 SETB ENB1 JNB FMOT2,DMOT2 CLR ENB1 CLR IN3_1 CLR IN4_1 JMP MANUAL EMOT2: SETB IN4_1 CLR IN3_1 SETB ENB1 JNB RMOT2,EMOT2 CLR ENB1 CLR IN3_1 CLR IN4_1 JMP MANUAL DMOT3: SETB IN1_2 CLR IN2_2 SETB ENA2 JNB FMOT3,DMOT3 CLR ENA2 CLR IN1_2 CLR IN2_2 JMP MANUAL ;VERIFICANDO QUAL BOTÃO FOI APERTADO ;VERIFICA SE O BIT B.0 É 1, SE FOR PASSA PARA O MODO ;AUTOMÁTICO ;RETORNA PARA A VERIFICAÇÃO 79 EMOT3: SETB IN2_2 CLR IN1_2 SETB ENA2 JNB RMOT3,EMOT3 CLR ENA2 CLR IN1_2 CLR IN2_2 JMP MANUAL ;####################################################### ;####################MODO AUTOMÁTICO#################### AUTOMATICO: MOV DPTR,#AUTOM MOV A,#0C0H LCALL CMDLCD LCALL MSG LJMP INICIO AUTOM: DB 'MODO AUTOMATICO' DB 00H INICIO: MOV P3,#00001010B CALL TEMPO MOVIMENTO: CALL DMOT1M CALL TEMPO CLR ENA1 JNB AUTO,MODOMANUAL1 ;VERIFICA SE O BIT B.0 É 0, SE FOR PASSA PARA O MODO MANUAL CALL EMOT2M CALL TEMPO CALL DMOT2M CALL TEMPO CLR ENB1 JNB AUTO,MODOMANUAL1 CALL EMOT1M CALL TEMPO CLR ENA1 JNB AUTO,MODOMANUAL1 CALL DMOT3M CALL TEMPO CLR ENA2 JNB AUTO,MODOMANUAL1 CALL EMOT3M CALL TEMPO CLR ENA2 JNB AUTO,MODOMANUAL1 JMP MOVIMENTO MODOMANUAL1: LJMP MODOMANUAL DMOT1M: SETB IN1_1 CLR IN2_1 SETB ENA1 RET EMOT1M: SETB IN2_1 CLR IN1_1 SETB ENA1 RET DMOT2M: SETB IN3_1 CLR IN4_1 SETB ENB1 RET EMOT2M: SETB IN4_1 CLR IN3_1 SETB ENB1 RET 80 DMOT3M: SETB IN1_2 CLR IN2_2 SETB ENA2 RET EMOT3M: SETB IN2_2 CLR IN1_2 SETB ENA2 RET TEMPO: TEMPO1: MOV R3,#20D MOV TMOD,#21H MOV TH0,#HIGH(65535-50000) MOV TL0,#LOW(65535-50000) CLR TF0 SETB TR0 JNB TF0,$ CLR TR0 CLR TF0 DJNZ R3,TEMPO1 RET ;TEMPO DE 1 SEGUNDO ;####################################################### ;#################INICIALIZAÇÃO DO LCD################# INITLCD: MOV A,#38H CALL CMDLCD MOV A,#38H CALL CMDLCD MOV A,#08H CALL CMDLCD MOV A,#0CH CALL CMDLCD MOV A,#01H CALL CMDLCD CALL CLRLCD RET DADOLCD: SETB RS MOV P0,A CALL DELAYCLR CALL HABILITA RET CMDLCD: CLR RS MOV P0,A CALL DELAYCLR CALL HABILITA RET CLRLCD: MOV A,#01H CLR RS MOV P0,A CALL DELAYCLR CALL HABILITA RET HABILITA: SETB EN CALL DELAYCLR CLR EN RET DELAYCLR: MOV R4,#250D MOV R5,#2D DJNZ R4,$ DJNZ R5,DELAYCLR1 RET DELAYCLR1: ;####################################################### INTRODUCAO1: MOV DPTR,#ESCOLA MOV A,#082H LCALL CMDLCD LCALL MSG MOV DPTR,#NAMI 81 MOV A,#0C3H LCALL CMDLCD LCALL MSG CALL DELAY CALL CLRLCD MOV DPTR,#BRACO MOV A,#081H LCALL CMDLCD LCALL MSG RET ESCOLA: DB 'ESCOLA SENAI' DB 00H NAMI: DB 'NAMI JAFET' DB 00H BRACO: DB 'Braco Robotico' DB 00H MSG: CLR A MOV A,#00H MOVC A,@A+DPTR CJNE A,#00H,MOSTRA RET MOSTRA: CALL DADOLCD INC DPTR JMP MSG DELAY: MOV R4,#250H MOV R5,#200H MOV R6,#20D DJNZ R4,$ DJNZ R5,DELAY1 DJNZ R6,DELAY1 RET DELAY1: ;####################################################### CARREGANDO: MOV DPTR,#CARRE MOV A,#080H LCALL CMDLCD LCALL MSG MOV DPTR,#PONTOS MOV A,#0C0H LCALL CMDLCD LCALL MSG1 RET CARRE: DB '---CARREGANDO---' DB 00H PONTOS: DB '>>>>>>>>>>>>>>>>' DB 00H MSG1: CLR A MOV A,#00H MOVC A,@A+DPTR CJNE A,#00H,MOSTRA1 RET MOSTRA1: CALL DADOLCD1 INC DPTR JMP MSG1 DADOLCD1: SETB RS MOV P0,A CALL DELAYCLR2 CALL HABILITA2 RET HABILITA2: SETB EN CALL DELAYCLR2 CLR EN RET 82 DELAYCLR2: DELAYCLR3: MOV R4,#00H MOV R5,#00H MOV R6,#01H DJNZ R4,$ DJNZ R5,DELAYCLR3 DJNZ R6,DELAYCLR3 RET ;####################################################### INTRODUCAO: MOV DPTR,#TRABALHO MOV A,#086H LCALL CMDLCD LCALL MSG MOV DPTR,#ELETRO MOV A,#0C0H LCALL CMDLCD LCALL MSG RET TRABALHO: DB 'TCC' DB 00H ELETRO: DB 'ELETROELETRONICA' DB 00H ;####################################################### END 83 7.2.4 FLUXOGRAMA DE FUNCIONAMENTO INÍCIO DECLARAÇÃO DAS VARIÁVEIS 0000H INTERRUPÇÃO RESET SALTA PARA ENDEREÇO MAIN 0013H INTERRUPÇÃO INT0 COMPLEMENTA B.0 CHAMA SUBROTINA DELAYAUTO SUBROTINA DE TEMPO DE 500mS MAIN ZERA AS VARIÁVEIS E REGISTRADORES HABILITA INT0 DEFINE COMO ALTA PRIORIDADE DEFINE DISPARO POR BORDA DE DESCIDA CHAMA SUBROTINA INITLCD CHAMA SUBROTINA CONFIG_SERIAL SUBROTINA PARA A INICIALIZAÇÃO DO DISPLAY LCD SUBROTINA PARA A CONFIGURAÇÃO DA INTERFACE SERIAL CHAMA SUBROTINA APRESENTACAO SALTA PARA ENDEREÇO RETORNA RETORNA 1 SUBROTINA PARA O ENVIO DE MENSAGEM VIA INTERFACE SERIAL 84 1 CHAMA SUBROTINA CARREGANDO SUBROTINA QUE ESCREVE CARREGANDO NO DISPLAY CHAMA SUBROTINA DELAY SUBROTINA DE TEMPO DE 1S SUBROTINA QUE LIMPA O DISPLAY LCD CHAMA SUBROTINA CLRLCD CHAMA SUBROTINA INTRODUCAO SUBROTINA QUE ESCREVE A PRIMEIRA INTRODUÇÃO AO PROJETO CHAMA SUBROTINA DELAY SUBROTINA DE TEMPO DE 1S CHAMA SUBROTINA CLRLCD SUBROTINA QUE LIMPA O DISPLAY LCD CHAMA SUBROTINA INTRODUCAO1 SUBROTINA QUE ESCREVE A SEGUNDA INTRODUÇÃO AO PROJETO MODOMANUAL DPTR = DB 'MODO MANUAL', 00H ACC = C0H 2 85 2 CHAMA SUBROTINA CMDLCD CHAMA SUBROTINA MSG SALTA PARA O ENDEREÇO MANUAL MANUAL P3 = 00001010B P2 && 11000000B SALTA PARA O ENDEREÇO MANUAL1 MANUAL1 VERIFICA O BOTÃO APERTADO SIM FOI FMOT1? SALTA PARA O ENDEREÇO DMOT1 NÃO SIM FOI RMOT1? SALTA PARA O ENDEREÇO EMOT1 NÃO SIM FOI FMOT2? SALTA PARA O ENDEREÇO DMOT2 NÃO SIM FOI RMOT2? SALTA PARA O ENDEREÇO EMOT2 NÃO SIM FOI FMOT3? SALTA PARA O ENDEREÇO DMOT3 NÃO SIM FOI DMOT3? NÃO 3 SALTA PARA O ENDEREÇO EMOT3 86 3 SIM FOI AUTO? SALTA PARA O ENDEREÇO AUTOMATICO NÃO SALTA PARA O ENDEREÇO MANUAL1 FIM 7.3 GRAVADOR ISP Para realizar a gravação do programa na memória flash do microcontrolador, foi incorporado ao circuito eletrônico um gravador ISP (In-Systen Programming) de acordo com o catálogo do fabricante, no caso a Atmel. O gravador consiste em um cabo de 6 vias, de preferência blindado para diminuir ruídos que possam interferir na comunicação, conectado à porta paralela do computador. A gravação é feita de modo serial, e a porta deve ser configurada para o modo EPP (Enhanced Parallel Port). O software utilizado para a gravação no microcontrolador foi o ISP Flash Programmer Version 3.0a do próprio fabricante do microcontrolador. O software é compatível em computadores com sistema operacional Windows (98,2000XP), não necessitando de nenhuma DLL (Dynamic-link library), pois o software já as possui inclusas. 87 7.3.1 UTILIZAÇÃO DO SOFTWARE ISP FLASH PROGRAMMER VERSION 3.0a Após a abertura o programa surgirá a seguinte tela, onde selecionaremos o componente a ser gravado o arquivo hexadecimal que deve ser transferido: Figura 7.5 - Tela inicial do programa. A primeira coisa que deve-se fazer é escolher o modelo de microcontrolador que será utilizado, no caso o AT89S52. Em seguida deve-se fazer a verificação da autenticidade do microcontrolador, clicando no botão Signature. Feita a verificação devemos abrir o programa gerado pelo compilador, através do botão Open File, e ir até ao diretório onde se encontra o programa a ser gravado, lembrando-se que sua extensão deve ser .hex, que é o tipo de arquivo compatível com a família de microcontroladores 8051. Agora o programa está pronto para fazer a gravação no microcontrolador, bastando apenas clicar no botão Write. 88 7.3.2 CABO DE TRANSFERÊNCIA DE DADOS A seguir o diagrama do cabo que compõe o gravador ISP. Figura 7.6 - Configuração do cabo para gravação. Para melhorar o desempenho do cabo pode-se conectar um buffer para diminuir as perdas de sinal em função do comprimento do cabo, porém obteve-se um bom resultado usando 2m de cabo manga blindado de 6 vias, sem a necessidade de um buffer. 89 8. RESULTADOS De acordo com as simulações feitas, foi possível identificar erros de hardware e software na etapa de montagem da placa eletrônica. Todas as simulações realizadas foram fiéis ao funcionamento final da unidade de processamento e do drive de controle dos motores. Em relação à alimentação do circuito eletrônico, observa-se que há a necessidade de uma alimentação separada para a unidade de processamento e para o drive dos motores. Ao decorrer do trabalho, foram testadas várias transmissões de movimento nos eixos. A que mais foi satisfatória foi a utilização de polias e correias sincronizadas, pois a correia não patina sobre a polia. Observou-se também que a resposta do display LCD é maior que a informada no catálogo do fabricante, permitindo uma escrita mais rápida e sem perdas de dados. 90 9. CONCLUSÃO Com este trabalho foi possível unir os conhecimentos de mecânica e eletrônica adquiridos no decorrer do curso. A construção do braço robótico foi fundamental para reforçar o aprendizado em sistemas microprocessados, eletrônica digital e eletrônica analógica, além de abrir caminhos para o estudo de elementos mecânicos utilizados no projeto, como transmissão de movimentos através de correias. Conclui-se que os sistemas robotizados atualmente surgiram de simples idéias que foram se desenvolvendo ao longo dos anos, com o advento da tecnologia. Sem os microprocessadores e microcontroladores não seria possível o controle de robôs, máquinas CNC e diversos outros equipamentos que necessitam de um elevado processamento de dados. A tecnologia foi fundamental para o desenvolvimento desses equipamentos que fazem parte das indústrias atualmente e sem eles não seria possível o desenvolvimento econômico de um país, visto que um dos fatores para se determinar o poder econômico de um país é o grau de tecnologia desenvolvido. REFERÊNCIAS SOUSA, Fernando Simplício. Programação BASIC para microcontroladores 8051:com base na IDE BASCOM-8051. 1ª ed. São Paulo: Érica, 2006. NICOLOSI, Denys E. C. Microcontrolador 8051 Detalhado. 6ª Ed. São Paulo: Érica, 2000. SÁ, Maurício Cardoso de. Programação C para microcontroladores 8051. 1ª Ed. São Paulo: Érica, 2005. CANZIAN, Edmur. Mini-curso Comunicação Serial RS232. 1ªed. São Paulo: CNZ Engenharia e Informática Ltda. ANEXO A - Desenhos do Braço Robótico $ % & ' /XFDV7DGHX &KHFNHGE\ /XFDV7DGHX 'DWH 0RQWDJHP /XFDV7DGHX $SSURYHGE\ ,620 ,6 0RWRUGREUDoR &RUUHLD;/ 3ROLD;/ 3ROLD;/ (L[RGDEDVH (L[RGRDQWHEUDoR (L[RGREUDoR $60[)ODW 3RLQW &RUUHLD;/ 3ROLD;/ 3ROLD;/ ,620[ ,620[ %UDoR $QWHEUDoR 0RWRUGRDQWHEUDoR &610[ 'HVLJQHGE\ /LVWDGH0DWHULDLV 3(d$ 48$17,'$'( 120( %DVH 2PEUR (L[RGDPmR ,60 ,6 0mR ,6 $60 &610[ (GLWLRQ %UDoR5REyWLFR 'DWH 6KHHW 0[[ &KDSDGH$OXPtQLR &KDSDGH$OXPtQLR 0RWRU'&99 3DUDIXVRFDEHoDHVIpULFD 0[[ 3DUDIXVRFDEHoDFLOtQGULFD 0[[ 3RUFD0 $UUXHODGHSUHVVmR0 0RWRU'&99 &RUUHLDGHERUUDFKD 3ROLDGHDOXPtQLR 3ROLDGHDOXPtQLR $oR$%17 $oR$%17 $oR$%17 3DUDIXVRKDOOHQVHPFDEHoD FRPSRQWDFKDWD0[[ &RUUHLDGHERUUDFKD 3ROLDGHDOXPtQLR 3ROLDGHDOXPtQLR 3DUDIXVRFDEHoDFLOtQGULFD 0[[ '(6&5,d2 &KDSDGH$OXPtQLR &KDSDGH$OXPtQLR $oR$%17 3RUFD0 $UUXHODGHSUHVVmR0 &KDSDGH$OXPtQLR $UUXHODGHSUHVVmR0 3RUFD0 3DUDIXVRFDEHoDHVIpULFD $ % & ' $ % & ' /XFDV7DGHX &KHFNHGE\ /XFDV7DGHX 'HVLJQHGE\ 48$17,'$'( 3(d$ 'DWH 0RQWDJHP /XFDV7DGHX $SSURYHGE\ (GLWLRQ %UDoR5REyWLFR 'DWH 6KHHW '(6&5,d2 %DVH &KDSDGH$OXPtQLR 2PEUR &KDSDGH$OXPtQLR $oR$%17 (L[RGDPmR ,60 3RUFD0 ,6 $UUXHODGHSUHVVmR0 0mR &KDSDGH$OXPtQLR ,6 $UUXHODGHSUHVVmR0 3RUFD0 $60 &610[ 3DUDIXVRFDEHoDHVIpULFD 0[[ %UDoR &KDSDGH$OXPtQLR $QWHEUDoR &KDSDGH$OXPtQLR 0RWRU'&99 0RWRUGRDQWHEUDoR &610[ 3DUDIXVRFDEHoDHVIpULFD 0[[ ,620[ 3DUDIXVRFDEHoDFLOtQGULFD 0[[ ,620 3RUFD0 ,6 $UUXHODGHSUHVVmR0 0RWRU'&99 0RWRUGREUDoR &RUUHLD;/ &RUUHLDGHERUUDFKD 3ROLD;/ 3ROLDGHDOXPtQLR 3ROLD;/ 3ROLDGHDOXPtQLR (L[RGDEDVH $oR$%17 (L[RGRDQWHEUDoR $oR$%17 (L[RGREUDoR $oR$%17 $60[)ODW 3DUDIXVRKDOOHQVHPFDEHoD 3RLQW FRPSRQWDFKDWD0[[ &RUUHLD;/ &RUUHLDGHERUUDFKD 3ROLD;/ 3ROLDGHDOXPtQLR 3ROLD;/ 3ROLDGHDOXPtQLR ,620[ 3DUDIXVRFDEHoDFLOtQGULFD 0[[ /LVWDGH0DWHULDLV 120( $ % & ' $SSURYHGE\ 'DWH 'DWH 6KHHW & ' /XFDV7DGHX /XFDV7DGHX &KHFNHGE\ 'HVLJQHGE\ 0RQWDJHP /XFDV7DGHX (GLWLRQ %UDoR5REyWLFR $ $ $ % $ % & ' $SSURYHGE\ 'DWH % 'DWH 6KHHW & ' /XFDV7DGHX /XFDV7DGHX &KHFNHGE\ 'HVLJQHGE\ 0RQWDJHP /XFDV7DGHX (GLWLRQ %UDoR5REyWLFR $ $ % % % & ' &KHFNHGE\ /XFDV7DGHX /XFDV7DGHX 3(d$ %DVH /XFDV7DGHX $SSURYHGE\ 'DWH 'DWH (GLWLRQ 6KHHW '(6&5,d2 &KDSDGH$OXPtQLR %UDoR5REyWLFR /LVWDGH0DWHULDLV 48$17,'$'( 120( %DVH 'HVLJQHGE\ Q Q Q Q Q &KHFNHGE\ /XFDV7DGHX /XFDV7DGHX 48$17,'$'( 'HVLJQHGE\ 3(d$ 'DWH 2PEUR /XFDV7DGHX $SSURYHGE\ /LVWDGH0DWHULDLV 120( 2PEUR Q (GLWLRQ %UDoR5REyWLFR 'DWH 6KHHW '(6&5,d2 &KDSDGH$OXPtQLR 5 5 Q &KHFNHGE\ /XFDV7DGHX /XFDV7DGHX 3(d$ Q Q %UDoR /XFDV7DGHX $SSURYHGE\ 'DWH /LVWDGH0DWHULDLV 48$17,'$'( 120( %UDoR Q 'HVLJQHGE\ (GLWLRQ %UDoR5REyWLFR 'DWH 6KHHW '(6&5,d2 &KDSDGH$OXPtQLR 5 Q53 3 4 /%) 3 Q3 !" ## $ ' -.,(% ,+'% 3 % %UDoR5REyWLFR &! %& ()*+ !#012 85 Q 5 75 45 5 5 95 5 0'*$ 4 5 5 !"# $%%& ./$-)$' -,' Q65 ' %UDoR5REyWLFR (" '(!)*+, !"%$123 5 45 Q . Q/ . Q1. %LR !""# % +,!*&! *)% . %UDoR5REyWLFR $ $&'() !!* . 0. 56 -'! . / Q %1 4 23 0 0 10 1.0 -'! . 10 !""# 0 $ $&'() !!* %UDoR5REyWLFR / Q % +,!*&! *)% /0 0 Q 0 %234/ 0 2 Q . . 3. . -'! 3. $ $&'() !!* %UDoR5REyWLFR !""# Q/. % +,!*&! *)% /. . . 0 Q %012/ Q . 1 1 21 21 /)# 0 !" #$$% Q 3 1 &! & ()*+ ##, %UDoR5REyWLFR 1 4 Q Q1 ' -.#,(# ,+' 1 1 21 '4563 5 Q [ 0 [ + [ Q /XFDV7DGHX /XFDV7DGHX 'DWH 'DWH (GLWLRQ 6KHHW '(6&5,d2 0RWRU'&99 %UDoR5REyWLFR 0RWRUGREUDoR /XFDV7DGHX $SSURYHGE\ /LVWDGH0DWHULDLV 48$17,'$'( 120( 0RWRUGREUDoR &KHFNHGE\ 3(d$ 'HVLJQHGE\ Q 01 1 ,#& 1 1 Q0 Q 03 4 0 . 3 5 6 # %UDoR5REyWLFR $ #$%&'( -./- 01 0RWRUGRD !!" *+ )% # )(# 31 1 01 Q1 Q21 ANEXO B - Datasheet do microcontrolador AT89S52 Features • Compatible with MCS®-51 Products • 8K Bytes of In-System Programmable (ISP) Flash Memory • • • • • • • • • • • • • • • • – Endurance: 10,000 Write/Erase Cycles 4.0V to 5.5V Operating Range Fully Static Operation: 0 Hz to 33 MHz Three-level Program Memory Lock 256 x 8-bit Internal RAM 32 Programmable I/O Lines Three 16-bit Timer/Counters Eight Interrupt Sources Full Duplex UART Serial Channel Low-power Idle and Power-down Modes Interrupt Recovery from Power-down Mode Watchdog Timer Dual Data Pointer Power-off Flag Fast Programming Time Flexible ISP Programming (Byte and Page Mode) Green (Pb/Halide-free) Packaging Option 1. Description 8-bit Microcontroller with 8K Bytes In-System Programmable Flash AT89S52 The AT89S52 is a low-power, high-performance CMOS 8-bit microcontroller with 8K bytes of in-system programmable Flash memory. The device is manufactured using Atmel’s high-density nonvolatile memory technology and is compatible with the industry-standard 80C51 instruction set and pinout. The on-chip Flash allows the program memory to be reprogrammed in-system or by a conventional nonvolatile memory programmer. By combining a versatile 8-bit CPU with in-system programmable Flash on a monolithic chip, the Atmel AT89S52 is a powerful microcontroller which provides a highly-flexible and cost-effective solution to many embedded control applications. The AT89S52 provides the following standard features: 8K bytes of Flash, 256 bytes of RAM, 32 I/O lines, Watchdog timer, two data pointers, three 16-bit timer/counters, a six-vector two-level interrupt architecture, a full duplex serial port, on-chip oscillator, and clock circuitry. In addition, the AT89S52 is designed with static logic for operation down to zero frequency and supports two software selectable power saving modes. The Idle Mode stops the CPU while allowing the RAM, timer/counters, serial port, and interrupt system to continue functioning. The Power-down mode saves the RAM contents but freezes the oscillator, disabling all other chip functions until the next interrupt or hardware reset. 1919D–MICRO–6/08 2. Pin Configurations P1.4 P1.3 P1.2 P1.1 (T2 EX) P1.0 (T2) NC VCC P0.0 (AD0) P0.1 (AD1) P0.2 (AD2) P0.3 (AD3) 40 39 38 37 36 35 34 33 32 31 30 29 28 27 26 25 24 23 22 21 VCC P0.0 (AD0) P0.1 (AD1) P0.2 (AD2) P0.3 (AD3) P0.4 (AD4) P0.5 (AD5) P0.6 (AD6) P0.7 (AD7) EA/VPP ALE/PROG PSEN P2.7 (A15) P2.6 (A14) P2.5 (A13) P2.4 (A12) P2.3 (A11) P2.2 (A10) P2.1 (A9) P2.0 (A8) (MOSI) P1.5 (MISO) P1.6 (SCK) P1.7 RST (RXD) P3.0 NC (TXD) P3.1 (INT0) P3.2 (INT1) P3.3 (T0) P3.4 (T1) P3.5 6 5 4 3 2 1 44 43 42 41 40 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 44-lead PLCC 7 8 9 10 11 12 13 14 15 16 17 39 38 37 36 35 34 33 32 31 30 29 18 19 20 21 22 23 24 25 26 27 28 (T2) P1.0 (T2 EX) P1.1 P1.2 P1.3 P1.4 (MOSI) P1.5 (MISO) P1.6 (SCK) P1.7 RST (RXD) P3.0 (TXD) P3.1 (INT0) P3.2 (INT1) P3.3 (T0) P3.4 (T1) P3.5 (WR) P3.6 (RD) P3.7 XTAL2 XTAL1 GND P0.4 (AD4) P0.5 (AD5) P0.6 (AD6) P0.7 (AD7) EA/VPP NC ALE/PROG PSEN P2.7 (A15) P2.6 (A14) P2.5 (A13) 44-lead TQFP 44 43 42 41 40 39 38 37 36 35 34 P1.4 P1.3 P1.2 P1.1 (T2 EX) P1.0 (T2) NC VCC P0.0 (AD0) P0.1 (AD1) P0.2 (AD2) P0.3 (AD3) 2.2 2.3 40-lead PDIP (WR) P3.6 (RD) P3.7 XTAL2 XTAL1 GND NC (A8) P2.0 (A9) P2.1 (A10) P2.2 (A11) P2.3 (A12) P2.4 2.1 33 32 31 30 29 28 27 26 25 24 23 1 2 3 4 5 6 7 8 9 10 11 P0.4 (AD4) P0.5 (AD5) P0.6 (AD6) P0.7 (AD7) EA/VPP NC ALE/PROG PSEN P2.7 (A15) P2.6 (A14) P2.5 (A13) (WR) P3.6 (RD) P3.7 XTAL2 XTAL1 GND GND (A8) P2.0 (A9) P2.1 (A10) P2.2 (A11) P2.3 (A12) P2.4 12 13 14 15 16 17 18 19 20 21 22 (MOSI) P1.5 (MISO) P1.6 (SCK) P1.7 RST (RXD) P3.0 NC (TXD) P3.1 (INT0) P3.2 (INT1) P3.3 (T0) P3.4 (T1) P3.5 2 AT89S52 1919D–MICRO–6/08 AT89S52 3. Block Diagram P0.0 - P0.7 P2.0 - P2.7 PORT 0 DRIVERS PORT 2 DRIVERS VCC GND RAM ADDR. REGISTER B REGISTER PORT 0 LATCH RAM PORT 2 LATCH FLASH PROGRAM ADDRESS REGISTER STACK POINTER ACC BUFFER TMP2 TMP1 PC INCREMENTER ALU INTERRUPT, SERIAL PORT, AND TIMER BLOCKS PROGRAM COUNTER PSW PSEN ALE/PROG EA / VPP TIMING AND CONTROL INSTRUCTION REGISTER DUAL DPTR RST WATCH DOG PORT 3 LATCH PORT 1 LATCH ISP PORT PROGRAM LOGIC OSC PORT 3 DRIVERS P3.0 - P3.7 PORT 1 DRIVERS P1.0 - P1.7 3 1919D–MICRO–6/08 4. Pin Description 4.1 VCC Supply voltage. 4.2 GND Ground. 4.3 Port 0 Port 0 is an 8-bit open drain bidirectional I/O port. As an output port, each pin can sink eight TTL inputs. When 1s are written to port 0 pins, the pins can be used as high-impedance inputs. Port 0 can also be configured to be the multiplexed low-order address/data bus during accesses to external program and data memory. In this mode, P0 has internal pull-ups. Port 0 also receives the code bytes during Flash programming and outputs the code bytes during program verification. External pull-ups are required during program verification. 4.4 Port 1 Port 1 is an 8-bit bidirectional I/O port with internal pull-ups. The Port 1 output buffers can sink/source four TTL inputs. When 1s are written to Port 1 pins, they are pulled high by the internal pull-ups and can be used as inputs. As inputs, Port 1 pins that are externally being pulled low will source current (IIL) because of the internal pull-ups. In addition, P1.0 and P1.1 can be configured to be the timer/counter 2 external count input (P1.0/T2) and the timer/counter 2 trigger input (P1.1/T2EX), respectively, as shown in the following table. Port 1 also receives the low-order address bytes during Flash programming and verification. 4.5 Port Pin Alternate Functions P1.0 T2 (external count input to Timer/Counter 2), clock-out P1.1 T2EX (Timer/Counter 2 capture/reload trigger and direction control) P1.5 MOSI (used for In-System Programming) P1.6 MISO (used for In-System Programming) P1.7 SCK (used for In-System Programming) Port 2 Port 2 is an 8-bit bidirectional I/O port with internal pull-ups. The Port 2 output buffers can sink/source four TTL inputs. When 1s are written to Port 2 pins, they are pulled high by the internal pull-ups and can be used as inputs. As inputs, Port 2 pins that are externally being pulled low will source current (IIL) because of the internal pull-ups. Port 2 emits the high-order address byte during fetches from external program memory and during accesses to external data memory that use 16-bit addresses (MOVX @ DPTR). In this application, Port 2 uses strong internal pull-ups when emitting 1s. During accesses to external data memory that use 8-bit addresses (MOVX @ RI), Port 2 emits the contents of the P2 Special Function Register. Port 2 also receives the high-order address bits and some control signals during Flash programming and verification. 4 AT89S52 1919D–MICRO–6/08 AT89S52 4.6 Port 3 Port 3 is an 8-bit bidirectional I/O port with internal pull-ups. The Port 3 output buffers can sink/source four TTL inputs. When 1s are written to Port 3 pins, they are pulled high by the internal pull-ups and can be used as inputs. As inputs, Port 3 pins that are externally being pulled low will source current (IIL) because of the pull-ups. Port 3 receives some control signals for Flash programming and verification. Port 3 also serves the functions of various special features of the AT89S52, as shown in the following table. 4.7 Port Pin Alternate Functions P3.0 RXD (serial input port) P3.1 TXD (serial output port) P3.2 INT0 (external interrupt 0) P3.3 INT1 (external interrupt 1) P3.4 T0 (timer 0 external input) P3.5 T1 (timer 1 external input) P3.6 WR (external data memory write strobe) P3.7 RD (external data memory read strobe) RST Reset input. A high on this pin for two machine cycles while the oscillator is running resets the device. This pin drives high for 98 oscillator periods after the Watchdog times out. The DISRTO bit in SFR AUXR (address 8EH) can be used to disable this feature. In the default state of bit DISRTO, the RESET HIGH out feature is enabled. 4.8 ALE/PROG Address Latch Enable (ALE) is an output pulse for latching the low byte of the address during accesses to external memory. This pin is also the program pulse input (PROG) during Flash programming. In normal operation, ALE is emitted at a constant rate of 1/6 the oscillator frequency and may be used for external timing or clocking purposes. Note, however, that one ALE pulse is skipped during each access to external data memory. If desired, ALE operation can be disabled by setting bit 0 of SFR location 8EH. With the bit set, ALE is active only during a MOVX or MOVC instruction. Otherwise, the pin is weakly pulled high. Setting the ALE-disable bit has no effect if the microcontroller is in external execution mode. 5 1919D–MICRO–6/08 4.9 PSEN Program Store Enable (PSEN) is the read strobe to external program memory. When the AT89S52 is executing code from external program memory, PSEN is activated twice each machine cycle, except that two PSEN activations are skipped during each access to external data memory. 4.10 EA/VPP External Access Enable. EA must be strapped to GND in order to enable the device to fetch code from external program memory locations starting at 0000H up to FFFFH. Note, however, that if lock bit 1 is programmed, EA will be internally latched on reset. EA should be strapped to VCC for internal program executions. This pin also receives the 12-volt programming enable voltage (VPP) during Flash programming. 4.11 XTAL1 Input to the inverting oscillator amplifier and input to the internal clock operating circuit. 4.12 XTAL2 Output from the inverting oscillator amplifier. 5. Special Function Registers A map of the on-chip memory area called the Special Function Register (SFR) space is shown in Table 5-1. Note that not all of the addresses are occupied, and unoccupied addresses may not be implemented on the chip. Read accesses to these addresses will in general return random data, and write accesses will have an indeterminate effect. User software should not write 1s to these unlisted locations, since they may be used in future products to invoke new features. In that case, the reset or inactive values of the new bits will always be 0. Timer 2 Registers: Control and status bits are contained in registers T2CON (shown in Table 52) and T2MOD (shown in Table 10-2) for Timer 2. The register pair (RCAP2H, RCAP2L) are the Capture/Reload registers for Timer 2 in 16-bit capture mode or 16-bit auto-reload mode. Interrupt Registers: The individual interrupt enable bits are in the IE register. Two priorities can be set for each of the six interrupt sources in the IP register. 6 AT89S52 1919D–MICRO–6/08 AT89S52 Table 5-1. AT89S52 SFR Map and Reset Values 0F8H 0F0H 0FFH B 00000000 0F7H 0E8H 0E0H 0EFH ACC 00000000 0E7H 0D8H 0DFH 0D0H PSW 00000000 0C8H T2CON 00000000 0D7H T2MOD XXXXXX00 RCAP2L 00000000 RCAP2H 00000000 TL2 00000000 TH2 00000000 0CFH 0C0H 0C7H 0B8H IP XX000000 0BFH 0B0H P3 11111111 0B7H 0A8H IE 0X000000 0AFH 0A0H P2 11111111 98H SCON 00000000 90H P1 11111111 88H TCON 00000000 TMOD 00000000 TL0 00000000 TL1 00000000 TH0 00000000 TH1 00000000 80H P0 11111111 SP 00000111 DP0L 00000000 DP0H 00000000 DP1L 00000000 DP1H 00000000 AUXR1 XXXXXXX0 WDTRST XXXXXXXX 0A7H SBUF XXXXXXXX 9FH 97H AUXR XXX00XX0 8FH PCON 0XXX0000 87H 7 1919D–MICRO–6/08 Table 5-2. T2CON – Timer/Counter 2 Control Register T2CON Address = 0C8H Reset Value = 0000 0000B Bit Addressable Bit TF2 EXF2 RCLK TCLK EXEN2 TR2 C/T2 CP/RL2 7 6 5 4 3 2 1 0 Symbol Function TF2 Timer 2 overflow flag set by a Timer 2 overflow and must be cleared by software. TF2 will not be set when either RCLK = 1 or TCLK = 1. EXF2 Timer 2 external flag set when either a capture or reload is caused by a negative transition on T2EX and EXEN2 = 1. When Timer 2 interrupt is enabled, EXF2 = 1 will cause the CPU to vector to the Timer 2 interrupt routine. EXF2 must be cleared by software. EXF2 does not cause an interrupt in up/down counter mode (DCEN = 1). RCLK Receive clock enable. When set, causes the serial port to use Timer 2 overflow pulses for its receive clock in serial port Modes 1 and 3. RCLK = 0 causes Timer 1 overflow to be used for the receive clock. TCLK Transmit clock enable. When set, causes the serial port to use Timer 2 overflow pulses for its transmit clock in serial port Modes 1 and 3. TCLK = 0 causes Timer 1 overflows to be used for the transmit clock. EXEN2 Timer 2 external enable. When set, allows a capture or reload to occur as a result of a negative transition on T2EX if Timer 2 is not being used to clock the serial port. EXEN2 = 0 causes Timer 2 to ignore events at T2EX. TR2 Start/Stop control for Timer 2. TR2 = 1 starts the timer. C/T2 Timer or counter select for Timer 2. C/T2 = 0 for timer function. C/T2 = 1 for external event counter (falling edge triggered). CP/RL2 Capture/Reload select. CP/RL2 = 1 causes captures to occur on negative transitions at T2EX if EXEN2 = 1. CP/RL2 = 0 causes automatic reloads to occur when Timer 2 overflows or negative transitions occur at T2EX when EXEN2 = 1. When either RCLK or TCLK = 1, this bit is ignored and the timer is forced to auto-reload on Timer 2 overflow. 8 AT89S52 1919D–MICRO–6/08 AT89S52 AUXR: Auxiliary Register Table 5-3. AUXR Address = 8EH Reset Value = XXX00XX0B Not Bit Addressable Bit – – – WDIDLE DISRTO – – DISALE 7 6 5 4 3 2 1 0 – Reserved for future expansion DISALE Disable/Enable ALE DISRTO DISALE Operating Mode 0 ALE is emitted at a constant rate of 1/6 the oscillator frequency 1 ALE is active only during a MOVX or MOVC instruction Disable/Enable Reset out DISRTO WDIDLE 0 Reset pin is driven High after WDT times out 1 Reset pin is input only Disable/Enable WDT in IDLE mode WDIDLE 0 WDT continues to count in IDLE mode 1 WDT halts counting in IDLE mode Dual Data Pointer Registers: To facilitate accessing both internal and external data memory, two banks of 16-bit Data Pointer Registers are provided: DP0 at SFR address locations 82H-83H and DP1 at 84H-85H. Bit DPS = 0 in SFR AUXR1 selects DP0 and DPS = 1 selects DP1. The user should ALWAYS initialize the DPS bit to the appropriate value before accessing the respective Data Pointer Register. Power Off Flag: The Power Off Flag (POF) is located at bit 4 (PCON.4) in the PCON SFR. POF is set to “1” during power up. It can be set and rest under software control and is not affected by reset. AUXR1: Auxiliary Register 1 Table 5-4. AUXR1 Address = A2H Reset Value = XXXXXXX0B Not Bit Addressable Bit – – – – – – – DPS 7 6 5 4 3 2 1 0 – Reserved for future expansion DPS Data Pointer Register Select DPS 0 Selects DPTR Registers DP0L, DP0H 1 Selects DPTR Registers DP1L, DP1H 9 1919D–MICRO–6/08 6. Memory Organization MCS-51 devices have a separate address space for Program and Data Memory. Up to 64K bytes each of external Program and Data Memory can be addressed. 6.1 Program Memory If the EA pin is connected to GND, all program fetches are directed to external memory. On the AT89S52, if EA is connected to VCC, program fetches to addresses 0000H through 1FFFH are directed to internal memory and fetches to addresses 2000H through FFFFH are to external memory. 6.2 Data Memory The AT89S52 implements 256 bytes of on-chip RAM. The upper 128 bytes occupy a parallel address space to the Special Function Registers. This means that the upper 128 bytes have the same addresses as the SFR space but are physically separate from SFR space. When an instruction accesses an internal location above address 7FH, the address mode used in the instruction specifies whether the CPU accesses the upper 128 bytes of RAM or the SFR space. Instructions which use direct addressing access the SFR space. For example, the following direct addressing instruction accesses the SFR at location 0A0H (which is P2). MOV 0A0H, #data Instructions that use indirect addressing access the upper 128 bytes of RAM. For example, the following indirect addressing instruction, where R0 contains 0A0H, accesses the data byte at address 0A0H, rather than P2 (whose address is 0A0H). MOV @R0, #data Note that stack operations are examples of indirect addressing, so the upper 128 bytes of data RAM are available as stack space. 7. Watchdog Timer (One-time Enabled with Reset-out) The WDT is intended as a recovery method in situations where the CPU may be subjected to software upsets. The WDT consists of a 14-bit counter and the Watchdog Timer Reset (WDTRST) SFR. The WDT is defaulted to disable from exiting reset. To enable the WDT, a user must write 01EH and 0E1H in sequence to the WDTRST register (SFR location 0A6H). When the WDT is enabled, it will increment every machine cycle while the oscillator is running. The WDT timeout period is dependent on the external clock frequency. There is no way to disable the WDT except through reset (either hardware reset or WDT overflow reset). When WDT overflows, it will drive an output RESET HIGH pulse at the RST pin. 7.1 Using the WDT To enable the WDT, a user must write 01EH and 0E1H in sequence to the WDTRST register (SFR location 0A6H). When the WDT is enabled, the user needs to service it by writing 01EH and 0E1H to WDTRST to avoid a WDT overflow. The 14-bit counter overflows when it reaches 16383 (3FFFH), and this will reset the device. When the WDT is enabled, it will increment every machine cycle while the oscillator is running. This means the user must reset the WDT at least every 16383 machine cycles. To reset the WDT the user must write 01EH and 0E1H to WDTRST. WDTRST is a write-only register. The WDT counter cannot be read or written. When 10 AT89S52 1919D–MICRO–6/08 AT89S52 WDT overflows, it will generate an output RESET pulse at the RST pin. The RESET pulse duration is 98xTOSC, where TOSC = 1/FOSC. To make the best use of the WDT, it should be serviced in those sections of code that will periodically be executed within the time required to prevent a WDT reset. 7.2 WDT During Power-down and Idle In Power-down mode the oscillator stops, which means the WDT also stops. While in Powerdown mode, the user does not need to service the WDT. There are two methods of exiting Power-down mode: by a hardware reset or via a level-activated external interrupt which is enabled prior to entering Power-down mode. When Power-down is exited with hardware reset, servicing the WDT should occur as it normally does whenever the AT89S52 is reset. Exiting Power-down with an interrupt is significantly different. The interrupt is held low long enough for the oscillator to stabilize. When the interrupt is brought high, the interrupt is serviced. To prevent the WDT from resetting the device while the interrupt pin is held low, the WDT is not started until the interrupt is pulled high. It is suggested that the WDT be reset during the interrupt service for the interrupt used to exit Power-down mode. To ensure that the WDT does not overflow within a few states of exiting Power-down, it is best to reset the WDT just before entering Power-down mode. Before going into the IDLE mode, the WDIDLE bit in SFR AUXR is used to determine whether the WDT continues to count if enabled. The WDT keeps counting during IDLE (WDIDLE bit = 0) as the default state. To prevent the WDT from resetting the AT89S52 while in IDLE mode, the user should always set up a timer that will periodically exit IDLE, service the WDT, and reenter IDLE mode. With WDIDLE bit enabled, the WDT will stop to count in IDLE mode and resumes the count upon exit from IDLE. 8. UART The UART in the AT89S52 operates the same way as the UART in the AT89C51 and AT89C52. For further information on the UART operation, please click on the document link below: http://www.atmel.com/dyn/resources/prod_documents/DOC4316.PDF 9. Timer 0 and 1 Timer 0 and Timer 1 in the AT89S52 operate the same way as Timer 0 and Timer 1 in the AT89C51 and AT89C52. For further information on the timers’ operation, please click on the document link below: http://www.atmel.com/dyn/resources/prod_documents/DOC4316.PDF 11 1919D–MICRO–6/08 10. Timer 2 Timer 2 is a 16-bit Timer/Counter that can operate as either a timer or an event counter. The type of operation is selected by bit C/T2 in the SFR T2CON (shown in Table 5-2). Timer 2 has three operating modes: capture, auto-reload (up or down counting), and baud rate generator. The modes are selected by bits in T2CON, as shown in Table 10-1. Timer 2 consists of two 8-bit registers, TH2 and TL2. In the Timer function, the TL2 register is incremented every machine cycle. Since a machine cycle consists of 12 oscillator periods, the count rate is 1/12 of the oscillator frequency. Timer 2 Operating Modes Table 10-1. RCLK +TCLK CP/RL2 TR2 MODE 0 0 1 16-bit Auto-reload 0 1 1 16-bit Capture 1 X 1 Baud Rate Generator X X 0 (Off) In the Counter function, the register is incremented in response to a 1-to-0 transition at its corresponding external input pin, T2. In this function, the external input is sampled during S5P2 of every machine cycle. When the samples show a high in one cycle and a low in the next cycle, the count is incremented. The new count value appears in the register during S3P1 of the cycle following the one in which the transition was detected. Since two machine cycles (24 oscillator periods) are required to recognize a 1-to-0 transition, the maximum count rate is 1/24 of the oscillator frequency. To ensure that a given level is sampled at least once before it changes, the level should be held for at least one full machine cycle. 10.1 Capture Mode In the capture mode, two options are selected by bit EXEN2 in T2CON. If EXEN2 = 0, Timer 2 is a 16-bit timer or counter which upon overflow sets bit TF2 in T2CON. This bit can then be used to generate an interrupt. If EXEN2 = 1, Timer 2 performs the same operation, but a 1-to-0 transition at external input T2EX also causes the current value in TH2 and TL2 to be captured into RCAP2H and RCAP2L, respectively. In addition, the transition at T2EX causes bit EXF2 in T2CON to be set. The EXF2 bit, like TF2, can generate an interrupt. The capture mode is illustrated in Figure 10-1. 10.2 Auto-reload (Up or Down Counter) Timer 2 can be programmed to count up or down when configured in its 16-bit auto-reload mode. This feature is invoked by the DCEN (Down Counter Enable) bit located in the SFR T2MOD (see Table 10-2). Upon reset, the DCEN bit is set to 0 so that timer 2 will default to count up. When DCEN is set, Timer 2 can count up or down, depending on the value of the T2EX pin. 12 AT89S52 1919D–MICRO–6/08 AT89S52 Figure 10-1. Timer in Capture Mode ÷12 OSC C/T2 = 0 TH2 TL2 TF2 OVERFLOW CONTROL TR2 C/T2 = 1 CAPTURE T2 PIN RCAP2H RCAP2L TRANSITION DETECTOR TIMER 2 INTERRUPT T2EX PIN EXF2 CONTROL EXEN2 Table 10-2. T2MOD – Timer 2 Mode Control Register T2MOD Address = 0C9H Reset Value = XXXX XX00B Not Bit Addressable Bit – – – – – – T2OE DCEN 7 6 5 4 3 2 1 0 Symbol Function – Not implemented, reserved for future T2OE Timer 2 Output Enable bit DCEN When set, this bit allows Timer 2 to be configured as an up/down counter Figure 10-2 shows Timer 2 automatically counting up when DCEN = 0. In this mode, two options are selected by bit EXEN2 in T2CON. If EXEN2 = 0, Timer 2 counts up to 0FFFFH and then sets the TF2 bit upon overflow. The overflow also causes the timer registers to be reloaded with the 16-bit value in RCAP2H and RCAP2L. The values in Timer in Capture ModeRCAP2H and RCAP2L are preset by software. If EXEN2 = 1, a 16-bit reload can be triggered either by an overflow or by a 1-to-0 transition at external input T2EX. This transition also sets the EXF2 bit. Both the TF2 and EXF2 bits can generate an interrupt if enabled. Setting the DCEN bit enables Timer 2 to count up or down, as shown in Figure 10-2. In this mode, the T2EX pin controls the direction of the count. A logic 1 at T2EX makes Timer 2 count up. The timer will overflow at 0FFFFH and set the TF2 bit. This overflow also causes the 16-bit value in RCAP2H and RCAP2L to be reloaded into the timer registers, TH2 and TL2, respectively. A logic 0 at T2EX makes Timer 2 count down. The timer underflows when TH2 and TL2 equal the values stored in RCAP2H and RCAP2L. The underflow sets the TF2 bit and causes 0FFFFH to be reloaded into the timer registers. The EXF2 bit toggles whenever Timer 2 overflows or underflows and can be used as a 17th bit of resolution. In this operating mode, EXF2 does not flag an interrupt. 13 1919D–MICRO–6/08 Figure 10-2. Timer 2 Auto Reload Mode (DCEN = 0) ÷12 OSC C/T2 = 0 TH2 TL2 OVERFLOW CONTR OL TR2 C/T2 = 1 RELO AD T2 PIN RCAP2H TIMER 2 INTERRUPT RCAP2L TF2 TRANSITION DETECTOR EXF2 T2EX PIN CONTROL EXEN2 Figure 10-3. Timer 2 Auto Reload Mode (DCEN = 1) TOGGLE (DOWN COUNTING RELOAD VALUE) 0FFH OSC 0FFH ÷ 12 EXF2 OVERFLOW C/T2 = 0 TH2 TL2 TF2 CONTROL TR2 TIMER 2 INTERRUPT C/T2 = 1 T2 PIN RCAP2H RCAP2L (UP COUNTING RELOAD VALUE) COUNT DIRECTION 1=UP 0=DOWN T2EX PIN 14 AT89S52 1919D–MICRO–6/08 AT89S52 11. Baud Rate Generator Timer 2 is selected as the baud rate generator by setting TCLK and/or RCLK in T2CON (Table 5-2). Note that the baud rates for transmit and receive can be different if Timer 2 is used for the receiver or transmitter and Timer 1 is used for the other function. Setting RCLK and/or TCLK puts Timer 2 into its baud rate generator mode, as shown in Figure 11-1. The baud rate generator mode is similar to the auto-reload mode, in that a rollover in TH2 causes the Timer 2 registers to be reloaded with the 16-bit value in registers RCAP2H and RCAP2L, which are preset by software. The baud rates in Modes 1 and 3 are determined by Timer 2’s overflow rate according to the following equation. Timer 2 Overflow Rate Modes 1 and 3 Baud Rates = -----------------------------------------------------------16 The Timer can be configured for either timer or counter operation. In most applications, it is configured for timer operation (CP/T2 = 0). The timer operation is different for Timer 2 when it is used as a baud rate generator. Normally, as a timer, it increments every machine cycle (at 1/12 the oscillator frequency). As a baud rate generator, however, it increments every state time (at 1/2 the oscillator frequency). The baud rate formula is given below. Oscillator Frequency Modes 1 and 3 --------------------------------------- = -------------------------------------------------------------------------------------32 x [65536-RCAP2H,RCAP2L)] Baud Rate where (RCAP2H, RCAP2L) is the content of RCAP2H and RCAP2L taken as a 16-bit unsigned integer. Timer 2 as a baud rate generator is shown in Figure 11-1. This figure is valid only if RCLK or TCLK = 1 in T2CON. Note that a rollover in TH2 does not set TF2 and will not generate an interrupt. Note too, that if EXEN2 is set, a 1-to-0 transition in T2EX will set EXF2 but will not cause a reload from (RCAP2H, RCAP2L) to (TH2, TL2). Thus, when Timer 2 is in use as a baud rate generator, T2EX can be used as an extra external interrupt. Note that when Timer 2 is running (TR2 = 1) as a timer in the baud rate generator mode, TH2 or TL2 should not be read from or written to. Under these conditions, the Timer is incremented every state time, and the results of a read or write may not be accurate. The RCAP2 registers may be read but should not be written to, because a write might overlap a reload and cause write and/or reload errors. The timer should be turned off (clear TR2) before accessing the Timer 2 or RCAP2 registers. 15 1919D–MICRO–6/08 Figure 11-1. Timer 2 in Baud Rate Generator Mode TIMER 1 OVERFLOW ÷2 "0" "1" NOTE: OSC. FREQ. IS DIVIDED BY 2, NOT 12 SMOD1 OSC ÷2 C/T2 = 0 "1" TH2 "0" TL2 RCLK CONTROL TR2 ÷ 16 Rx CLOCK C/T2 = 1 "1" "0" T2 PIN TCLK RCAP2H RCAP2L TRANSITION DETECTOR ÷ 16 T2EX PIN EXF2 Tx CLOCK TIMER 2 INTERRUPT CONTROL EXEN2 12. Programmable Clock Out A 50% duty cycle clock can be programmed to come out on P1.0, as shown in Figure 12-1. This pin, besides being a regular I/O pin, has two alternate functions. It can be programmed to input the external clock for Timer/Counter 2 or to output a 50% duty cycle clock ranging from 61 Hz to 4 MHz (for a 16-MHz operating frequency). To configure the Timer/Counter 2 as a clock generator, bit C/T2 (T2CON.1) must be cleared and bit T2OE (T2MOD.1) must be set. Bit TR2 (T2CON.2) starts and stops the timer. The clock-out frequency depends on the oscillator frequency and the reload value of Timer 2 capture registers (RCAP2H, RCAP2L), as shown in the following equation. Oscillator Frequency Clock-Out Frequency = -----------------------------------------------------------------------------------4 x [65536-(RCAP2H,RCAP2L)] In the clock-out mode, Timer 2 roll-overs will not generate an interrupt. This behavior is similar to when Timer 2 is used as a baud-rate generator. It is possible to use Timer 2 as a baud-rate generator and a clock generator simultaneously. Note, however, that the baud-rate and clock-out frequencies cannot be determined independently from one another since they both use RCAP2H and RCAP2L. 16 AT89S52 1919D–MICRO–6/08 AT89S52 Figure 12-1. Timer 2 in Clock-Out Mode OSC TL2 (8-BITS) ÷2 TH2 (8-BITS) TR2 RCAP2L RCAP2H C/T2 BIT P1.0 (T2) ÷2 T2OE (T2MOD.1) TRANSITION DETECTOR P1.1 (T2EX) EXF2 TIMER 2 INTERRUPT EXEN2 13. Interrupts The AT89S52 has a total of six interrupt vectors: two external interrupts (INT0 and INT1), three timer interrupts (Timers 0, 1, and 2), and the serial port interrupt. These interrupts are all shown in Figure 13-1. Each of these interrupt sources can be individually enabled or disabled by setting or clearing a bit in Special Function Register IE. IE also contains a global disable bit, EA, which disables all interrupts at once. Note that Table 13-1 shows that bit position IE.6 is unimplemented. User software should not write a 1 to this bit position, since it may be used in future AT89 products. Timer 2 interrupt is generated by the logical OR of bits TF2 and EXF2 in register T2CON. Neither of these flags is cleared by hardware when the service routine is vectored to. In fact, the service routine may have to determine whether it was TF2 or EXF2 that generated the interrupt, and that bit will have to be cleared in software. The Timer 0 and Timer 1 flags, TF0 and TF1, are set at S5P2 of the cycle in which the timers overflow. The values are then polled by the circuitry in the next cycle. However, the Timer 2 flag, TF2, is set at S2P2 and is polled in the same cycle in which the timer overflows. 17 1919D–MICRO–6/08 Table 13-1. Interrupt Enable (IE) Register (MSB) (LSB) EA – ET2 ES ET1 EX1 ET0 EX0 Enable Bit = 1 enables the interrupt. Enable Bit = 0 disables the interrupt. Symbol Position Function EA IE.7 Disables all interrupts. If EA = 0, no interrupt is acknowledged. If EA = 1, each interrupt source is individually enabled or disabled by setting or clearing its enable bit. – IE.6 Reserved. ET2 IE.5 Timer 2 interrupt enable bit. ES IE.4 Serial Port interrupt enable bit. ET1 IE.3 Timer 1 interrupt enable bit. EX1 IE.2 External interrupt 1 enable bit. ET0 IE.1 Timer 0 interrupt enable bit. EX0 IE.0 External interrupt 0 enable bit. User software should never write 1s to reserved bits, because they may be used in future AT89 products. Figure 13-1. Interrupt Sources 0 INT0 IE0 1 TF0 0 INT1 1 IE1 TF1 TI RI TF2 EXF2 18 AT89S52 1919D–MICRO–6/08 AT89S52 14. Oscillator Characteristics XTAL1 and XTAL2 are the input and output, respectively, of an inverting amplifier that can be configured for use as an on-chip oscillator, as shown in Figure 16-1. Either a quartz crystal or ceramic resonator may be used. To drive the device from an external clock source, XTAL2 should be left unconnected while XTAL1 is driven, as shown in Figure 16-2. There are no requirements on the duty cycle of the external clock signal, since the input to the internal clocking circuitry is through a divide-by-two flip-flop, but minimum and maximum voltage high and low time specifications must be observed. 15. Idle Mode In idle mode, the CPU puts itself to sleep while all the on-chip peripherals remain active. The mode is invoked by software. The content of the on-chip RAM and all the special functions registers remain unchanged during this mode. The idle mode can be terminated by any enabled interrupt or by a hardware reset. Note that when idle mode is terminated by a hardware reset, the device normally resumes program execution from where it left off, up to two machine cycles before the internal reset algorithm takes control. On-chip hardware inhibits access to internal RAM in this event, but access to the port pins is not inhibited. To eliminate the possibility of an unexpected write to a port pin when idle mode is terminated by a reset, the instruction following the one that invokes idle mode should not write to a port pin or to external memory. 16. Power-down Mode In the Power-down mode, the oscillator is stopped, and the instruction that invokes Power-down is the last instruction executed. The on-chip RAM and Special Function Registers retain their values until the Power-down mode is terminated. Exit from Power-down mode can be initiated either by a hardware reset or by an enabled external interrupt. Reset redefines the SFRs but does not change the on-chip RAM. The reset should not be activated before VCC is restored to its normal operating level and must be held active long enough to allow the oscillator to restart and stabilize. Figure 16-1. Oscillator Connections C2 XTAL2 C1 XTAL1 GND Note: 1. C1, C2 = 30 pF ± 10 pF for Crystals = 40 pF ± 10 pF for Ceramic Resonators 19 1919D–MICRO–6/08 Figure 16-2. External Clock Drive Configuration NC XTAL2 EXTERNAL OSCILLATOR SIGNAL XTAL1 GND Status of External Pins During Idle and Power-down Modes Table 16-1. Mode Program Memory Idle ALE PSEN PORT0 PORT1 PORT2 PORT3 Internal 1 1 Data Data Data Data Idle External 1 1 Float Data Address Data Power-down Internal 0 0 Data Data Data Data Power-down External 0 0 Float Data Data Data 17. Program Memory Lock Bits The AT89S52 has three lock bits that can be left unprogrammed (U) or can be programmed (P) to obtain the additional features listed in Table 17-1. Lock Bit Protection Modes Table 17-1. Program Lock Bits 1 LB1 LB2 LB3 Protection Type U U U No program lock features 2 P U U MOVC instructions executed from external program memory are disabled from fetching code bytes from internal memory, EA is sampled and latched on reset, and further programming of the Flash memory is disabled 3 P P U Same as mode 2, but verify is also disabled 4 P P P Same as mode 3, but external execution is also disabled When lock bit 1 is programmed, the logic level at the EA pin is sampled and latched during reset. If the device is powered up without a reset, the latch initializes to a random value and holds that value until reset is activated. The latched value of EA must agree with the current logic level at that pin in order for the device to function properly. 20 AT89S52 1919D–MICRO–6/08 AT89S52 18. Programming the Flash – Parallel Mode The AT89S52 is shipped with the on-chip Flash memory array ready to be programmed. The programming interface needs a high-voltage (12-volt) program enable signal and is compatible with conventional third-party Flash or EPROM programmers. The AT89S52 code memory array is programmed byte-by-byte. Programming Algorithm: Before programming the AT89S52, the address, data, and control signals should be set up according to the “Flash Programming Modes” (Table 22-1) and Figure 22-1 and Figure 22-2. To program the AT89S52, take the following steps: 1. Input the desired memory location on the address lines. 2. Input the appropriate data byte on the data lines. 3. Activate the correct combination of control signals. 4. Raise EA/VPP to 12V. 5. Pulse ALE/PROG once to program a byte in the Flash array or the lock bits. The bytewrite cycle is self-timed and typically takes no more than 50 µs. Repeat steps 1 through 5, changing the address and data for the entire array or until the end of the object file is reached. Data Polling: The AT89S52 features Data Polling to indicate the end of a byte write cycle. During a write cycle, an attempted read of the last byte written will result in the complement of the written data on P0.7. Once the write cycle has been completed, true data is valid on all outputs, and the next cycle may begin. Data Polling may begin any time after a write cycle has been initiated. Ready/Busy: The progress of byte programming can also be monitored by the RDY/BSY output signal. P3.0 is pulled low after ALE goes high during programming to indicate BUSY. P3.0 is pulled high again when programming is done to indicate READY. Program Verify: If lock bits LB1 and LB2 have not been programmed, the programmed code data can be read back via the address and data lines for verification. The status of the individual lock bits can be verified directly by reading them back. Reading the Signature Bytes: The signature bytes are read by the same procedure as a normal verification of locations 000H, 100H, and 200H, except that P3.6 and P3.7 must be pulled to a logic low. The values returned are as follows. (000H) = 1EH indicates manufactured by Atmel (100H) = 52H indicates AT89S52 (200H) = 06H Chip Erase: In the parallel programming mode, a chip erase operation is initiated by using the proper combination of control signals and by pulsing ALE/PROG low for a duration of 200 ns 500 ns. In the serial programming mode, a chip erase operation is initiated by issuing the Chip Erase instruction. In this mode, chip erase is self-timed and takes about 500 ms. During chip erase, a serial read from any address location will return 00H at the data output. 21 1919D–MICRO–6/08 19. Programming the Flash – Serial Mode The Code memory array can be programmed using the serial ISP interface while RST is pulled to VCC. The serial interface consists of pins SCK, MOSI (input) and MISO (output). After RST is set high, the Programming Enable instruction needs to be executed first before other operations can be executed. Before a reprogramming sequence can occur, a Chip Erase operation is required. The Chip Erase operation turns the content of every memory location in the Code array into FFH. Either an external system clock can be supplied at pin XTAL1 or a crystal needs to be connected across pins XTAL1 and XTAL2. The maximum serial clock (SCK) frequency should be less than 1/16 of the crystal frequency. With a 33 MHz oscillator clock, the maximum SCK frequency is 2 MHz. 20. Serial Programming Algorithm To program and verify the AT89S52 in the serial programming mode, the following sequence is recommended: 1. Power-up sequence: a. Apply power between VCC and GND pins. b. Set RST pin to “H”. If a crystal is not connected across pins XTAL1 and XTAL2, apply a 3 MHz to 33 MHz clock to XTAL1 pin and wait for at least 10 milliseconds. 2. Enable serial programming by sending the Programming Enable serial instruction to pin MOSI/P1.5. The frequency of the shift clock supplied at pin SCK/P1.7 needs to be less than the CPU clock at XTAL1 divided by 16. 3. The Code array is programmed one byte at a time in either the Byte or Page mode. The write cycle is self-timed and typically takes less than 0.5 ms at 5V. 4. Any memory location can be verified by using the Read instruction which returns the content at the selected address at serial output MISO/P1.6. 5. At the end of a programming session, RST can be set low to commence normal device operation. Power-off sequence (if needed): 1. Set XTAL1 to “L” (if a crystal is not used). 2. Set RST to “L”. 3. Turn VCC power off. Data Polling: The Data Polling feature is also available in the serial mode. In this mode, during a write cycle an attempted read of the last byte written will result in the complement of the MSB of the serial output byte on MISO. 21. Serial Programming Instruction Set The Instruction Set for Serial Programming follows a 4-byte protocol and is shown in Table 24-1. 22 AT89S52 1919D–MICRO–6/08 AT89S52 22. Programming Interface – Parallel Mode Every code byte in the Flash array can be programmed by using the appropriate combination of control signals. The write operation cycle is self-timed and once initiated, will automatically time itself to completion. Most major worldwide programming vendors offer support for the Atmel AT89 microcontroller series. Please contact your local programming vendor for the appropriate software revision. Table 22-1. Flash Programming Modes Mode VCC RST PSEN Write Code Data 5V H L Read Code Data 5V H L P0.7-0 P2.4-0 P1.7-0 ALE/ EA/ PROG VPP P2.6 P2.7 P3.3 P3.6 P3.7 Data 12V L H H H H DIN A12-8 A7-0 H L L L H H DOUT A12-8 A7-0 12V H H H H H X X X 12V H H H L L X X X 12V H L H H L X X X H H H L H L P0.2, P0.3, P0.4 X X 12V H L H L L X X X Address (2) H (3) Write Lock Bit 1 5V H L Write Lock Bit 2 5V H L Write Lock Bit 3 5V H L 5V H L Chip Erase 5V H L Read Atmel ID 5V H L H H L L L L L 1EH X 0000 00H Read Device ID 5V H L H H L L L L L 52H X 0001 00H Read Device ID 5V H L H H L L L L L 06H X 0010 00H (3) (3) Read Lock Bits 1, 2, 3 H (1) Notes: 1. 2. 3. 4. 5. Each PROG pulse is 200 ns - 500 ns for Chip Erase. Each PROG pulse is 200 ns - 500 ns for Write Code Data. Each PROG pulse is 200 ns - 500 ns for Write Lock Bits. RDY/BSY signal is output on P3.0 during programming. X = don’t care. 23 1919D–MICRO–6/08 Figure 22-1. Programming the Flash Memory (Parallel Mode) VCC AT89S52 ADDR. 0000H/1FFFH A0 - A7 A8 - A12 VCC P1.0-P1.7 P2.6 P2.7 P3.3 P3.6 SEE FLASH PROGRAMMING MODES TABLE PGM DATA P0 P2.0 - P2.4 ALE PROG EA VIH/VPP P3.7 XTAL2 3-33 MHz XTAL1 GND P3.0 RDY/ BSY RST VIH PSEN Figure 22-2. Verifying the Flash Memory (Parallel Mode) VCC AT89S52 A0 - A7 ADDR. 0000H/1FFFH A8 - A12 SEE FLASH PROGRAMMING MODES TABLE P1.0-P1.7 VCC P2.0 - P2.4 P0 P2.6 P2.7 P3.3 P3.6 P3.7 PGM DATA (USE 10K PULLUPS) ALE VIH XTAL 2 EA XTAL1 RST 3-33 MHz GND 24 VIH PSEN AT89S52 1919D–MICRO–6/08 AT89S52 23. Flash Programming and Verification Characteristics (Parallel Mode) TA = 20°C to 30°C, VCC = 4.5 to 5.5V Symbol Parameter Min Max Units VPP Programming Supply Voltage 11.5 12.5 V IPP Programming Supply Current 10 mA ICC VCC Supply Current 30 mA 1/tCLCL Oscillator Frequency 33 MHz tAVGL Address Setup to PROG Low 48 tCLCL tGHAX Address Hold After PROG 48 tCLCL tDVGL Data Setup to PROG Low 48 tCLCL tGHDX Data Hold After PROG 48 tCLCL tEHSH P2.7 (ENABLE) High to VPP 48 tCLCL tSHGL VPP Setup to PROG Low 10 µs tGHSL VPP Hold After PROG 10 µs tGLGH PROG Width 0.2 tAVQV Address to Data Valid 48 tCLCL tELQV ENABLE Low to Data Valid 48 tCLCL tEHQZ Data Float After ENABLE tGHBL PROG High to BUSY Low 1.0 µs tWC Byte Write Cycle Time 50 µs 3 1 0 µs 48 tCLCL Figure 23-1. Flash Programming and Verification Waveforms – Parallel Mode PROGRAMMING ADDRESS P1.0 - P1.7 P2.0 - P2.4 VERIFICATION ADDRESS tAVQV PORT 0 DATA IN tAVGL tDVGL tGHDX DATA OUT tGHAX ALE/PROG tSHGL tGLGH VPP LOGIC 1 LOGIC 0 EA/VPP P2.7 (ENABLE) tGHSL tEHSH tEHQZ tELQV tGHBL P3.0 (RDY/BSY) BUSY READY tWC 25 1919D–MICRO–6/08 Figure 23-2. Flash Memory Serial Downloading VCC AT89S52 VCC INSTRUCTION INPUT P1.5/MOSI DATA OUTPUT P1.6/MISO P1.7/SCK CLOCK IN XTAL2 3-33 MHz XTAL1 RST VIH GND 24. Flash Programming and Verification Waveforms – Serial Mode Figure 24-1. Serial Programming Waveforms 7 26 6 5 4 3 2 1 0 AT89S52 1919D–MICRO–6/08 AT89S52 Table 24-1. Serial Programming Instruction Set Instruction Format Byte 1 Byte 2 Byte 3 Byte 4 Operation 1010 1100 0101 0011 xxxx xxxx xxxx xxxx 0110 1001 (Output on MISO) Enable Serial Programming while RST is high xxxx xxxx Chip Erase Flash memory array A7 A6 A5 A4 A3 A2 A1 A0 D7 D6 D5 D4 D3 D2 D1 D0 Read data from Program memory in the byte mode A7 A6 A5 A4 A3 A2 A1 A0 D7 D6 D5 D4 D3 D2 D1 D0 Read Program Memory (Byte Mode) 0010 0000 xxx Write Program Memory (Byte Mode) 0100 0000 xxx Write data to Program memory in the byte mode Write Lock Bits(1) 1010 1100 1110 00 0010 0100 xxxx xxxx 0010 1000 xxx 0011 0000 xxx 0101 0000 xxx xxxx xxxx xxxx xxxx xxxx xxxx xxx Note: A7 Write Program Memory (Page Mode) Read back current status of the lock bits (a programmed lock bit reads back as a “1”) A12 A11 A10 A9 A8 Read Program Memory (Page Mode) xx Signature Byte A12 A11 A10 A9 A8 Read Signature Bytes Write Lock bits. See Note (1). Byte 0 Byte 1... Byte 255 Read data from Program memory in the Page Mode (256 bytes) A12 A11 A10 A9 A8 Read Lock Bits LB2 LB1 100x xxxx B1 B2 xxxx xxxx A12 A11 A10 A9 A8 1010 1100 Chip Erase A12 A11 A10 A9 A8 Programming Enable LB3 Instruction Byte 0 Byte 1... Byte 255 Write data to Program memory in the Page Mode (256 bytes) 1. B1 = 0, B2 = 0 ---> Mode 1, no lock protection B1 = 0, B2 = 1 ---> Mode 2, lock bit 1 activated B1 = 1, B2 = 0 ---> Mode 3, lock bit 2 activated B1 = 1, B2 = 1 ---> Mode 4, lock bit 3 activated xxx xxx0 } Read Signature Byte Each of the lock bit modes needs to be activated sequentially before Mode 4 can be executed. After Reset signal is high, SCK should be low for at least 64 system clocks before it goes high to clock in the enable data bytes. No pulsing of Reset signal is necessary. SCK should be no faster than 1/16 of the system clock at XTAL1. For Page Read/Write, the data always starts from byte 0 to 255. After the command byte and upper address byte are latched, each byte thereafter is treated as data until all 256 bytes are shifted in/out. Then the next instruction will be ready to be decoded. 27 1919D–MICRO–6/08 25. Serial Programming Characteristics Figure 25-1. Serial Programming Timing MOSI tSHOX tOVSH SCK tSLSH tSHSL MISO tSLIV Table 25-1. Serial Programming Characteristics, TA = -40⋅ C to 85⋅ C, VCC = 4.0 - 5.5V (Unless Otherwise Noted) Symbol Parameter 1/tCLCL Oscillator Frequency 3 tCLCL Oscillator Period 30 ns tSHSL SCK Pulse Width High 8 tCLCL ns tSLSH SCK Pulse Width Low 8 tCLCL ns tOVSH MOSI Setup to SCK High tCLCL ns tSHOX MOSI Hold after SCK High 2 tCLCL ns tSLIV SCK Low to MISO Valid tERASE Chip Erase Instruction Cycle Time tSWC Serial Byte Write Cycle Time 28 Min 10 Typ 16 Max Units 33 MHz 32 ns 500 ms 64 tCLCL + 400 µs AT89S52 1919D–MICRO–6/08 AT89S52 26. Absolute Maximum Ratings* Operating Temperature.................................. -55°C to +125°C *NOTICE: Storage Temperature ..................................... -65°C to +150°C Voltage on Any Pin with Respect to Ground .....................................-1.0V to +7.0V Maximum Operating Voltage ............................................ 6.6V Stresses beyond those listed under “Absolute Maximum Ratings” may cause permanent damage to the device. This is a stress rating only and functional operation of the device at these or any other conditions beyond those indicated in the operational sections of this specification is not implied. Exposure to absolute maximum rating conditions for extended periods may affect device reliability. DC Output Current...................................................... 15.0 mA 27. DC Characteristics The values shown in this table are valid for TA = -40°C to 85°C and VCC = 4.0V to 5.5V, unless otherwise noted. Symbol Parameter Condition Min VIL Input Low Voltage (Except EA) -0.5 0.2 VCC-0.1 V VIL1 Input Low Voltage (EA) -0.5 0.2 VCC-0.3 V VIH Input High Voltage 0.2 VCC+0.9 VCC+0.5 V VIH1 Input High Voltage 0.7 VCC VCC+0.5 V IOL = 1.6 mA 0.45 V IOL = 3.2 mA 0.45 V VOL Output Low Voltage (Except XTAL1, RST) (XTAL1, RST) (1) (Ports 1,2,3) Max Units (1) VOL1 Output Low Voltage (Port 0, ALE, PSEN) VOH Output High Voltage (Ports 1,2,3, ALE, PSEN) IOH = -60 µA, VCC = 5V ± 10% 2.4 V IOH = -25 µA 0.75 VCC V IOH = -10 µA 0.9 VCC V 2.4 V IOH = -300 µA 0.75 VCC V IOH = -80 µA 0.9 VCC V IOH = -800 µA, VCC = 5V ± 10% Output High Voltage (Port 0 in External Bus Mode) VOH1 IIL Logical 0 Input Current (Ports 1,2,3) VIN = 0.45V -50 µA ITL Logical 1 to 0 Transition Current (Ports 1,2,3) VIN = 2V, VCC = 5V ± 10% -300 µA ILI Input Leakage Current (Port 0, EA) 0.45 < VIN < VCC ±10 µA RRST Reset Pulldown Resistor 300 KΩ CIO Pin Capacitance 10 pF 50 Test Freq. = 1 MHz, TA = 25°C Active Mode, 12 MHz 25 mA Idle Mode, 12 MHz 6.5 mA VCC = 5.5V 50 µA Power Supply Current ICC Power-down Mode(1) Notes: 1. Under steady state (non-transient) conditions, IOL must be externally limited as follows: Maximum IOL per port pin: 10 mA Maximum IOL per 8-bit port: Port 0: 26 mA Ports 1, 2, 3: 15 mA Maximum total IOL for all output pins: 71 mA If IOL exceeds the test condition, VOL may exceed the related specification. Pins are not guaranteed to sink current greater than the listed test conditions. 2. Minimum VCC for Power-down is 2V. 29 1919D–MICRO–6/08 28. AC Characteristics Under operating conditions, load capacitance for Port 0, ALE/PROG, and PSEN = 100 pF; load capacitance for all other outputs = 80 pF. 28.1 External Program and Data Memory Characteristics 12 MHz Oscillator Variable Oscillator Min Min Max Units 0 33 MHz Symbol Parameter 1/tCLCL Oscillator Frequency tLHLL ALE Pulse Width 127 2tCLCL-40 ns tAVLL Address Valid to ALE Low 43 tCLCL-25 ns tLLAX Address Hold After ALE Low 48 tCLCL-25 ns tLLIV ALE Low to Valid Instruction In tLLPL ALE Low to PSEN Low 43 tCLCL-25 ns tPLPH PSEN Pulse Width 205 3tCLCL-45 ns tPLIV PSEN Low to Valid Instruction In tPXIX Input Instruction Hold After PSEN tPXIZ Input Instruction Float After PSEN tPXAV PSEN to Address Valid tAVIV Address to Valid Instruction In 312 5tCLCL-80 ns tPLAZ PSEN Low to Address Float 10 10 ns tRLRH RD Pulse Width 400 6tCLCL-100 ns tWLWH WR Pulse Width 400 6tCLCL-100 ns tRLDV RD Low to Valid Data In tRHDX Data Hold After RD tRHDZ Data Float After RD 97 2tCLCL-28 ns tLLDV ALE Low to Valid Data In 517 8tCLCL-150 ns tAVDV Address to Valid Data In 585 9tCLCL-165 ns tLLWL ALE Low to RD or WR Low 200 3tCLCL+50 ns tAVWL Address to RD or WR Low 203 4tCLCL-75 ns tQVWX Data Valid to WR Transition 23 tCLCL-30 ns tQVWH Data Valid to WR High 433 7tCLCL-130 ns tWHQX Data Hold After WR 33 tCLCL-25 ns tRLAZ RD Low to Address Float tWHLH RD or WR High to ALE High 30 Max 233 4tCLCL-65 145 0 3tCLCL-60 0 59 75 ns 5tCLCL-90 0 300 3tCLCL-50 0 43 ns tCLCL-8 0 123 tCLCL-25 ns ns tCLCL-25 252 ns ns ns 0 ns tCLCL+25 ns AT89S52 1919D–MICRO–6/08 AT89S52 29. External Program Memory Read Cycle tLHLL ALE tAVLL tLLIV tLLPL tPLIV PSEN tPXAV tPLAZ tPXIZ tLLAX tPXIX A0 - A7 PORT 0 tPLPH INSTR IN A0 - A7 tAVIV A8 - A15 PORT 2 A8 - A15 30. External Data Memory Read Cycle tLHLL ALE tWHLH PSEN tLLDV tRLRH tLLWL RD tLLAX tAVLL PORT 0 tRLDV tRLAZ A0 - A7 FROM RI OR DPL tRHDZ tRHDX DATA IN A0 - A7 FROM PCL INSTR IN tAVWL tAVDV PORT 2 P2.0 - P2.7 OR A8 - A15 FROM DPH A8 - A15 FROM PCH 31 1919D–MICRO–6/08 31. External Data Memory Write Cycle tLHLL ALE tWHLH PSEN tLLWL WR tAVLL PORT 0 tLLAX tQVWX A0 - A7 FROM RI OR DPL tWLWH tQVWH DATA OUT tWHQX A0 - A7 FROM PCL INSTR IN tAVWL PORT 2 P2.0 - P2.7 OR A8 - A15 FROM DPH A8 - A15 FROM PCH 32. External Clock Drive Waveforms tCHCX VCC - 0.5V tCHCX tCLCH tCHCL 0.7 VCC 0.2 VCC - 0.1V 0.45V tCLCX tCLCL 33. External Clock Drive Symbol Parameter Min Max Units 1/tCLCL Oscillator Frequency 0 33 MHz tCLCL Clock Period 30 ns tCHCX High Time 12 ns tCLCX Low Time 12 ns tCLCH Rise Time 5 ns tCHCL Fall Time 5 ns 32 AT89S52 1919D–MICRO–6/08 AT89S52 34. Serial Port Timing: Shift Register Mode Test Conditions The values in this table are valid for VCC = 4.0V to 5.5V and Load Capacitance = 80 pF. 12 MHz Osc Variable Oscillator Symbol Parameter Min Max Min Max tXLXL Serial Port Clock Cycle Time 1.0 12 tCLCL µs tQVXH Output Data Setup to Clock Rising Edge 700 10 tCLCL-133 ns tXHQX Output Data Hold After Clock Rising Edge 50 2 tCLCL-80 ns tXHDX Input Data Hold After Clock Rising Edge 0 0 ns tXHDV Clock Rising Edge to Input Data Valid 700 Units 10 tCLCL-133 ns 35. Shift Register Mode Timing Waveforms INSTRUCTION ALE 0 1 2 3 4 5 6 8 7 tXLXL CLOCK tQVXH tXHQX WRITE TO SBUF 0 1 2 tXHDV OUTPUT DATA CLEAR RI 3 4 5 6 tXHDX VALID VALID VALID 7 SET TI VALID VALID VALID VALID VALID SET RI INPUT DATA 36. AC Testing Input/Output Waveforms(1) VCC - 0.5V 0.2 VCC + 0.9V TEST POINTS 0.2 VCC - 0.1V 0.45V Note: 1. AC Inputs during testing are driven at VCC - 0.5V for a logic 1 and 0.45V for a logic 0. Timing measurements are made at VIH min. for a logic 1 and VIL max. for a logic 0. 37. Float Waveforms(1) V LOAD+ 0.1V V LOAD V LOAD - Note: 0.1V V OL - 0.1V V OL + 0.1V Timing Reference Points 1. For timing purposes, a port pin is no longer floating when a 100 mV change from load voltage occurs. A port pin begins to float when a 100 mV change from the loaded VOH/VOL level occurs. 33 1919D–MICRO–6/08 38. Ordering Information 38.1 Green Package Option (Pb/Halide-free) Speed (MHz) 24 33 Power Supply Ordering Code Package 4.0V to 5.5V AT89S52-24AU AT89S52-24JU AT89S52-24PU 44A 44J 40P6 Operation Range Industrial (-40° C to 85° C) 4.5V to 5.5V AT89S52-33AU AT89S52-33JU AT89S52-33PU 44A 44J 40P6 Industrial (-40° C to 85° C) Package Type 44A 44-lead, Thin Plastic Gull Wing Quad Flatpack (TQFP) 44J 44-lead, Plastic J-leaded Chip Carrier (PLCC) 40P6 40-pin, 0.600" Wide, Plastic Dual Inline Package (PDIP) 34 AT89S52 1919D–MICRO–6/08 AT89S52 39. Packaging Information 39.1 44A – TQFP PIN 1 B PIN 1 IDENTIFIER E1 e E D1 D C 0˚~7˚ A1 A2 A L COMMON DIMENSIONS (Unit of Measure = mm) MIN NOM MAX A – – 1.20 A1 0.05 – 0.15 SYMBOL Notes: 1. This package conforms to JEDEC reference MS-026, Variation ACB. 2. Dimensions D1 and E1 do not include mold protrusion. Allowable protrusion is 0.25 mm per side. Dimensions D1 and E1 are maximum plastic body size dimensions including mold mismatch. 3. Lead coplanarity is 0.10 mm maximum. A2 0.95 1.00 1.05 D 11.75 12.00 12.25 D1 9.90 10.00 10.10 E 11.75 12.00 12.25 E1 9.90 10.00 10.10 B 0.30 – 0.45 C 0.09 – 0.20 L 0.45 – 0.75 e NOTE Note 2 Note 2 0.80 TYP 10/5/2001 TITLE R 2325 Orchard Parkway San Jose, CA 95131 44A, 44-lead, 10 x 10 mm Body Size, 1.0 mm Body Thickness, 0.8 mm Lead Pitch, Thin Profile Plastic Quad Flat Package (TQFP) DRAWING NO. REV. 44A B 35 1919D–MICRO–6/08 39.2 44J – PLCC 1.14(0.045) X 45˚ PIN NO. 1 1.14(0.045) X 45˚ 0.318(0.0125) 0.191(0.0075) IDENTIFIER E1 B E D2/E2 B1 e A2 D1 A1 D A 0.51(0.020)MAX 45˚ MAX (3X) COMMON DIMENSIONS (Unit of Measure = mm) Notes: 1. This package conforms to JEDEC reference MS-018, Variation AC. 2. Dimensions D1 and E1 do not include mold protrusion. Allowable protrusion is .010"(0.254 mm) per side. Dimension D1 and E1 include mold mismatch and are measured at the extreme material condition at the upper or lower parting line. 3. Lead coplanarity is 0.004" (0.102 mm) maximum. SYMBOL MIN NOM MAX A 4.191 – 4.572 A1 2.286 – 3.048 A2 0.508 – – D 17.399 – 17.653 D1 16.510 – 16.662 E 17.399 – 17.653 E1 16.510 – 16.662 D2/E2 14.986 – 16.002 B 0.660 – 0.813 B1 0.330 – 0.533 e NOTE Note 2 Note 2 1.270 TYP 10/04/01 R 36 2325 Orchard Parkway San Jose, CA 95131 TITLE 44J, 44-lead, Plastic J-leaded Chip Carrier (PLCC) DRAWING NO. REV. 44J B AT89S52 1919D–MICRO–6/08 AT89S52 39.3 40P6 – PDIP D PIN 1 E1 A SEATING PLANE A1 L B B1 e E 0º ~ 15º C COMMON DIMENSIONS (Unit of Measure = mm) REF MIN NOM MAX A – – 4.826 A1 0.381 – – D 52.070 – 52.578 E 15.240 – 15.875 E1 13.462 – 13.970 B 0.356 – 0.559 B1 1.041 – 1.651 L 3.048 – 3.556 SYMBOL eB Notes: 1. This package conforms to JEDEC reference MS-011, Variation AC. 2. Dimensions D and E1 do not include mold Flash or Protrusion. Mold Flash or Protrusion shall not exceed 0.25 mm (0.010"). C 0.203 – 0.381 eB 15.494 – 17.526 e NOTE Note 2 Note 2 2.540 TYP 09/28/01 R 2325 Orchard Parkway San Jose, CA 95131 TITLE 40P6, 40-lead (0.600"/15.24 mm Wide) Plastic Dual Inline Package (PDIP) DRAWING NO. 40P6 REV. B 37 1919D–MICRO–6/08 Headquarters International Atmel Corporation 2325 Orchard Parkway San Jose, CA 95131 USA Tel: 1(408) 441-0311 Fax: 1(408) 487-2600 Atmel Asia Room 1219 Chinachem Golden Plaza 77 Mody Road Tsimshatsui East Kowloon Hong Kong Tel: (852) 2721-9778 Fax: (852) 2722-1369 Atmel Europe Le Krebs 8, Rue Jean-Pierre Timbaud BP 309 78054 Saint-Quentin-enYvelines Cedex France Tel: (33) 1-30-60-70-00 Fax: (33) 1-30-60-71-11 Atmel Japan 9F, Tonetsu Shinkawa Bldg. 1-24-8 Shinkawa Chuo-ku, Tokyo 104-0033 Japan Tel: (81) 3-3523-3551 Fax: (81) 3-3523-7581 Technical Support [email protected] Sales Contact www.atmel.com/contacts Product Contact Web Site www.atmel.com Literature Requests www.atmel.com/literature Disclaimer: The information in this document is provided in connection with Atmel products. No license, express or implied, by estoppel or otherwise, to any intellectual property right is granted by this document or in connection with the sale of Atmel products. EXCEPT AS SET FORTH IN ATMEL’S TERMS AND CONDITIONS OF SALE LOCATED ON ATMEL’S WEB SITE, ATMEL ASSUMES NO LIABILITY WHATSOEVER AND DISCLAIMS ANY EXPRESS, IMPLIED OR STATUTORY WARRANTY RELATING TO ITS PRODUCTS INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, OR NON-INFRINGEMENT. IN NO EVENT SHALL ATMEL BE LIABLE FOR ANY DIRECT, INDIRECT, CONSEQUENTIAL, PUNITIVE, SPECIAL OR INCIDENTAL DAMAGES (INCLUDING, WITHOUT LIMITATION, DAMAGES FOR LOSS OF PROFITS, BUSINESS INTERRUPTION, OR LOSS OF INFORMATION) ARISING OUT OF THE USE OR INABILITY TO USE THIS DOCUMENT, EVEN IF ATMEL HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. Atmel makes no representations or warranties with respect to the accuracy or completeness of the contents of this document and reserves the right to make changes to specifications and product descriptions at any time without notice. Atmel does not make any commitment to update the information contained herein. Unless specifically provided otherwise, Atmel products are not suitable for, and shall not be used in, automotive applications. Atmel’s products are not intended, authorized, or warranted for use as components in applications intended to support or sustain life. © 2008 Atmel Corporation. All rights reserved. Atmel®, logo and combinations thereof, and others are registered trademarks or trademarks of Atmel Corporation or its subsidiaries. Other terms and product names may be trademarks of others. 1919D–MICRO–6/08 ANEXO C - Como calcular o capacitor de reset dos microcontroladores da família 8051. How to Calculate the Capacitor of the Reset Input of a C51 Microcontroller 80C51 This application note explains how the reset of the 80C51 microcontroller works when the RST pin is a pure input pin and when the RST input is bi-directional. It gives rules to determine the extra components required to operate the reset function properly. The reset process can be active on low or high level depending on the product. In this application note only the high level case is discussed. Microcontrollers Application Note Introduction The reset is used to start-up or to restart the 80C51 microcontroller activities. It forces the 80C51 in a known state by reinitializing all the internal registers needed to properly start the program execution. The reset must be kept active until all three of the following conditions are respected: • The power supply must be in the specified range. • The oscillator must reach a minimum oscillation level to ensure a good noise to signal ratio and a correct internal duty cycle generation. • The reset pulse width duration must be at least two machine cycles. If one of the conditions is not respected the microcontroller will not startup properly. Theory of Reset Operation To ensure a good startup, the reset pulse width has to be wide enough to cover the period of time where the electrical conditions are not met. Two parameters should be considered for a proper reset sequence to determine the reset pulse width (see Figure 1): • tosc: time needed by the oscillator to reach the Vih1 or Vil1 level. • tvddrise: rise time of the power-supply taken between 10 to 90% of VDD. When these two parameter conditions are met, the reset has to be maintained at least two machine cycles in order to synchronize the internal activity of the core. In normal mode, a machine cycle is 12-clock periods and in X2 mode is 6-clock periods. Rev. 4284A–8051–09/03 Figure 1. tosc and tvddrise are the Two Parameters to Evaluate, Depending on the Application treset tosc Vih1 VDD tvddrise XTAL1 Vih1 is the reference parameter taken to calculate and determine the time constant of the reset. Indeed, normally the input is considered to be low when its level reaches Vil1. But in reality the trigger is somewhere between Vih1 and Vil1. So, the worst case condition is considered at the Vih1 level. When the reset is released, the program execution starts and the ALE signal toggles as it is illustrated in Figure 2. and showing a proper startup condition: • VDD is within the voltage operating range, • The level of Xtal1 is greater than the Vih1 level specification, • The reset reached its active level (Vih1) and is maintained at least two machine cycles. Figure 2. Reset Conditions to Properly Startup a Microcontroller ALE V VDDDD Vrst Reset is released XTAL2 2 C51 Reset Guidelines 4284A–8051–09/03 C51 Reset Guidelines Why Does the Reset Does Not Properly Start the Microcontroller? The Oscillator is not Stabilized Figure 3 shows the case where the RST signal is applied while the oscillator is not stabilized and there is no clock to reset the internal registers of the CPU. Due to this bad reset, the first address fetched can be anywhere in the program space except address 0000h. Figure 3. If electrical Conditions are not Met, the Reset Signal is Applied but without the Clock ALE VDD The reset is applied while the clock is not stabilized XTAL2 Vrst Reset is Released before VDD is Stable Figure 4 shows the case where the reset is released before the VDD is stable. The microcontroller will never see the reset and can start anywhere in the program space and with a bad register initialization. Figure 4. The Reset is Released before the Clock and the VDD are Stable ALE VDD XTAL2 Vrst 3 4284A–8051–09/03 Reset Input Circuitry Description At least two kinds of reset input structure exist in C51 products. The first one is a pure input which allows an external device to reset the microcontroller. The second one is bidirectional. The microcontroller can be reset by an external device. The microcontroller can reset an external device when, for example the internal watchdog expires. Table 1 lists some C51 Atmel products which have uni-directional or bi-directional reset. Table 1. Examples of Products Using Uni-directional and Bi-directional Reset Product Main Features Uni/Bidir T83C51RB2 16 KB of ROM, Watchdog B T89C51RD2 64 KB of Flash, Watchdog B AT89C51CC01 10-bit ADC, CAN controller B AT89C51SND1 MP3 decoder, TWI, MMC, USB U uni-directional Reset Input Description The uni-directional reset input circuitry is shown in Figure 5. A pull-down resistor, Rrst, is connected between the RST input and the ground. An external capacitor, Crst, is connected between the RST input and the VDD. The value of Crst determines the reset time duration. The calculation of Crst is explained in the next chapter. Figure 5. Reset Structure for an uni-directional Circuitry Theory of Operation 4 When a reset is applied on the RST input, Crst is discharged and then charged through Rrst. The reset is active until the level applied on the RST pin is below Vih1. Crst determines the reset pulse width duration. C51 Reset Guidelines 4284A–8051–09/03 C51 Reset Guidelines Bi-directional Reset Input Description The bi-directional reset circuitry is shown in Figure 6. In addition to the uni-directional structure, the RST pin is able to drive an external reset for example when a watchdog expires. To do this, a pull-up resistor (Rrstwt) controlled by the rstcon signal drives a high level on the RST pin. An extra resistor (Rrstext) must be added between the RST input and Crst (Figure 6.). Figure 6. Reset Structure in a Bi-directional Mode 2 VDD 1 rstcon Crst Rrstwt Rrstext RST Internal reset Rrst External reset Reset circuitry vrst(t) Oscillator 2 X1 Q1 1 X2 ALE CPU clock Theory of Operation External Reset During a power-up or when an external reset is applied to the RST input, the Crst capacitor is charged through the two resistors Rrstext and Rrst. The reset is active until the level applied on the RST pin is below Vih1. The Rsrtext resistor is required when an internal reset is applied by the microcontroller and will be explained in the next session. Internal Reset In some cases, such as a watchdog reset, the microcontroller generates an internal reset by driving the rstcon signal and consequently by applying a high level on the RST pin. The pulse duration depends on the product and is typically equal to 96 clock periods (see the product datasheet). The Rrstext allows a reset pulse to occur on the RST pin. The reset time constant (several ms) is large in comparison to the reset pulse duration (96 clock periods). In that condition, Crst maintains its charge (VDD) for all the duration of the reset pulse even if Rrstwt is active (see Figure 7). VDD is applied across the Rrst and Rrstwt resistors and expression of Vrst is given below: Rrstext Vrst = VDD × ------------------------------------------Rrstext + Rstwt For a given Rrstwt resistance, Rrstext determines the active level of the reset pin. To take into account on the external and internal reset constraints, Rrstext must be chosen in the 1 kΩ and 10 kΩ range. 5 4284A–8051–09/03 Figure 7. Reset Circuitry When an Internal Reset is Applied VDD Rrstwt Internal reset Vrst Crst VDD Rrstext Rrst Vih1 0 0 Without Rrstext no external reset signal will be generated. Use Excel File to Determine Crst To determine Crst, the reset pulse width needs to be calculated using the following equation: treset = tvddrise + tosc • • tvddrise (typically 1 ms to 100 ms), is the rise time of the VDD (10% and 90% of the VDD). It depends on the power supply and the decoupling capacitors used. tosc (typically 1 ms to 50 ms), time taken by the oscillator at startup. It depends on the crystal characteristics and the capacitors connected to the crystal. Because the power supply has a finite transition time (several hundreds of microseconds to several milliseconds), Crst is not so easy to compute by hand. Excel tool is used to calculate Crst versus tvddrise and tosc parameters. A spreadsheet can be downloaded from the Atmel Web site to compute Crst. Four parameters have to be entered and Crst is directly computed by the spreadsheet while 1kΩ is chosen for Rrst. Here is how to do it: • VDD, the power supply voltage, is entered in the cell F3 • tvddrise, the rise time of the power-supply, is entered in the cell F4 • tosc, the oscillator startup time, is entered in cell F8 • Rrstmin, the minimum pull-down resistor, is entered in the cell F13 After these steps, the cell E31 has to be clicked to compute the Crst and the minimum reset pulse width. 6 C51 Reset Guidelines 4284A–8051–09/03 C51 Reset Guidelines Table 2. Excel Spreadsheet Use to Calculate Crst Power Supply Characteristics VDD = 5 V tvddrs = 1 ms tosct = 10 ms Rrstmin = 100 kΩ trstmin = 22, 726 ms Minimum reset pulse width Trst = 65, 545 ms Value of reset capacitor C C= 0.649 µF Power Supply Voltage Power Supply Rise Time (10% to 90%) Oscillator Oscillator Startup Time time, measured at VIH1 Electrical Characteristics of the Reset Input Minimum pull-down resistance Minimum Pulse Width Calculation of the reset pulse width Evaluation of Reset Capacitor: C Table 3 gives the Crst value computed from the Excel file for different values of tvddrise and tosc parameters. Table 3. Minimum Reset Capacitor Value for a 50kΩ Pull-down Resistor (Rrstmin) tvddrise tosc 1 ms 10 ms 100 ms 5 ms 820 nF 1.2 µF 12 µF 20 ms 2.7 µF 3.9 µF 12 µF Table 4. Minimum Reset Capacitor Value for a 100KΩ Pull-down Resistor tvddrise tosc 1 ms 10 ms 100 ms 5 ms 390 nF 0.56 µF 5.6 µF 20 ms 1.2 µF 2 µF 5.6 µF 7 4284A–8051–09/03 Atmel Corporation 2325 Orchard Parkway San Jose, CA 95131, USA Tel: 1(408) 441-0311 Fax: 1(408) 487-2600 Regional Headquarters Europe Atmel Sarl Route des Arsenaux 41 Case Postale 80 CH-1705 Fribourg Switzerland Tel: (41) 26-426-5555 Fax: (41) 26-426-5500 Asia Room 1219 Chinachem Golden Plaza 77 Mody Road Tsimshatsui East Kowloon Hong Kong Tel: (852) 2721-9778 Fax: (852) 2722-1369 Japan 9F, Tonetsu Shinkawa Bldg. 1-24-8 Shinkawa Chuo-ku, Tokyo 104-0033 Japan Tel: (81) 3-3523-3551 Fax: (81) 3-3523-7581 Atmel Operations Memory 2325 Orchard Parkway San Jose, CA 95131, USA Tel: 1(408) 441-0311 Fax: 1(408) 436-4314 Microcontrollers 2325 Orchard Parkway San Jose, CA 95131, USA Tel: 1(408) 441-0311 Fax: 1(408) 436-4314 La Chantrerie BP 70602 44306 Nantes Cedex 3, France Tel: (33) 2-40-18-18-18 Fax: (33) 2-40-18-19-60 ASIC/ASSP/Smart Cards Zone Industrielle 13106 Rousset Cedex, France Tel: (33) 4-42-53-60-00 Fax: (33) 4-42-53-60-01 RF/Automotive Theresienstrasse 2 Postfach 3535 74025 Heilbronn, Germany Tel: (49) 71-31-67-0 Fax: (49) 71-31-67-2340 1150 East Cheyenne Mtn. Blvd. Colorado Springs, CO 80906, USA Tel: 1(719) 576-3300 Fax: 1(719) 540-1759 Biometrics/Imaging/Hi-Rel MPU/ High Speed Converters/RF Datacom Avenue de Rochepleine BP 123 38521 Saint-Egreve Cedex, France Tel: (33) 4-76-58-30-00 Fax: (33) 4-76-58-34-80 1150 East Cheyenne Mtn. Blvd. Colorado Springs, CO 80906, USA Tel: 1(719) 576-3300 Fax: 1(719) 540-1759 Scottish Enterprise Technology Park Maxwell Building East Kilbride G75 0QR, Scotland Tel: (44) 1355-803-000 Fax: (44) 1355-242-743 Literature Requests www.atmel.com/literature Disclaimer: Atmel Corporation makes no warranty for the use of its products, other than those expressly contained in the Company’s standard warranty which is detailed in Atmel’s Terms and Conditions located on the Company’s web site. The Company assumes no responsibility for any errors which may appear in this document, reserves the right to change devices or specifications detailed herein at any time without notice, and does not make any commitment to update the information contained herein. No licenses to patents or other intellectual property of Atmel are granted by the Company in connection with the sale of Atmel products, expressly or by implication. Atmel’s products are not authorized for use as critical components in life support devices or systems. © Atmel Corporation 2003. All rights reserved. Atmel ® and combinations thereof are the registered trademarks of Atmel Corporation or its subsidiaries. Other terms and product names may be the trademarks of others. Printed on recycled paper. 4284A–8051–09/03 ANEXO D - In-System Flash Programming para microcontroladores da família 8051 ANM076 C51 In-System FLASH Programming 1. Introduction Most C51 microcontroller based applications using an on-board FLASH memory for code and data storage take the advantage of being In-System Programmabled thanks to the FLASH technology. This application note describes the basic hardware and software requirements to build such a system based on a C51 product (or C251 product configured for C51 memory model). Basic In-System Programming features described in this document are: FLASH identifying, erasing and programming from a HEX file. The C51/C251 Demo Board demonstrates this In-System Programming implementation using an Atmel AT49HF010 FLASH memory. 2. Description 2.1. System Requirements The In-System FLASH Programming (ISP) described in this document assumes a typical C51 configuration shown in Figure 1. UART FLASH Program Memory Data Bus C51 SRAM Data Memory Addr Bus Control ISP Control Glue Figure 1. Typical C51 Configuration The basic system includes a C51, a FLASH memory for code and a SRAM for data. The C51 interfaces the memory devices through some ISP dedicated glue to allow the C51 to write into the FLASH as if it would be a SRAM. The C51 is also connected to a terminal via a RS-232 serial link using its embedded UART. This terminal will be used to download a new program into the FLASH memory. 2.2. Memory Mapping C51 microcontrollers have several memory space areas: • • • • • The The The The The internal data memory internal Special Function Register (SFR) memory to address on-chip resources optional expanded on-chip data memory (on-chip XRAM) external program memory external data memory Rev A - 21 Jan 2000 1 ANM076 2.2.1. Standard Program Execution Mode FFFF Upper Optional Internal RAM FFFF External Data Memory FF Special Function Register direct accesses External Program Memory 80 00 FLASH device SRAM device Lower 128 bytes Internal Ram direct or indirect accesses On-Chip Program Memory Optional on-chip XRAM 0000 (Disabled) 0000 0000 0000 Figure 2. C51 Memory Mapping in Standard Mode When the application is running (standard mode), the SRAM is used for application data storage and the FLASH memory for code and constant data storage. Data in SRAM are accessed thanks to the MOVX instruction and constant data are retrieved from the FLASH memory thanks to the MOVC. 2.2.2. ISP Program Execution Mode FFFF Upper Optional Internal RAM FF Special Function Register direct accesses FFFF External Data Memory External Program Memory FLASH device SRAM device 80 Lower 128 bytes Internal Ram direct or indirect accesses 00 On-Chip Program Memory Optional on-chip XRAM 0000 (ISP Program) 0000 0000 0000 Figure 3. C51 Memory Mapping in ISP Mode In ISP mode, the FLASH memory is re-mapped in the data space area so that a new program can be writen using data write instructions (MOVX). In this mode, the FLASH memory is no longer available for program execution and the ISP program must carried out from the on-chip program memory. Because the C51 microcontroller has a Harward architecture (separate memory data/code address spaces) the FLASH memory can be easily re-mapped into the data space providing a simple logic glue and few control signals. Some C51 derivatives provide an extra on-chip data memory area called on-chip XRAM. This area is overlaid with the external data memory accessed using MOVX instructions. In ISP mode, this on-chip XRAM must be disabled otherwise MOVX instruction would not access to a part of the FLASH memory but to the on-chip XRAM area. 2 Rev A - 21 Jan 2000 ANM076 2.2.3. Special Considerations In order to simplify the discussion, it is assumed there is no need to store application routines in the on-chip memory and the C51 would behave as a ROMless version: • In standard mode, the microcontroller would reset with EA#=0 and the application would start from address • 0000h located in FLASH memory In ISP mode, the microcontroller would reset with EA#=1 and the ISP program would start from address 0000h in the on-chip ROM/EPROM or FLASH memory depending on the part. However some applications may require to store some extra routines in the on-chip memory for several reasons like cost reduction using the same ROM version on many different applications, crypted ROM routines for secured applications, auto-configuring application with on-chip FLASH program memory... In this latter case, some room must be left for the ISP subroutines and the microcontroller would always reset with EA#=1. To help the reset service routine to determine whether the application is in standard mode or ISP mode, an extra signal should be provided by the application. Note that a special care should be taken for the interrupt routine design since some interrupts vectors may be shared between the ISP program and the application. 3. Hardware Figure 4 shows the typical hardware configuration for an application providing the In-System FLASH Programming feature. The ISP input signal configures the system in Standard Mode or in In-System Programming Mode. ALE P0AD7:0 SRAM MEMORY A7:0 573 D7:0 RXD TXD RS232 Interface P3.0/RxD A15:8 P2/A15:8 P3.1/TxD P3.7/RD# WR RD PSEN OE P3.6/WR# EA# FLASH MEMORY ISP A7:0 D7:0 A15:8 WR RD OE VSS Figure 4. In-System Programming Hardware Configuration When ISP is high, the standard mode is selected. After reset, the program branches at address 0000h which is located in the on-board FLASH memory (EA#=0). When ISP is low, the ISP mode is selected. After reset, the program branches to address 0000h located in the onchip memory and executes the ISP program. Rev A - 21 Jan 2000 3 ANM076 The ISP also controls the FLASH / SRAM memory address area swap. The decoding equations for memory control signals are shown in Table 1. The glue logic that controls the memory signals may be programmed in a PLD (Programmable Logic Device). Table 1. Equations for Memory Control Operating Mode FLASH Memory SRAM Memory ISP = 0 (In-System Programming Mode) - RD = PSEN & RD# WR = WR - RD = RD# WR = WR OE = 1 ISP = 1 (Standard Mode) - RD = PSEN WR = 1 - RD = X WR = X OE = 0 4. Software The software in charge of the ISP is splitted into three parts: the IO interface, the Intel HEX file parser and the FLASH programming. 4.1. Operation The ISP program performs the following tasks: • Atmel FLASH authentification (AT49HF010) • FLASH chip erase • Download the HEX file and program data to the FLASH For demonstration purpose, the host terminal displays the following messages during the ISP averall process: ** Welcome to the ISP program! ** Check if FLASH device is a Atmel AT49HF010... OK. Erasing the on-board FLASH memory... OK. Ready for FLASH programming. Send .hex file with the following terminal configuration: - ASCII character transmission, - 8 bits, 1 stop, parity none, - XON-XOFF flow control. Waiting for download... ........................................................ ........................................................ ........................................ External FLASH memory is now programmed. 4.2. IO Interface The HEX file is downloaded from a host via the standard C51 UART using a full-duplex communication protocol with a XON/XOFF data flow control. The program assumes a host as a simple terminal emulator that can display messages and download ASCII files. The UART routines implement one circular buffer dedicated to the character reception. An interrupt service routine is in charge of the character reception so that FLASH programming can occur while receiving characters from the host. • UART Reception 4 Rev A - 21 Jan 2000 ANM076 • Upon reception of a character, the UART interrupt routine stores the received byte in the Rx circular buffer. As soon as the ISP program detects the Rx buffer is not empty, newly received characters are read from this buffer and are processed by the HEX file decoder. As soon as the Rx buffer is almost full, an XOFF character is automatically transmitted to indicate the terminal that reception shall stop. When a sufficient number of characters have been read and the Rx buffer is almost empty, an XON character is sent to the terminal to resume the transmission. UART Transmission Some simple messages are sent to the host for demonstration purpose. They are sent to the UART using the printf function provided by the Keil Development Kit [5]. This printf function is based on a putchar function that handles the XON/XOFF flow control. 4.3. Intel HEX File Parser The Intel HEX file is a standard file format for binary program code encoding using ASCII characters (see [3]). Basically, the Intel HEX file contains records. Each record is made of the following items: • • • • Record length: number of bytes in the record Record type: describes the information contained in the record (data, end of file, segment address, ...) Address field: indicated where the following bytes are stored in the memory Checksum To minimize the data storage volume, the HEX file parser function analyses on a per byte basis each record. The HEX decoder decodes each record fields and extracts the address offset and the actual bytes that need to be programmed to the FLASH memory. The parser structure is based on state machine shown in Figure 5. Since the HEX file transmitted by the host encodes hexadecimal byte in ASCII form, the HEX decoder function must convert ASCII digits into binary format before processing. This conversion is made over 2 or 4 ASCII digits according to the record field (addresses are 4-digit numbers, data are 2-digit numbers). Rev A - 21 Jan 2000 5 ANM076 Record Mark Wait for ’:’ Get record length 2 digits (MSB & LSB) Get Address Offset 4 digits Get Record type 2 digits Check if still data to read in the record Get data 2 digits & FLASH programming Final checksum computation Checksum Error Checksum OK ? Flash Programmed Figure 5. HEX File Decoder State Machine 4.4. FLASH Programming A FLASH memory controller provides the user several write and erase operations like byte write, page write, page erase etc... The FLASH programming software routines implemented here provide the erasing of the whole FLASH memory array and the writing of one byte. The FLASH memory controller handshaking required for an erase or write operation are detailled in [4]. The two basic sequences are shown Figure 6 and Figure 7. 6 Rev A - 21 Jan 2000 ANM076 4.4.1. Chip Erase The Chip Erase command consists of a 6 cycle sequence. Upon reception of the command, the FLASH memory starts its erasure process. While erasure process is on-going, the bit 6 of the FLASH databus toggles each time a memory location is accessed. As soon as this bit stops flipping when accessed, the erasing operation is over. Erase command Write AAh @ 5555h Write 55h @ 2AAAh Write 80h @ 5555h Write AAh @ 5555h Write 55h @ 2AAAh Write 10h @ 5555h Read @ 5555h Checks bit IO6 toggles? End of Erase Sequence Figure 6. FLASH Erase Sequence 4.4.2. Byte Programming The Byte Programming command consists of a 4 cycle sequence. Upon reception of the command, the FLASH memory waits for the data write sequence and starts its programming process. While programming process is ongoing, the bit 7 of the FLASH databus is inverted each time the memory location is accessed. As soon as the correct data is read from the last programmed FLASH memory location, the programming operation is over. Rev A - 21 Jan 2000 7 ANM076 Write command Write AAh @ 5555h Write 55h @ 2AAAh Write A0h @ 5555h Write data @ addr Read data @ addr Bit 7 of data negated? End of Byte Programming Figure 7. FLASH Write Sequence 5. Bibliography [1] C51 Product Datasheets (Atmel Wireless & Microcontrollers) [2] TSC80251G1 Design Guide ((Atmel Wireless & Microcontrollers) [3] Hexdecimal Object File Format Specification (Intel) [4] AT49HF010 FLASH Memory Datasheet (Atmel) [5] Keil C51 C Compiler Manual 6. Sites to Visit Atmel Wireless & Microcontrollers Web site: http://www.atmel-wm.com.com 8 Rev A - 21 Jan 2000 ANM076 7. Appendix A: Software 7.1. MAIN.C /*C************************************************************************** * NAME: main.c *---------------------------------------------------------------------------* PURPOSE: * Main entry for ISP program and system initialization. * Main entry includes all the ISP sequence from FLASH erase to FLASH prog. *****************************************************************************/ /*_____ I N C L U D E S ____________________________________________________*/ #include <stdio.h> #include "config.h" #include "isp.h" /*F************************************************************************** * NAME: _DEAD_ *---------------------------------------------------------------------------* PURPOSE: * When a fatal error occurs, this function is called to end with a standard * error message and a never end loop. *****************************************************************************/ void _DEAD_(void) { printf("\nError: cannot continue!\n"); while (1); } /*F************************************************************************** * NAME: system_init *---------------------------------------------------------------------------* PURPOSE: * Initializes the microcontroller: XRAM disabled to enable the FLASH mapping * into the data space and uart settings. *****************************************************************************/ void system_init(void) { /* Disable on-chip XRAM if exists */ #ifdef HAVE_XRAM AUXR = NO_XDATA; #endif /* Initialize communication port */ uart_init(); EA = 1; } /*F************************************************************************** * NAME: main *---------------------------------------------------------------------------* PURPOSE: * Program main entry. Manages the basic ISP sequence flow from FLASH ersure * to FLASH programming. *****************************************************************************/ void main(void) { Uchar status; Rev A - 21 Jan 2000 9 ANM076 /* System initialization: IO, welcome message, ... */ system_init(); printf("\n\n** Welcome to the ISP program! **\n\n"); /* Check the Flash manufacturer and device Id (Atmel=1F, 49HF010=17) */ printf("Check if FLASH device is a Atmel AT49HF010... "); if (flash_id()==0x1F17) { printf("OK.\n"); } else { printf("KO!\n"); _DEAD_(); } /* On-board FLASH erase operation */ printf("\nErasing the on-board FLASH memory... "); flash_erase(); printf("OK.\n\n"); /* FLASH erased: ready for programming */ printf("Ready for FLASH programming.\n"); printf("Send .hex file with the following terminal configuration:\n"); printf(" - ASCII character transmission,\n"); printf(" - 8 bits, 1 stop, parity none,\n"), printf(" - XON-XOFF flow control.\n"); printf("\nWaiting for download...\n"); /* Parses the downloaded HEX file and program the on-board FLASH memory */ uart_rx_enable(); status = hex_parser(); uart_rx_disable(); if (status == HEX_DEC_CSERR) { printf("\nChecksum error: external FLASH memory is not programmed!\n"); _DEAD_(); } else printf("\nExternal FLASH memory is now programmed.\n"); /* Happy end! */ while(1); } 10 Rev A - 21 Jan 2000 ANM076 7.2. IO.C /*C************************************************************************** * NAME: io.c *---------------------------------------------------------------------------* PURPOSE: * Functions dedicated to the HEX file reception from the host via the Uart. * These functions provide uart initialization, interrupt handling and * Rx circular buffer management. *****************************************************************************/ /*_____ I N C L U D E S ____________________________________________________*/ #include "compiler.h" #include "config.h" #include "isp.h" /*_____ M A C R O S ________________________________________________________*/ /* XON / XOFF Contro characters */ #define XON 17 #define XOFF 19 /* Must be 2^y for modulo computation */ #define RX_BUF_SIZE 16 /* XOFF when only 50% buffer size left */ /* XON when 25% rx buffer full */ #define XOFF_THRESH (RX_BUF_SIZE - (RX_BUF_SIZE / 2) ) #define XON_THRESH (RX_BUF_SIZE / 4) /* Wait for end of Tx over the Uart */ #define WAIT_EO_TX {while (TI==0); TI=0;} /*_____ D E F I N I T I O N ________________________________________________*/ static Uchar rx_buffer[RX_BUF_SIZE]; /* Rx circular buffer */ static Uchar rx_index_wr; /* Rx circular buffer indexes */ static Uchar rx_index_rd; static Bool tx_off; /* XOFF state indicator */ Uchar nb_rx_data; /* Number of data in the Rx buffer */ /*_____ D E C L A R A T I O N ______________________________________________*/ void rx_buffer_wr(Uchar rx_data); /*F************************************************************************** * NAME: uart *---------------------------------------------------------------------------* PURPOSE: * Uart interrupt handler: processes Rx uart events only. *****************************************************************************/ Interrupt(void uart(void),4) { if (RI == 1) /* Processes Rx event only, not Tx */ { rx_buffer_wr(SBUF); /* Writes the received data into the Rx buffer */ RI = 0; } } /*F************************************************************************** Rev A - 21 Jan 2000 11 ANM076 * NAME: uart_tx *---------------------------------------------------------------------------* PURPOSE: * Send a character over the serial link. Exit when the character * transmission is over. *****************************************************************************/ void uart_tx(Uchar tx_data) { SBUF = tx_data; WAIT_EO_TX; } /*F************************************************************************** * NAME: uart_init *---------------------------------------------------------------------------* PURPOSE: * Set the C51 Uart in 8-bit data, 9600 bauds, no parity operating mode. *****************************************************************************/ void uart_init(void) { SCON = 0x50; TMOD = TMOD | 0x20 ; /* Timer1 in mode 2 & not gated */ TH1 = 0xFD; /* 9600 bauds at 11.059200 MHZ */ TL1 = 0xFD; PCON = PCON & 0X80; TCON |= 0x40; TI=1; } /*F************************************************************************** * NAME: uart_rx_enable *---------------------------------------------------------------------------* PURPOSE: * Initializes Uart for data reception: circular buffer reset, XON/XOFF * protocol initialization and interrupt enabled. *****************************************************************************/ void uart_rx_enable(void) { rx_index_wr = rx_index_rd = nb_rx_data = 0; WAIT_EO_TX; /* Wait any previous transmission (printf) */ uart_tx(XON); ES = 1; } /*F************************************************************************** * NAME: uart_rx_disable *---------------------------------------------------------------------------* PURPOSE: * Disable Rx reception upon interrupts. *****************************************************************************/ void uart_rx_disable(void) { ES = 0; TI = 1; /* Enable Tx for printf (polling) */ } /*F************************************************************************** 12 Rev A - 21 Jan 2000 ANM076 * NAME: rx_buffer_empty *---------------------------------------------------------------------------* PARAMS: * return: TRUE when Rx buffer is empty. *---------------------------------------------------------------------------* PURPOSE: * Check if new Rx data have been stored in the Rx buffer. *****************************************************************************/ Bool rx_buffer_empty(void) { if (nb_rx_data == 0) return TRUE; else return FALSE; } /*F************************************************************************** * NAME: rx_buffer_wr *---------------------------------------------------------------------------* PARAMS: * rx_data: Rx data to store in the buffer. *---------------------------------------------------------------------------* PURPOSE: * Stores the newly received data in the buffer and keep indexes updated. *****************************************************************************/ void rx_buffer_wr(Uchar rx_data) { nb_rx_data++; rx_buffer[rx_index_wr] = rx_data; /* Circular buffer index computation */ rx_index_wr = (rx_index_wr + 1) % RX_BUF_SIZE; /* Stops host transmission when more than XOFF_THRES characters are stored * in the Rx buffer */ if ((tx_off==FALSE) && (nb_rx_data > XOFF_THRESH)) { uart_tx(XOFF); tx_off = TRUE; } } /*F************************************************************************** * NAME: rx_buffer_rd *---------------------------------------------------------------------------* PARAMS: * return: the next data available from the Rx buffer. *---------------------------------------------------------------------------* PURPOSE: * Retrieve the next data from the RX buffer. ***************************************************************************** * NOTE: * All interrupts are disabled when updating rx_data because a Rx interrupt * may occur and disturb the computation (rx_data also updated in the Uart * interrupt handler. *****************************************************************************/ Uchar rx_buffer_rd(void) { static Uchar data_cnt=0; /* For progression dots */ Rev A - 21 Jan 2000 13 ANM076 Uchar rx_data; EA=0; nb_rx_data--; EA=1; /* Avoid conflicts with rx_buffer_wr() */ rx_data = rx_buffer[rx_index_rd]; /* Circular buffer index computation */ rx_index_rd = (rx_index_rd + 1) % RX_BUF_SIZE; /* Progression dots every 256 data */ data_cnt++; if (data_cnt == 0) uart_tx('.'); /* Resumes host transmission when less than XON_THRES characters are stored * in the Rx buffer */ EA = 0; if ((tx_off == TRUE) && (nb_rx_data < XON_THRESH)) { uart_tx(XON); tx_off = FALSE; } EA = 1; return(rx_data); } 14 Rev A - 21 Jan 2000 ANM076 7.3. FLASH.C /*C************************************************************************** * NAME: flash.c *---------------------------------------------------------------------------* PURPOSE: *****************************************************************************/ /*_____ I N C L U D E S ____________________________________________________*/ #include "config.h" #include "isp.h" /*F************************************************************************** * NAME: flash_wr *---------------------------------------------------------------------------* PARAMS: * addr: FLASH address location mapped in the external data area * val: Data value to write to the FLASH. *---------------------------------------------------------------------------* PURPOSE: * Writes a byte to the FLASH memory when located in the external data area. *****************************************************************************/ void flash_wr(Uchar xdata *addr, Uchar val) { *addr = val; /* addr is a pointer to external data mem */ } /*F************************************************************************** * NAME: flash_rd *---------------------------------------------------------------------------* PARAMS: * addr: FLASH address location mapped in the external data area * return: Byte value read from the FLASH memory *---------------------------------------------------------------------------* PURPOSE: * Reads a byte from the FLASH memory when located in the external data area. *****************************************************************************/ Uchar flash_rd(Uchar xdata *addr) { return *addr; } /*F************************************************************************** * NAME: flash_cmd *---------------------------------------------------------------------------* PARAMS: * cmd: FLASH command used by the FLASH command sequence *---------------------------------------------------------------------------* PURPOSE: * Performs a FLASH command sequence (on-FLASH memory controller configuration) * The command is defined by the cmd code (erase, chip-id access, ...) *****************************************************************************/ void flash_cmd(Uchar cmd) { flash_wr(0x5555, 0xAA); flash_wr(0x2AAA, 0x55); flash_wr(0x5555, cmd); } Rev A - 21 Jan 2000 15 ANM076 /*F************************************************************************** * NAME: flash_erase *---------------------------------------------------------------------------* PURPOSE: * Erases the entire FLASH memory. *****************************************************************************/ void flash_erase(void) { Uchar pol_n, pol_n_1; /* Erase command sequence */ flash_cmd(0x80); flash_cmd(0x10); /* Toggle /* End of pol_n_1 = pol_n = bit algorithm: IO6 toggles each time a data read occurs */ toggoling signals end of erase */ flash_rd(0x5555); flash_rd(0x5555); while ((pol_n ^ pol_n_1) == 0x40) /* Checks if bit6 has changed between 2 polls */ { pol_n_1 = pol_n; pol_n = flash_rd(0x5555); } } /*F************************************************************************** * NAME: flash_prog *---------------------------------------------------------------------------* PARAMS: * addr: FLASH address location mapped in the external data area * val: Data value to program to the FLASH. *---------------------------------------------------------------------------* PURPOSE: * Programs one byte to the FLASH memory. *****************************************************************************/ void flash_prog(Uint16 addr, Uchar value) { /* Programming command */ flash_cmd(0xA0); flash_wr(addr, value); /* Wait until end of programming: IO7 is negated until end of programming */ while (flash_rd(addr) != value); } /*F************************************************************************** * NAME: flash_id *---------------------------------------------------------------------------* PARAMS: * return: FLASH memory manufacturer id and device id bytes. * MSB is Manufacturer Id and LSB Device Id. *---------------------------------------------------------------------------* PURPOSE: * Read the manufactuer and device Id's. *****************************************************************************/ Uint16 flash_id() 16 Rev A - 21 Jan 2000 ANM076 { Uint16 flash_id=0; /* Product Id Entry mode */ flash_cmd(0x90); /* @0000: manufacturer, @0001: device */ flash_id = flash_rd(0x0000) << 8 | flash_rd(0x0001); /* Exit from Product Id */ flash_cmd(0xF0); return flash_id; } Rev A - 21 Jan 2000 17 ANM076 7.4. HEX.C /*C************************************************************************** * NAME: hex.c *---------------------------------------------------------------------------* PURPOSE: * HEX file decoder: extracts HEX file information, retrieve data and program * the FLASH memory on the fly. *****************************************************************************/ /*_____ I N C L U D E S ____________________________________________________*/ #include "config.h" #include "isp.h" #include <ctype.h> /*_____ M A C R O S /* State definition #define REC_MARK #define REC_LEN_1 #define REC_LEN_2 #define OFFSET_1 #define OFFSET_2 #define OFFSET_3 #define OFFSET_4 #define REC_TYP_1 #define REC_TYP_2 #define DATA_1 #define DATA_2 #define CHEKSUM_1 #define CHEKSUM_2 ________________________________________________________*/ of the HEX file decoder state machine */ 0x01 0x02 0x03 0x04 0x05 0x06 0x07 0x08 0x09 0x0A 0x0B 0x0C 0x0D /*_____ D E C L A R A T I O N ______________________________________________*/ Uchar hex_decoder(Uchar hex_data); /*F************************************************************************** * NAME: hex_parser *---------------------------------------------------------------------------* PARAMS: * return: Exit status of the HEX file parser: OK or bad CRC encountered. *---------------------------------------------------------------------------* PURPOSE: * Monitors the HEX file Rx buffer and call the HEX decoder as soon as data * are available. *****************************************************************************/ Uchar hex_parser(void) { Uchar hex_data, status; status = HEX_DEC_OK; while (status == HEX_DEC_OK) /* Processes while hex decoder status is OK */ { if(nb_rx_data != 0) { hex_data = rx_buffer_rd(); status = hex_decoder(hex_data); } } return status; 18 Rev A - 21 Jan 2000 ANM076 } /*F************************************************************************** * NAME: hex_decoder *---------------------------------------------------------------------------* PARAMS: * hex_data: data from the HEX file to decode * return: Hex decoder exit status: OK or bad CRC encountered. *---------------------------------------------------------------------------* PURPOSE: * Decodes all HEX file records on a byte per byte basis: analyse HEX record, * extracts data for FLASH programming and verifies the checksum. ***************************************************************************** * NOTE: * HEX data are ASCII data format. Each byte is made of 2 ASCII form digits * that needed to be converted. Conversion uses toint which is not a ANSI * C function. One should use strtol when available (not in Keil C lib). *****************************************************************************/ Uchar hex_decoder(Uchar hex_data) { static state = REC_MARK; static Uchar length, type, nb_byte, data_value, sum, sum_1, sum_2; static Uint16 offset; Uchar status; status = HEX_DEC_OK; switch(state) { case REC_MARK: { if (hex_data == ':') { state = REC_LEN_1; nb_byte=0; } else state = REC_MARK; break; } /* Start of a new record */ /* Check if the right character */ /* If ok, next step: get the 1st lenght char */ /* If ko, spurious char and skip */ case REC_LEN_1: /* Get the 1st digit of the length byte */ { length = toint(hex_data) * 16; state = REC_LEN_2; break; } case REC_LEN_2: /* Get the 2nd digit of the lenght byte */ { length = length + toint(hex_data); state = OFFSET_1; break; } case OFFSET_1: /* Get the 1st digit of the adress byte */ { offset = toint(hex_data) * 4096; Rev A - 21 Jan 2000 19 ANM076 state = OFFSET_2; break; } case OFFSET_2: /* Get the 2nd digit of the adress byte */ { offset = offset + toint(hex_data) * 256; sum_1= offset / 256; state = OFFSET_3; break; } case OFFSET_3: /* Get the 3rd digit of the adress byte */ { offset = offset + toint(hex_data) * 16; state = OFFSET_4; break; } case OFFSET_4: /* Get the 4th digit of the adress byte */ { offset = offset + toint(hex_data); sum_2 = offset - sum_1 * 256; state = REC_TYP_1; break; } case REC_TYP_1: /* Get the 1st digit of the record type */ { type = toint(hex_data) * 16; state =REC_TYP_2; break; } case REC_TYP_2: /* Get the 2nd digit of the record type */ { type = type + toint(hex_data); sum = length + sum_1 + sum_2 + type; if (length==0x00) state=CHEKSUM_1; /* If no data, go to checksum computation */ else state = DATA_1; /* Otherwise next is data record acquisition */ break; } case DATA_1: /* Get the 1st digit of one data */ { data_value = toint(hex_data) * 16 ; state = DATA_2; break; } case DATA_2: /* Get the 2nd digit of one data */ { data_value = data_value + toint(hex_data); sum = sum + data_value; flash_prog(offset + nb_byte, data_value); 20 Rev A - 21 Jan 2000 ANM076 nb_byte++; if (nb_byte == length) state = CHEKSUM_1; else state = DATA_1; break; /* If end of data block, go to checksum */ /* Otherwise, get the next data in the block */ } case CHEKSUM_1: /* Get 1st digit of the checksum */ { sum_1 = toint(hex_data) * 16; sum = (~sum) + 1; /* Checksum 2 complement */ state = CHEKSUM_2; break; } case CHEKSUM_2: /* Get 2nd digit of the checksum */ { sum_1 = sum_1 + toint(hex_data); if (sum_1 != sum) status = HEX_DEC_CSERR; state = REC_MARK; /* Ready for next record */ if(type==0x01) status = HEX_DEC_END; /* end of transmission */ break; } } return status; } Rev A - 21 Jan 2000 21 ANM076 7.5. CONFIG.H /*H*************************************************************************** * NAME: myfile.h *---------------------------------------------------------------------------* PURPOSE: *****************************************************************************/ #ifndef _CONFIG_H_ #define _CONFIG_H_ /*_____ I N C L U D E S ____________________________________________________*/ #include <reg51.h> #include "compiler.h" /* ______________________ User Configuration Section ______________________ */ #define HAVE_XRAM /* Target chip: T89C51RD2 with on-chip XRAM */ /* ______________________ User Configuration Section ______________________ */ #ifdef HAVE_XRAM entire */ #define NO_XDATA 0x02 Sfr (AUXR, 0x8E); #endif /* If on-chip XRAM, disable the XRAM to access to the /* FLASH when mapped in the data area */ #endif /* _CONFIG_H_ */ 22 Rev A - 21 Jan 2000 ANM076 7.6. COMPILER.H /*H*************************************************************************** * NAME: compiler.h *---------------------------------------------------------------------------* PURPOSE: * Defines compiler dependant definitions to enhance program portability. * Allows to remap exotic syntaxes to another exotic syntaxe without changing * C source files. *****************************************************************************/ #ifndef _COMPILER_H_ #define _COMPILER_H_ /*_____ M A C R O S ________________________________________________________*/ #define FALSE 0 #define TRUE 1 /*_____ typedef typedef typedef typedef typedef D E F I N I T I unsigned char unsigned short signed int float unsigned char O N ________________________________________________*/ Uchar; Uint16; Int16; Float16; Bool; /* KEIL #define #define #define #define #define compiler syntax Reentrant(x) Sfr(x,y) Sbit(x,y,z) Interrupt(x,y) At(x) redefinition */ x reentrant sfr x = y sbit x = y ^ z x interrupt y _at_ x #endif /* _COMPILER_H_ */ Rev A - 21 Jan 2000 23 ANM076 7.7. ISP.H /*H*************************************************************************** * NAME: isp.h *---------------------------------------------------------------------------* PURPOSE: Header file shared by all ISP C files. *****************************************************************************/ #ifndef _ISP_H_ #define _ISP_H_ /* Uart */ extern Uchar nb_rx_data; void uart_init(void); void uart_rx_enable(void); void uart_rx_disable(void); Bool rx_buffer_empty(void); Uchar rx_buffer_rd(void); /* HEX file parser */ #define HEX_DEC_OK 0x01 #define HEX_DEC_END 0x02 #define HEX_DEC_CSERR 0x03 Uchar hex_parser (void); /* FLASH API's*/ void flash_erase(void); void flash_prog(Uint16, Uchar value); Uint16 flash_id(void); #endif /* _ISP_H_ */ 24 Rev A - 21 Jan 2000 ANEXO E - Datasheet do controlador HD44780 HD44780U (LCD-II) (Dot Matrix Liquid Crystal Display Controller/Driver) ADE-207-272(Z) '99.9 Rev. 0.0 Description The HD44780U dot-matrix liquid crystal display controller and driver LSI displays alphanumerics, Japanese kana characters, and symbols. It can be configured to drive a dot-matrix liquid crystal display under the control of a 4- or 8-bit microprocessor. Since all the functions such as display RAM, character generator, and liquid crystal driver, required for driving a dot-matrix liquid crystal display are internally provided on one chip, a minimal system can be interfaced with this controller/driver. A single HD44780U can display up to one 8-character line or two 8-character lines. The HD44780U has pin function compatibility with the HD44780S which allows the user to easily replace an LCD-II with an HD44780U. The HD44780U character generator ROM is extended to generate 208 5 × 8 dot character fonts and 32 5 × 10 dot character fonts for a total of 240 different character fonts. The low power supply (2.7V to 5.5V) of the HD44780U is suitable for any portable battery-driven product requiring low power dissipation. Features • 5 × 8 and 5 × 10 dot matrix possible • Low power operation support: 2.7 to 5.5V • Wide range of liquid crystal display driver power 3.0 to 11V • Liquid crystal drive waveform A (One line frequency AC waveform) • Correspond to high speed MPU bus interface 2 MHz (when VCC = 5V) • 4-bit or 8-bit MPU interface enabled • 80 × 8-bit display RAM (80 characters max.) • 9,920-bit character generator ROM for a total of 240 character fonts 208 character fonts (5 × 8 dot) 32 character fonts (5 × 10 dot) 1 HD44780U • 64 × 8-bit character generator RAM 8 character fonts (5 × 8 dot) 4 character fonts (5 × 10 dot) • 16-common × 40-segment liquid crystal display driver • Programmable duty cycles 1/8 for one line of 5 × 8 dots with cursor 1/11 for one line of 5 × 10 dots with cursor 1/16 for two lines of 5 × 8 dots with cursor • Wide range of instruction functions: Display clear, cursor home, display on/off, cursor on/off, display character blink, cursor shift, display shift • Pin function compatibility with HD44780S • Automatic reset circuit that initializes the controller/driver after power on • Internal oscillator with external resistors • Low power consumption Ordering Information Type No. Package CGROM HD44780UA00FS HCD44780UA00 HD44780UA00TF HD44780UA02FS HCD44780UA02 HD44780UA02TF FP-80B Chip TFP-80F FP-80B Chip TFP-80F Japanese standard font HD44780UBxxFS HCD44780UBxx HD44780UBxxTF FP-80B Chip TFP-80F Custom font Note: xx: ROM code No. 2 European standard font HD44780U HD44780U Block Diagram OSC1 OSC2 M Reset circuit ACL Timing generator CPG 8 RS R/W E Instruction register (IR) 7 Address counter DB0 to DB3 7 8 40-bit shift register 8 7 DB4 to DB7 D Display data RAM (DDRAM) 80 × 8 bits Instruction decoder MPU interface Input/ output buffer CL1 CL2 16-bit shift register Common signal driver 40-bit latch circuit Segment signal driver SEG1 to SEG40 7 Data register (DR) 8 40 8 8 LCD drive voltage selector Busy flag GND COM1 to COM16 Character generator ROM (CGROM) 9,920 bits Character generator RAM (CGRAM) 64 bytes 5 Cursor and blink controller 5 Parallel/serial converter and attribute circuit VCC V1 V2 V3 V4 V5 3 HD44780U 65 66 67 68 69 70 71 72 73 74 75 76 77 78 1 64 2 63 3 62 4 61 5 60 6 59 7 58 8 57 9 56 10 55 11 54 FP-80B (Top view) 12 13 53 52 42 24 41 OSC2 V1 V2 V3 V4 V5 CL1 CL2 VCC M D RS R/W E DB0 DB1 40 23 39 43 38 44 22 37 21 36 45 35 46 20 34 19 33 47 32 48 18 31 17 30 49 29 50 16 28 15 27 51 26 14 25 SEG22 SEG21 SEG20 SEG19 SEG18 SEG17 SEG16 SEG15 SEG14 SEG13 SEG12 SEG11 SEG10 SEG9 SEG8 SEG7 SEG6 SEG5 SEG4 SEG3 SEG2 SEG1 GND OSC1 79 80 SEG23 SEG24 SEG25 SEG26 SEG27 SEG28 SEG29 SEG30 SEG31 SEG32 SEG33 SEG34 SEG35 SEG36 SEG37 SEG38 HD44780U Pin Arrangement (FP-80B) 4 SEG39 SEG40 COM16 COM15 COM14 COM13 COM12 COM11 COM10 COM9 COM8 COM7 COM6 COM5 COM4 COM3 COM2 COM1 DB7 DB6 DB5 DB4 DB3 DB2 HD44780U 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 1 60 2 59 3 58 4 57 5 56 6 55 7 54 8 53 9 52 TFP-80F (Top view) 10 11 51 50 40 39 38 37 36 35 34 41 33 20 32 42 31 43 19 30 18 29 44 28 45 17 27 16 26 46 25 47 15 24 14 23 48 22 49 13 21 12 COM16 COM15 COM14 COM13 COM12 COM11 COM10 COM9 COM8 COM7 COM6 COM5 COM4 COM3 COM2 COM1 DB7 DB6 DB5 DB4 GND OSC1 OSC2 V1 V2 V3 V4 V5 CL1 CL2 VCC M D RS R/W E DB0 DB1 DB2 DB3 SEG20 SEG19 SEG18 SEG17 SEG16 SEG15 SEG14 SEG13 SEG12 SEG11 SEG10 SEG9 SEG8 SEG7 SEG6 SEG5 SEG4 SEG3 SEG2 SEG1 79 80 SEG21 SEG22 SEG23 SEG24 SEG25 SEG26 SEG27 SEG28 SEG29 SEG30 SEG31 SEG32 SEG33 SEG34 SEG35 SEG36 SEG37 SEG38 SEG39 SEG40 HD44780U Pin Arrangement (TFP-80F) 5 HD44780U HD44780U Pad Arrangement Chip size: 4.90 × 4.90 mm2 Coordinate: Pad center (µm) 2 1 Origin: Chip center Pad size: 114 × 114 µm2 80 63 Y Type code HD44780U 42 23 X 6 HD44780U HCD44780U Pad Location Coordinates Pad No. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 Function SEG22 SEG21 SEG20 SEG19 SEG18 SEG17 SEG16 SEG15 SEG14 SEG13 SEG12 SEG11 SEG10 SEG9 SEG8 SEG7 SEG6 SEG5 SEG4 SEG3 SEG2 SEG1 GND OSC1 OSC2 V1 V2 V3 V4 V5 CL1 CL2 VCC M D RS R/W E DB0 DB1 Coordinate X (um) Y (um) –2100 2313 –2280 2313 –2313 2089 –2313 1833 –2313 1617 –2313 1401 –2313 1186 –2313 970 –2313 755 –2313 539 –2313 323 –2313 108 –2313 –108 –2313 –323 –2313 –539 –2313 –755 –2313 –970 –2313 –1186 –2313 –1401 –2313 –1617 –2313 –1833 –2313 –2073 –2280 –2290 –2080 –2290 –1749 –2290 –1550 –2290 –1268 –2290 –941 –2290 –623 –2290 –304 –2290 –48 –2290 142 –2290 309 –2290 475 –2290 665 –2290 832 –2290 1022 –2290 1204 –2290 1454 –2290 1684 –2290 Pad No. 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 Function DB2 DB3 DB4 DB5 DB6 DB7 COM1 COM2 COM3 COM4 COM5 COM6 COM7 COM8 COM9 COM10 COM11 COM12 COM13 COM14 COM15 COM16 SEG40 SEG39 SEG38 SEG37 SEG36 SEG35 SEG34 SEG33 SEG32 SEG31 SEG30 SEG29 SEG28 SEG27 SEG26 SEG25 SEG24 SEG23 Coordinate X (um) Y (um) 2070 –2290 2260 –2290 2290 –2099 2290 –1883 2290 –1667 2290 –1452 2313 –1186 2313 –970 2313 –755 2313 –539 2313 –323 2313 –108 2313 108 2313 323 2313 539 2313 755 2313 970 2313 1186 2313 1401 2313 1617 2313 1833 2313 2095 2296 2313 2100 2313 1617 2313 1401 2313 1186 2313 970 2313 755 2313 539 2313 323 2313 108 2313 –108 2313 –323 2313 –539 2313 –755 2313 –970 2313 –1186 2313 –1401 2313 –1617 2313 7 HD44780U Pin Functions Signal No. of Lines I/O Device Interfaced with RS 1 I MPU Selects registers. 0: Instruction register (for write) Busy flag: address counter (for read) 1: Data register (for write and read) R/W 1 I MPU Selects read or write. 0: Write 1: Read E 1 I MPU Starts data read/write. DB4 to DB7 4 I/O MPU Four high order bidirectional tristate data bus pins. Used for data transfer and receive between the MPU and the HD44780U. DB7 can be used as a busy flag. DB0 to DB3 4 I/O MPU Four low order bidirectional tristate data bus pins. Used for data transfer and receive between the MPU and the HD44780U. These pins are not used during 4-bit operation. CL1 1 O Extension driver Clock to latch serial data D sent to the extension driver CL2 1 O Extension driver Clock to shift serial data D M 1 O Extension driver Switch signal for converting the liquid crystal drive waveform to AC D 1 O Extension driver Character pattern data corresponding to each segment signal COM1 to COM16 16 O LCD Common signals that are not used are changed to non-selection waveforms. COM9 to COM16 are non-selection waveforms at 1/8 duty factor and COM12 to COM16 are non-selection waveforms at 1/11 duty factor. SEG1 to SEG40 40 O LCD Segment signals V1 to V5 5 — Power supply Power supply for LCD drive VCC –V5 = 11 V (max) VCC, GND 2 — Power supply VCC: 2.7V to 5.5V, GND: 0V OSC1, OSC2 2 — Oscillation resistor clock When crystal oscillation is performed, a resistor must be connected externally. When the pin input is an external clock, it must be input to OSC1. 8 Function HD44780U Function Description Registers The HD44780U has two 8-bit registers, an instruction register (IR) and a data register (DR). The IR stores instruction codes, such as display clear and cursor shift, and address information for display data RAM (DDRAM) and character generator RAM (CGRAM). The IR can only be written from the MPU. The DR temporarily stores data to be written into DDRAM or CGRAM and temporarily stores data to be read from DDRAM or CGRAM. Data written into the DR from the MPU is automatically written into DDRAM or CGRAM by an internal operation. The DR is also used for data storage when reading data from DDRAM or CGRAM. When address information is written into the IR, data is read and then stored into the DR from DDRAM or CGRAM by an internal operation. Data transfer between the MPU is then completed when the MPU reads the DR. After the read, data in DDRAM or CGRAM at the next address is sent to the DR for the next read from the MPU. By the register selector (RS) signal, these two registers can be selected (Table 1). Busy Flag (BF) When the busy flag is 1, the HD44780U is in the internal operation mode, and the next instruction will not be accepted. When RS = 0 and R/W = 1 (Table 1), the busy flag is output to DB7. The next instruction must be written after ensuring that the busy flag is 0. Address Counter (AC) The address counter (AC) assigns addresses to both DDRAM and CGRAM. When an address of an instruction is written into the IR, the address information is sent from the IR to the AC. Selection of either DDRAM or CGRAM is also determined concurrently by the instruction. After writing into (reading from) DDRAM or CGRAM, the AC is automatically incremented by 1 (decremented by 1). The AC contents are then output to DB0 to DB6 when RS = 0 and R/W = 1 (Table 1). Table 1 Register Selection RS R/W Operation 0 0 IR write as an internal operation (display clear, etc.) 0 1 Read busy flag (DB7) and address counter (DB0 to DB6) 1 0 DR write as an internal operation (DR to DDRAM or CGRAM) 1 1 DR read as an internal operation (DDRAM or CGRAM to DR) 9 HD44780U Display Data RAM (DDRAM) Display data RAM (DDRAM) stores display data represented in 8-bit character codes. Its extended capacity is 80 × 8 bits, or 80 characters. The area in display data RAM (DDRAM) that is not used for display can be used as general data RAM. See Figure 1 for the relationships between DDRAM addresses and positions on the liquid crystal display. The DDRAM address (ADD ) is set in the address counter (AC) as hexadecimal. • 1-line display (N = 0) (Figure 2) When there are fewer than 80 display characters, the display begins at the head position. For example, if using only the HD44780, 8 characters are displayed. See Figure 3. When the display shift operation is performed, the DDRAM address shifts. See Figure 3. High order bits Low order bits Example: DDRAM address 4E AC (hexadecimal) AC6 AC5 AC4 AC3 AC2 AC1 AC0 1 0 0 1 1 Figure 1 DDRAM Address Display position (digit) 1 2 3 DDRAM 00 01 address (hexadecimal) 4 02 5 79 .................. 03 04 Figure 2 1-Line Display Display position 1 2 3 4 5 6 7 8 DDRAM address 00 01 02 03 04 05 06 07 For shift left 01 02 03 04 05 06 07 08 For shift right 4F 00 01 02 03 04 05 06 Figure 3 1-Line by 8-Character Display Example 10 80 4E 4F 1 0 HD44780U • 2-line display (N = 1) (Figure 4) Case 1: When the number of display characters is less than 40 × 2 lines, the two lines are displayed from the head. Note that the first line end address and the second line start address are not consecutive. For example, when just the HD44780 is used, 8 characters × 2 lines are displayed. See Figure 5. When display shift operation is performed, the DDRAM address shifts. See Figure 5. Display position 1 2 3 00 01 DDRAM address (hexadecimal) 40 41 4 5 39 40 02 03 04 .................. 26 27 42 43 44 .................. 66 67 Figure 4 2-Line Display Display position 1 2 3 4 5 6 7 8 DDRAM address 00 01 02 03 04 05 06 07 For shift left 01 02 03 04 05 06 07 08 40 41 42 43 44 45 46 47 41 42 43 44 45 46 47 48 27 00 01 02 03 04 05 06 For shift right 67 40 41 42 43 44 45 46 Figure 5 2-Line by 8-Character Display Example 11 HD44780U Case 2: For a 16-character × 2-line display, the HD44780 can be extended using one 40-output extension driver. See Figure 6. When display shift operation is performed, the DDRAM address shifts. See Figure 6. Display position DDRAM address 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 00 01 02 03 04 05 06 07 08 09 0A 0B 0C 0D 0E 0F 40 41 42 43 44 45 46 47 48 49 4A 4B 4C 4D 4E 4F HD44780U display For shift left Extension driver display 01 02 03 04 05 06 07 08 09 0A 0B 0C 0D 0E 0F 10 41 42 43 44 45 46 47 48 49 4A 4B 4C 4D 4E 4F 50 27 00 01 02 03 04 05 06 07 08 09 0A 0B 0C 0D 0E For shift right 67 40 41 42 43 44 45 46 47 48 49 4A 4B 4C 4D 4E Figure 6 2-Line by 16-Character Display Example 12 HD44780U Character Generator ROM (CGROM) The character generator ROM generates 5 × 8 dot or 5 × 10 dot character patterns from 8-bit character codes (Table 4). It can generate 208 5 × 8 dot character patterns and 32 5 × 10 dot character patterns. Userdefined character patterns are also available by mask-programmed ROM. Character Generator RAM (CGRAM) In the character generator RAM, the user can rewrite character patterns by program. For 5 × 8 dots, eight character patterns can be written, and for 5 × 10 dots, four character patterns can be written. Write into DDRAM the character codes at the addresses shown as the left column of Table 4 to show the character patterns stored in CGRAM. See Table 5 for the relationship between CGRAM addresses and data and display patterns. Areas that are not used for display can be used as general data RAM. Modifying Character Patterns • Character pattern development procedure The following operations correspond to the numbers listed in Figure 7: 1. Determine the correspondence between character codes and character patterns. 2. Create a listing indicating the correspondence between EPROM addresses and data. 3. Program the character patterns into the EPROM. 4. Send the EPROM to Hitachi. 5. Computer processing on the EPROM is performed at Hitachi to create a character pattern listing, which is sent to the user. 6. If there are no problems within the character pattern listing, a trial LSI is created at Hitachi and samples are sent to the user for evaluation. When it is confirmed by the user that the character patterns are correctly written, mass production of the LSI proceeds at Hitachi. 13 HD44780U Hitachi User Start Computer processing Create character pattern listing 5 Evaluate character patterns No Determine character patterns 1 Create EPROM address data listing 2 Write EPROM 3 EPROM → Hitachi 4 OK? Yes Art work M/T Masking Trial Sample Sample evaluation OK? 6 No Yes Mass production Note: For a description of the numbers used in this figure, refer to the preceding page. Figure 7 Character Pattern Development Procedure 14 HD44780U • Programming character patterns This section explains the correspondence between addresses and data used to program character patterns in EPROM. The HD44780U character generator ROM can generate 208 5 × 8 dot character patterns and 32 5 × 10 dot character patterns for a total of 240 different character patterns. Character patterns EPROM address data and character pattern data correspond with each other to form a 5 × 8 or 5 × 10 dot character pattern (Tables 2 and 3). Table 2 Example of Correspondence between EPROM Address Data and Character Pattern (5 × 8 Dots) Data EPROM Address LSB A 1 1A 1 0 A9 A8 A7 A6 A5 A4 A3 A2 A1 A0 O 4 O3 O2 O1 O0 0 1 1 0 0 0 Character code Notes: 1. 2. 3. 4. 5. 6. 1 0 0 0 0 0 1 0 0 0 0 0 0 0 1 1 0 0 0 0 0 0 1 0 1 0 1 1 0 0 0 1 1 1 1 0 0 1 0 1 0 0 1 0 0 0 1 0 1 0 1 1 0 0 0 1 0 1 1 0 1 1 1 1 0 0 1 1 1 0 0 0 0 0 1 0 0 0 0 0 0 0 0 1 0 0 1 0 0 0 0 0 1 0 1 0 0 0 0 0 0 1 0 1 1 0 0 0 0 0 1 1 0 0 0 0 0 0 0 1 1 0 1 0 0 0 0 0 1 1 1 0 0 0 0 0 0 1 1 1 1 0 0 0 0 0 Cursor position Line position EPROM addresses A11 to A4 correspond to a character code. EPROM addresses A3 to A0 specify a line position of the character pattern. EPROM data O4 to O0 correspond to character pattern data. EPROM data O5 to O7 must be specified as 0. A lit display position (black) corresponds to a 1. Line 9 and the following lines must be blanked with 0s for a 5 × 8 dot character fonts. 15 HD44780U Handling unused character patterns 1. EPROM data outside the character pattern area: Always input 0s. 2. EPROM data in CGRAM area: Always input 0s. (Input 0s to EPROM addresses 00H to FFH.) 3. EPROM data used when the user does not use any HD44780U character pattern: According to the user application, handled in one of the two ways listed as follows. a. When unused character patterns are not programmed: If an unused character code is written into DDRAM, all its dots are lit. By not programing a character pattern, all of its bits become lit. (This is due to the EPROM being filled with 1s after it is erased.) b. When unused character patterns are programmed as 0s: Nothing is displayed even if unused character codes are written into DDRAM. (This is equivalent to a space.) Table 3 Example of Correspondence between EPROM Address Data and Character Pattern (5 × 10 Dots) Data EPROM Address LSB A 1 1A 1 0 A9 A8 A7 A6 A5 A4 A3 A2 A1 A0 O 4 O3 O2 O1 O0 0 1 0 1 0 0 Character code Notes: 1. 2. 3. 4. 5. 6. 16 1 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 1 0 0 1 1 0 1 0 0 1 1 1 0 0 1 1 0 1 0 0 1 0 0 0 1 0 1 0 1 1 0 0 0 1 0 1 1 0 0 1 1 1 1 0 1 1 1 0 0 0 0 1 1 0 0 0 0 0 0 0 1 1 0 0 1 0 0 0 0 1 1 0 1 0 0 0 0 0 0 1 0 1 1 0 0 0 0 0 1 1 0 0 0 0 0 0 0 1 1 0 1 0 0 0 0 0 1 1 1 0 0 0 0 0 0 1 1 1 1 0 0 0 0 0 Cursor position Line position EPROM addresses A11 to A3 correspond to a character code. EPROM addresses A3 to A0 specify a line position of the character pattern. EPROM data O4 to O0 correspond to character pattern data. EPROM data O5 to O7 must be specified as 0. A lit display position (black) corresponds to a 1. Line 11 and the following lines must be blanked with 0s for a 5 × 10 dot character fonts. HD44780U Table 4 Lower 4 Bits Upper 4 Bits Correspondence between Character Codes and Character Patterns (ROM Code: A00) 0000 0001 0010 0011 0100 0101 0110 0111 1000 1001 1010 xxxx0000 CG RAM (1) xxxx0001 (2) xxxx0010 (3) xxxx0011 (4) xxxx0100 (5) xxxx0101 (6) xxxx0110 (7) xxxx0111 (8) xxxx1000 (1) xxxx1001 (2) xxxx1010 (3) xxxx1011 (4) xxxx1100 (5) xxxx1101 (6) xxxx1110 (7) xxxx1111 (8) 1011 1100 1101 1110 1111 Note: The user can specify any pattern for character-generator RAM. 17 HD44780U Table 4 Lower 4 Bits Upper 4 Bits Correspondence between Character Codes and Character Patterns (ROM Code: A02) 0000 0001 0010 0011 0100 0101 0110 0111 1000 1001 1010 1011 1100 1101 1110 1111 xxxx0000 CG RAM (1) xxxx0001 (2) xxxx0010 (3) xxxx0011 (4) xxxx0100 (5) xxxx0101 (6) xxxx0110 (7) xxxx0111 (8) xxxx1000 (1) xxxx1001 (2) xxxx1010 (3) xxxx1011 (4) xxxx1100 (5) xxxx1101 (6) xxxx1110 (7) xxxx1111 (8) 18 HD44780U Table 5 Relationship between CGRAM Addresses, Character Codes (DDRAM) and Character Patterns (CGRAM Data) For 5 × 8 dot character patterns Character Codes (DDRAM data) CGRAM Address Character Patterns (CGRAM data) 7 6 5 4 3 2 1 0 5 4 3 2 1 0 7 6 5 4 3 2 1 0 High High High Low 0 0 0 0 * 0 0 0 0 0 0 0 * 0 0 1 0 0 0 0 * 1 1 1 0 0 0 0 0 1 1 1 1 Low 0 0 0 0 1 1 1 1 0 0 0 0 1 1 1 1 0 0 0 0 1 1 0 0 1 1 0 0 1 1 0 0 1 1 0 0 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 1 1 1 1 0 0 1 1 0 1 0 1 * * * * * * * * * * * * * * * Low 1 1 1 1 1 1 1 0 1 0 1 0 1 0 0 0 1 0 0 1 0 0 0 0 0 1 1 0 1 0 0 0 1 0 0 1 1 0 0 0 0 0 1 1 1 1 1 0 1 0 0 1 0 1 0 0 0 1 1 0 1 0 0 0 0 1 1 0 0 0 1 0 1 0 1 0 1 0 0 0 Character pattern (1) Cursor position Character pattern (2) Cursor position * * * Notes: 1. Character code bits 0 to 2 correspond to CGRAM address bits 3 to 5 (3 bits: 8 types). 2. CGRAM address bits 0 to 2 designate the character pattern line position. The 8th line is the cursor position and its display is formed by a logical OR with the cursor. Maintain the 8th line data, corresponding to the cursor display position, at 0 as the cursor display. If the 8th line data is 1, 1 bits will light up the 8th line regardless of the cursor presence. 3. Character pattern row positions correspond to CGRAM data bits 0 to 4 (bit 4 being at the left). 4. As shown Table 5, CGRAM character patterns are selected when character code bits 4 to 7 are all 0. However, since character code bit 3 has no effect, the R display example above can be selected by either character code 00H or 08H. 5. 1 for CGRAM data corresponds to display selection and 0 to non-selection. * Indicates no effect. 19 HD44780U Table 5 Relationship between CGRAM Addresses, Character Codes (DDRAM) and Character Patterns (CGRAM Data) (cont) For 5 × 10 dot character patterns Character Codes (DDRAM data) CGRAM Address Character Patterns (CGRAM data) 7 6 5 4 3 2 1 0 5 4 3 2 1 0 7 6 5 4 3 2 1 0 High High High Low 0 0 0 0 * 0 0 * 0 0 0 0 * 1 1 * 0 0 1 1 Low 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 0 0 0 0 0 0 1 1 1 1 0 0 0 0 1 1 1 1 0 0 0 0 1 1 0 0 1 1 0 0 1 1 0 0 1 1 0 0 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 1 1 1 1 1 1 1 0 0 0 1 1 1 1 0 1 1 0 0 1 1 1 0 1 0 1 0 1 * * * * * * * * * * * * * * * Low 0 0 1 1 1 1 1 1 1 1 0 * 0 0 0 1 0 0 1 0 0 0 0 * 0 0 1 0 0 0 1 0 0 0 0 * 0 0 1 0 0 0 1 0 0 0 0 * 0 0 0 1 1 1 0 0 0 0 0 * Character pattern Cursor position * * * * * * * * * * * * * * * * * * * * * * * * Notes: 1. Character code bits 1 and 2 correspond to CGRAM address bits 4 and 5 (2 bits: 4 types). 2. CGRAM address bits 0 to 3 designate the character pattern line position. The 11th line is the cursor position and its display is formed by a logical OR with the cursor. Maintain the 11th line data corresponding to the cursor display positon at 0 as the cursor display. If the 11th line data is “1”, “1” bits will light up the 11th line regardless of the cursor presence. Since lines 12 to 16 are not used for display, they can be used for general data RAM. 3. Character pattern row positions are the same as 5 × 8 dot character pattern positions. 4. CGRAM character patterns are selected when character code bits 4 to 7 are all 0. However, since character code bits 0 and 3 have no effect, the P display example above can be selected by character codes 00H, 01H, 08H, and 09H. 5. 1 for CGRAM data corresponds to display selection and 0 to non-selection. * Indicates no effect. 20 HD44780U Timing Generation Circuit The timing generation circuit generates timing signals for the operation of internal circuits such as DDRAM, CGROM and CGRAM. RAM read timing for display and internal operation timing by MPU access are generated separately to avoid interfering with each other. Therefore, when writing data to DDRAM, for example, there will be no undesirable interferences, such as flickering, in areas other than the display area. Liquid Crystal Display Driver Circuit The liquid crystal display driver circuit consists of 16 common signal drivers and 40 segment signal drivers. When the character font and number of lines are selected by a program, the required common signal drivers automatically output drive waveforms, while the other common signal drivers continue to output non-selection waveforms. Sending serial data always starts at the display data character pattern corresponding to the last address of the display data RAM (DDRAM). Since serial data is latched when the display data character pattern corresponding to the starting address enters the internal shift register, the HD44780U drives from the head display. Cursor/Blink Control Circuit The cursor/blink control circuit generates the cursor or character blinking. The cursor or the blinking will appear with the digit located at the display data RAM (DDRAM) address set in the address counter (AC). For example (Figure 8), when the address counter is 08H, the cursor position is displayed at DDRAM address 08H. AC6 AC5 AC4 AC3 AC2 AC1 AC0 AC 0 0 0 1 0 0 0 Display position 1 2 3 4 5 6 7 8 9 10 11 DDRAM address (hexadecimal) 00 01 02 03 04 05 06 07 08 09 0A For a 1-line display cursor position For a 2-line display Display position DDRAM address (hexadecimal) 1 2 3 4 5 6 7 8 9 10 11 00 01 02 03 04 05 06 07 08 09 0A 40 41 42 43 44 45 46 47 48 49 4A cursor position Note: The cursor or blinking appears when the address counter (AC) selects the character generator RAM (CGRAM). However, the cursor and blinking become meaningless. The cursor or blinking is displayed in the meaningless position when the AC is a CGRAM address. Figure 8 Cursor/Blink Display Example 21 HD44780U Interfacing to the MPU The HD44780U can send data in either two 4-bit operations or one 8-bit operation, thus allowing interfacing with 4- or 8-bit MPUs. • For 4-bit interface data, only four bus lines (DB4 to DB7) are used for transfer. Bus lines DB0 to DB3 are disabled. The data transfer between the HD44780U and the MPU is completed after the 4-bit data has been transferred twice. As for the order of data transfer, the four high order bits (for 8-bit operation, DB4 to DB7) are transferred before the four low order bits (for 8-bit operation, DB0 to DB3). The busy flag must be checked (one instruction) after the 4-bit data has been transferred twice. Two more 4-bit operations then transfer the busy flag and address counter data. • For 8-bit interface data, all eight bus lines (DB0 to DB7) are used. RS R/W E DB7 IR7 IR3 BF AC3 DR7 DR3 DB6 IR6 IR2 AC6 AC2 DR6 DR2 DB5 IR5 IR1 AC5 AC1 DR5 DR1 DB4 IR4 IR0 AC4 AC0 DR4 DR0 Instruction register (IR) write Busy flag (BF) and address counter (AC) read Figure 9 4-Bit Transfer Example 22 Data register (DR) read HD44780U Reset Function Initializing by Internal Reset Circuit An internal reset circuit automatically initializes the HD44780U when the power is turned on. The following instructions are executed during the initialization. The busy flag (BF) is kept in the busy state until the initialization ends (BF = 1). The busy state lasts for 10 ms after VCC rises to 4.5 V. 1. Display clear 2. Function set: DL = 1; 8-bit interface data N = 0; 1-line display F = 0; 5 × 8 dot character font 3. Display on/off control: D = 0; Display off C = 0; Cursor off B = 0; Blinking off 4. Entry mode set: I/D = 1; Increment by 1 S = 0; No shift Note: If the electrical characteristics conditions listed under the table Power Supply Conditions Using Internal Reset Circuit are not met, the internal reset circuit will not operate normally and will fail to initialize the HD44780U. For such a case, initial-ization must be performed by the MPU as explained in the section, Initializing by Instruction. Instructions Outline Only the instruction register (IR) and the data register (DR) of the HD44780U can be controlled by the MPU. Before starting the internal operation of the HD44780U, control information is temporarily stored into these registers to allow interfacing with various MPUs, which operate at different speeds, or various peripheral control devices. The internal operation of the HD44780U is determined by signals sent from the MPU. These signals, which include register selection signal (RS), read/ write signal (R/W), and the data bus (DB0 to DB7), make up the HD44780U instructions (Table 6). There are four categories of instructions that: • Designate HD44780U functions, such as display format, data length, etc. • Set internal RAM addresses • Perform data transfer with internal RAM • Perform miscellaneous functions 23 HD44780U Normally, instructions that perform data transfer with internal RAM are used the most. However, autoincrementation by 1 (or auto-decrementation by 1) of internal HD44780U RAM addresses after each data write can lighten the program load of the MPU. Since the display shift instruction (Table 11) can perform concurrently with display data write, the user can minimize system development time with maximum programming efficiency. When an instruction is being executed for internal operation, no instruction other than the busy flag/address read instruction can be executed. Because the busy flag is set to 1 while an instruction is being executed, check it to make sure it is 0 before sending another instruction from the MPU. Note: Be sure the HD44780U is not in the busy state (BF = 0) before sending an instruction from the MPU to the HD44780U. If an instruction is sent without checking the busy flag, the time between the first instruction and next instruction will take much longer than the instruction time itself. Refer to Table 6 for the list of each instruc-tion execution time. Table 6 Instructions Code Execution Time (max) (when f cp or f OSC is 270 kHz) Instruction RS R/W DB7 DB6 DB5 DB4 DB3 DB2 DB1 DB0 Description Clear display 0 0 0 0 0 0 0 0 0 1 Clears entire display and sets DDRAM address 0 in address counter. Return home 0 0 0 0 0 0 0 0 1 — Sets DDRAM address 0 in address counter. Also returns display from being shifted to original position. DDRAM contents remain unchanged. 1.52 ms Entry mode set 0 0 0 0 0 0 0 1 I/D S Sets cursor move direction and specifies display shift. These operations are performed during data write and read. 37 µs Display on/off control 0 0 0 0 0 0 1 D C B Sets entire display (D) on/off, 37 µs cursor on/off (C), and blinking of cursor position character (B). Cursor or display shift 0 0 0 0 0 1 S/C R/L — — Moves cursor and shifts display without changing DDRAM contents. Function set 0 0 0 0 1 DL N — — 37 µs Sets interface data length (DL), number of display lines (N), and character font (F). Set CGRAM address 0 0 0 1 ACG ACG ACG ACG ACG ACG Sets CGRAM address. CGRAM data is sent and received after this setting. 37 µs Set DDRAM address 0 0 1 ADD ADD ADD ADD ADD ADD ADD Sets DDRAM address. DDRAM data is sent and received after this setting. 37 µs Read busy 0 flag & address 1 BF AC 0 µs 24 AC AC AC F AC AC AC Reads busy flag (BF) indicating internal operation is being performed and reads address counter contents. 37 µs HD44780U Table 6 Instructions (cont) Execution Time (max) (when f cp or f OSC is 270 kHz) Code Instruction RS R/W DB7 DB6 DB5 DB4 DB3 DB2 DB1 DB0 Description 1 0 Write data Writes data into DDRAM or CGRAM. 37 µs tADD = 4 µs* Read data 1 from CG or DDRAM 1 Read data Reads data from DDRAM or CGRAM. 37 µs tADD = 4 µs* = 1: = 0: = 1: = 1: = 0: = 1: = 0: = 1: = 1: = 1: = 1: = 0: Increment Decrement Accompanies display shift Display shift Cursor move Shift to the right Shift to the left 8 bits, DL = 0: 4 bits 2 lines, N = 0: 1 line 5 × 10 dots, F = 0: 5 × 8 dots Internally operating Instructions acceptable DDRAM: Display data RAM CGRAM: Character generator RAM ACG: CGRAM address ADD: DDRAM address (corresponds to cursor address) AC: Address counter used for both DD and CGRAM addresses Execution time changes when frequency changes Example: When fcp or fOSC is 250 kHz, 270 37 µs × = 40 µs 250 Write data to CG or DDRAM I/D I/D S S/C S/C R/L R/L DL N F BF BF Note: — indicates no effect. * After execution of the CGRAM/DDRAM data write or read instruction, the RAM address counter is incremented or decremented by 1. The RAM address counter is updated after the busy flag turns off. In Figure 10, tADD is the time elapsed after the busy flag turns off until the address counter is updated. Busy signal (DB7 pin) Address counter (DB0 to DB6 pins) Busy state A A+1 t ADD Note: t ADD depends on the operation frequency t ADD = 1.5/(f cp or f OSC ) seconds Figure 10 Address Counter Update 25 HD44780U Instruction Description Clear Display Clear display writes space code 20H (character pattern for character code 20H must be a blank pattern) into all DDRAM addresses. It then sets DDRAM address 0 into the address counter, and returns the display to its original status if it was shifted. In other words, the display disappears and the cursor or blinking goes to the left edge of the display (in the first line if 2 lines are displayed). It also sets I/D to 1 (increment mode) in entry mode. S of entry mode does not change. Return Home Return home sets DDRAM address 0 into the address counter, and returns the display to its original status if it was shifted. The DDRAM contents do not change. The cursor or blinking go to the left edge of the display (in the first line if 2 lines are displayed). Entry Mode Set I/D: Increments (I/D = 1) or decrements (I/D = 0) the DDRAM address by 1 when a character code is written into or read from DDRAM. The cursor or blinking moves to the right when incremented by 1 and to the left when decremented by 1. The same applies to writing and reading of CGRAM. S: Shifts the entire display either to the right (I/D = 0) or to the left (I/D = 1) when S is 1. The display does not shift if S is 0. If S is 1, it will seem as if the cursor does not move but the display does. The display does not shift when reading from DDRAM. Also, writing into or reading out from CGRAM does not shift the display. Display On/Off Control D: The display is on when D is 1 and off when D is 0. When off, the display data remains in DDRAM, but can be displayed instantly by setting D to 1. C: The cursor is displayed when C is 1 and not displayed when C is 0. Even if the cursor disappears, the function of I/D or other specifications will not change during display data write. The cursor is displayed using 5 dots in the 8th line for 5 × 8 dot character font selection and in the 11th line for the 5 × 10 dot character font selection (Figure 13). B: The character indicated by the cursor blinks when B is 1 (Figure 13). The blinking is displayed as switching between all blank dots and displayed characters at a speed of 409.6-ms intervals when fcp or f OSC is 250 kHz. The cursor and blinking can be set to display simultaneously. (The blinking frequency changes according to f OSC or the reciprocal of f cp . For example, when fcp is 270 kHz, 409.6 × 250/270 = 379.2 ms.) 26 HD44780U Cursor or Display Shift Cursor or display shift shifts the cursor position or display to the right or left without writing or reading display data (Table 7). This function is used to correct or search the display. In a 2-line display, the cursor moves to the second line when it passes the 40th digit of the first line. Note that the first and second line displays will shift at the same time. When the displayed data is shifted repeatedly each line moves only horizontally. The second line display does not shift into the first line position. The address counter (AC) contents will not change if the only action performed is a display shift. Function Set DL: Sets the interface data length. Data is sent or received in 8-bit lengths (DB7 to DB0) when DL is 1, and in 4-bit lengths (DB7 to DB4) when DL is 0.When 4-bit length is selected, data must be sent or received twice. N: Sets the number of display lines. F: Sets the character font. Note: Perform the function at the head of the program before executing any instructions (except for the read busy flag and address instruction). From this point, the function set instruction cannot be executed unless the interface data length is changed. Set CGRAM Address Set CGRAM address sets the CGRAM address binary AAAAAA into the address counter. Data is then written to or read from the MPU for CGRAM. 27 HD44780U RS Clear display Code 0 RS Return home Code 0 RS Entry mode set Code 0 RS Display on/off control Code 0 RS Cursor or display shift Code 0 RS Function set Code 0 RS Set CGRAM address Code 0 R/W DB7 DB6 DB5 DB4 DB3 DB2 DB1 DB0 0 0 0 0 0 0 0 1 R/W DB7 DB6 DB5 DB4 DB3 DB2 DB1 DB0 0 0 0 0 0 0 0 1 * Note: * Don’t care. R/W DB7 DB6 DB5 DB4 DB3 DB2 DB1 DB0 0 0 0 0 0 0 1 I/D S R/W DB7 DB6 DB5 DB4 DB3 DB2 DB1 DB0 0 0 0 0 0 1 D C B R/W DB7 DB6 DB5 DB4 DB3 DB2 DB1 DB0 0 0 0 0 1 S/C R/L * * R/W DB7 DB6 DB5 DB4 DB3 DB2 DB1 DB0 0 0 0 1 DL N F * * R/W DB7 DB6 DB5 DB4 DB3 DB2 DB1 DB0 0 0 1 A A A Higher order bit Figure 11 Instruction (1) 28 0 A A Lower order bit A Note: * Don’t care. HD44780U Set DDRAM Address Set DDRAM address sets the DDRAM address binary AAAAAAA into the address counter. Data is then written to or read from the MPU for DDRAM. However, when N is 0 (1-line display), AAAAAAA can be 00H to 4FH. When N is 1 (2-line display), AAAAAAA can be 00H to 27H for the first line, and 40H to 67H for the second line. Read Busy Flag and Address Read busy flag and address reads the busy flag (BF) indicating that the system is now internally operating on a previously received instruction. If BF is 1, the internal operation is in progress. The next instruction will not be accepted until BF is reset to 0. Check the BF status before the next write operation. At the same time, the value of the address counter in binary AAAAAAA is read out. This address counter is used by both CG and DDRAM addresses, and its value is determined by the previous instruction. The address contents are the same as for instructions set CGRAM address and set DDRAM address. Table 7 Shift Function S/C R/L 0 0 Shifts the cursor position to the left. (AC is decremented by one.) 0 1 Shifts the cursor position to the right. (AC is incremented by one.) 1 0 Shifts the entire display to the left. The cursor follows the display shift. 1 1 Shifts the entire display to the right. The cursor follows the display shift. Table 8 Function Set N F No. of Display Lines 0 0 1 5 × 8 dots 1/8 0 1 1 5 × 10 dots 1/11 1 * 2 5 × 8 dots 1/16 Note: * Character Font Duty Factor Remarks Cannot display two lines for 5 × 10 dot character font Indicates don’t care. 29 HD44780U Cursor 5 × 8 dot character font 5 × 10 dot character font Alternating display Cursor display example Blink display example Figure 12 Cursor and Blinking RS Set DDRAM address Code 0 R/W DB7 DB6 DB5 DB4 DB3 DB2 DB1 DB0 0 1 A A A A Higher order bit RS Read busy flag and address Code 0 A A Lower order bit R/W DB7 DB6 DB5 DB4 DB3 DB2 DB1 DB0 1 BF A A A Higher order bit Figure 13 Instruction (2) 30 A A A A Lower order bit A HD44780U Write Data to CG or DDRAM Write data to CG or DDRAM writes 8-bit binary data DDDDDDDD to CG or DDRAM. To write into CG or DDRAM is determined by the previous specification of the CGRAM or DDRAM address setting. After a write, the address is automatically incremented or decremented by 1 according to the entry mode. The entry mode also determines the display shift. Read Data from CG or DDRAM Read data from CG or DDRAM reads 8-bit binary data DDDDDDDD from CG or DDRAM. The previous designation determines whether CG or DDRAM is to be read. Before entering this read instruction, either CGRAM or DDRAM address set instruction must be executed. If not executed, the first read data will be invalid. When serially executing read instructions, the next address data is normally read from the second read. The address set instructions need not be executed just before this read instruction when shifting the cursor by the cursor shift instruction (when reading out DDRAM). The operation of the cursor shift instruction is the same as the set DDRAM address instruction. After a read, the entry mode automatically increases or decreases the address by 1. However, display shift is not executed regardless of the entry mode. Note: The address counter (AC) is automatically incremented or decremented by 1 after the write instructions to CGRAM or DDRAM are executed. The RAM data selected by the AC cannot be read out at this time even if read instructions are executed. Therefore, to correctly read data, execute either the address set instruction or cursor shift instruction (only with DDRAM), then just before reading the desired data, execute the read instruction from the second time the read instruction is sent. RS Write data to CG or DDRAM Code 1 R/W DB7 DB6 DB5 DB4 DB3 DB2 DB1 DB0 0 D D D D D Higher order bits RS Read data from CG or DDRAM Code 1 D D D Lower order bits R/W DB7 DB6 DB5 DB4 DB3 DB2 DB1 DB0 1 D D D Higher order bits D D D D D Lower order bits Figure 14 Instruction (3) 31 HD44780U Interfacing the HD44780U Interface to MPUs • Interfacing to an 8-bit MPU 2 % / . , + * ) & ( $ 0" See Figure 16 for an example of using a I/O port (for a single-chip microcomputer) as an interface device. In this example, P30 to P37 are connected to the data bus DB0 to DB7, and P75 to P77 are connected to E, R/W, and RS, respectively. RS R/W E Internal operation Functioning Data Busy Busy Instruction write Busy flag check Busy flag check DB7 Not busy Data Busy flag check Instruction write Figure 15 Example of Busy Flag Check Timing Sequence H8/325 HD44780U P30 to P37 P77 P76 P75 8 DB0 to DB7 E RS R/W COM1 to COM16 16 SEG1 to SEG40 40 LCD Figure 16 H8/325 Interface (Single-Chip Mode) 32 HD44780U • Interfacing to a 4-bit MPU The HD44780U can be connected to the I/O port of a 4-bit MPU. If the I/O port has enough bits, 8-bit data can be transferred. Otherwise, one data transfer must be made in two operations for 4-bit data. In this case, the timing sequence becomes somewhat complex. (See Figure 17.) See Figure 18 for an interface example to the HMCS4019R. Note that two cycles are needed for the busy flag check as well as for the data transfer. The 4-bit operation is selected by the program. RS 2 ) ( ' & % * $ ! 6 5 4 3 -!"01'., R/W E Internal operation DB7 Functioning IR7 IR3 Instruction write Busy AC3 Not busy AC3 Busy flag check Busy flag check D7 D3 Instruction write Note: IR7 , IR3 are the 7th and 3rd bits of the instruction. AC3 is the 3rd bit of the address counter. Figure 17 Example of 4-Bit Data Transfer Timing Sequence HMCS4019R HD44780 D15 RS D14 R/W D13 E R10 to R13 4 DB4 to DB7 COM1 to COM16 16 LCD SEG1 to SEG40 40 Figure 18 Example of Interface to HMCS4019R 33 HD44780U Interface to Liquid Crystal Display Character Font and Number of Lines: The HD44780U can perform two types of displays, 5 × 8 dot and 5 × 10 dot character fonts, each with a cursor. Up to two lines are displayed for 5 × 8 dots and one line for 5 × 10 dots. Therefore, a total of three types of common signals are available (Table 9). The number of lines and font types can be selected by the program. (See Table 6, Instructions.) Connection to HD44780 and Liquid Crystal Display: See Figure 19 for the connection examples. Table 9 Common Signals Number of Lines Character Font Number of Common Signals Duty Factor 1 5 × 8 dots + cursor 8 1/8 1 5 × 10 dots + cursor 11 1/11 2 5 × 8 dots + cursor 16 1/16 HD44780 COM1 COM8 SEG1 SEG40 Example of a 5 × 8 dot, 8-character × 1-line display (1/4 bias, 1/8 duty cycle) HD44780 COM1 COM11 SEG1 SEG40 Example of a 5 × 10 dot, 8-character × 1-line display (1/4 bias, 1/11 duty cycle) Figure 19 Liquid Crystal Display and HD44780 Connections 34 HD44780U Since five segment signal lines can display one digit, one HD44780U can display up to 8 digits for a 1-line display and 16 digits for a 2-line display. The examples in Figure 19 have unused common signal pins, which always output non-selection waveforms. When the liquid crystal display panel has unused extra scanning lines, connect the extra scanning lines to these common signal pins to avoid any undesirable effects due to crosstalk during the floating state. HD44780 COM1 COM8 COM9 COM16 SEG1 SEG40 Example of a 5 × 8 dot, 8-character × 2-line display (1/5 bias, 1/16 duty cycle) Figure 19 Liquid Crystal Display and HD44780 Connections (cont) 35 HD44780U Connection of Changed Matrix Layout: In the preceding examples, the number of lines correspond to the scanning lines. However, the following display examples (Figure 20) are made possible by altering the matrix layout of the liquid crystal display panel. In either case, the only change is the layout. The display characteristics and the number of liquid crystal display characters depend on the number of common signals or on duty factor. Note that the display data RAM (DDRAM) addresses for 4 characters × 2 lines and for 16 characters × 1 line are the same as in Figure 19. HD44780 COM1 COM8 SEG1 SEG40 COM9 COM16 5 × 8 dot, 16-character × 1-line display (1/5 bias, 1/16 duty cycle) Figure 20 Changed Matrix Layout Displays 36 HD44780U Power Supply for Liquid Crystal Display Drive Various voltage levels must be applied to pins V1 to V5 of the HD44780U to obtain the liquid crystal display drive waveforms. The voltages must be changed according to the duty factor (Table 10). VLCD is the peak value for the liquid crystal display drive waveforms, and resistance dividing provides voltages V1 to V5 (Figure 21). Table 10 Duty Factor and Power Supply for Liquid Crystal Display Drive Duty Factor 1/8, 1/11 1/16 Bias Power Supply 1/4 1/5 V1 VCC–1/4 VLCD VCC–1/5 VLCD V2 VCC–1/2 VLCD VCC–2/5 VLCD V3 VCC–1/2 VLCD VCC–3/5 VLCD V4 VCC–3/4 VLCD VCC–4/5 VLCD V5 VCC–VLCD VCC–VLCD VCC (+5 V) VCC (+5 V) VCC VCC R V1 V1 V2 V3 R VLCD R V4 R V5 V2 V3 V4 V5 R R VLCD R R VR VR –5 V –5 V 1/4 bias (1/8, 1/11 duty cycle) R 1/5 bias (1/16, duty cycle) Figure 21 Drive Voltage Supply Example 37 HD44780U Relationship between Oscillation Frequency and Liquid Crystal Display Frame Frequency The liquid crystal display frame frequencies of Figure 22 apply only when the oscillation frequency is 270 kHz (one clock pulse of 3.7 µs). 1/8 duty cycle COM1 400 clocks 1 2 3 4 8 1 2 11 1 2 1 2 VCC V1 V2 (V3) V4 V5 1 frame 1 frame = 3.7 µs × 400 × 8 = 11850 µs = 11.9 ms 1 Frame frequency = = 84.3 Hz 11.9 ms 1/11 duty cycle COM1 400 clocks 1 2 3 4 VCC V1 V2 (V3) V4 V5 1 frame 1 frame = 3.7 µs × 400 × 11 = 16300 µs = 16.3 ms 1 Frame frequency = = 61.4 Hz 16.3 ms 1/16 duty cycle COM1 200 clocks 1 2 3 4 VCC 16 V1 V2 V3 V4 V5 1 frame 1 frame = 3.7 µs × 200 × 16 = 11850 µs = 11.9 ms 1 = 84.3 Hz 11.9 ms Frame frequency = Figure 22 Frame Frequency 38 HD44780U Instruction and Display Correspondence • 8-bit operation, 8-digit × 1-line display with internal reset Refer to Table 11 for an example of an 8-digit × 1-line display in 8-bit operation. The HD44780U functions must be set by the function set instruction prior to the display. Since the display data RAM can store data for 80 characters, as explained before, the RAM can be used for displays such as for advertising when combined with the display shift operation. Since the display shift operation changes only the display position with DDRAM contents unchanged, the first display data entered into DDRAM can be output when the return home operation is performed. • 4-bit operation, 8-digit × 1-line display with internal reset The program must set all functions prior to the 4-bit operation (Table 12). When the power is turned on, 8-bit operation is automatically selected and the first write is performed as an 8-bit operation. Since DB0 to DB3 are not connected, a rewrite is then required. However, since one operation is completed in two accesses for 4-bit operation, a rewrite is needed to set the functions (see Table 12). Thus, DB4 to DB7 of the function set instruction is written twice. • 8-bit operation, 8-digit × 2-line display For a 2-line display, the cursor automatically moves from the first to the second line after the 40th digit of the first line has been written. Thus, if there are only 8 characters in the first line, the DDRAM address must be again set after the 8th character is completed. (See Table 13.) Note that the display shift operation is performed for the first and second lines. In the example of Table 13, the display shift is performed when the cursor is on the second line. However, if the shift operation is performed when the cursor is on the first line, both the first and second lines move together. If the shift is repeated, the display of the second line will not move to the first line. The same display will only shift within its own line for the number of times the shift is repeated. Note: When using the internal reset, the electrical characteristics in the Power Supply Conditions Using Internal Reset Circuit table must be satisfied. If not, the HD44780U must be initialized by instructions. See the section, Initializing by Instruction. 39 HD44780U Table 11 8-Bit Operation, 8-Digit × 1-Line Display Example with Internal Reset Instruction Step No. RS 1 Power supply on (the HD44780U is initialized by the internal reset circuit) Initialized. No display. 2 Function set 0 0 0 Sets to 8-bit operation and selects 1-line display and 5 × 8 dot character font. (Number of display lines and character fonts cannot be changed after step #2.) 3 4 5 6 R/W DB7 DB6 DB5 DB4 DB3 DB2 DB1 DB0 Display 0 1 1 0 0 * * Display on/off control 0 0 0 0 0 0 1 1 1 0 Entry mode set 0 0 0 0 0 0 0 1 1 0 Write data to CGRAM/DDRAM 1 0 0 1 0 0 1 0 0 0 Write data to CGRAM/DDRAM 1 0 0 1 0 0 1 0 0 1 7 8 9 10 40 Write data to CGRAM/DDRAM 1 0 0 1 0 0 0 0 Turns on display and cursor. Entire display is in space mode because of initialization. _ Sets mode to increment the address by one and to shift the cursor to the right at the time of write to the DD/CGRAM. Display is not shifted. _ Writes H. DDRAM has already been selected by initialization when the power was turned on. The cursor is incremented by one and shifted to the right. H_ Writes I. HI_ · · · · · · · · · · Entry mode set 0 0 0 Operation 1 0 0 1 0 0 1 1 1 Write data to CGRAM/DDRAM 1 0 0 0 1 0 0 0 0 0 HITACHI_ HITACHI_ ITACHI _ Writes I. Sets mode to shift display at the time of write. Writes a space. HD44780U Table 11 8-Bit Operation, 8-Digit × 1-Line Display Example with Internal Reset (cont) Instruction Step No. RS R/W DB7 DB6 DB5 DB4 DB3 DB2 DB1 DB0 Display 11 Write data to CGRAM/DDRAM 1 0 0 1 0 0 12 13 14 15 16 17 18 19 1 0 1 · · · · · 1 1 1 1 Cursor or display shift 0 0 0 0 0 1 0 0 * * Cursor or display shift 0 0 0 0 0 1 0 0 * * Write data to CGRAM/DDRAM 1 0 0 1 0 0 0 0 1 1 Cursor or display shift 0 0 0 0 0 1 1 1 * * Cursor or display shift 0 0 0 0 0 1 0 1 * * Write data to CGRAM/DDRAM 1 0 0 1 0 0 1 1 0 1 0 0 Writes M. MICROKO_ Writes O. MICROKO _ Shifts only the cursor position to the left. MICROKO _ Shifts only the cursor position to the left. ICROCO _ Writes C over K. The display moves to the left. MICROCO _ Shifts the display and cursor position to the right. MICROCO_ Shifts the display and cursor position to the right. ICROCOM_ Writes M. · · · · · · · · · · Return home 0 0 0 TACHI M_ · · · · · Write data to CGRAM/DDRAM 1 0 0 1 0 0 20 21 1 Operation 0 0 0 1 0 HITACHI _ Returns both display and cursor to the original position (address 0). 41 HD44780U Table 12 4-Bit Operation, 8-Digit × 1-Line Display Example with Internal Reset Instruction Step No. RS 1 Power supply on (the HD44780U is initialized by the internal reset circuit) Initialized. No display. 2 Function set 0 0 0 0 1 0 Sets to 4-bit operation. In this case, operation is handled as 8 bits by initialization, and only this instruction completes with one write. Function set 0 0 0 0 0 0 0 0 1 * 0 * 3 4 5 6 Note: 42 R/W DB7 DB6 DB5 DB4 Display on/off control 0 0 0 0 0 0 1 1 0 1 0 0 Entry mode set 0 0 0 0 0 0 0 1 0 0 0 1 Write data to CGRAM/DDRAM 1 0 0 1 0 0 1 0 1 0 0 0 Display Operation Sets 4-bit operation and selects 1-line display and 5 × 8 dot character font. 4-bit operation starts from this step and resetting is necessary. (Number of display lines and character fonts cannot be changed after step #3.) _ _ H_ The control is the same as for 8-bit operation beyond step #6. Turns on display and cursor. Entire display is in space mode because of initialization. Sets mode to increment the address by one and to shift the cursor to the right at the time of write to the DD/CGRAM. Display is not shifted. Writes H. The cursor is incremented by one and shifts to the right. HD44780U Table 13 8-Bit Operation, 8-Digit × 2-Line Display Example with Internal Reset Instruction Step No. RS 1 Power supply on (the HD44780U is initialized by the internal reset circuit) Initialized. No display. 2 Function set 0 0 0 Sets to 8-bit operation and selects 2-line display and 5 × 8 dot character font. 3 4 5 R/W DB7 DB6 DB5 DB4 DB3 DB2 DB1 DB0 Display 0 1 1 1 0 * * Display on/off control 0 0 0 0 0 0 1 1 1 0 Entry mode set 0 0 0 0 0 0 1 1 0 0 Write data to CGRAM/DDRAM 1 0 0 1 0 0 6 7 8 1 0 0 0 Turns on display and cursor. All display is in space mode because of initialization. _ Sets mode to increment the address by one and to shift the cursor to the right at the time of write to the DD/CGRAM. Display is not shifted. _ Writes H. DDRAM has already been selected by initialization when the power was turned on. The cursor is incremented by one and shifted to the right. H_ · · · · · · · · · · Write data to CGRAM/DDRAM 1 0 0 1 0 0 1 0 0 1 Set DDRAM address 0 0 1 1 0 0 0 0 0 Operation 0 HITACHI_ HITACHI _ Writes I. Sets DDRAM address so that the cursor is positioned at the head of the second line. 43 HD44780U Table 13 8-Bit Operation, 8-Digit × 2-Line Display Example with Internal Reset (cont) Instruction Step No. RS R/W DB7 DB6 DB5 DB4 DB3 DB2 DB1 DB0 Display 9 Write data to CGRAM/DDRAM 1 0 0 1 0 0 10 11 12 13 44 1 0 1 · · · · · HITACHI M_ 1 1 1 1 HITACHI MICROCO_ Entry mode set 0 0 0 0 0 1 1 1 HITACHI MICROCO_ Write data to CGRAM/DDRAM 1 0 0 1 0 0 1 1 0 1 ITACHI ICROCOM_ 0 0 · · · · · Return home 0 0 0 0 0 Writes M. · · · · · Write data to CGRAM/DDRAM 1 0 0 1 0 0 14 15 1 Operation Writes O. Sets mode to shift display at the time of write. Writes M. Display is shifted to the left. The first and second lines both shift at the same time. · · · · · 0 0 0 1 0 _ HITACHI MICROCOM Returns both display and cursor to the original position (address 0). HD44780U Initializing by Instruction If the power supply conditions for correctly operating the internal reset circuit are not met, initialization by instructions becomes necessary. Refer to Figures 23 and 24 for the procedures on 8-bit and 4-bit initializations, respectively. Power on Wait for more than 40 ms after VCC rises to 2.7 V Wait for more than 15 ms after VCC rises to 4.5 V RS R/WDB7 DB6 DB5 DB4 DB3DB2 DB1 DB0 0 0 0 0 1 1 * * * * BF cannot be checked before this instruction. Function set (Interface is 8 bits long.) Wait for more than 4.1 ms RS R/WDB7 DB6 DB5 DB4 DB3 DB2 DB1 DB0 0 0 0 0 1 1 * * * * BF cannot be checked before this instruction. Function set (Interface is 8 bits long.) Wait for more than 100 µs RS R/WDB7 DB6 DB5 DB4 DB3 DB2 DB1 DB0 0 0 0 0 1 1 * * * * BF cannot be checked before this instruction. Function set (Interface is 8 bits long.) BF can be checked after the following instructions. When BF is not checked, the waiting time between instructions is longer than the execution instuction time. (See Table 6.) RS R/WDB7 DB6 DB5 DB4 DB3 DB2 DB1 DB0 0 0 0 0 1 1 N F * * 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 1 I/D S Function set (Interface is 8 bits long. Specify the number of display lines and character font.) The number of display lines and character font cannot be changed after this point. Display off Display clear Entry mode set Initialization ends Figure 23 8-Bit Interface 45 HD44780U Power on Wait for more than 15 ms after VCC rises to 4.5 V RS R/W DB7 DB6 DB5 DB4 0 0 0 0 1 1 Wait for more than 40 ms after VCC rises to 2.7 V BF cannot be checked before this instruction. Function set (Interface is 8 bits long.) Wait for more than 4.1 ms RS R/W DB7 DB6 DB5 DB4 0 0 0 0 1 1 BF cannot be checked before this instruction. Function set (Interface is 8 bits long.) Wait for more than 100 µs RS R/W DB7 DB6 DB5 DB4 0 0 0 0 1 1 BF cannot be checked before this instruction. RS R/W DB7 DB6 DB5 DB4 0 0 0 0 1 0 BF can be checked after the following instructions. When BF is not checked, the waiting time between instructions is longer than the execution instuction time. (See Table 6.) 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 N 0 1 0 0 0 0 0 F 0 0 0 0 0 1 1 0 * * 0 0 0 0 0 0 0 1 0 0 I/D S Function set (Interface is 8 bits long.) Function set (Set interface to be 4 bits long.) Interface is 8 bits in length. Function set (Interface is 4 bits long. Specify the number of display lines and character font.) The number of display lines and character font cannot be changed after this point. Display off Display clear Initialization ends Entry mode set Figure 24 4-Bit Interface 46 HD44780U Absolute Maximum Ratings* Item Symbol Value Unit Notes Power supply voltage (1) VCC–GND –0.3 to +7.0 V 1 Power supply voltage (2) VCC–V5 –0.3 to +13.0 V 1, 2 Input voltage Vt –0.3 to VCC +0.3 V 1 Operating temperature Topr –30 to +75 °C Storage temperature Tstg –55 to +125 °C Note: * 4 If the LSI is used above these absolute maximum ratings, it may become permanently damaged. Using the LSI within the following electrical characteristic limits is strongly recommended for normal operation. If these electrical characteristic conditions are also exceeded, the LSI will malfunction and cause poor reliability. 47 HD44780U DC Characteristics (VCC = 2.7 to 4.5 V, Ta = –30 to +75°C*3) Item Symbol Min Typ Max Unit Input high voltage (1) (except OSC1) VIH1 0.7V CC — VCC V 6 Input low voltage (1) (except OSC1) VIL1 –0.3 — 0.55 V 6 Input high voltage (2) (OSC1) VIH2 0.7V CC — VCC V 15 Input low voltage (2) (OSC1) VIL2 — — 0.2V CC V 15 Output high voltage (1) VOH1 (DB0–DB7) 0.75V CC — — V –I OH = 0.1 mA 7 Output low voltage (1) (DB0–DB7) — — 0.2V CC V I OL = 0.1 mA 7 Output high voltage (2) VOH2 (except DB0–DB7) 0.8V CC — — V –I OH = 0.04 mA 8 Output low voltage (2) (except DB0–DB7) VOL2 — — 0.2V CC V I OL = 0.04 mA 8 Driver on resistance (COM) RCOM — 2 20 kΩ ±Id = 0.05 mA, VLCD = 4 V 13 Driver on resistance (SEG) RSEG — 2 30 kΩ ±Id = 0.05 mA, VLCD = 4 V 13 Input leakage current I LI –1 — 1 µA VIN = 0 to VCC 9 Pull-up MOS current (DB0–DB7, RS, R/W) –I p 10 50 120 µA VCC = 3 V Power supply current I CC — 150 300 µA Rf oscillation, external clock VCC = 3 V, f OSC = 270 kHz LCD voltage VLCD1 3.0 — 11.0 V VCC–V5, 1/5 bias 16 VLCD2 3.0 — 11.0 V VCC–V5, 1/4 bias 16 Note: 48 * VOL1 Test Condition Notes* Refer to the Electrical Characteristics Notes section following these tables. 10, 14 HD44780U AC Characteristics (VCC = 2.7 to 4.5 V, Ta = –30 to +75°C*3) Clock Characteristics Item Symbol Min Typ Max Unit External External clock frequency clock External clock duty operation External clock rise time f cp 125 250 350 kHz Duty 45 50 55 % t rcp — — 0.2 µs t fcp — — 0.2 µs 190 270 350 kHz External clock fall time Rf Clock oscillation frequency f OSC oscillation Note: * Test Condition Note* 11 Rf = 75 kΩ, VCC = 3 V 12 Refer to the Electrical Characteristics Notes section following these tables. Bus Timing Characteristics Write Operation Item Symbol Min Typ Max Unit Test Condition Enable cycle time t cycE 1000 — — ns Figure 25 Enable pulse width (high level) PWEH 450 — — Enable rise/fall time t Er, t Ef — — 25 Address set-up time (RS, R/W to E) t AS 60 — — Address hold time t AH 20 — — Data set-up time t DSW 195 — — Data hold time tH 10 — — Item Symbol Min Typ Max Unit Test Condition Enable cycle time t cycE 1000 — — ns Figure 26 Enable pulse width (high level) PWEH 450 — — Enable rise/fall time t Er, t Ef — — 25 Address set-up time (RS, R/W to E) t AS 60 — — Address hold time t AH 20 — — Data delay time t DDR — — 360 Data hold time t DHR 5 — — Read Operation 49 HD44780U Interface Timing Characteristics with External Driver Item Symbol Min Typ Max Unit Test Condition High level t CWH 800 — — ns Figure 27 Low level t CWL 800 — — Clock set-up time t CSU 500 — — Data set-up time t SU 300 — — Data hold time t DH 300 — — M delay time t DM –1000 — 1000 Clock rise/fall time t ct — — 200 Clock pulse width Power Supply Conditions Using Internal Reset Circuit Item Symbol Min Typ Max Unit Test Condition Power supply rise time t rCC 0.1 — 10 ms Figure 28 Power supply off time t OFF 1 — — 50 HD44780U DC Characteristics (VCC = 4.5 to 5.5 V, Ta = –30 to +75°C*3) Item Symbol Min Typ Max Unit Input high voltage (1) (except OSC1) VIH1 2.2 — VCC V 6 Input low voltage (1) (except OSC1) VIL1 –0.3 — 0.6 V 6 Input high voltage (2) (OSC1) VIH2 VCC–1.0 — VCC V 15 Input low voltage (2) (OSC1) VIL2 — — 1.0 V 15 Output high voltage (1) VOH1 (DB0–DB7) 2.4 — — V –I OH = 0.205 mA 7 Output low voltage (1) (DB0–DB7) — — 0.4 V I OL = 1.2 mA 7 Output high voltage (2) VOH2 (except DB0–DB7) 0.9 VCC — — V –I OH = 0.04 mA 8 Output low voltage (2) (except DB0–DB7) VOL2 — — 0.1 VCC V I OL = 0.04 mA 8 Driver on resistance (COM) RCOM — 2 20 kΩ ±Id = 0.05 mA, VLCD = 4 V 13 Driver on resistance (SEG) RSEG — 2 30 kΩ ±Id = 0.05 mA, VLCD = 4 V 13 Input leakage current I LI –1 — 1 µA VIN = 0 to VCC 9 Pull-up MOS current (DB0–DB7, RS, R/W) –I p 50 125 250 µA VCC = 5 V Power supply current I CC — 350 600 µA Rf oscillation, external clock VCC = 5 V, f OSC = 270 kHz 10, 14 LCD voltage VLCD1 3.0 — 11.0 V VCC–V5, 1/5 bias 16 VLCD2 3.0 — 11.0 V VCC–V5, 1/4 bias 16 Note: * VOL1 Test Condition Notes* Refer to the Electrical Characteristics Notes section following these tables. 51 HD44780U AC Characteristics (VCC = 4.5 to 5.5 V, Ta = –30 to +75°C*3) Clock Characteristics Item Symbol Min Typ Max Unit External External clock frequency clock External clock duty operation External clock rise time f cp 125 250 350 kHz 11 Duty 45 50 55 % 11 t rcp — — 0.2 µs 11 t fcp — — 0.2 µs 11 190 270 350 kHz External clock fall time Rf Clock oscillation frequency f OSC oscillation Note: * Test Condition Notes* Rf = 91 kΩ VCC = 5.0 V 12 Refer to the Electrical Characteristics Notes section following these tables. Bus Timing Characteristics Write Operation Item Symbol Min Typ Max Unit Test Condition Enable cycle time t cycE 500 — — ns Figure 25 Enable pulse width (high level) PWEH 230 — — Enable rise/fall time t Er, t Ef — — 20 Address set-up time (RS, R/W to E) t AS 40 — — Address hold time t AH 10 — — Data set-up time t DSW 80 — — Data hold time tH 10 — — Item Symbol Min Typ Max Unit Test Condition Enable cycle time t cycE 500 — — ns Figure 26 Enable pulse width (high level) PWEH 230 — — Enable rise/fall time t Er, t Ef — — 20 Address set-up time (RS, R/W to E) t AS 40 — — Address hold time t AH 10 — — Data delay time t DDR — — 160 Data hold time t DHR 5 — — Read Operation 52 HD44780U Interface Timing Characteristics with External Driver Item Symbol Min Typ Max Unit Test Condition High level t CWH 800 — — ns Figure 27 Low level t CWL 800 — — Clock set-up time t CSU 500 — — Data set-up time t SU 300 — — Data hold time t DH 300 — — M delay time t DM –1000 — 1000 Clock rise/fall time t ct — — 100 Clock pulse width Power Supply Conditions Using Internal Reset Circuit Item Symbol Min Typ Max Unit Test Condition Power supply rise time t rCC 0.1 — 10 ms Figure 28 Power supply off time t OFF 1 — — 53 HD44780U Electrical Characteristics Notes 1. All voltage values are referred to GND = 0 V. VCC B V1 A = VCC –V5 B = VCC –V1 A ≥ 1.5 V B ≤ 0.25 × A A V5 The conditions of V1 and V5 voltages are for proper operation of the LSI and not for the LCD output level. The LCD drive voltage condition for the LCD output level is specified as LCD voltage VLCD. 2. VCC ≥ V1 ≥ V2 ≥ V3 ≥ V4 ≥ V5 must be maintained. 3. For die products, specified at 75°C. 4. For die products, specified by the die shipment specification. 5. The following four circuits are I/O pin configurations except for liquid crystal display output. Input pin Pin: E (MOS without pull-up) Output pin Pins: CL1, CL2, M, D Pins: RS, R/W (MOS with pull-up) VCC VCC PMOS PMOS VCC PMOS PMOS NMOS NMOS (pull up MOS) NMOS I/O Pin Pins: DB0 –DB7 (MOS with pull-up) VCC (pull-up MOS) VCC (input circuit) PMOS PMOS Input enable NMOS VCC NMOS PMOS Output enable Data NMOS (output circuit) (tristate) 54 HD44780U 6. Applies to input pins and I/O pins, excluding the OSC1 pin. 7. Applies to I/O pins. 8. Applies to output pins. 9. Current flowing through pull–up MOSs, excluding output drive MOSs. 10. Input/output current is excluded. When input is at an intermediate level with CMOS, the excessive current flows through the input circuit to the power supply. To avoid this from happening, the input level must be fixed high or low. 11. Applies only to external clock operation. Th Oscillator Open Tl OSC1 0.7 VCC 0.5 VCC 0.3 VCC OSC2 t rcp Duty = t fcp Th × 100% Th + Tl 12. Applies only to the internal oscillator operation using oscillation resistor Rf. OSC1 Rf OSC2 R f : 75 k Ω ± 2% (when VCC = 3 V) R f : 91 k Ω ± 2% (when VCC = 5 V) Since the oscillation frequency varies depending on the OSC1 and OSC2 pin capacitance, the wiring length to these pins should be minimized. VCC = 5 V 500 500 400 300 (270) max. 200 typ. min. 50 (91)100 R f (k Ω) 150 f OSC (kHz) f OSC (kHz) 400 100 VCC = 3 V 300 (270) max. 200 100 typ. 50 (75) 100 min. 150 R f (k Ω) 55 HD44780U 13. RCOM is the resistance between the power supply pins (VCC, V1, V4, V5) and each common signal pin (COM1 to COM16). RSEG is the resistance between the power supply pins (VCC, V2, V3, V5) and each segment signal pin (SEG1 to SEG40). 14. The following graphs show the relationship between operation frequency and current consumption. VCC = 3 V 1.8 1.8 1.6 1.6 1.4 1.4 1.2 1.2 1.0 max. 0.8 typ. 0.6 ICC (mA) ICC (mA) VCC = 5 V 1.0 0.8 0.6 0.4 0.4 0.2 0.2 0.0 0 100 200 300 fOSC or fcp (kHz) 400 500 0.0 max. typ. 0 100 200 300 400 500 fOSC or fcp (kHz) 15. Applies to the OSC1 pin. 16. Each COM and SEG output voltage is within ±0.15 V of the LCD voltage (V CC, V1, V2, V3, V4, V5) when there is no load. 56 HD44780U Load Circuits Data Bus DB0 to DB7 VCC = 5 V For VCC = 4.5 to 5.5 V For VCC = 2.7 to 4.5 V 3.9 k Ω Test point 90 pF 11 k Ω Test point IS2074 H diodes 50 pF External Driver Control Signals: CL1, CL2, D, M Test point 30 pF 57 HD44780U Timing Characteristics VIH1 VIL1 RS VIH1 VIL1 tAS R/W tAH VIL1 VIL1 PWEH tAH tEf VIH1 VIL1 E VIH1 VIL1 tEr tH tDSW VIH1 VIL1 DB0 to DB7 VIL1 VIH1 VIL1 Valid data tcycE Figure 25 Write Operation VIH1 VIL1 RS VIH1 VIL1 tAS tAH VIH1 R/W VIH1 PWEH tAH tEf VIH1 VIL1 E VIH1 VIL1 VIL1 tEr tDHR tDDR DB0 to DB7 VOH1 VOL1 * Valid data tcycE Note: * VOL1 is assumed to be 0.8 V at 2 MHz operation. Figure 26 Read Operation 58 VOH1 * VOL1 HD44780U tct VOH2 CL1 VOH2 tCWH tCSU CL2 VOL2 tCWH VOH2 VOL2 tCWL tct tCSU VOH2 VOL2 D tDH tSU VOH2 M t DM Figure 27 Interface Timing with External Driver VCC 2.7 V/4.5 V*2 0.2 V 0.2 V 0.2 V tOFF*1 trcc 0.1 ms ≤ trcc ≤ 10 ms tOFF ≥ 1 ms Notes: 1. tOFF compensates for the power oscillation period caused by momentary power supply oscillations. 2. Specified at 4.5 V for 5-V operation, and at 2.7 V for 3-V operation. 3. For if 4.5 V is not reached during 5-V operation, the internal reset circuit will not operate normally. In this case, the LSI must be initialized by software. (Refer to the Initializing by Instruction section.) Figure 28 Internal Power Supply Reset 59 HD44780U Cautions 1. Hitachi neither warrants nor grants licenses of any rights of Hitachi’s or any third party’s patent, copyright, trademark, or other intellectual property rights for information contained in this document. Hitachi bears no responsibility for problems that may arise with third party’s rights, including intellectual property rights, in connection with use of the information contained in this document. 2. Products and product specifications may be subject to change without notice. Confirm that you have received the latest product standards or specifications before final design, purchase or use. 3. Hitachi makes every attempt to ensure that its products are of high quality and reliability. However, contact Hitachi’s sales office before using the product in an application that demands especially high quality and reliability or where its failure or malfunction may directly threaten human life or cause risk of bodily injury, such as aerospace, aeronautics, nuclear power, combustion control, transportation, traffic, safety equipment or medical equipment for life support. 4. Design your application so that the product is used within the ranges guaranteed by Hitachi particularly for maximum rating, operating supply voltage range, heat radiation characteristics, installation conditions and other characteristics. Hitachi bears no responsibility for failure or damage when used beyond the guaranteed ranges. Even within the guaranteed ranges, consider normally foreseeable failure rates or failure modes in semiconductor devices and employ systemic measures such as failsafes, so that the equipment incorporating Hitachi product does not cause bodily injury, fire or other consequential damage due to operation of the Hitachi product. 5. This product is not designed to be radiation resistant. 6. No one is permitted to reproduce or duplicate, in any form, the whole or part of this document without written approval from Hitachi. 7. Contact Hitachi’s sales office for any questions regarding this document or Hitachi semiconductor products. Hitachi, Ltd. Semiconductor & Integrated Circuits. Nippon Bldg., 2-6-2, Ohte-machi, Chiyoda-ku, Tokyo 100-0004, Japan Tel: Tokyo (03) 3270-2111 Fax: (03) 3270-5109 URL NorthAmerica : http:semiconductor.hitachi.com/ Europe : http://www.hitachi-eu.com/hel/ecg Asia (Singapore) : http://www.has.hitachi.com.sg/grp3/sicd/index.htm Asia (Taiwan) : http://www.hitachi.com.tw/E/Product/SICD_Frame.htm Asia (HongKong) : http://www.hitachi.com.hk/eng/bo/grp3/index.htm Japan : http://www.hitachi.co.jp/Sicd/indx.htm For further information write to: Hitachi Semiconductor (America) Inc. 179 East Tasman Drive, San Jose,CA 95134 Tel: <1> (408) 433-1990 Fax: <1>(408) 433-0223 Hitachi Europe GmbH Electronic components Group Dornacher Straße 3 D-85622 Feldkirchen, Munich Germany Tel: <49> (89) 9 9180-0 Fax: <49> (89) 9 29 30 00 Hitachi Europe Ltd. Electronic Components Group. Whitebrook Park Lower Cookham Road Maidenhead Berkshire SL6 8YA, United Kingdom Tel: <44> (1628) 585000 Fax: <44> (1628) 778322 Hitachi Asia Pte. Ltd. 16 Collyer Quay #20-00 Hitachi Tower Singapore 049318 Tel: 535-2100 Fax: 535-1533 Hitachi Asia Ltd. Taipei Branch Office 3F, Hung Kuo Building. No.167, Tun-Hwa North Road, Taipei (105) Tel: <886> (2) 2718-3666 Fax: <886> (2) 2718-8180 Hitachi Asia (Hong Kong) Ltd. Group III (Electronic Components) 7/F., North Tower, World Finance Centre, Harbour City, Canton Road, Tsim Sha Tsui, Kowloon, Hong Kong Tel: <852> (2) 735 9218 Fax: <852> (2) 730 0281 Telex: 40815 HITEC HX Copyright © Hitachi, Ltd., 1998. All rights reserved. Printed in Japan. 60 ANEXO F - Datasheet do CI L298 L298 .. .. . DUAL FULL-BRIDGE DRIVER OPERATING SUPPLY VOLTAGE UP TO 46 V TOTAL DC CURRENT UP TO 4 A LOW SATURATION VOLTAGE OVERTEMPERATURE PROTECTION LOGICAL ”0” INPUT VOLTAGE UP TO 1.5 V (HIGH NOISE IMMUNITY) DESCRIPTION The L298 is an integrated monolithic circuit in a 15lead Multiwatt and PowerSO20 packages. It is a high voltage, high current dual full-bridge driver designed to accept standardTTL logic levels and drive inductive loads such as relays, solenoids, DC and stepping motors. Two enableinputs are provided to enableor disable the deviceindependentlyof the input signals. The emitters of the lower transistors of each bridge are connected together and the corresponding external terminal can be used for the con- Multiw att15 PowerSO20 O RDERING NUMBERS : L298N (Multiwatt Vert.) L298HN (Multiwatt Horiz.) L298P (PowerSO20) nectionof an externalsensing resistor. Anadditional supply input is provided so that the logic works at a lower voltage. BLOCK DIAGRAM Jenuary 2000 1/13 L298 ABSOLUTE MAXIMUM RATINGS Symb ol Parameter Value Unit VS Power Supply 50 V V SS Logic Supply Voltage 7 V –0.3 to 7 V 3 2.5 2 A A A VI,Ven IO Vsens Input and Enable Voltage Peak Output Current (each Channel) – Non Repetitive (t = 100µs) –Repetitive (80% on –20% off; ton = 10ms) –DC Operation Sensing Voltage –1 to 2.3 V 25 W P tot Total Power Dissipation (Tcase = 75°C) Top Junction Operating Temperature –25 to 130 °C Storage and Junction Temperature –40 to 150 °C Tstg, Tj PIN CONNECTIONS (top view) Multiwatt15 15 CURRENT SENSING B 14 OUTPUT 4 13 OUTPUT 3 12 INPUT 4 11 ENABLE B 10 INPUT 3 9 LOGIC SUPPLY VOLTAGE VSS 8 GND 7 INPUT 2 6 ENABLE A 5 INPUT 1 4 SUPPLY VOLTAGE VS 3 OUTPUT 2 2 OUTPUT 1 1 CURRENT SENSING A TAB CONNECTED TO PIN 8 D95IN240A GND 1 20 GND Sense A 2 19 Sense B N.C. 3 18 N.C. 17 Out 4 16 Out 3 Out 1 4 Out 2 5 VS 6 15 Input 4 Input 1 7 14 Enable B Enable A 8 13 Input 3 Input 2 9 12 VSS 10 11 GND GND PowerSO20 D95IN239 THERMAL DATA Symb ol Po werSO20 Mu ltiwatt15 Unit Rth j-case Thermal Resistance Junction-case Parameter Max. – 3 °C/W Rth j-amb Thermal Resistance Junction-ambient Max. 13 (*) 35 °C/W (*) Mounted on aluminum substrate 2/13 L298 PIN FUNCTIONS (refer to the block diagram) MW.15 Po werSO Name 1;15 2;19 Sense A; Sense B Between this pin and ground is connected the sense resistor to control the current of the load. Fun ction 2;3 4;5 Out 1; Out 2 Outputs of the Bridge A; the current that flows through the load connected between these two pins is monitored at pin 1. 4 6 VS Supply Voltage for the Power Output Stages. A non-inductive 100nF capacitor must be connected between this pin and ground. 5;7 7;9 Input 1; Input 2 6;11 8;14 Enable A; Enable B TTL Compatible Inputs of the Bridge A. 8 1,10,11,20 GND Ground. 9 12 VSS Supply Voltage for the Logic Blocks. A100nF capacitor must be connected between this pin and ground. 10; 12 13;15 Input 3; Input 4 13; 14 16;17 Out 3; Out 4 – 3;18 N.C. TTL Compatible Enable Input: the L state disables the bridge A (enable A) and/or the bridge B (enable B). TTL Compatible Inputs of the Bridge B. Outputs of the Bridge B. The current that flows through the load connected between these two pins is monitored at pin 15. Not Connected ELECTRICAL CHARACTERISTICS (VS = 42V; VSS = 5V, Tj = 25°C; unless otherwise specified) Symbol Parameter VS Supply Voltage (pin 4) VSS Logic Supply Voltage (pin 9) Test Co nditions Operative Condition Min . 4.5 Ven = H; IL = 0 Typ . VIH +2.5 Unit 46 V 5 7 V 13 50 22 70 mA mA 4 mA 24 7 36 12 mA mA 6 mA 1.5 V IS Quiescent Supply Current (pin 4) ISS Quiescent Current from VSS (pin 9) Ven = H; IL = 0 V iL Input Low Voltage (pins 5, 7, 10, 12) –0.3 ViH Input High Voltage (pins 5, 7, 10, 12) 2.3 VSS V IiL Low Voltage Input Current (pins 5, 7, 10, 12) Vi = L –10 µA IiH High Voltage Input Current (pins 5, 7, 10, 12) Vi = H ≤ VSS –0.6V 100 µA Ven = L Vi = L Vi = H Max. Vi = X Ven = L Vi = L Vi = H Vi = X 30 Ven = L Enable Low Voltage (pins 6, 11) –0.3 1.5 V Ven = H Enable High Voltage (pins 6, 11) 2.3 VSS V Ien = L Low Voltage Enable Current (pins 6, 11) Ven = L –10 µA Ien = H High Voltage Enable Current (pins 6, 11) Ven = H ≤ VSS –0.6V 30 100 µA 0.95 1.35 2 1.7 2.7 V V 1.2 1.7 1.6 2.3 V V VCEsat (H) Source Saturation Voltage IL = 1A IL = 2A VCEsat (L) Sink Saturation Voltage IL = 1A IL = 2A (5) (5) 0.85 IL = 1A IL = 2A (5) (5) 1.80 3.2 4.9 V V –1 (1) 2 V VCEsat Total Drop Vsens Sensing Voltage (pins 1, 15) 3/13 L298 ELECTRICAL CHARACTERISTICS (continued) Symbol Parameter Test Co nditions Min . Typ . Max. Unit T1 (Vi) Source Current Turn-off Delay 0.5 V i to 0.9 I L (2); (4) 1.5 µs T2 (Vi) Source Current Fall Time 0.9 IL to 0.1 IL (2); (4) 0.2 µs T3 (Vi) Source Current Turn-on Delay 0.5 V i to 0.1 I L (2); (4) 2 µs T4 (Vi) Source Current Rise Time 0.1 IL to 0.9 IL (2); (4) 0.7 µs T5 (Vi) Sink Current Turn-off Delay 0.5 V i to 0.9 I L (3); (4) 0.7 µs T6 (Vi) Sink Current Fall Time 0.9 IL to 0.1 IL (3); (4) 0.25 µs T7 (Vi) Sink Current Turn-on Delay 0.5 V i to 0.9 I L (3); (4) 1.6 µs T8 (Vi) Sink Current Rise Time 0.1 IL to 0.9 IL (3); (4) 0.2 µs fc (Vi) Commutation Frequency IL = 2A T1 (Ven) Source Current Turn-off Delay 0.5 V en to 0.9 IL 25 T2 (Ven) Source Current Fall Time 0.9 IL to 0.1 IL T3 (Ven) Source Current Turn-on Delay 0.5 V en to 0.1 IL T4 (Ven) Source Current Rise Time 0.1 IL to 0.9 IL T5 (Ven) Sink Current Turn-off Delay 0.5 V en to 0.9 IL (2); (4) (2); (4) (2); (4) (2); (4) T6 (Ven) Sink Current Fall Time 0.9 IL to 0.1 IL T7 (Ven) Sink Current Turn-on Delay 0.5 V en to 0.9 IL T8 (Ven) Sink Current Rise Time 0.1 IL to 0.9 IL (3); (4) (3); (4) (3); (4) (3); (4) 40 µs 1 µs 0.3 µs 0.4 µs 2.2 µs 0.35 µs 0.25 µs 0.1 µs 1) 1)Sensing voltage can be –1 V for t ≤ 50 µsec; in steady state V sens min ≥ – 0.5 V. 2) See fig. 2. 3) See fig. 4. 4) The load must be a pure resistor. Figure 1 : Typical Saturation Voltage vs. Output Current. Figure 2 : Switching Times Test Circuits. Note : For INPUT Switching, set EN = H For ENABLESwitching, set IN = H 4/13 KHz 3 L298 Figure 3 : Source Current Delay Times vs. Input or Enable Switching. Figure 4 : Switching Times Test Circuits. Note : For INPUT Switching, set EN = H For ENABLE Switching, set IN = L 5/13 L298 Figure 5 : Sink Current Delay Times vs. Input 0 V Enable Switching. Figure 6 : Bidirectional DC Motor Control. In pu ts Ven = H Ven = L L = Low 6/13 Fu nctio n C=H;D=L Forward C =L; D= H Reverse C=D Fast Motor Stop C=X;D=X Free Running Motor Stop H = High X = Don’t care L298 Figure 7 : For higher currents, outputs can be paralleled. Take care to parallel channel 1 with channel 4 and channel 2 with channel 3. APPLICATION INFORMATION (Refer to the block diagram) 1.1. POWER OUTPUT STAGE Each input must be connected to the source of the driving signals by means of a very short path. TheL298integratestwo poweroutputstages(A ; B). The power output stage is a bridge configuration Turn-On and Turn-Off : Before to Turn-ON the Supand its outputs can drive an inductive load in comply Voltageand beforeto Turnit OFF, the Enableinmon or differenzialmode, dependingon the state of put must be driven to the Low state. the inputs. The current that flows through the load 3. APPLICATIONS comes out from the bridge at the sense output : an Fig 6 shows a bidirectional DC motor control Scheexternal resistor (RSA ; RSB.) allows to detect the inmatic Diagram for which only one bridge is needed. tensity of this current. The external bridge of diodes D1 to D4 is made by 1.2. INPUT STAGE four fast recovery elements (trr ≤ 200 nsec) that Each bridge is driven by means of four gates the inmust be chosen of a VF as low as possible at the put of which are In1 ; In2 ; EnA and In3 ; In4 ; EnB. worst case of the load current. The In inputs set the bridge state when The En input The sense outputvoltage can be used to control the is high ; a lowstate of the En inputinhibitsthe bridge. current amplitude by chopping the inputs, or to proAll the inputs are TTL compatible. vide overcurrent protection by switching low the enable input. 2. SUGGESTIONS The brake function (Fast motor stop) requires that A non inductive capacitor, usually of 100 nF, must the Absolute Maximum Rating of 2 Amps must be foreseen between both Vs and Vss, to ground, never be overcome. as near as possible to GND pin. When the large capacitor of the power supply is too far from the IC, a When the repetitive peak current needed from the second smaller one must be foreseen near the load is higher than 2 Amps, a paralleled configuraL298. tion can be chosen (See Fig.7). The sense resistor, not of a wire wound type, must An external bridge of diodes are required when inbe grounded near the negative pole of Vs that must ductive loads are driven and when the inputs of the be near the GND pin of the I.C. IC are chopped; Shottkydiodeswould be preferred. 7/13 L298 This solution can drive until 3 Amps In DC operation and until 3.5 Amps of a repetitive peak current. OnFig 8 it is shownthe driving ofa twophasebipolar stepper motor ; the needed signals to drive the inputs of the L298 are generated, in this example, from the IC L297. Fig 9 shows an example of P.C.B. designed for the application of Fig 8. Fig 10 shows a second two phase bipolar stepper motor control circuit where the current is controlled by the I.C. L6506. Figure 8 : Two Phase Bipolar Stepper Motor Circuit. This circuit drives bipolar stepper motors with winding currents up to 2 A. The diodes are fast 2 A types. RS1 = RS2 = 0.5 Ω D1 to D8 = 2 A Fast diodes 8/13 { VF ≤ 1.2 V @ I = 2 A trr ≤ 200 ns L298 Figure 9 : Suggested Printed Circuit Board Layout for the Circuit of fig. 8 (1:1 scale). Figure 10 : Two Phase Bipolar Stepper Motor Control Circuit by Using the Current Controller L6506. RR and Rsense depend from the load current 9/13 L298 mm DIM. MIN. TYP. inch MAX. MIN. TYP. MAX. A 5 B 2.65 0.104 C 1.6 0.063 D 0.197 1 0.039 E 0.49 0.55 0.019 F 0.66 0.75 0.026 G 1.02 1.27 1.52 0.040 0.050 0.060 G1 17.53 17.78 18.03 0.690 0.700 0.710 H1 19.6 0.022 0.030 0.772 H2 20.2 0.795 L 21.9 22.2 22.5 0.862 0.874 0.886 L1 21.7 22.1 22.5 0.854 0.870 0.886 L2 17.65 18.1 0.695 L3 17.25 17.5 17.75 0.679 0.689 0.699 L4 10.3 10.7 10.9 0.406 0.421 0.429 L7 2.65 2.9 0.104 0.713 0.114 M 4.25 4.55 4.85 0.167 0.179 0.191 M1 4.63 5.08 5.53 0.182 0.200 0.218 S 1.9 2.6 0.075 S1 1.9 2.6 0.075 0.102 Dia1 3.65 3.85 0.144 0.152 10/13 OUTLINE AND MECHANICAL DATA 0.102 Multiwatt15 V L298 mm DIM. MIN. TYP. inch MAX. MIN. TYP. MAX. A 5 0.197 B 2.65 0.104 C 1.6 0.063 E 0.49 0.55 0.019 0.022 F 0.66 0.75 0.026 0.030 G 1.14 1.27 1.4 0.045 0.050 0.055 G1 17.57 17.78 17.91 0.692 0.700 0.705 H1 19.6 0.772 H2 20.2 0.795 L 20.57 0.810 L1 18.03 0.710 L2 2.54 0.100 L3 17.25 17.5 17.75 0.679 0.689 0.699 L4 10.3 10.7 10.9 0.406 0.421 0.429 L5 5.28 L6 OUTLINE AND MECHANICAL DATA 0.208 0.094 2.38 L7 2.65 2.9 0.104 0.114 S 1.9 2.6 0.075 0.102 S1 1.9 2.6 0.075 0.102 Dia1 3.65 3.85 0.144 0.152 Multiwatt15 H 11/13 L298 DIM. A a1 a2 a3 b c D (1) D1 E e e3 E1 (1) E2 E3 G H h L N S T MIN. mm TYP. 0.1 0 0.4 0.23 15.8 9.4 13.9 MAX. 3.6 0.3 3.3 0.1 0.53 0.32 16 9.8 14.5 MIN. 0.004 0.000 0.016 0.009 0.622 0.370 0.547 1.27 11.43 10.9 inch TYP. 0.050 0.450 11.1 0.429 2.9 6.2 0.228 0.1 0.000 15.9 0.610 1.1 1.1 0.031 10° (max.) 8° (max.) 5.8 0 15.5 0.8 OUTLINE AND MECHANICAL DATA MAX. 0.142 0.012 0.130 0.004 0.021 0.013 0.630 0.386 0.570 10 0.437 0.114 0.244 0.004 0.626 0.043 0.043 JEDEC MO-166 0.394 PowerSO20 (1) ”D and F” do not include mold flash or protrusions. - Mold flash or protrusions shall not exceed 0.15 mm (0.006”). - Critical dimensions: ”E”, ”G” and ”a3” N R N a2 b A e DETAIL A c a1 DETAIL B E e3 H DETAIL A lead D slug a3 DETAIL B 20 11 0.35 Gage Plane -C- S SEATING PLANE L G E2 E1 BOTTOM VIEW T E3 1 h x 45 12/13 10 PSO20MEC C (COPLANARITY) D1 L298 Information furnished is believed to be accurate and reliable. However, STMicroelectronics assumes no responsibility for the consequences of use of such information nor for any infringement of patents or other rights of third parties which may result from its use. No license is granted by implication or otherwise under any patent or patent rights of STMicroelectronics. Specification mentioned in this publication are subject to change without notice. This publication supersedes and replaces all information previously supplied. STMicroelectronics products are not authorized for use as critical components in life support devices or systems without express written approval of STMicroelectronics. The ST logo is a registered trademark of STMicroelectronics 2000 STMicroelectronics – Printed in Italy – All Rights Reserved STMicroelectronics GROUP OF COMPANIES Australia - Brazil - China - Finland - France - Germany - Hong Kong - India - Italy - Japan - Malaysia - Malta - Morocco Singapore - Spain - Sweden - Switzerland - United Kingdom - U.S.A. http://www.st.com 13/13 ANEXO G - Datasheet do regulador de tensão LM7805 LM78XX/LM78XXA 3-Terminal 1A Positive Voltage Regulator Features • • • • • General Description Output Current up to 1A Output Voltages of 5, 6, 8, 9, 10, 12, 15, 18, 24 Thermal Overload Protection Short Circuit Protection Output Transistor Safe Operating Area Protection The LM78XX series of three terminal positive regulators are available in the TO-220 package and with several fixed output voltages, making them useful in a wide range of applications. Each type employs internal current limiting, thermal shut down and safe operating area protection, making it essentially indestructible. If adequate heat sinking is provided, they can deliver over 1A output current. Although designed primarily as fixed voltage regulators, these devices can be used with external components to obtain adjustable voltages and currents. Ordering Information Product Number Output Voltage Tolerance Package Operating Temperature LM7805CT ±4% TO-220 -40 C to +125 C LM7806CT LM7808CT LM7809CT LM7810CT LM7812CT LM7815CT LM7818CT LM7824CT LM7805ACT 0 C to +125 C ±2% LM7806ACT LM7808ACT LM7809ACT LM7810ACT LM7812ACT LM7815ACT LM7818ACT LM7824ACT © 2010 Fairchild Semiconductor Corporation LM78XX/LM78XXA Rev. 1.0 www.fairchildsemi.com 1 LM78XX/LM78XXA — 3-Terminal 1A Positive Voltage Regulator April 2010 LM78XX/LM78XXA 3-Terminal 1A Positive Voltage Regulator Block Diagram Input Series Pass Element 1 Current Generator Starting Circuit Output 3 SOA Protection Reference Voltage Error Amplifier Thermal Protection GND 2 Figure 1. Pin Assignment TO-220 GND 1. Input 2. GND 3. Output 1 Figure 2. Absolute Maximum Ratings Absolute maximum ratings are those values beyond which damage to the device may occur. The datasheet specifications should be met, without exception, to ensure that the system design is reliable over its power supply, temperature, and output/input loading variables. Fairchild does not recommend operation outside datasheet specifications. Symbol VI Parameter Input Voltage Value Unit VO = 5V to 18V 35 V VO = 24V 40 V RθJC Thermal Resistance Junction-Cases (TO-220) 5 °C/W RθJA Thermal Resistance Junction-Air (TO-220) 65 °C/W TOPR Operating Temperature Range -40 to +125 °C TSTG LM78xx LM78xxA Storage Temperature Range -65 to +150 2 LM78XX/LM78XXA Rev. 1.0 0 to +125 °C www.fairchildsemi.com Refer to the test circuits. -40°C < TJ < 125°C, IO = 500mA, VI = 10V, CI = 0.1µF, unless otherwise specified. Symbol VO Regline Parameter Output Voltage Line Regulation(1) Min. Typ. Max. Unit TJ = +25°C Conditions 4.8 5.0 5.2 V 5mA ≤ IO ≤ 1A, PO ≤ 15W, VI = 7V to 20V 4.75 5.0 5.25 VO = 7V to 25V – 4.0 100 VI = 8V to 12V – 1.6 50.0 IO = 5mA to 1.5A – 9.0 100 TJ = +25°C Regulation(1) TJ = +25°C Quiescent Current TJ = +25°C Regload Load IO = 250mA to 750mA IQ ∆IQ ∆VO/∆T VN RR VDROP mV mV – 4.0 50.0 – 5.0 8.0 mA Quiescent Current Change IO = 5mA to 1A – 0.03 0.5 mA VI = 7V to 25V – 0.3 1.3 IO = 5mA – -0.8 – mV/°C f = 10Hz to 100kHz, TA = +25°C – 42.0 – µV/VO 62.0 73.0 – dB IO = 1A, TJ = +25°C – 2.0 – V f = 1kHz – 15.0 – mΩ Output Voltage Drift(2) Output Noise Voltage Ripple Rejection(2) Dropout Voltage Resistance(2) f = 120Hz, VO = 8V to 18V rO Output ISC Short Circuit Current VI = 35V, TA = +25°C – 230 – mA IPK Peak Current(2) TJ = +25°C – 2.2 – A Notes: 1. Load and line regulation are specified at constant junction temperature. Changes in VO due to heating effects must be taken into account separately. Pulse testing with low duty is used. 2. These parameters, although guaranteed, are not 100% tested in production. 3 LM78XX/LM78XXA Rev. 1.0 www.fairchildsemi.com LM78XX/LM78XXA 3-Terminal 1A Positive Voltage Regulator Electrical Characteristics (LM7805) Refer to the test circuits. -40°C < TJ < 125°C, IO = 500mA, VI = 11V, CI = 0.33µF, CO = 0.1µF, unless otherwise specified. Symbol VO Parameter Conditions Output Voltage Min Typ. Max. Unit TJ = +25°C 5.75 6.0 6.25 V 5mA ≤ IO ≤ 1A, PO ≤ 15W, VI = 8.0V to 21V 5.7 6.0 6.3 VI = 8V to 25V – 5.0 120 VI = 9V to 13V – 1.5 60.0 IO = 5mA to 1.5A – 9.0 120 IO = 250mA to 750mA – 3.0 60.0 Regline Line Regulation(3) TJ = +25°C Regload Load Regulation(3) TJ = +25°C mV mV IQ Quiescent Current TJ = +25°C – 5.0 8.0 mA ∆IQ Quiescent Current Change IO = 5mA to 1A – – 0.5 mA VI = 8V to 25V – – 1.3 Output Voltage Drift IO = 5mA – -0.8 – mV/°C Output Noise Voltage f = 10Hz to 100kHz, TA = +25°C – 45.0 – µV/VO 62.0 73.0 – dB ∆VO/∆T VN RR (4) Ripple Rejection(4) f = 120Hz, VO = 8V to 18V Dropout Voltage IO = 1A, TJ = +25°C – 2.0 – V rO Output Resistance(4) f = 1kHz – 19.0 – mΩ ISC Short Circuit Current VI = 35V, TA = +25°C – 250 – mA IPK Current(4) TJ = +25°C – 2.2 – A VDROP Peak Notes: 3. Load and line regulation are specified at constant junction temperature. Changes in VO due to heating effects must be taken into account separately. Pulse testing with low duty is used. 4. These parameters, although guaranteed, are not 100% tested in production. 4 LM78XX/LM78XXA Rev. 1.0 www.fairchildsemi.com LM78XX/LM78XXA 3-Terminal 1A Positive Voltage Regulator Electrical Characteristics (LM7806) (Continued) Refer to the test circuits. -40°C < TJ < 125°C, IO = 500mA, VI = 14V, CI = 0.33µF, CO = 0.1µF, unless otherwise specified. Symbol VO Regline Parameter Output Voltage Line Regulation(5) Regload Load Regulation(5) IQ ∆IQ ∆VO/∆T VN RR Conditions Min. Typ. Max. Unit TJ = +25°C 7.7 8.0 8.3 V 5mA ≤ IO ≤ 1A, PO ≤ 15W, VI = 10.5V to 23V 7.6 8.0 8.4 – 5.0 160 TJ = +25°C TJ = +25°C VI = 10.5V to 25V VI = 11.5V to 17V – 2.0 80.0 IO = 5mA to 1.5A – 10.0 160 IO = 250mA to 750mA – 5.0 80.0 mV mV Quiescent Current TJ = +25°C – 5.0 8.0 mA Quiescent Current Change IO = 5mA to 1A – 0.05 0.5 mA VI = 10.5V to 25V – 0.5 1.0 IO = 5mA – -0.8 – mV/°C f = 10Hz to 100kHz, TA = +25°C – 52.0 – µV/VO f = 120Hz, VO = 11.5V to 21.5V 56.0 73.0 – dB Output Voltage Drift(6) Output Noise Voltage Ripple Rejection(6) Dropout Voltage IO = 1A, TJ = +25°C – 2.0 – V rO Output Resistance(6) f = 1kHz – 17.0 – mΩ ISC Short Circuit Current VI = 35V, TA = +25°C – 230 – mA IPK Current(6) TJ = +25°C – 2.2 – A VDROP Peak Notes: 5. Load and line regulation are specified at constant junction temperature. Changes in VO due to heating effects must be taken into account separately. Pulse testing with low duty is used. 6. These parameters, although guaranteed, are not 100% tested in production. 5 LM78XX/LM78XXA Rev. 1.0 www.fairchildsemi.com LM78XX/LM78XXA 3-Terminal 1A Positive Voltage Regulator Electrical Characteristics (LM7808) (Continued) Refer to the test circuits. -40°C < TJ < 125°C, IO = 500mA, VI = 15V, CI = 0.33µF, CO = 0.1µF, unless otherwise specified. Symbol VO Regline Parameter Output Voltage Line Regulation(7) Conditions Min. Typ. Max. Unit TJ = +25°C 8.65 9.0 9.35 V 5mA ≤ IO ≤ 1A, PO ≤ 15W, VI = 11.5V to 24V 8.6 9.0 9.4 – 6.0 180 – 2.0 90.0 – 12.0 180 – 4.0 90.0 – 5.0 8.0 mA – – 0.5 mA VI = 11.5V to 26V – – 1.3 IO = 5mA – -1.0 – mV/°C f = 10Hz to 100kHz, TA = +25°C – 58.0 – µV/VO 56.0 71.0 – dB TJ = +25°C VI = 11.5V to 25V VI = 12V to 17V Regload Load Regulation(7) TJ = +25°C IO = 5mA to 1.5A IO = 250mA to 750mA IQ ∆IQ ∆VO/∆T VN RR Quiescent Current TJ = +25°C Quiescent Current Change IO = 5mA to 1A Output Voltage Drift(8) Output Noise Voltage Ripple Rejection(8) f = 120Hz, VO = 13V to 23V mV mV Dropout Voltage IO = 1A, TJ = +25°C – 2.0 – V rO Output Resistance(8) f = 1kHz – 17.0 – mΩ ISC Short Circuit Current VI = 35V, TA = +25°C – 250 – mA IPK Current(8) TJ = +25°C – 2.2 – A VDROP Peak Notes: 7. Load and line regulation are specified at constant junction temperature. Changes in VO due to heating effects must be taken into account separately. Pulse testing with low duty is used. 8. These parameters, although guaranteed, are not 100% tested in production. 6 LM78XX/LM78XXA Rev. 1.0 www.fairchildsemi.com LM78XX/LM78XXA 3-Terminal 1A Positive Voltage Regulator Electrical Characteristics (LM7809) (Continued) Refer to the test circuits. -40°C < TJ < 125°C, IO = 500mA, VI = 16V, CI = 0.33µF, CO = 0.1µF, unless otherwise specified. Symbol Min. Typ. Max. Unit TJ = +25°C 9.6 10.0 10.4 V 5mA ≤ IO ≤ 1A, PO ≤ 15W, VI = 12.5V to 25V 9.5 10.0 10.5 VI = 12.5V to 25V – 10.0 200 VI = 13V to 25V – 3.0 100 IO = 5mA to 1.5A – 12.0 200 IO = 250mA to 750mA – 4.0 400 – 5.1 8.0 mA – – 0.5 mA VI = 12.5V to 29V – – 1.0 Output Voltage Drift(10) IO = 5mA – -1.0 – mV/°C VN Output Noise Voltage f = 10Hz to 100kHz, TA = +25°C – 58.0 – µV/VO RR Ripple Rejection(10) f = 120Hz, VO = 13V to 23V 56.0 71.0 – dB Dropout Voltage IO = 1A, TJ = +25°C – 2.0 – V rO Output Resistance(10) f = 1kHz – 17.0 – mΩ ISC Short Circuit Current VI = 35V, TA = +25°C – 250 – mA IPK Peak Current(10) TJ = +25°C – 2.2 – A VO Regline Parameter Output Voltage Line Regulation(9) Regload Load Regulation(9) IQ ∆IQ ∆VO/∆T VDROP Quiescent Current Conditions TJ = +25°C TJ = +25°C TJ = +25°C Quiescent Current Change IO = 5mA to 1A mV mV Notes: 9. Load and line regulation are specified at constant junction temperature. Changes in VO due to heating effects must be taken into account separately. Pulse testing with low duty is used. 10. These parameters, although guaranteed, are not 100% tested in production. 7 LM78XX/LM78XXA Rev. 1.0 www.fairchildsemi.com LM78XX/LM78XXA 3-Terminal 1A Positive Voltage Regulator Electrical Characteristics (LM7810) (Continued) Refer to the test circuits. -40°C < TJ < 125°C, IO = 500mA, VI = 19V, CI = 0.33µF, CO = 0.1µF, unless otherwise specified. Symbol VO Parameter Output Voltage Conditions Min. Typ. Max. Unit TJ = +25°C 11.5 12.0 12.5 V 5mA ≤ IO ≤ 1A, PO ≤ 15W, VI = 14.5V to 27V 11.4 12.0 12.6 – 10.0 240 – 3.0 120 – 11.0 240 – 5.0 120 – 5.1 8.0 mA – 0.1 0.5 mA VI = 14.5V to 30V – 0.5 1.0 IO = 5mA – -1.0 – mV/°C f = 10Hz to 100kHz, TA = +25°C – 76.0 – µV/VO 55.0 71.0 – dB Regline Line Regulation(11) TJ = +25°C VI = 14.5V to 30V Regload Load Regulation(11) TJ = +25°C IO = 5mA to 1.5A VI = 16V to 22V IO = 250mA to 750mA IQ ∆IQ ∆VO/∆T VN RR Quiescent Current TJ = +25°C Quiescent Current Change IO = 5mA to 1A Output Voltage Drift(12) Output Noise Voltage Ripple Rejection(12) f = 120Hz, VI = 15V to 25V mV mV Dropout Voltage IO = 1A, TJ = +25°C – 2.0 – V rO Output Resistance(12) f = 1kHz – 18.0 – mΩ ISC Short Circuit Current VI = 35V, TA = +25°C – 230 – mA TJ = +25°C – 2.2 – A VDROP IPK Peak Current(12) Notes: 11. Load and line regulation are specified at constant junction temperature. Changes in VO due to heating effects must be taken into account separately. Pulse testing with low duty is used. 12. These parameters, although guaranteed, are not 100% tested in production. 8 LM78XX/LM78XXA Rev. 1.0 www.fairchildsemi.com LM78XX/LM78XXA 3-Terminal 1A Positive Voltage Regulator Electrical Characteristics (LM7812) (Continued) Refer to the test circuits. -40°C < TJ < 125°C, IO = 500mA, VI = 23V, CI = 0.33µF, CO = 0.1µF, unless otherwise specified. Symbol VO Regline Parameter Output Voltage Line Regulation(13) Conditions Min. Typ. Max. Unit TJ = +25°C 14.4 15.0 15.6 V 5mA ≤ IO ≤ 1A, PO ≤ 15W, VI = 17.5V to 30V 14.25 15.0 15.75 – 11.0 300 – 3.0 150 – 12.0 300 – 4.0 150 – 5.2 8.0 mA – – 0.5 mA VI = 17.5V to 30V – – 1.0 IO = 5mA – -1.0 – mV/°C f = 10Hz to 100kHz, TA = +25°C – 90.0 – µV/VO f = 120Hz, VI = 18.5V to 28.5V 54.0 70.0 – dB TJ = +25°C VI = 17.5V to 30V VI = 20V to 26V Regload Load Regulation(13) TJ = +25°C IO = 5mA to 1.5A IO = 250mA to 750mA IQ ∆IQ ∆VO/∆T VN RR Quiescent Current TJ = +25°C Quiescent Current Change IO = 5mA to 1A Output Voltage Drift(14) Output Noise Voltage Ripple Rejection(14) mV mV Dropout Voltage IO = 1A, TJ = +25°C – 2.0 – V rO Output Resistance(14) f = 1kHz – 19.0 – mΩ ISC Short Circuit Current VI = 35V, TA = +25°C – 250 – mA TJ = +25°C – 2.2 – A VDROP IPK Peak Current(14) Notes: 13. Load and line regulation are specified at constant junction temperature. Changes in VO due to heating effects must be taken into account separately. Pulse testing with low duty is used. 14. These parameters, although guaranteed, are not 100% tested in production. 9 LM78XX/LM78XXA Rev. 1.0 www.fairchildsemi.com LM78XX/LM78XXA 3-Terminal 1A Positive Voltage Regulator Electrical Characteristics (LM7815) (Continued) Refer to the test circuits. -40°C < TJ < 125°C, IO = 500mA, VI = 27V, CI = 0.33µF, CO = 0.1µF, unless otherwise specified. Symbol VO Regline Parameter Min. Typ. Max. Unit TJ = +25°C 17.3 18.0 18.7 V 5mA ≤ IO ≤ 1A, PO ≤ 15W, VI = 21V to 33V 17.1 18.0 18.9 TJ = +25°C VI = 21V to 33V – 15.0 360 VI = 24V to 30V – 5.0 180 – 15.0 360 – 5.0 180 – 5.2 8.0 mA Quiescent Current Change IO = 5mA to 1A – – 0.5 mA VI = 21V to 33V – – 1.0 IO = 5mA – -1.0 – mV/°C f = 10Hz to 100kHz, TA = +25°C – 110 – µV/VO 53.0 69.0 – dB Output Voltage Line Regulation(15) Regload Load Regulation(15) Conditions TJ = +25°C IO = 5mA to 1.5A IO = 250mA to 750mA IQ ∆IQ ∆VO/∆T VN RR Quiescent Current Output Voltage Drift(16) Output Noise Voltage Ripple Rejection(16) TJ = +25°C f = 120Hz, VI = 22V to 32V mV mV Dropout Voltage IO = 1A, TJ = +25°C – 2.0 – V rO Output Resistance(16) f = 1kHz – 22.0 – mΩ ISC Short Circuit Current VI = 35V, TA = +25°C – 250 – mA TJ = +25°C – 2.2 – A VDROP IPK Peak Current(16) Notes: 15. Load and line regulation are specified at constant junction temperature. Changes in VO due to heating effects must be taken into account separately. Pulse testing with low duty is used. 16. These parameters, although guaranteed, are not 100% tested in production. 10 LM78XX/LM78XXA Rev. 1.0 www.fairchildsemi.com LM78XX/LM78XXA 3-Terminal 1A Positive Voltage Regulator Electrical Characteristics (LM7818) (Continued) Refer to the test circuits. -40°C < TJ < 125°C, IO = 500mA, VI = 33V, CI = 0.33µF, CO = 0.1µF, unless otherwise specified. Symbol VO Regline Parameter Min. Typ. Max. Unit TJ = +25°C 23.0 24.0 25.0 V 5mA ≤ IO ≤ 1A, PO ≤ 15W, VI = 27V to 38V 22.8 24.0 25.25 VI = 27V to 38V – 17.0 480 VI = 30V to 36V – 6.0 240 IO = 5mA to 1.5A – 15.0 480 IO = 250mA to 750mA – 5.0 240 – 5.2 8.0 mA Quiescent Current Change IO = 5mA to 1A – 0.1 0.5 mA VI = 27V to 38V – 0.5 1.0 IO = 5mA – -1.5 – mV/°C f = 10Hz to 100kHz, TA = +25°C – 60.0 – µV/VO 50.0 67.0 – dB Output Voltage Line Regulation(17) Regload Load Regulation(17) IQ ∆IQ ∆VO/∆T VN RR Quiescent Current Output Voltage Drift(18) Output Noise Voltage Ripple Rejection(18) Conditions TJ = +25°C TJ = +25°C TJ = +25°C f = 120Hz, VI = 28V to 38V mV mV Dropout Voltage IO = 1A, TJ = +25°C – 2.0 – V rO Output Resistance(18) f = 1kHz – 28.0 – mΩ ISC Short Circuit Current VI = 35V, TA = +25°C – 230 – mA TJ = +25°C – 2.2 – A VDROP IPK Peak Current(18) Notes: 17. Load and line regulation are specified at constant junction temperature. Changes in VO due to heating effects must be taken into account separately. Pulse testing with low duty is used. 18. These parameters, although guaranteed, are not 100% tested in production. 11 LM78XX/LM78XXA Rev. 1.0 www.fairchildsemi.com LM78XX/LM78XXA 3-Terminal 1A Positive Voltage Regulator Electrical Characteristics (LM7824) (Continued) Symbol VO Regline Parameter Output Voltage Line Regulation(19) Min. Typ. Max. Unit TJ = +25°C Conditions 4.9 5.0 5.1 V IO = 5mA to 1A, PO ≤ 15W, VI = 7.5V to 20V 4.8 5.0 5.2 VI = 7.5V to 25V, IO = 500mA – 5.0 50.0 VI = 8V to 12V – 3.0 50.0 VI = 7.3V to 20V – 5.0 50.0 VI = 8V to 12V TJ = +25°C Regload Load Regulation(19) – 1.5 25.0 TJ = +25°C, IO = 5mA to 1.5A – 9.0 100 IO = 5mA to 1A – 9.0 100 IO = 250mA to 750mA – 4.0 50.0 mV mV IQ Quiescent Current TJ = +25°C – 5.0 6.0 mA ∆IQ Quiescent Current Change IO = 5mA to 1A – – 0.5 mA VI = 8V to 25V, IO = 500mA – – 0.8 VI = 7.5V to 20V, TJ = +25°C – – 0.8 IO = 5mA – -0.8 – mV/°C ∆VO/∆T Output Voltage Drift(20) VN Output Noise Voltage f = 10Hz to 100kHz, TA = +25°C – 10.0 – µV/VO RR Ripple Rejection(20) f = 120Hz, IO = 500mA, VI = 8V to 18V – 68.0 – dB Dropout Voltage IO = 1A, TJ = +25°C – 2.0 – V f = 1kHz – 17.0 – mΩ VI = 35V, TA = +25°C – 250 – mA TJ = +25°C – 2.2 – A VDROP Resistance(20) rO Output ISC Short Circuit Current IPK Peak Current(20) Notes: 19. Load and line regulation are specified at constant junction temperature. Changes in VO due to heating effects must be taken into account separately. Pulse testing with low duty is used. 20. These parameters, although guaranteed, are not 100% tested in production. 12 LM78XX/LM78XXA Rev. 1.0 www.fairchildsemi.com LM78XX/LM78XXA 3-Terminal 1A Positive Voltage Regulator Electrical Characteristics (LM7805A) (Continued) Refer to the test circuits. 0°C < TJ < 125°C, IO = 1A, VI = 10V, CI = 0.33µF, CO = 0.1µF, unless otherwise specified. Symbol VO Regline Regload IQ ∆IQ ∆VO/∆T Parameter Output Voltage Line Regulation(21) Load Regulation(21) Quiescent Current Min. Typ. Max. Unit TJ = +25°C Conditions 5.58 6.0 6.12 V IO = 5mA to 1A, PO ≤ 15W, VI = 8.6V to 21V 5.76 6.0 6.24 VI = 8.6V to 25V, IO = 500mA – 5.0 60.0 VI = 9V to 13V – 3.0 60.0 TJ = +25°C VI = 8.3V to 21V – 5.0 60.0 VI = 9V to 13V – 1.5 30.0 TJ = +25°C, IO = 5mA to 1.5A – 9.0 100 IO = 5mA to 1A – 9.0 100 IO = 250mA to 750mA – 5.0 50.0 TJ = +25°C – 4.3 6.0 mA – – 0.5 mA VI = 19V to 25V, IO = 500mA – – 0.8 VI = 8.5V to 21V, TJ = +25°C – – 0.8 IO = 5mA – -0.8 – mV/°C Quiescent Current Change IO = 5mA to 1A Output Voltage Drift(22) mV mV VN Output Noise Voltage f = 10Hz to 100kHz, TA = +25°C – 10.0 – µV/VO RR Ripple Rejection(22) f = 120Hz, IO = 500mA, VI = 9V to 19V – 65.0 – dB Dropout Voltage IO = 1A, TJ = +25°C – 2.0 – V f = 1kHz – 17.0 – mΩ VI = 35V, TA = +25°C – 250 – mA TJ = +25°C – 2.2 – A VDROP Resistance(22) rO Output ISC Short Circuit Current IPK Peak Current(22) Notes: 21. Load and line regulation are specified at constant junction temperature. Changes in VO due to heating effects must be taken into account separately. Pulse testing with low duty is used. 22. These parameters, although guaranteed, are not 100% tested in production. 13 LM78XX/LM78XXA Rev. 1.0 www.fairchildsemi.com LM78XX/LM78XXA 3-Terminal 1A Positive Voltage Regulator Electrical Characteristics (LM7806A) (Continued) Refer to the test circuits. 0°C < TJ < 125°C, IO = 1A, VI = 11V, CI = 0.33µF, CO = 0.1µF, unless otherwise specified. Symbol VO Regline Regload IQ ∆IQ ∆VO/∆T Parameter Output Voltage Line Regulation(23) Load Regulation(23) Quiescent Current Min. Typ. Max. Unit TJ = +25°C Conditions 7.84 8.0 8.16 V IO = 5mA to 1A, PO ≤ 15W, VI = 10.6V to 23V 7.7 8.0 8.3 VI = 10.6V to 25V, IO = 500mA – 6.0 80.0 VI = 11V to 17V – 3.0 80.0 TJ = +25°C VI = 10.4V to 23V – 6.0 80.0 VI = 11V to 17V – 2.0 40.0 TJ = +25°C, IO = 5mA to 1.5A – 12.0 100 IO = 5mA to 1A – 12.0 100 IO = 250mA to 750mA – 5.0 50.0 TJ = +25°C – 5.0 6.0 mA – – 0.5 mA VI = 11V to 25V, IO = 500mA – – 0.8 VI = 10.6V to 23V, TJ = +25°C – – 0.8 IO = 5mA – -0.8 – mV/°C Quiescent Current Change IO = 5mA to 1A Output Voltage Drift(24) mV mV VN Output Noise Voltage f = 10Hz to 100kHz, TA = +25°C – 10.0 – µV/VO RR Ripple Rejection(24) f = 120Hz, IO = 500mA, VI = 11.5V to 21.5V – 62.0 – dB Dropout Voltage IO = 1A, TJ = +25°C – 2.0 – V f = 1kHz – 18.0 – mΩ VI = 35V, TA = +25°C – 250 – mA TJ = +25°C – 2.2 – A VDROP Resistance(24) rO Output ISC Short Circuit Current IPK Peak Current(24) Notes: 23. Load and line regulation are specified at constant junction temperature. Changes in VO due to heating effects must be taken into account separately. Pulse testing with low duty is used. 24. These parameters, although guaranteed, are not 100% tested in production. 14 LM78XX/LM78XXA Rev. 1.0 www.fairchildsemi.com LM78XX/LM78XXA 3-Terminal 1A Positive Voltage Regulator Electrical Characteristics (LM7808A) (Continued) Refer to the test circuits. 0°C < TJ < 125°C, IO = 1A, VI = 14V, CI = 0.33µF, CO = 0.1µF, unless otherwise specified. Symbol Min. Typ. Max. Units TJ = +25°C 8.82 9.0 9.16 V IO = 5mA to 1A, PO ≤ 15W, VI = 11.2V to 24V 8.65 9.0 9.35 VI = 11.7V to 25V, IO = 500mA – 6.0 90.0 VI = 12.5V to 19V – 4.0 45.0 TJ = +25°C VI = 11.5V to 24V – 6.0 90.0 VI = 12.5V to 19V – 2.0 45.0 TJ = +25°C, IO = 5mA to 1.5A – 12.0 100 IO = 5mA to 1A – 12.0 100 IO = 250mA to 750mA – 5.0 50.0 TJ = +25°C – 5.0 6.0 mA – – 0.5 mA VI = 12V to 25V, IO = 500mA – – 0.8 VI = 11.7V to 25V, TJ = +25°C – – 0.8 IO = 5mA – -1.0 – mV/°C f = 10Hz to 100kHz, TA = +25°C – 10.0 – µV/VO f = 120Hz, IO = 500mA, VI = 12V to 22V – 62.0 – dB Dropout Voltage IO = 1A, TJ = +25°C – 2.0 – V rO Output Resistance(26) f = 1kHz – 17.0 – mΩ ISC Short Circuit Current VI = 35V, TA = +25°C – 250 – mA TJ = +25°C – 2.2 – A VO Regline Regload IQ ∆IQ ∆VO/∆T VN RR VDROP IPK Parameter Output Voltage Line Regulation(25) Load Regulation(25) Quiescent Current Conditions Quiescent Current Change IO = 5mA to 1A Output Voltage Drift(26) Output Noise Voltage Ripple Peak Rejection(26) Current(26) mV mV Notes: 25. Load and line regulation are specified at constant junction temperature. Changes in VO due to heating effects must be taken into account separately. Pulse testing with low duty is used. 26. These parameters, although guaranteed, are not 100% tested in production. 15 LM78XX/LM78XXA Rev. 1.0 www.fairchildsemi.com LM78XX/LM78XXA 3-Terminal 1A Positive Voltage Regulator Electrical Characteristics (LM7809A) (Continued) Refer to the test circuits. 0°C < TJ < 125°C, IO = 1A, VI = 15V, CI = 0.33µF, CO = 0.1µF, unless otherwise specified. Symbol VO Regline Parameter Output Voltage Line Regulation(27) Min. Typ. Max. Units TJ = +25°C Conditions 9.8 10.0 10.2 V IO = 5mA to 1A, PO ≤ 15W, VI = 12.8V to 25V 9.6 10.0 10.4 VI = 12.8V to 26V, IO = 500mA – 8.0 100 VI = 13V to 20V – 4.0 50.0 VI = 12.5V to 25V – 8.0 100 VI = 13V to 20V TJ = +25°C Regload Load Regulation(27) mV – 3.0 50.0 TJ = +25°C, IO = 5mA to 1.5A – 12.0 100 IO = 5mA to 1A – 12.0 100 IO = 250mA to 750mA – 5.0 50.0 mV IQ Quiescent Current TJ = +25°C – 5.0 6.0 mA ∆IQ Quiescent Current Change IO = 5mA to 1A – – 0.5 mA VI = 12.8V to 25V, IO = 500mA – – 0.8 VI = 13V to 26V, TJ = +25°C – – 0.5 IO = 5mA – -1.0 – mV/°C ∆VO/∆T Output Voltage Drift(28) VN Output Noise Voltage f = 10Hz to 100kHz, TA = +25°C – 10.0 – µV/VO RR Ripple Rejection(28) f = 120Hz, IO = 500mA, VI = 14V to 24V – 62.0 – dB Dropout Voltage IO = 1A, TJ = +25°C – 2.0 – V f = 1kHz – 17.0 – mΩ VI = 35V, TA = +25°C – 250 – mA TJ = +25°C – 2.2 – A VDROP Resistance(28) rO Output ISC Short Circuit Current IPK Peak Current(28) Notes: 27. Load and line regulation are specified at constant junction temperature. Changes in VO due to heating effects must be taken into account separately. Pulse testing with low duty is used. 28. These parameters, although guaranteed, are not 100% tested in production. 16 LM78XX/LM78XXA Rev. 1.0 www.fairchildsemi.com LM78XX/LM78XXA 3-Terminal 1A Positive Voltage Regulator Electrical Characteristics (LM7810A) (Continued) Refer to the test circuits. 0°C < TJ < 125°C, IO = 1A, VI = 16V, CI = 0.33µF, CO = 0.1µF, unless otherwise specified. Symbol VO Regline Regload IQ ∆IQ ∆VO/∆T Parameter Output Voltage Line Regulation(29) Load Regulation(29) Quiescent Current Min. Typ. Max. Units TJ = +25°C Conditions 11.75 12.0 12.25 V IO = 5mA to 1A, PO ≤ 15W, VI = 14.8V to 27V 11.5 12.0 12.5 VI = 14.8V to 30V, IO = 500mA – 10.0 120 VI = 16V to 22V – 4.0 120 TJ = +25°C VI = 14.5V to 27V – 10.0 120 VI = 16V to 22V – 3.0 60.0 TJ = +25°C, IO = 5mA to 1.5A – 12.0 100 IO = 5mA to 1A – 12.0 100 IO = 250mA to 750mA – 5.0 50.0 TJ = +25°C – 5.1 6.0 mA – – 0.5 mA VI = 14V to 27V, IO = 500mA – – 0.8 VI = 15V to 30V, TJ = +25°C – – 0.8 IO = 5mA – -1.0 – mV/°C Quiescent Current Change IO = 5mA to 1A Output Voltage Drift(30) mV mV VN Output Noise Voltage f = 10Hz to 100kHz, TA = +25°C – 10.0 – µV/VO RR Ripple Rejection(30) f = 120Hz, IO = 500mA, VI = 14V to 24V – 60.0 – dB Dropout Voltage IO = 1A, TJ = +25°C – 2.0 – V f = 1kHz – 18.0 – mΩ VI = 35V, TA = +25°C – 250 – mA TJ = +25°C – 2.2 – A VDROP Resistance(30) rO Output ISC Short Circuit Current IPK Peak Current(30) Note: 29. Load and line regulation are specified at constant junction temperature. Changes in VO due to heating effects must be taken into account separately. Pulse testing with low duty is used. 30. These parameters, although guaranteed, are not 100% tested in production. 17 LM78XX/LM78XXA Rev. 1.0 www.fairchildsemi.com LM78XX/LM78XXA 3-Terminal 1A Positive Voltage Regulator Electrical Characteristics (LM7812A) (Continued) Refer to the test circuits. 0°C < TJ < 125°C, IO = 1A, VI = 19V, CI = 0.33µF, CO = 0.1µF, unless otherwise specified. Symbol VO Regline Regload IQ ∆IQ ∆VO/∆T Parameter Output Voltage Line Regulation(31) Load Regulation(31) Quiescent Current Min. Typ. Max. Units TJ = +25°C Conditions 14.75 15.0 15.3 V IO = 5mA to 1A, PO ≤ 15W, VI = 17.7V to 30V 14.4 15.0 15.6 VI = 17.4V to 30V, IO = 500mA – 10.0 150 VI = 20V to 26V – 5.0 150 TJ = +25°C VI = 17.5V to 30V – 11.0 150 VI = 20V to 26V – 3.0 75.0 TJ = +25°C, IO = 5mA to 1.5A – 12.0 100 IO = 5mA to 1A – 12.0 100 IO = 250mA to 750mA – 5.0 50.0 TJ = +25°C – 5.2 6.0 mA – – 0.5 mA VI = 17.5V to 30V, IO = 500mA – – 0.8 VI = 17.5V to 30V, TJ = +25°C – – 0.8 IO = 5mA – -1.0 – mV/°C Quiescent Current Change IO = 5mA to 1A Output Voltage Drift(32) mV mV VN Output Noise Voltage f = 10Hz to 100kHz, TA = +25°C – 10.0 – µV/VO RR Ripple Rejection(32) f = 120Hz, IO = 500mA, VI = 18.5V to 28.5V – 58.0 – dB Dropout Voltage IO = 1A, TJ = +25°C – 2.0 – V f = 1kHz – 19.0 – mΩ VI = 35V, TA = +25°C – 250 – mA TJ = +25°C – 2.2 – A VDROP Resistance(32) rO Output ISC Short Circuit Current IPK Peak Current(32) Notes: 31. Load and line regulation are specified at constant junction temperature. Changes in VO due to heating effects must be taken into account separately. Pulse testing with low duty is used. 32. These parameters, although guaranteed, are not 100% tested in production. 18 LM78XX/LM78XXA Rev. 1.0 www.fairchildsemi.com LM78XX/LM78XXA 3-Terminal 1A Positive Voltage Regulator Electrical Characteristics (LM7815A) (Continued) Refer to the test circuits. 0°C < TJ < 125°C, IO = 1A, VI = 23V, CI = 0.33µF, CO = 0.1µF, unless otherwise specified. Symbol VO Regline Regload IQ ∆IQ ∆VO/∆T Parameter Output Voltage Line Regulation(33) Min. Typ. Max. Units TJ = +25°C Conditions 17.64 18.0 18.36 V IO = 5mA to 1A, PO ≤ 15W, VI = 21V to 33V 17.3 18.0 18.7 VI = 21V to 33V, IO = 500mA – 15.0 180 VI = 21V to 33V – 5.0 180 TJ = +25°C VI = 20.6V to 33V – 15.0 180 mV VI = 24V to 30V – 5.0 90.0 TJ = +25°C, IO = 5mA to 1.5A – 15.0 100 IO = 5mA to 1A – 15.0 100 IO = 250mA to 750mA – 7.0 50.0 Quiescent Current TJ = +25°C – 5.2 6.0 mA Quiescent Current Change IO = 5mA to 1A – – 0.5 mA VI = 12V to 33V, IO = 500mA – – 0.8 VI = 12V to 33V, TJ = +25°C – – 0.8 IO = 5mA – -1.0 – mV/°C Load Regulation(33) Output Voltage Drift(34) mV VN Output Noise Voltage f = 10Hz to 100kHz, TA = +25°C – 10.0 – µV/VO RR Ripple Rejection(34) f = 120Hz, IO = 500mA, VI = 22V to 32V – 57.0 – dB Dropout Voltage IO = 1A, TJ = +25°C – 2.0 – V f = 1kHz – 19.0 – mΩ VI = 35V, TA = +25°C – 250 – mA TJ = +25°C – 2.2 – A VDROP Resistance(34) rO Output ISC Short Circuit Current IPK Peak Current(34) Notes: 33. Load and line regulation are specified at constant junction temperature. Changes in VO due to heating effects must be taken into account separately. Pulse testing with low duty is used. 34. These parameters, although guaranteed, are not 100% tested in production. 19 LM78XX/LM78XXA Rev. 1.0 www.fairchildsemi.com LM78XX/LM78XXA 3-Terminal 1A Positive Voltage Regulator Electrical Characteristics (LM7818A) (Continued) Refer to the test circuits. 0°C < TJ < 125°C, IO = 1A, VI = 27V, CI = 0.33µF, CO = 0.1µF, unless otherwise specified. Symbol VO Regline Parameter Output Voltage Line Regulation(35) Min. Typ. Max. Units TJ = +25°C Conditions 23.5 24.0 24.5 V IO = 5mA to 1A, PO ≤ 15W, VI = 27.3V to 38V 23.0 24.0 25.0 VI = 27V to 38V, IO = 500mA – 18.0 240 VI = 21V to 33V – 6.0 240 VI = 26.7V to 38V – 18.0 240 VI = 30V to 36V TJ = +25°C Regload IQ ∆IQ ∆VO/∆T Load Regulation(35) Quiescent Current – 6.0 120 TJ = +25°C, IO = 5mA to 1.5A – 15.0 100 IO = 5mA to 1A – 15.0 100 IO = 250mA to 750mA – 7.0 50.0 TJ = +25°C – 5.2 6.0 mA – – 0.5 mA VI = 27.3V to 38V, IO = 500mA – – 0.8 VI = 27.3V to 38V, TJ = +25°C – – 0.8 IO = 5mA – -1.5 – mV/°C Quiescent Current Change IO = 5mA to 1A Output Voltage Drift(36) mV mV VN Output Noise Voltage f = 10Hz to 100kHz, TA = +25°C – 10.0 – µV/VO RR Ripple Rejection(36) f = 120Hz, IO = 500mA, VI = 28V to 38V – 54.0 – dB Dropout Voltage IO = 1A, TJ = +25°C – 2.0 – V f = 1kHz – 20.0 – mΩ VI = 35V, TA = +25°C – 250 – mA TJ = +25°C – 2.2 – A VDROP Resistance(36) rO Output ISC Short Circuit Current IPK Peak Current(36) Notes: 35. Load and line regulation are specified at constant junction temperature. Changes in VO due to heating effects must be taken into account separately. Pulse testing with low duty is used. 36. These parameters, although guaranteed, are not 100% tested in production. 20 LM78XX/LM78XXA Rev. 1.0 www.fairchildsemi.com LM78XX/LM78XXA 3-Terminal 1A Positive Voltage Regulator Electrical Characteristics (LM7824A) (Continued) Refer to the test circuits. 0°C < TJ < 125°C, IO = 1A, VI = 33V, CI = 0.33µF, CO = 0.1µF, unless otherwise specified. 3 VI = 10V VO = 5V IO = 5mA 5.75 TJ = 25°C ∆VO = 100mV 2.5 OUTPUT CURRENT (A) QUIESCENT CURRENT (mA) 6 5.5 5.25 5 4.75 2 1.5 1 .5 4.5 -50 -25 0 25 50 75 100 0 125 0 JUNCTION TEMPERATURE (°C) Figure 3. Quiescent Current 7 VI – VO = 5V IO = 5mA 1.01 1 0.99 0.98 -50 -25 0 25 50 75 100 15 20 25 30 35 TJ = 25°C VO = 5V IO = 10mA 6.5 6 5.5 5 4.5 4 125 JUNCTION TEMPERATURE (°C) 5 10 15 20 25 30 35 INPUT VOLTAGE (V) Figure 5. Output Voltage Figure 6. Quiescent Current 21 LM78XX/LM78XXA Rev. 1.0 10 Figure 4. Peak Output Current QUIESCENT CURRENT (mA) NORMALIZED OUTPUT VOLTAGE (V) 1.02 5 INPUT-OUTPUT DIFFERENTIAL (V) www.fairchildsemi.com LM78XX/LM78XXA 3-Terminal 1A Positive Voltage Regulator Typical Performance Characteristics 1 Input Output CO 2 CI 3 LM78XX 0.1µF 0.33µF Figure 7. DC Parameters 1 3 LM78XX Input Output 2 270pF RL VO 2N6121 or EQ 0.33µF 0V VO 30µS 100Ω Figure 8. Load Regulation 5.1Ω 1 LM78XX Input 3 Output 0.33µF 2 RL 470µF 120Hz + Figure 9. Ripple Rejection 22 LM78XX/LM78XXA Rev. 1.0 www.fairchildsemi.com LM78XX/LM78XXA 3-Terminal 1A Positive Voltage Regulator Typical Applications LM78XX Input CI 3 Output CO 2 LM78XX/LM78XXA 3-Terminal 1A Positive Voltage Regulator 1 0.1µF 0.33µF Figure 10. Fixed Output Regulator 1 Input CI 3 LM78XX Output CO 2 0.33µF V XX 0.1µF R1 IQ IO RL V XX IO = + R1 IQ Notes: 1. To specify an output voltage, substitute voltage value for “XX.” A common ground is required between the input and the output voltage. The input voltage must remain typically 2.0V above the output voltage even during the low point on the input ripple voltage. 2. CI is required if regulator is located an appreciable distance from power supply filter. 3. CO improves stability and transient response. Figure 11. 1 Input CI LM78XX CO 2 0.33µF Output 3 0.1µF V XX R1 IQ R2 IRI ≥ 5 IQ VO = VXX(1 + R2 / R1) + IQR2 Figure 12. Circuit for Increasing Output Voltage 23 LM78XX/LM78XXA Rev. 1.0 www.fairchildsemi.com 1 LM7805 Output 3 2 CI 0.33µF CO - 2 LM741 + 3 4 6 10kΩ 0.1µF IRI ≥ 5 IQ VO = VXX(1 + R2 / R1) + IQR2 Figure 13. Adjustable Output Regulator (7V to 30V) Q1 BD536 Input IQ1 R1 1 3Ω R1 = LM78XX IO IREG V BEQ1 Output 3 2 0.1µF 0.33µF IREG–IQ1 BQ1 IO = IREG + BQ1 (IREG–VBEQ1/R1) Figure 14. High Current Voltage Regulator Input Q1 RSC Q2 R1 1 LM78XX 3 Output 3Ω 0.33µF Q1 = TIP42 Q2 = TIP42 RSC = 2 0.1µF V BEQ2 I SC Figure 15. High Output Current with Short Circuit Protection 24 LM78XX/LM78XXA Rev. 1.0 www.fairchildsemi.com LM78XX/LM78XXA 3-Terminal 1A Positive Voltage Regulator Input 3 LM78XX VI VO 2 0.33µF 0.1µF 7 COMMON 6 COMMON 2 LM741 4 -VIN _ 4.7kΩ + 3 4.7kΩ -VO TIP42 Figure 16. Tracking Voltage Regulator 1 +20V LM7815 3 +15V 0.33µF + 2 0.1µF 1N4001 2.2µF 1µF + 1 2 -20V 1N4001 MC7915 3 -15V Figure 17. Split Power Supply (±15V – 1A) 25 LM78XX/LM78XXA Rev. 1.0 www.fairchildsemi.com LM78XX/LM78XXA 3-Terminal 1A Positive Voltage Regulator 1 Input + 0.1µF 2 1 3 LM78XX Figure 18. Negative Output Voltage Circuit D45H11 Input 1mH Output 470Ω 4.7Ω Z1 1 + 0.33µF LM78XX 3 2 10µF + 0.5Ω 2000µF Figure 19. Switching Regulator 26 LM78XX/LM78XXA Rev. 1.0 www.fairchildsemi.com LM78XX/LM78XXA 3-Terminal 1A Positive Voltage Regulator Output LM78XX/LM78XXA — 3-Terminal 1A Positive Voltage Regulator Mechanical Dimensions Dimensions in millimeters TO-220 [ SINGLE GAUGE ] © 2010 Fairchild Semiconductor Corporation LM78XX/LM78XXA Rev. 1.0 www.fairchildsemi.com 27 TRADEMARKS The following includes registered and unregistered trademarks and service marks, owned by Fairchild Semiconductor and/or its global subsidiaries, and is not intended to be an exhaustive list of all such trademarks. FRFET® SM Global Power Resource Green FPS¥ Green FPS¥ e-Series¥ Gmax¥ GTO¥ IntelliMAX¥ ISOPLANAR¥ MegaBuck¥ MICROCOUPLER¥ MicroFET¥ MicroPak¥ MicroPak2¥ MillerDrive¥ MotionMax¥ Motion-SPM¥ OptoHiT™ OPTOLOGIC® ® OPTOPLANAR AccuPower¥ Auto-SPM¥ Build it Now¥ CorePLUS¥ CorePOWER¥ CROSSVOLT¥ CTL¥ Current Transfer Logic¥ DEUXPEED® Dual Cool™ EcoSPARK® EfficientMax¥ ® Fairchild® Fairchild Semiconductor® FACT Quiet Series¥ FACT® FAST® FastvCore¥ FETBench¥ FlashWriter®* FPS¥ F-PFS¥ ® PDP SPM™ Power-SPM¥ PowerTrench® PowerXS™ Programmable Active Droop¥ QFET® QS¥ Quiet Series¥ RapidConfigure¥ ¥ Saving our world, 1mW/W/kW at a time™ SignalWise¥ SmartMax¥ SMART START¥ SPM® STEALTH¥ SuperFET¥ SuperSOT¥-3 SuperSOT¥-6 SuperSOT¥-8 SupreMOS¥ SyncFET¥ Sync-Lock™ ® * The Power Franchise® TinyBoost¥ TinyBuck¥ TinyCalc¥ TinyLogic® TINYOPTO¥ TinyPower¥ TinyPWM¥ TinyWire¥ TriFault Detect¥ TRUECURRENT¥* PSerDes¥ UHC® Ultra FRFET¥ UniFET¥ VCX¥ VisualMax¥ XS™ * Trademarks of System General Corporation, used under license by Fairchild Semiconductor. DISCLAIMER FAIRCHILD SEMICONDUCTOR RESERVES THE RIGHT TO MAKE CHANGES WITHOUT FURTHER NOTICE TO ANY PRODUCTS HEREIN TO IMPROVE RELIABILITY, FUNCTION, OR DESIGN. FAIRCHILD DOES NOT ASSUME ANY LIABILITY ARISING OUT OF THE APPLICATION OR USE OF ANY PRODUCT OR CIRCUIT DESCRIBED HEREIN; NEITHER DOES IT CONVEY ANY LICENSE UNDER ITS PATENT RIGHTS, NOR THE RIGHTS OF OTHERS. THESE SPECIFICATIONS DO NOT EXPAND THE TERMS OF FAIRCHILD’S WORLDWIDE TERMS AND CONDITIONS, SPECIFICALLY THE WARRANTY THEREIN, WHICH COVERS THESE PRODUCTS. LIFE SUPPORT POLICY FAIRCHILD’S PRODUCTS ARE NOT AUTHORIZED FOR USE AS CRITICAL COMPONENTS IN LIFE SUPPORT DEVICES OR SYSTEMS WITHOUT THE EXPRESS WRITTEN APPROVAL OF FAIRCHILD SEMICONDUCTOR CORPORATION. As used herein: 1. Life support devices or systems are devices or systems which, (a) are intended for surgical implant into the body or (b) support or sustain life, and (c) whose failure to perform when properly used in accordance with instructions for use provided in the labeling, can be reasonably expected to result in a significant injury of the user. 2. A critical component in any component of a life support, device, or system whose failure to perform can be reasonably expected to cause the failure of the life support device or system, or to affect its safety or effectiveness. ANTI-COUNTERFEITING POLICY Fairchild Semiconductor Corporation's Anti-Counterfeiting Policy. Fairchild's Anti-Counterfeiting Policy is also stated on our external website, www.fairchildsemi.com, under Sales Support. Counterfeiting of semiconductor parts is a growing problem in the industry. All manufacturers of semiconductor products are experiencing counterfeiting of their parts. Customers who inadvertently purchase counterfeit parts experience many problems such as loss of brand reputation, substandard performance, failed applications, and increased cost of production and manufacturing delays. Fairchild is taking strong measures to protect ourselves and our customers from the proliferation of counterfeit parts. Fairchild strongly encourages customers to purchase Fairchild parts either directly from Fairchild or from Authorized Fairchild Distributors who are listed by country on our web page cited above. Products customers buy either from Fairchild directly or from Authorized Fairchild Distributors are genuine parts, have full traceability, meet Fairchild's quality standards for handling and storage and provide access to Fairchild's full range of up-to-date technical and product information. Fairchild and our Authorized Distributors will stand behind all warranties and will appropriately address any warranty issues that may arise. Fairchild will not provide any warranty coverage or other assistance for parts bought from Unauthorized Sources. Fairchild is committed to combat this global problem and encourage our customers to do their part in stopping this practice by buying direct or from authorized distributors. PRODUCT STATUS DEFINITIONS Definition of Terms Datasheet Identification Product Status Advance Information Formative / In Design Preliminary First Production No Identification Needed Full Production Obsolete Not In Production Definition Datasheet contains the design specifications for product development. Specifications may change in any manner without notice. Datasheet contains preliminary data; supplementary data will be published at a later date. Fairchild Semiconductor reserves the right to make changes at any time without notice to improve design. Datasheet contains final specifications. Fairchild Semiconductor reserves the right to make changes at any time without notice to improve the design. Datasheet contains specifications on a product that is discontinued by Fairchild Semiconductor. The datasheet is for reference information only. Rev. I47 © Fairchild Semiconductor Corporation www.fairchildsemi.com ANEXO H - Datasheet do diodo 1N4148 DISCRETE SEMICONDUCTORS DATA SHEET M3D176 1N4148; 1N4448 High-speed diodes Product specification Supersedes data of 1996 Sep 03 1999 May 25 Philips Semiconductors Product specification High-speed diodes 1N4148; 1N4448 FEATURES DESCRIPTION • Hermetically sealed leaded glass SOD27 (DO-35) package The 1N4148 and 1N4448 are high-speed switching diodes fabricated in planar technology, and encapsulated in hermetically sealed leaded glass SOD27 (DO-35) packages. • High switching speed: max. 4 ns • General application • Continuous reverse voltage: max. 75 V • Repetitive peak reverse voltage: max. 75 V handbook, halfpage k a • Repetitive peak forward current: max. 450 mA. MAM246 The diodes are type branded. APPLICATIONS Fig.1 Simplified outline (SOD27; DO-35) and symbol. • High-speed switching. LIMITING VALUES In accordance with the Absolute Maximum Rating System (IEC 134). SYMBOL PARAMETER CONDITIONS MIN. MAX. UNIT VRRM repetitive peak reverse voltage − 75 V VR continuous reverse voltage − 75 V IF continuous forward current − 200 mA − 450 mA − 4 A IFRM repetitive peak forward current IFSM non-repetitive peak forward current see Fig.2; note 1 square wave; Tj = 25 °C prior to surge; see Fig.4 t = 1 µs Ptot total power dissipation t = 1 ms − 1 A t=1s − 0.5 A − 500 mW Tamb = 25 °C; note 1 Tstg storage temperature −65 +200 °C Tj junction temperature − 200 °C Note 1. Device mounted on an FR4 printed circuit-board; lead length 10 mm. 1999 May 25 2 Philips Semiconductors Product specification High-speed diodes 1N4148; 1N4448 ELECTRICAL CHARACTERISTICS Tj = 25 °C unless otherwise specified. SYMBOL VF IR IR PARAMETER forward voltage CONDITIONS MIN. MAX. UNIT see Fig.3 1N4148 IF = 10 mA − 1 V 1N4448 IF = 5 mA 0.62 0.72 V IF = 100 mA − 1 V reverse current reverse current; 1N4448 25 nA VR = 20 V; Tj = 150 °C; see Fig.5 VR = 20 V; see Fig.5 − 50 µA VR = 20 V; Tj = 100 °C; see Fig.5 − 3 µA Cd diode capacitance f = 1 MHz; VR = 0; see Fig.6 4 pF trr reverse recovery time when switched from IF = 10 mA to IR = 60 mA; RL = 100 Ω; measured at IR = 1 mA; see Fig.7 4 ns Vfr forward recovery voltage when switched from IF = 50 mA; tr = 20 ns; see Fig.8 2.5 V − THERMAL CHARACTERISTICS SYMBOL PARAMETER CONDITIONS VALUE UNIT Rth j-tp thermal resistance from junction to tie-point lead length 10 mm 240 K/W Rth j-a thermal resistance from junction to ambient lead length 10 mm; note 1 350 K/W Note 1. Device mounted on a printed circuit-board without metallization pad. 1999 May 25 3 Philips Semiconductors Product specification High-speed diodes 1N4148; 1N4448 GRAPHICAL DATA MBG451 300 MBG464 600 handbook, halfpage handbook, halfpage IF (mA) IF (mA) 200 400 (1) 0 100 Tamb (oC) 0 200 0 1 2 VF (V) (1) Tj = 175 °C; typical values. Device mounted on an FR4 printed-circuit board; lead length 10 mm. Fig.2 (3) 200 100 0 (2) (2) Tj = 25 °C; typical values. (3) Tj = 25 °C; maximum values. Maximum permissible continuous forward current as a function of ambient temperature. Fig.3 Forward current as a function of forward voltage. MBG704 102 handbook, full pagewidth IFSM (A) 10 1 10−1 1 10 102 103 tp (µs) Based on square wave currents. Tj = 25 °C prior to surge. Fig.4 Maximum permissible non-repetitive peak forward current as a function of pulse duration. 1999 May 25 4 104 Philips Semiconductors Product specification High-speed diodes 1N4148; 1N4448 MGD290 103 handbook, halfpage MGD004 1.2 handbook, halfpage IR (µA) 10 Cd (pF) 2 1.0 (1) 10 (2) 0.8 1 0.6 10−1 10−2 0 100 Tj (oC) 0.4 200 0 10 VR (V) 20 (1) VR = 75 V; typical values. (2) VR = 20 V; typical values. Fig.5 f = 1 MHz; Tj = 25 °C. Reverse current as a function of junction temperature. 1999 May 25 Fig.6 5 Diode capacitance as a function of reverse voltage; typical values. Philips Semiconductors Product specification High-speed diodes 1N4148; 1N4448 handbook, full pagewidth tr tp t D.U.T. 10% IF RS = 50 Ω IF SAMPLING OSCILLOSCOPE t rr t R = 50 Ω i V = VR I F x R S MGA881 (1) 90% VR output signal input signal (1) IR = 1 mA. Fig.7 Reverse recovery voltage test circuit and waveforms. I R = 50 Ω S 1 kΩ D.U.T. 450 Ω I V 90% OSCILLOSCOPE V fr R i = 50 Ω 10% MGA882 t tr input signal Fig.8 Forward recovery voltage test circuit and waveforms. 1999 May 25 6 t tp output signal Philips Semiconductors Product specification High-speed diodes 1N4148; 1N4448 PACKAGE OUTLINE Hermetically sealed glass package; axial leaded; 2 leads SOD27 (1) b D G1 L L DIMENSIONS (mm are the original dimensions) G1 UNIT b max. D max. max. L min. mm 0.56 1.85 4.25 25.4 0 1 2 mm scale Note 1. The marking band indicates the cathode. REFERENCES OUTLINE VERSION IEC JEDEC EIAJ SOD27 A24 DO-35 SC-40 EUROPEAN PROJECTION ISSUE DATE 97-06-09 DEFINITIONS Data Sheet Status Objective specification This data sheet contains target or goal specifications for product development. Preliminary specification This data sheet contains preliminary data; supplementary data may be published later. Product specification This data sheet contains final product specifications. Limiting values Limiting values given are in accordance with the Absolute Maximum Rating System (IEC 134). Stress above one or more of the limiting values may cause permanent damage to the device. These are stress ratings only and operation of the device at these or at any other conditions above those given in the Characteristics sections of the specification is not implied. Exposure to limiting values for extended periods may affect device reliability. Application information Where application information is given, it is advisory and does not form part of the specification. LIFE SUPPORT APPLICATIONS These products are not designed for use in life support appliances, devices, or systems where malfunction of these products can reasonably be expected to result in personal injury. Philips customers using or selling these products for use in such applications do so at their own risk and agree to fully indemnify Philips for any damages resulting from such improper use or sale. 1999 May 25 7 Philips Semiconductors – a worldwide company Argentina: see South America Australia: 34 Waterloo Road, NORTH RYDE, NSW 2113, Tel. +61 2 9805 4455, Fax. +61 2 9805 4466 Austria: Computerstr. 6, A-1101 WIEN, P.O. Box 213, Tel. +43 1 60 101 1248, Fax. +43 1 60 101 1210 Belarus: Hotel Minsk Business Center, Bld. 3, r. 1211, Volodarski Str. 6, 220050 MINSK, Tel. +375 172 20 0733, Fax. +375 172 20 0773 Belgium: see The Netherlands Brazil: see South America Bulgaria: Philips Bulgaria Ltd., Energoproject, 15th floor, 51 James Bourchier Blvd., 1407 SOFIA, Tel. +359 2 68 9211, Fax. +359 2 68 9102 Canada: PHILIPS SEMICONDUCTORS/COMPONENTS, Tel. +1 800 234 7381, Fax. +1 800 943 0087 China/Hong Kong: 501 Hong Kong Industrial Technology Centre, 72 Tat Chee Avenue, Kowloon Tong, HONG KONG, Tel. +852 2319 7888, Fax. +852 2319 7700 Colombia: see South America Czech Republic: see Austria Denmark: Sydhavnsgade 23, 1780 COPENHAGEN V, Tel. +45 33 29 3333, Fax. +45 33 29 3905 Finland: Sinikalliontie 3, FIN-02630 ESPOO, Tel. +358 9 615 800, Fax. +358 9 6158 0920 France: 51 Rue Carnot, BP317, 92156 SURESNES Cedex, Tel. +33 1 4099 6161, Fax. +33 1 4099 6427 Germany: Hammerbrookstraße 69, D-20097 HAMBURG, Tel. +49 40 2353 60, Fax. +49 40 2353 6300 Hungary: see Austria India: Philips INDIA Ltd, Band Box Building, 2nd floor, 254-D, Dr. Annie Besant Road, Worli, MUMBAI 400 025, Tel. +91 22 493 8541, Fax. +91 22 493 0966 Indonesia: PT Philips Development Corporation, Semiconductors Division, Gedung Philips, Jl. Buncit Raya Kav.99-100, JAKARTA 12510, Tel. +62 21 794 0040 ext. 2501, Fax. +62 21 794 0080 Ireland: Newstead, Clonskeagh, DUBLIN 14, Tel. +353 1 7640 000, Fax. +353 1 7640 200 Israel: RAPAC Electronics, 7 Kehilat Saloniki St, PO Box 18053, TEL AVIV 61180, Tel. +972 3 645 0444, Fax. +972 3 649 1007 Italy: PHILIPS SEMICONDUCTORS, Piazza IV Novembre 3, 20124 MILANO, Tel. +39 02 67 52 2531, Fax. +39 02 67 52 2557 Japan: Philips Bldg 13-37, Kohnan 2-chome, Minato-ku, TOKYO 108-8507, Tel. +81 3 3740 5130, Fax. +81 3 3740 5057 Korea: Philips House, 260-199 Itaewon-dong, Yongsan-ku, SEOUL, Tel. +82 2 709 1412, Fax. +82 2 709 1415 Malaysia: No. 76 Jalan Universiti, 46200 PETALING JAYA, SELANGOR, Tel. +60 3 750 5214, Fax. +60 3 757 4880 Mexico: 5900 Gateway East, Suite 200, EL PASO, TEXAS 79905, Tel. +9-5 800 234 7381, Fax +9-5 800 943 0087 Middle East: see Italy Netherlands: Postbus 90050, 5600 PB EINDHOVEN, Bldg. VB, Tel. +31 40 27 82785, Fax. +31 40 27 88399 New Zealand: 2 Wagener Place, C.P.O. Box 1041, AUCKLAND, Tel. +64 9 849 4160, Fax. +64 9 849 7811 Norway: Box 1, Manglerud 0612, OSLO, Tel. +47 22 74 8000, Fax. +47 22 74 8341 Pakistan: see Singapore Philippines: Philips Semiconductors Philippines Inc., 106 Valero St. Salcedo Village, P.O. Box 2108 MCC, MAKATI, Metro MANILA, Tel. +63 2 816 6380, Fax. +63 2 817 3474 Poland: Ul. Lukiska 10, PL 04-123 WARSZAWA, Tel. +48 22 612 2831, Fax. +48 22 612 2327 Portugal: see Spain Romania: see Italy Russia: Philips Russia, Ul. Usatcheva 35A, 119048 MOSCOW, Tel. +7 095 755 6918, Fax. +7 095 755 6919 Singapore: Lorong 1, Toa Payoh, SINGAPORE 319762, Tel. +65 350 2538, Fax. +65 251 6500 Slovakia: see Austria Slovenia: see Italy South Africa: S.A. PHILIPS Pty Ltd., 195-215 Main Road Martindale, 2092 JOHANNESBURG, P.O. Box 58088 Newville 2114, Tel. +27 11 471 5401, Fax. +27 11 471 5398 South America: Al. Vicente Pinzon, 173, 6th floor, 04547-130 SÃO PAULO, SP, Brazil, Tel. +55 11 821 2333, Fax. +55 11 821 2382 Spain: Balmes 22, 08007 BARCELONA, Tel. +34 93 301 6312, Fax. +34 93 301 4107 Sweden: Kottbygatan 7, Akalla, S-16485 STOCKHOLM, Tel. +46 8 5985 2000, Fax. +46 8 5985 2745 Switzerland: Allmendstrasse 140, CH-8027 ZÜRICH, Tel. +41 1 488 2741 Fax. +41 1 488 3263 Taiwan: Philips Semiconductors, 6F, No. 96, Chien Kuo N. Rd., Sec. 1, TAIPEI, Taiwan Tel. +886 2 2134 2886, Fax. +886 2 2134 2874 Thailand: PHILIPS ELECTRONICS (THAILAND) Ltd., 209/2 Sanpavuth-Bangna Road Prakanong, BANGKOK 10260, Tel. +66 2 745 4090, Fax. +66 2 398 0793 Turkey: Yukari Dudullu, Org. San. Blg., 2.Cad. Nr. 28 81260 Umraniye, ISTANBUL, Tel. +90 216 522 1500, Fax. +90 216 522 1813 Ukraine: PHILIPS UKRAINE, 4 Patrice Lumumba str., Building B, Floor 7, 252042 KIEV, Tel. +380 44 264 2776, Fax. +380 44 268 0461 United Kingdom: Philips Semiconductors Ltd., 276 Bath Road, Hayes, MIDDLESEX UB3 5BX, Tel. +44 181 730 5000, Fax. +44 181 754 8421 United States: 811 East Arques Avenue, SUNNYVALE, CA 94088-3409, Tel. +1 800 234 7381, Fax. +1 800 943 0087 Uruguay: see South America Vietnam: see Singapore Yugoslavia: PHILIPS, Trg N. Pasica 5/v, 11000 BEOGRAD, Tel. +381 11 62 5344, Fax.+381 11 63 5777 For all other countries apply to: Philips Semiconductors, International Marketing & Sales Communications, Building BE-p, P.O. Box 218, 5600 MD EINDHOVEN, The Netherlands, Fax. +31 40 27 24825 Internet: http://www.semiconductors.philips.com © Philips Electronics N.V. 1999 SCA 65 All rights are reserved. Reproduction in whole or in part is prohibited without the prior written consent of the copyright owner. The information presented in this document does not form part of any quotation or contract, is believed to be accurate and reliable and may be changed without notice. No liability will be accepted by the publisher for any consequence of its use. Publication thereof does not convey nor imply any license under patent- or other industrial or intellectual property rights. Printed in The Netherlands 115002/03/pp8 Date of release: 1999 May 25 Document order number: 9397 750 05892 ANEXO I - Datasheet do diodo 1N4007 DISCRETE SEMICONDUCTORS DATA SHEET handbook, halfpage M3D119 1N4001ID to 1N4007ID Rectifiers Product specification Supersedes data of April 1992 File under Discrete Semiconductors, SC01 1996 Jun 10 Philips Semiconductors Product specification Rectifiers 1N4001ID to 1N4007ID FEATURES DESCRIPTION • Glass passivated Cavity free cylindrical glass package through Implotec(1) technology. • High maximum operating temperature • Low leakage current This package is hermetically sealed and fatigue free as coefficients of expansion of all used parts are matched. (1) Implotec is a trademark of Philips. • Excellent stability • Available in ammo-pack. k handbook, 4 columns a MAM123 Fig.1 Simplified outline (SOD81) and symbol. LIMITING VALUES In accordance with the Absolute Maximum Rating System (IEC 134). SYMBOL VRRM PARAMETER CONDITIONS − 50 UNIT V 1N4002ID − 100 V 1N4003ID − 200 V 1N4004ID − 400 V 1N4005ID − 600 V 1N4006ID − 800 V 1N4007ID − 1000 V − 50 V continuous reverse voltage 1N4001ID 1N4002ID − 100 V 1N4003ID − 200 V 1N4004ID − 400 V 1N4005ID − 600 V 1N4006ID − 800 V − 1000 V 1N4007ID IF(AV) MAX. repetitive peak reverse voltage 1N4001ID VR MIN. average forward current averaged over any 20 ms period; Tamb = 75 °C; see Fig.2 − 1.00 A averaged over any 20 ms period; Tamb = 100 °C; see Fig.2 − 0.75 A − 10 A half sinewave; 60 Hz − 20 A IFRM repetitive peak forward current IFSM non-repetitive peak forward current Tstg storage temperature −65 +175 °C Tj junction temperature −65 +175 °C 1996 Jun 10 2 Philips Semiconductors Product specification Rectifiers 1N4001ID to 1N4007ID ELECTRICAL CHARACTERISTICS Tj = 25 °C; unless otherwise specified. SYMBOL PARAMETER CONDITIONS MAX. UNIT VF forward voltage IF = 1 A; see see Fig.3 1.1 V VF(AV) full-cycle average forward voltage IF(AV) = 1 A 0.8 V IR reverse current VR = VRmax VR = VRmax; Tamb = 100 °C 50 µA IR(AV) full-cycle average reverse current VR = VRRMmax; Tamb = 75 °C 30 µA 10 µA THERMAL CHARACTERISTICS SYMBOL PARAMETER CONDITIONS Rth j-tp thermal resistance from junction to tie-point lead length = 10 mm Rth j-a thermal resistance from junction to ambient note 1 VALUE 60 K/W 120 K/W Note 1. Device mounted on epoxy-glass printed-circuit board, 1.5 mm thick; thickness of copper ≥40 µm, see Fig.4. For more information please refer to the “General Part of Handbook SC01”. 1996 Jun 10 3 UNIT Philips Semiconductors Product specification Rectifiers 1N4001ID to 1N4007ID GRAPHICAL DATA MBH386 1.5 MBH385 10 handbook, halfpage handbook, halfpage IF (A) IF (A) 1 1 0.5 (1) 0 10−1 0 100 Tamb (°C) 200 0 0.5 (2) (3) 1 VF (V) 1.5 (1) Tamb = 100 °C. (2) Tamb = 20 °C. (3) Tamb = −50 °C. Fig.2 Maximum forward current as a function of ambient temperature. Fig.3 50 handbook, halfpage 25 7 50 2 3 MGA200 Dimensions in mm. Fig.4 Device mounted on a printed-circuit board. 1996 Jun 10 4 Forward current as a function of forward voltage; typical values. Philips Semiconductors Product specification Rectifiers 1N4001ID to 1N4007ID PACKAGE OUTLINE 5 max handbook, full pagewidth 0.81 max 2.15 max 28 min 3.8 max 28 min MBC051 Dimensions in mm. Fig.5 SOD81. DEFINITIONS Data sheet status Objective specification This data sheet contains target or goal specifications for product development. Preliminary specification This data sheet contains preliminary data; supplementary data may be published later. Product specification This data sheet contains final product specifications. Limiting values Limiting values given are in accordance with the Absolute Maximum Rating System (IEC 134). Stress above one or more of the limiting values may cause permanent damage to the device. These are stress ratings only and operation of the device at these or at any other conditions above those given in the Characteristics sections of the specification is not implied. Exposure to limiting values for extended periods may affect device reliability. Application information Where application information is given, it is advisory and does not form part of the specification. LIFE SUPPORT APPLICATIONS These products are not designed for use in life support appliances, devices, or systems where malfunction of these products can reasonably be expected to result in personal injury. Philips customers using or selling these products for use in such applications do so at their own risk and agree to fully indemnify Philips for any damages resulting from such improper use or sale. 1996 Jun 10 5 ANEXO J - Especificações das polias e correias XL