como funciona rs232

12
 Como funciona RS232 Como fazer o trabalho RS232: Siga estas regras simples, em seguida, ele irá trabalhar. Clique aqui para obter informações sobre como RS232 funciona no nível físico bit. Tenho vindo a utilizar RS232 a trabalhar há anos e ele sempre voa bem e é sempre confiável, mas existem algumas regras simples para seguir caso contrário, você pode entrar em grande bagunça. Ir para Regra 1: Mantenha-o simples. Jump to Regra 2: Use um cabo direto. Ir para Regra 3: Fazer a cruz em cima da dev. . tabuleiro Ir para Regra 4: conjunto idêntico RS232 em cada po nta. Jump to Rule 5: Re chec k- conexõe s em ambo s os conector es.  Jump to Configurando Hyperterminal. Ir para outros problemas RS232.  Se você estiver procurando por informações sobre uso geral RS232, em seguida, essas regras pode agir como orientação, mas você precisa entender mais sobre o DCE (equipamento de comunicação de dados) e (Data Terminal Equipment) DTE, todos handshaking e todos os tipos de cabo para a sua do sistema.Basicamente, existem muitos - de modo a olhar para as informações a seguir podem ajudá-lo a obter uma alça sobre a configuração mais simples para mostrar que de fato RS232 funciona. RS232 pode realmente funcionar bem, mas um monte de software exige que todos os sinais de aperto de mão para estar no lugar e é por isso que ele pode ser tão frustrante - perder um fora ou conectar um único fio errado e ela só vai sentar-se lá a fazer absolutamente nada. Regra 1: Mantenha-o simples. RS232 só é difícil se você tentar usar todas as facilidades que o padrãooferece. Você realmente não precisa considerar todos os sinais quando usar RS232 no banco (por simples comunicação entre o hardware e um PC) ou seja, para tornar o trabalho mais de RS232 a poucos metros. Se você quiser fazer o trabalho RS232 a longas distâncias, então você deve usar todos os sinais incluindo sinais de aperto de mão como estes assegurar o funcionamento correto. Para 1-3 metros eu só use o seguinte: TXD Transmissão de dados RXD Receber dados GND Terra Estes trabalham para velocidades de 9600 e além. Você pode testar como muito além de experimentar com os ajustes no programa PIC e software PC.

Upload: rafael-bezerra-da-silva

Post on 09-Jul-2015

408 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Como Funciona RS232

5/10/2018 Como Funciona RS232 - slidepdf.com

http://slidepdf.com/reader/full/como-funciona-rs232 1/12

 

Como funciona RS232

Como fazer o trabalho RS232: Siga estas regras simples, em seguida, eleirá trabalhar. Clique aqui para obter informações sobre como RS232funciona no nível físico bit.

Tenho vindo a utilizar RS232 a trabalhar há anos e ele sempre voa bem e é sempreconfiável, mas existem algumas regras simples para seguir caso contrário, vocêpode entrar em grande bagunça.

Ir para Regra 1: Mantenha-o simples.Jump to Regra 2: Use um cabo direto.Ir para Regra 3: Fazer a cruz em cima da dev. . tabuleiroIr para Regra 4: conjunto idêntico RS232 em cada ponta.Jump to Rule 5: Re check- conexões em ambos os conectores. 

Jump to Configurando Hyperterminal.

Ir para outros problemas RS232.

 

Se você estiver procurando por informações sobre uso geral RS232, em seguida,essas regras pode agir como orientação, mas você precisa entender mais sobre oDCE (equipamento de comunicação de dados) e (Data Terminal Equipment) DTE,todos handshaking e todos os tipos de cabo para a sua do sistema.Basicamente,existem muitos - de modo a olhar para as informações a seguir podem ajudá-lo aobter uma alça sobre a configuração mais simples para mostrar que de fato RS232funciona.

RS232 pode realmente funcionar bem, mas um monte de software exige que todosos sinais de aperto de mão para estar no lugar e é por isso que ele pode ser tãofrustrante - perder um fora ou conectar um único fio errado e ela só vai sentar-selá a fazer absolutamente nada.

Regra 1: Mantenha-o simples.

RS232 só é difícil se você tentar usar todas as facilidades que o

padrãooferece. Você realmente não precisa considerar todos os sinais quando usarRS232 no banco (por simples comunicação entre o hardware e um PC) ou seja,para tornar o trabalho mais de RS232 a poucos metros.

Se você quiser fazer o trabalho RS232 a longas distâncias, então você deve usartodos os sinais incluindo sinais de aperto de mão como estes assegurar ofuncionamento correto. Para 1-3 metros eu só use o seguinte:

• TXD Transmissão de dados• RXD Receber dados• GND Terra

Estes trabalham para velocidades de 9600 e além. Você pode testar como muitoalém de experimentar com os ajustes no programa PIC e software PC.

Page 2: Como Funciona RS232

5/10/2018 Como Funciona RS232 - slidepdf.com

http://slidepdf.com/reader/full/como-funciona-rs232 2/12

 

Regra 2: Use um cabo direto.

Este é um cabo pino 1, onde se conecta ao pino 1 na outra extremidade, o pino2 se conecta ao pino 2 do outro lado etc

Existem dois tipos de cabos:

• Direto - também conhecido como modem.• Atravesse - também conhecido como modem nulo.

Nota: Os sinais que são cruzadas ao longo de um cabo de modem nulo são (TX,RX) e sinais de handshaking (RTS, CTS) e (DSR, DTR).

Se você não sabe o tipo de cabo que você tem, em seguida, use um multímetropara testar a sua configuração buzz. Para certificar-se de não derrubar tudonochão furar um pedaço de fio no conector fêmea e enrole a outra extremidade dofio ao redor da sonda multímetro - então você pode se concentrar em investigar o

pino no conector macho. Para manter as coisas simples usar um cabo direto.

Observação: Os cabos Serial nunca são marcados como modem nulo ou modem -eles parecem todos iguais!

A chave para obter um sistema de RS232 para trabalhar é saber exatamente ocabo que você tem e sua conexões de pinos 

 

. Usando um cabo direto você nãoprecisa se preocupar com Modem / Nulo cabos do modem e isso eliminaumafonte de confusão.

Regra 3: Crossover em seu dev. bordo.

Você não pode fazer o cruzamento, no final PC como você basta conectar o caboserial no PC - e isso é bom. Neste ponto, você tem ligações directas a partir doconector serial na parte de trás do PC todo o caminho até a sua placa dedesenvolvimento.

Para você saber exatamente onde você está - todas as conexões para a placa dedesenvolvimento estão em linha reta através do PC. O passo final é fazer o crossover na placa.

O esquema abaixo mostra uma placa de desenvolvimento com uma conexão serialde / para o PC que permite o trabalho RS232 entre um microcontrolador eo PC.

Page 3: Como Funciona RS232

5/10/2018 Como Funciona RS232 - slidepdf.com

http://slidepdf.com/reader/full/como-funciona-rs232 3/12

 

Eu tenho marcado o conector serial com as conexões localizadas no PC - o quetorna mais fácil de visualizar todo o sistema.

Você pode pensar no PC e um cabo como uma unidade conectando-se diretamenteà placa de desenvolvimento e você não precisa se preocupar com nulos os cabos do

modem , cabos crossover, trocadores de gênero, atravessar caixas, etc Você sóprecisa se concentrar no esquema com o porta serial do PC como uma extensão doesquema.

Tudo o que você fazer agora é ligar o conector serial rotulados TX (que é a entradade série para a placa de desenvolvimento a partir do PC) para o receptor em suaplaca de desenvolvimento (rotulado R1IN). Da mesma forma se conectar T1OUT(que é a saída serial da placa de desenvolvimento) para a porta serial do PCrotulados RX. Isso torna o cross-over em sua placa. Em seguida conectar osmotivos juntos (GND e 0 volts).

Regra 4: Use configurações idênticas em cada extremidade.

Em cada programa haverá uma configuração que define o uso dos bits transmitidosentre o PC eo microcontrolador. Para tornar o trabalho RS232 essasconfigurações devem ser idênticas. Como ponto de partida use as seguintesconfigurações em cada extremidade.

Bits por segundo (baud) 9600

Número de bits 8

Paridade Nenhum

Bits de parada 1

Page 4: Como Funciona RS232

5/10/2018 Como Funciona RS232 - slidepdf.com

http://slidepdf.com/reader/full/como-funciona-rs232 4/12

 

Controle de fluxo Nenhum

Se você quiser mudar alguma coisa só mudar uma coisa de cada vez, masnovamente manter o mesmo valor (s) em ambos os pedaços de software.

Essas configurações são as configurações padrão

Configurações Hyperterminal 

No Windows você pode encontrar Hyperterminal (um acessório do programa),navegando a partir do menu Iniciar (no Windows XP):

Iniciar-> Todos os Programas-> Acessórios -> Comunicações-> Hyperterminal

O diálogo de começar a seguir é mostrado (I digitou o nome do PIC para identificara sessão):

Pressione OK e você está mostrado o diálogo de conexão.

Page 5: Como Funciona RS232

5/10/2018 Como Funciona RS232 - slidepdf.com

http://slidepdf.com/reader/full/como-funciona-rs232 5/12

 

Clique em Cancelar para este diálogo que você não deseja discar para fora.

Agora no menu principal no Hyperterminal Hit Arquivo-> Propriedades

Selecione a opção ' Conectar usando "drop down menu (no meio) e selecione aporta serial que você deseja usar COM1 por exemplo.

Page 6: Como Funciona RS232

5/10/2018 Como Funciona RS232 - slidepdf.com

http://slidepdf.com/reader/full/como-funciona-rs232 6/12

 

Em seguida, aperte o botão 'Configurar' embaixo.

Page 7: Como Funciona RS232

5/10/2018 Como Funciona RS232 - slidepdf.com

http://slidepdf.com/reader/full/como-funciona-rs232 7/12

 

Ufa! - Lá no passado - agora definir os parâmetros conforme mostradoanteriormente.

Regra 5: Verifique os conectores antes de construir um pcb.

A grande fonte de confusão em tornar o trabalho é o gênero RS232 conector(masculino ou feminino). Normalmente, um designer pcb é dado um diagrama quenão especifica o gênero da peça - e usa o que foi usado pela última vez.Quando setrata de construir a bordo as conexões são espelhados (conectores macho e fêmeasão espelhos um do outro) e você tem que fio mão a conexão.

Para garantir que isso não acontece sempre lay out todas as partes antes determinar o esquema de modo que você garantir o gênero correto de conexões apartir de uma extremidade do sistema para o outro.

Ficando o gênero das conexões é essencial para dobrar e até triplicar verificar aspeças para que você saiba em sua cabeça que caminho conectar o sistema.

Agora dirigir o micro PIC, utilizando o código USART.

Outras razões que o RS232 pode não funcionar

Se você estiver escrevendo código no PC as portas seriais são muito exigentessobre o que as conexões são feitas com a porta serial e exigem looped volta sinais ,a menos que se tenha o cuidado de programar os chips no PC para que eles nãoprecisam de sinais de loop backed. É melhor apenas para uso conhecido programasde trabalho, tais como Hyperterminal.

Nota: back loop significa simular os sinais em uma extremidade - DTS está ligado aRTS e DTR é conectado ao DSR (no final mesmo) - às vezes você precisa paracontrolar CD também.

Outra razão para RS232 não trabalhar é se você usar o equipamento que éalimentado pela porta serial. Laptops são otimizados para economia de energia,para que dar o mínimo de energia (volts e baixa corrente).

Outra possibilidade para RS232 não trabalhar é de sensoriamento nível detensão. Níveis detectados pelo chip de série no PC, não pode permitir a detecção dosinal.

Novos chips da porta serial no PC detectar tensões abaixo de 3V (e acima de 3V)como um 'um', mas mais velhos chips não vai denunciá-lo desde o padrão RS232define esta faixa de tensão como indeterminados. Para esses chips mais velhos atensão para um 'um' (marca) deve ser inferior a-3V e por um 'zero' (espaço) deveser superior a 3V. A área de 3V ± indeterminado dá a imunidade do sistema RS232ao ruído e isso permite que o sistema funcione em um ambiente com ruídoeléctrico, mas sacrificar a imunidade a ruídos significa que é mais fácil interfaceusando os níveis padrão de lógica CMOS (0,5 V).

A única maneira de descobrir se o seu sistema funciona com níveis de (0,5 V) alógica é testá-lo - que é uma dor (e que se você alterá-lo posteriormente). Por isso,é apenas muito mais fácil usar um chip tradutor nível, como um MAX232.

Assim funciona RS232? - Se você seguir estas orientações, em seguida, RS232 vaifuncionar.

Page 8: Como Funciona RS232

5/10/2018 Como Funciona RS232 - slidepdf.com

http://slidepdf.com/reader/full/como-funciona-rs232 8/12

 

This document describes how RS232 works at the physical level so you will knowwhat signals you can expect to see at the microcontroller pins.

Click here to find more information on how RS232 works in a system and how toset it up and for pinout information click here.

What is it ?

It is a method (or protocol - an agreed standard) that defines how to transfer databetween two devices using a few wires.

It uses a serial transmission method where bytes of data are output one bit at atime onto a single wire.

Data is only transmitted in one direction for each wire so for bi-directionalcommunication (two directions) you needtwo wires.

These two along with a ground reference (total: three wires) make up the minimumconfiguration that you can get away with.

Note: For more reliablecommunication over long distances you may need 

more wires for handshake signals etc.

More formally RS232 is an asynchronous communication protocol that lets youtransfer data between electronic devices.

Basically it can transfer a single byte of data over a serial cable having between 3to 22 signals and running at speeds from 100 to 20k baud. Common baud ratesused are 2.4k, 9.6k, 19.2k, The cable length can be up to 50ft. Higher baud ratesare used but not covered by the standardthey still work though e.g. 38400,57600Baud (bits/s).

To transfer a block of data individual bytes are transmitted one after another.

How RS232 works

This section describes how RS232 works in general without describing complexhandshake methods - only the simplest system is described - this it themost useful and the most likely to work!.

Data is transmitted serially in one direction over a pair of wires. Data going out islabeled Tx (indicating transmission) while data coming in is labeled Rx (indicatingreception). To create a two way communication system a minimum of three wires are needed Tx, Rx and GND (ground). Crossing over Tx & Rx betweenthe two systems lets each unit talk to the opposite one.

Each byte can be transmitted at any time (as long as the previous byte has beentransmitted). The transmitted byte is not synchronized to the receiver - it is an

asynchronous protocol i.e. there is no clock signal. For this reason software at eachend of the communication link must be set up exactly the same so that each serial

Page 9: Como Funciona RS232

5/10/2018 Como Funciona RS232 - slidepdf.com

http://slidepdf.com/reader/full/como-funciona-rs232 9/12

 

decoder chip can decode the serial data stream.

Note: The signal level inversion (logic 1 is -12V and logic 0 is +12V).

How RS232 works : Baud

This is simply the transmission speed measured in bits per second. It defines thefrequency of each bit period.

For a baud rate of 2400 (2400 bps) the frequency is 2400Hz and the bit period is1/2400 or 416.6us. This is the information that a receiver uses to recover the bitsfrom the data stream.

How RS232 works : Voltage levels

Transmitter 

How RS232 works when transmitting a data bit stream.To make it work over long cables high voltages are sent from each transmittersince due to cable resistance the voltage reduces the further the signal has to

travel. The output voltage specification isfrom +5V to +25V (transmitting a logicalzero) and -5V to -25V (transmitting a logical one).

Note: all signals in the cable have to generate the same voltage levels e.g. DTR,DSR, RTS, CTS. So you need a lot of level translator chips for a full interface but forvery short distances you only need TX and RX and ground.

The receiver can accept minimum signal levels of ±3V.

The maximum voltage of ±25V does not have to be used and a common voltage in

use is ±12V (output by MAX232 transceiver chip).

Page 10: Como Funciona RS232

5/10/2018 Como Funciona RS232 - slidepdf.com

http://slidepdf.com/reader/full/como-funciona-rs232 10/12

 

A mark (logical one) is sent as -12V and a space (logical zero) is sent as +12V i.e.the logic sense is inverted.

Note: The fact that high voltages exist at the serial port allows powering devicesthat you would not normally expect to find on it. But they must draw very little

current.

Receiver 

How RS232 works when receiving a data bit stream.At the receiver the input voltage levels are defined as ±3V i.e. to receive a logiczero the voltage must be greater than 3V and to receive a logic one the voltagemust be smaller than -3V. This allows for losses as the signal travels down thecable and provides noise immunity i.e. any spurious noise up to a level of ±3V canbe tolerated without it having any effect on the receiver.

How RS232 works : Bit stream

How RS232 works - the Start BitThe protocol is described as asynchronous as there is no clock transmitted at all.Instead a different method of clock recovery is used.

At the beginning of each transmission a start bit is transmitted indicating to thereceiver that a byte of data is about to follow.

The start bit lets the receiver synchronize to the data bits. What this means is thatthe receiver can create its own sample clock at the middle of each bit. Note that

once the start bit is found the receiver knows where the following bits will be as it isgiven the sample period (derived from the baud rate) as part of theinitialization process.

How RS232 works - the Data bitsData bits follow the start bit. There will be seven or eight data bits with the lsbtransmitted first. The reason you can choose between seven or eight is that ASCIIis made up of the alphabet within the first seven bits (as well as the controlcharacters). The eighth bit extends the character set for graphical symbols.

If you only want to transmit text then you only need 7 bits. This saves a bit and

increases transmission speed when transmitting large blocks of data. Other data bitsizes are 5 and 6 bits. However bit length is usually ignored and a transmissionsize of 8 bits is commonly used.

Note: If you use RS232 to transmit raw data (binary data) then you will need 8

data bits.

How RS232 works - the Parity BitThe parity bit is a crude error detection mechanism. You can use either odd parityor even parity or none at all (in this case no parity bit is transmitted).

It simply evaluates all the data bits and for odd parity returns a logic one if there isan odd number of data bits that are set. For even parity an even number of data

Page 11: Como Funciona RS232

5/10/2018 Como Funciona RS232 - slidepdf.com

http://slidepdf.com/reader/full/como-funciona-rs232 11/12

 

bits that are set, sets the parity bit.

At the receiver the parity bit is used to tell if an error occurred during transmission.You can use this in the receiver software by reading a flag in the UART module.

The problem with error detection using the parity bit is that if two bits are in errorthen the parity check fails. This is because each error cancels the effect of the other(in terms of the parity calculation). Any even number of errors causes a failure inerror detection.

It won't be a problem on a bench top based system (that has no critical datatransfer). Over a short cable e.g. 6ft you probably won't see any errors anyway.Normally I use no parity and there is no problem at all.

For systems running over a long distance or in a noisy environment a better systemshould be used e.g. Adding a cyclic redundancy check to the data stream before

and after it is sent over the RS232. CRCs let you check for and correct quite a fewerrors without re transmitting the data.

How RS232 works - the Stop bitThe stop bit merely gives a period of time before the next start bit can betransmitted. It is the opposite sense to the start bit and because of this allows thestart bit to be seen.

If there was no stop bit then the last bit in the data stream would be the parity bit(or data bit if parity is not active). This would change depending on the data sentso if it had the same sense as the start bit then the start bit could not be seen!

The stop bit can be set choosing from 1, 1.5, or 2 bit periods.

How RS232 works : Typical Settings

Typical settings for use on the desktop e.g. between a microcontroller andhyperterminal:

How RS232 works : Typical Baud rate settings.

Baud 9600

Data bits 8

Parity None

Stop bits 1

Hardware Connections 3 (Rx,Tx,GND) - Rx and Tx crossed over.

Signals : How RS232 works with signal levels

At some point you may want to make a software UART perhaps to save code spacein your current design (maybe you don't need the receive part - just outputtingvariables) or to use a spare pin or perhaps your provider's library does not work.

Page 12: Como Funciona RS232

5/10/2018 Como Funciona RS232 - slidepdf.com

http://slidepdf.com/reader/full/como-funciona-rs232 12/12

 

Note: you can find receive and transmit software USART code in the12F675 Tutorial 

 pages.

To create it you need the actual signal diagrams that you see at the microcontrollerpin (strangely these are hard to find on the web).

The following diagram shows how RS232 works by generating 0-5V logicbitstream at the output pin of the microcontroller or UART followed by thetranslated voltages that are transmitted to the serial cable. These are generated bysending the 0-5V logic levels to a transceiver chip e.g. MAX232. which can use a 5Vpower supply and boost it to the required 12 volts.

How RS232 works when transmitting a character

End of page : How RS232 works.