uart

Upload: rafael-sierra

Post on 08-Jan-2016

215 views

Category:

Documents


0 download

DESCRIPTION

modelo usart

TRANSCRIPT

UARTA Universal Asynchronous Receiver and Transmitter (UART) can be used to send and receive data between two devices. More specific these devices can be PC-to-PC, PC-to-micro controller and micro controller-to-micro controller. The UART communicates using TTL voltages +5V and 0V or LVTTL depending on your micro controllers VCC voltage.If you wish to connect to a PC you need to use RS232 protocol specifications. This means that the hardware communication is done with specific voltage levels. (+15V and -15V) This can be achieved by using a MAX232 level shifter.The hardware is explained in this schematic:

The DB-9 connector has 9 pins but you only need to use 3 of them. Notice that the drawing above shows the FRONT VIEW thus remember that you are soldering on the other side. On most connectors the pin outs can also be found on the connector itself.If your controller has no UART you can use a software UART see below. If your controller has one UART you connect controller pins TxD and RxD to TxD and RxD in the schematic above. If your controller has more than one UART you connect controller pins TxD0 and RxD0 to TxD and RxD in the schematic above.You now need to initialize the program in your micro controller, open a new .bas file and add the following code in the beginning of your program.$regfile="your micro here def.dat"$crystal=8000000$baud=19200Make sure to define your micro controller after $regfile for example if you use the ATMega32$regfile="m32def.dat"Some new chips can use an internal oscillator, also some chips are configured to use the internal oscillator by default. Using an internal oscillator means you do not need an external crystal.Perform this step only if you have an internal oscillator.Open the BASCOM-AVR programmer like this:

Select the Lock and Fuse Bits tab and maximize the programmer window.

Check if you see the following in the Fusebit section:

"1:Divide Clock by 8 Disabled" and "Int. RC Osc. 8 MHz; Start-up time: X CK + X ms; [CKSEL=XXXX SUT=XX]"

These options are not available for all AVRs, if you dont have the option do not change any fuse bits.If these options are available, but in a wrong setting. Change the setting in the drop down box and click another Fuse section. Finally click the "Program FS" button. Click "Refresh" to see the actual setting.Now connect a straight cable between the DB-9 connector, micro controller side and the PC side.Program a test program into your micro controller, it should look like this:$regfile="m32def.dat"'Define your own$crystal=8000000 $baud=19200 DoPrint"Hello World"Waitms25LoopEndNow open the BASCOM-AVR Terminal and set your connection settings by clicking Terminal -> Settings Select your computers COM port and select baud 19200, Parity none, Data bits 8, Stop bits 1, Handshake none, emulation none.If you see the Hello World displayed in the BASCOM-AVR Terminal emulator window, your configuration is OK. Congratulations.ExampleYou can also try this example with the BASCOM Terminal emulator, it shows you how to send and receive with various commands.$regfile="m88def.dat"$crystal=8000000$baud=19200DimAkeyAsByte'HerewedeclareabytevariablePrintPrint"Hello,hitanyalphanumericalkey..."Akey=Waitkey()'WaitkeywaitsuntillacharisreceivedfromtheUARTPrintAkeyWait1PrintPrint"Thanks!,asyoucouldseethecontrollerprintsanumber"Print"butnotthekeyyoupressed."Wait1PrintPrint"Nowtrytheenterkey..."Akey=Waitkey()Akey=Waitkey()PrintAkeyPrintPrint"ThenumberyouseeistheASCIIvalueofthekeyyoupressed."Print"Weneedtoconvertthenumberbacktothekey..."Print'NoticewhatthislinedoesPrint"Pleasetryanalphanumericalkeyagain..."Akey=Waitkey()PrintChr(akey)'NoticewhatthisdoesPrint"That'sfine!"Wait1PrintPrint"Foralotoffunctions,justonekeyisnotenough..."Print"Nowtypeyournameandhitentertoconfirm"DimInputstringAsString*12'DeclareastringvariablehereDoAkey=Waitkey()IfAkey=13ThenGotoThanks'OnenterkeygotothanksInputstring=Inputstring+Chr(akey)'AssignthestringLoopThanks:Print"Thankyou";Inputstring;"!"'Noticewhat;doesWait1PrintPrint"Takealookattheprogramcodeandtrytounderstand"Print"howthisprogramworks.AlsopressF1atthestatements"PrintPrint"Ifyouunderstandeverythingcontinuetothenextexperiment"EndASCIIAs you could have seen in the previous example we use the PRINT statement to send something to the UART. Actually we do not send just text. We send ASCII characters. ASCII means American Standard Code for Information Interchange. Basically ASCII is a list of 127 characters.ASCII Table (Incomplete)Decimal Hex Binary Value------- --- ------ -----000 000 00000000 NUL (Null char.)008 008 00001000 BS (Backspace)009 009 00001001 HT (Horizontal Tab)010 00A 00001010 LF (Line Feed)012 00C 00001100 FF (Form Feed)013 00D 00001101 CR (Carriage Return)048 030 00110000 0049 031 00110001 1052 034 00110100 4065 041 01000001 A066 042 01000010 B067 043 01000011 CYou can find a complete ASCII tablehereCARRIAGE RETURN (CR) AND LINE FEED (LF)In the previous example you can also see that a second print statement always prints the printed text to the following line. This is caused by the fact that the print statement always adds the CR and LF characters.Basically if we state:PrintABCWe send 65 66 67 13 10 to the UART. (In binary format)The carriage return character (13) returns the cursor back to column position 0 of the current line. The line feed (10) moves the cursor to the next line.PrintABC;When we type a semicolon ( ; ) at the end of the line...Bascom does not send a carriage return/line feed, so you can print another text after the ABC on the same line.PrintABC;Chr(13) ;This would send only ABC CR. The next print would overwrite the ABC.OVERVIEWHere are some other commands that you can use for UART communications:Waitkey()Waitkey will until a character is received in the serial buffer.Ischarwaiting()Returns 1 when a character is waiting in the hardware UART buffer.Inkey()Inkey returns the ASCII value of the first character in the serial input buffer.PrintSends a variable or non-variable string to the UARTANOTHER EXAMPLEThis example shows how to use Ischarwaiting to test if there is a key pressed. And if there is, read to a variable.'Print "Press B key to start"DimSerialcharwaitingAsByte,SerialcharAsByteSerialcharwaiting=Ischarwaiting()'Check if B or b pressed then gotoIfSerialcharwaiting=1ThenSerialchar=Inkey()IfSerialchar=66OrSerialchar=98Then GotoMyRoutineEndIfEndIfGotoMainMyroutine:'StatementsMain:'StatementsEndBUFFERING SERIAL DATAIf you wish to send and receive data at high speed, you need to use serial input and serial output buffers. This buffering is implemented in BASCOM-AVR and can only be used for hardware UARTs.To configure a UART to use buffers, you need to use the Config statement.ConfigSerialout=Buffered,Size=20and/orConfigSerialin=Buffered,Size=20More information can be found in BASCOM-Help. Search topic = "config serialin". There is also a sample program RS232BUFFER.BAS in the samples folder if you wish a demonstration of the buffering.SOFTWARE UARTThe previous examples used the hardware UART. That means the compiler uses the internal UART registers and internal hardware (RxD(0) and TxD(0)) of the AVR. If you dont have a hardware UART you can also use a software UART.The Bascom compiler makes it easy to create additional UARTs. Bascom creates software UARTs on virtually every port pin. Remember that a software UART is not as robust as a hardware UART, thus you can get timing problems if you have lots of interrupts in your program.For this example we use micro controller pins portc.1 and portc.2.Connect portc.1 to TxD and portc.2 to RxD see the schematic above.Change the $regfile and program this example:$regfile="m88def.dat"$crystal=8000000$baud=19200DimBAsByteWaitms100'OpenaTRANSMITchannelforoutputOpen"comc.1:19200,8,n,1"ForOutputAs#1Print#1,"serialoutput"'NowopenaRECEIVEchannelforinputOpen"comc.2:19200,8,n,1"ForInputAs#2'Sincethereisnorelationbetweentheinputandoutputpin'thereisNOECHOwhilekeysaretypedPrint#1,"Pressanyalphanumericalkey"'WithINKEY()wecancheckifthereisdataavailable'TouseitwiththesoftwareUARTyoumustprovidethechannelDo'StoreinbyteB=Inkey(#2)'Whenthevalue>0wegotsomethingIfB>0ThenPrint#1,Chr(b)'PrintthecharacterEndIfLoopClose#2'ClosethechannelsClose#1EndAfter you have programmed the controller and you connected the serial cable, open the terminal emulator by clicking onin Bascom.You should see the program asking for an alphanumerical input, and it should print the input back to the terminal.