Home

AT89S8252 In-System Programming MCU Application Note

image

Contents

1. Issue command to hang up mov dptr hangup_cmd point to hang up string call modem_cmd transmit string jnc hh jump on pass The polite way didn t work so drop DTR 5 94 Microcontroller memm ees MiCrOCONntroller hh modem_cmd The controller must be reset to exit this state setb ret DTR_ force modem to drop the line Transmit command string to modem and validate the response Return with carry set if modem fails to respond as expected or if excessive parity errors or receive timeouts occur Valid responses consist of a byte code followed by a carriage return Parity errors and timeouts cause the command to be resent Expected delays for command responses are absorbed by GET_CHAR On entry DPTR must point to a null terminated command string mm1 mm2 mm3 mm4 send_string push mov call clr call jc cjne call jc cjne clr jmp djnzb setb pop ret b b MTRIES send_string RI get_char mm3 a OK mm2 get_char mm3 a CR mm2 mm4 mm1 c Transmit string pointed to by DPTR String may be of any length but must be null terminated push push push acc dpl dph number of attempts transmit command string discard any waiting character receive result code jump on parity error or timeout loop if response is not valid receive carriage return jump on parity error or timeout loop if respon
2. djnz b 500 us 12 MHz djnz b 500 us Q 12 MHz djnz acc dd pop b pop acc ret delay sec Delay for 1 second times the value in the accumulator push acc push b mov b a ddd mov a 250 call delay_ms 250 ms call delay_ms 500 ms call delay_ms 750 ms call delay_ms 1000 ms djnz b ddd pop b pop acc ret END Appendix 3 Code for AT89S8252 Programmer NAME AT89S8252_ Programmer The programmer powers up with the control signals to the target AT89S8252 inactive allowing the program in the target to run normally Upon receipt of the first valid data record the programmer puts the target into write mode The first and subsequent valid records are dissected as they are received and their data is written into the target Receipt of a valid end of file record terminates programming and resets the target control signals allowing the new program in the target to run Each record received is checked for validity If it is invalid the receiver sends a NAK to the remote system and discards the record Bad records are not programmed into the target AT89S8252 Valid records 5 86 Microcontroller memm ees MiCrOCOONntroller are programmed into the target AT89S8252 and verified If verification succeeds an ACK is sent to the remote system If verification fails the receiver sends CAN to abort the upload Failure to verify is a fatal error The target AT89S8252 will be left in prog
3. ret RI reset receive flag Read two hexadecimal ASCII characters from the serial port and return their binary equivalent in the accumulator Return with carry set if either character was invalid or contained a parity error gb ascii2bin call jc call jc swap mov call jc call jc orl ret get_char get first char from serial port gb exit on parity error ascii2bin convert hex to binary gb exit on invalid char a first hex digit times 16 b a save value get_char get second char from serial port gb exit on parity error ascii2bin convert hex to binary gb exit on invalid char a b combined binary equivalent Convert hexadecimal digit in the accumulator to its binary equivalent and return it in the accumulator Valid hex digits are 0 9 and A F upper case only Return with carry set if the character received is not a valid hex digit al mov clr subb jnc mov clr subb jmp mov subb cpl temp a save char c prepare for subtraction a 9 1 compare to 9 al jump if char above 9 a temp get original char c prepare for subtraction a 0 compare to 0 a4 return error if char below 0 else binary value in accumulator a temp get original char a F 1 compare to F c invert error flag a4 return error if char is above F Almer 5 97 a2 a3 a4 get_record mov subb add re
4. ORG 0023h serial I O interrupt vector jmp serial_int ORG 40h begin constant data space attn_cmd DB 0 modem return to command mode reset_cmd DB ATZ CR 0 modem reset string must be last command on line and modem returns code before executing init_cmd DB AT amp R1 amp A0 CR 0 modem init string hangup_cmd DB ATH CR O modem on hook string ORG 0080h begin code space USING 0 register bank 0 init mov sp stack 1 initialize stack pointer call initialize initialize controller registers seto LTOF disable long timer 0 seto LT1F disable long timer 1 Initialize the modem seto TI set transmit interrupt flag kludge for first use setb ETO enable timer 0 interrupt call modem_init initialize modem clr ETO disable timer 0 interrupt jnc m1 jump if modem init passes clr EA global interrupt disable orl PCON 1 idle the controller reset exits m1 Clear pending interrupts before enabling serial interrupts jnb TI wait for transmitter to clear clr Tl Clear transmit interrupt flag clr RI clear receive interrupt flag setb ES enable serial ints to wake controller clr FO clear connect flag PSW 5 bit idle orl PCON 1 idle the controller serial int exits jnb FO idle return to idle if not connected Connection has been established 5 90 Microcontroller memm ees MiCrOCONntroller m2 m3 m4 m5 m6 m7 ms m9 Begin p
5. The line driver receiver produces RS 232 levels at the modem interface while requiring only a 5 V power supply The AT89C2051 micro controller does not support external program or data mem ory which requires that program code be kept small enough to fit into on chip memory L L PEELE J AIMEL 74HCT32 U2C 9 74HCT32 vA ELEELE Faa DL1414T 74HCT32 The serial interface through which the programmer con nects to the modem supports two handshaking signals DTR and DSR On power up the programmer asserts DTR to which the modem responds by asserting DSR If the modem should fail to respond to any command includ ing the command to hang up the programmer deasserts DTR which forces the modem to hang up The programmer controls the modem by sending ASCII command strings over the serial interface to which the modem responds with Hayes style ASCII numeric codes The programmer code is optimized for use with the U S Robotics Sportster 14 400 baud external modem used in the test configuration and may require modifications if used with other modems Since a reset circuit is absent from the modified application the programmer provides the power on reset function to the AT89S8252 microcontroller The programmer powers up with RST asserted resetting the microcontroller Some 5 75 AIMEL time later RST is deasserted under firmware control allow ing the applica
6. available in the Tools menu The ASPECT Editor pro vides the option to compile a source file in the Editor Tools menu Launch Procomm Plus and create a Connection Directory entry for the remote station Under Port Settings set the baud rate to 9600 parity to EVEN number of data bits to 7 number of stop bits to 1 plex to FULL Creating a Hex File The example source code for the modified display applica tion Appendix 2 contains a string at location usr_msg which is written repeatedly to the alphanumeric displays The user may substitute a different message as long as it is enclosed in single quotes and is null terminated Long messages may require that the value in the subsequent ORG directive be increased to prevent the message from being over written by code The message may contain only characters with ASCII codes from 20 5F hexadecimal The modified source code may then be assembled linked and an Intel hex file produced During the development of this application note code was assembled and hex files generated utilizing the tools ina vintage copy of the Intel MCS 51 Software Development Package for the IBM PC The source code may require cosmetic changes for compatibility with other assemblers and software tools It is especially important to note that variations exist in Intel hex file format This application requires that record data fields be limited to 16 or fewer entries and that address fields contain 4 hex digi
7. EQU r4 EQU 10 EQU r5 EQU r6 EQU r7 BIT p3 3 BIT p3 7 BIT p1 7 BIT p1 6 BIT p1 4 BIT p1 3 BIT p1 2 DSEG AT 20h DATA 20h BIT flags 0 BIT flags 1 ORG30h DS 1 DS 1 DS 1 DS 1 DS 32 ORG 60h DS 20h DATA 87h CSEG ORG 0000h jmp init max attempts to access modem erase chip function first byte second byte enable write function first byte second byte function third byte write code memory function Flash read code memory function write data memory function EEPROM read data memory function long timer one low byte long timer one high byte long timer two only byte general purpose index register running checksum on record temporary storage loop counter modem control signals target control signals serial clock serial data out serial data in misc flags long timer 0 overflow flag long timer 1 overflow flag record type record load address low byte record load address high byte record data byte count storage for record data field stack origin stack depth address of Power Control register added to enlighten the assembler power on reset vector Almer Microcontroller 5 89 AIMEL ORG 0003h external interrupt 0 vector reti undefined ORG 000Bh timer 0 overflow vector jmp timer_int ORG 0013h external interrupt 1 vector reti undefined ORG 001Bh timer 1 overflow vector reti undefined
8. display control signals inactive when RST is asserted eliminating erratic oper ation of the displays during program ming No isolation of the display address or data inputs is required since these inputs are ignored by the displays when the control signals are inactive After programming when RST is deasserted the microcontroller I O ports are high as AIMEL Microcontroller Application Note 0898A A 12 97 5 73 AIMEL the latch becomes transparent Since the display control inputs are inactive high the display contents are not dis turbed until the new firmware writes the displays Although not essential in this application it might be imperative in some applications that the state of the peripheral circuitry not be disturbed during programming Finally programmer access has been provided to three AT89S8252 SPI port pins P1 5 MOSI P1 6 MISO and P1 7 SCK SPI port pin P1 4 SS is not used during pro gramming In the example application the SPI port pins are Figure 1 AT89S8252 Moving Display Application Example vi vec c2 o oe 31 30pf I ka vi 19 tur 6 MHz c3 Sr k 18 l 30 pF 9 19 P3 0 RXD 1 P3 1 TXD 15 P3 2 INTO 12 P3 3 NT 15 si oo J SW SPST 20 JI o Jon ja w r 5 74 P1 6 MISO P1 7 SCK AT89S8252 available for use in programming the microcontroller Appli cations which utilize the SPI port pins must be modified by the add
9. invalid record type record length or checksum is invalid Program data accumulated during the processing of an invalid packet is discarded The programmer sends a NAK to the computer to signal recep tion of an invalid packet and resumes polling for a valid packet header Receipt of the first valid data packet causes the program mer to interrupt the application microcontroller The micro controller responds to the interrupt by abandoning its usual routine and displaying a message PROGRAMMING indicating that programming is taking place If this is the first valid data packet since power was applied or an end of file packet was received the programmer asserts the control signals necessary to place the microcontroller into programming mode The first and subsequent valid data packets are dissected as they are received and the data which they contain is pro grammed into the application microcontroller at the address indicated in the packet load address field After program ming the data is read back from the microcontroller and verified against the received packet data If programming was successful the programmer sends ACK to the com puter The programmer then resumes polling for a valid packet header subject to the thirty second reset delay If programming fails the programmer sends CAN to signal the computer to abort the file transfer The modem hangs up and the programmer returns to sleep waiting for the next call The app
10. load address anl a 00011111b isolate 5 bits Microcontroller ees MiCrOCOONntroller wit we ws wa v5 rl a rl a rl a orl a READ_CODE mov temp a mov index data_buf mov kount data_len mov a temp call shout mov a r2 call shout Read data and verify call shin mov b index cjne a b we2 jmp vv3 setb c jmp vv5 Next address mov a r2 add a 1 mov r2 a jnc vv4 carry out of low byte mov a r3 add a 1 mov r3 a anl a 00011111b rl a rl a rl a orl a READ_CODE mov temp a Next data inc index djnz kount vv1 clr c ret move 5 bits to top specify code read function save adjusted high byte pointer to data buffer byte counter send adjusted high byte of address send low byte of address read data get record data jump on verify fail verify OK do next address set error flag return get low byte of address increment low byte save incremented value jump if no carry out of low byte get high byte of address increment high byte save incremented value isolate 5 bits move 5 bits to top specify code write function save adjusted high byte point to next buffer location decrement byte count and loop clear error flag Almer 5 101 AIMEL shout Shift out a byte most significant bit first SCK expected low on entry Return with SCK low Called with data
11. of displaying digits 0 9 the upper case alphabet and punc tuation characters The displayable char acter codes are ASCII 20 5F hexadeci mal A power on reset circuit and a 6 MHz crystal complete the application Neither external program memory nor external data memory is used Modifications to the Application to Support In System Programming The AT89S8252 microcontroller features an SPI port through which on chip Flash memory and EEPROM may be pro grammed To program the microcontrol ler RST is held high while commands addresses and data are applied to the SPI port For command format and tim ing requirements refer to the Atmel AT89S8252 Microcontroller data sheet Figure 2 shows the example application modified for in system programming The microcontroller reset circuit has been eliminated and RST is controlled by the programmer The absence of a reset circuit requires that the program mer reset the microcontroller when power is first applied to the application An optional connection SHUTDN to an AT89S8252 interrupt input has been pro vided to allow the programmer to signal the microcontroller prior to programming The resident firmware responds to the interrupt by displaying a message PROGRAMMING indicating that pro gramming is in progress A simple latch composed of four OR gates has been added between the out puts of the microcontroller and the dis play control inputs The latch holds the
12. to send in A push b mov ob 8 bit counter x42 rlc a move bit into CY mov MOSI c output bit nop enforce data setup nop setb SCK raise clock nop enforce SCK high nop nop nop clr SCK drop clock djnz b x42 next bit pop b ret shin Shift in a byte most significant bit first SCK expected low on entry Return with SCK low Returns received data byte in A push b mov b 8 bit counter x43 setb SCK raise clock mov c MISO input bit rlc a move bit into byte nop enforce SCK high nop clr SCK drop clock nop enforce SCK low nop djnz b x43 next bit pop b ret erase_chip Erase target AT89S8252 5 102 Microcontroller memm ees MiCrOCOONntroller shutdown setb RST force target into reset mov a ERASE_1 send first byte of erase function call shout mov a ERASE 2 send second byte call shout mov a DUMMY send third byte call shout mov a 10 wait 10 milliseconds call delay ms clr RST remove reset from target ret Force target to abandon execution of its internal program set_pgm clr SHUTDN_ notify target of impending reset mov a 5 give target 5 ms to shut down call delay_ms seto SHUTDN_ deassert interrupt ret Prepare the target AT89S8252 for programming clear_pgm init_longtimerO seto RST force target into reset mov a 1 wait 1 ms arbitrary call delay_ms Enable writes to code a
13. 1 Intel Hex File Definition Each record in hexadecimal object file format Intel hex contains the following fields lt gt lt rec length gt lt load address gt lt rec type gt lt data gt lt checksum gt The colon is the record header The record length field consists of two hex digits and represents the number of entries in the data field The load address field consists of four hex digits and indicates the absolute address at which the data in the data field is to be loaded The record type field consists of two hex digits which are always zero in data records The data field contains from one to 16 pairs of hex digits The last two hex digits are a checksum on the record length load address record type and data fields The sum of the binary equivalents of these fields and the checksum itself is zero Each record in the file is terminated by a carriage return OD hex and line feed OA hex A type one record marks the end of the file The record always contains 00000001FF Appendix 2 Code for Modified Display Application NAME LEDShow1 Displays predefined text strings on the LED display in one of two modes The display mode can be changed at run time with the switch The program may be interrupted by External Interrupt 1 This will cause the processor to display a string and enter a wait loop with interrupts disabled Only reset will restore normal operation This facility is provided so that the progr
14. AT89S8252 In System Programming Introduction This application note illustrates the in system programmability of the Atmel AT89SXXXxX S series microcontrol lers A method is shown by which an AT89S8252 in an application may be programmed remotely over a standard telephone line The software for this application note may be obtained by downloading from Atmel BBS 408 436 4309 or Website http www atmel com An Example Application The application shown in Figure 1 is a simple implementation of a moving dis play This application was selected for its simplicity and ability to show graphically the results of in system programming The text to be displayed is programmed into the AT89S8252 microcontroller as part of its firmware and can be changed by reprogramming the device The displayed text is presented in one of two modes selected by a switch In the first mode one character at a time enters the display from the right and moves quickly to the left through each element of the display to its final position in the assembled message In the sec ond mode the message moves through the display from right to left with the dis play acting as a window onto the mes sage This mode is familiar as the method often used in displays of stock prices The text is displayed on four DL1414T four element 17 segment alphanumeric displays with integral decoders and driv ers This yields 16 total display ele ments each capable
15. NNECT 9600 si1 ignore wrong char seto FO set connect flag sit clr RI reset receive flag si2 reti timer_int Process Timer Zero interrupt which occurs about every 65 5 ms Each long timer count is decremented if its overflow flag is clear When a long timer count reaches zero its overflow flag is set 5 92 Microcontroller memm ees MiCrOCONntroller Counts are reloaded and overflow flags are reset elsewhere push setb jo cjne dec til djnz cjne setb ti2 jo djnz setb ti3 pop reti initialize Initialize controller registers and I O lines psw save flags RSO select register bank one LTOF ti2 skip if long timer 0 overflow set ItO_lo 0 tit test low byte ItO_ hi low byte is zero borrow from high It0_lo ti2 dec low byte skip if not zero ItO_hi 0 ti2 low byte is zero test high byte both bytes equal zero LTOF set overflow flag LT1F ti3 skip if long timer 1 overflow set t1 TIS decrement count and skip if not zero LT1F count is zero set overflow flag psw restore flags and reg bank zero mov PCON 0 initialize power control register mov IE 0 deactivate all interrupts mov SCON 01000000b serial port mode 1 mov TMOD 00100001b timer 1 8 bit auto reload timer 0 16 bit mov TH1 BAUD_1200 timer 1 reload value mov TH1 BAUD_ 9600 timer 1 reload value mov TCON 01000000b start timer 1 mov TLO 0 set timer 0 to max count mo
16. ammer can trigger an orderly shutdown before reprogramming the part The LED display consists of four devices of four elements each for a total display capacity of 16 characters The display devices are numbered 0 to 3 from the right The display elements are numbered from 0 to 3 from the right Character positions are numbered 1 to 16 from the right NDEVS EQU 4 number of devices NELMS EQU 4 number of elements in each device SPACE EQU 20h blank DSEG AT 60h stack origin stack DS 20h stack depth SWITCH BIT p1 0 display mode select input CSEG ORG 0000h power on reset vector jmp init ORG 0003h external interrupt 0 vector reti undefined ORG 000bh timer 0 overflow vector reti undefined ORG 0013h external interrupt 1 vector 5 80 Microcontroller memm ees MiCrOCOONntroller jmp shutdown ORG 001bh timer 1 overflow vector reti undefined ORG 0023h serial I O interrupt vector reti undefined ORG 30h begin constant data space pgm msg DB PROGRAMMING 0 usr msg DB ATMEL AT89S8252 CMOS MICROCONTROLLER ORG 0100h begin code space USING 0 Register bank 0 RBO init mov sp stack 1 initialize stack pointer setb IT1 ext 1 interrupt edge triggered mov IE 10000100b enable ext 1 and global interrupts m0 jo SWITCH m1 check position of switch call rotate_msg display message jmp m0 again m1 call shift_msg display message mov a 3 pause 3 sec between disp
17. attempts to establish communication with the caller If a connection is established the modem sends a connect code to the programmer waking it up The AIMEL programmer verifies the connect code and begins polling for a valid packet header Invalid connect codes are ignored Incoming packets must arrive fewer than 30 seconds apart or the modem hangs up and the programmer returns to sleep waiting for the next call If the caller hangs up the 30 second period must expire before another call will be answered Calls incoming during the reset delay period are ignored If a valid packet header is received prior to the expiration of the reset delay period the programmer will attempt to read and validate the incoming packet At any time during packet reception an invalid character parity error or time out during character reception will cause the partial packet to be declared invalid and discarded Two packet types are defined data and end of file A data packet contains five fields in addition to the packet header one of which is a variable length data field The data field contains program data to be written into the application microcontroller The load address field contains the address at which the data is to be written The end of file packet contains the same fields as the data packet except that the data field is empty This packet type has special meaning to the programmer as explained below Any packet which contains an
18. cript for Procomm Plus PROCOMM ASPECT script to read and transmit an Intel hex file The script does not set up communications parameters initialize the modem dial out or establish a connection with the receiver this is done manually via the PROCOMM Connection Directory Each record in the hex file is terminated by a CR LF The receiver is expected to respond with an ACK after each record is validated and programmed into the target processor If the receiver cannot validate the record it responds with a NAK If the receiver cannot verify the record data after programming the target processor it responds with a CAN which tells the transmitter to abort the upload The transmitter waits 2 seconds between records for a response If a response is not received in the allowed interval or if the response is other than an ACK or a CAN the record is retransmitted define ACK 6 OF define NAK 21 U define CAN 24 AX define MAXRETRIES 4 proc main string filename record integer retry rxcode sdlgfopen Select HEX File hex single filename get file name if failure get file name failed exit endif if filename validate path and file name if fopen 0 filename read open file for read fgets 0 record read record else errormsg FILE OPEN FAILED exit endif else errormsg FILE DOES NOT EXIST exit endif set aspect rxdata on script processes receive data while not feof 0 check for EOF termw
19. er might respond to a packet by sending a CAN which indicates that a non recoverable error has occurred and that the computer should immediately abort the file transfer If the programmer fails to respond to a 5 76 Microcontroller memm ees MiCrOCOONntroller packet within a limited period of time the computer will resend the same packet The computer will continue to resend the same packet until a valid response is received or until the allowed number of attempts is exceeded at which time the file transfer is aborted The send and wait nature of the FTP allows the time required for the programmer to program the packet data into the application microcontroller to be easily absorbed Programming verification requires no explicit command or result codes or additional data transfers The program mer s response to a packet reflects the result of the pro gramming verification operation performed by the program mer ACK indicates success CAN indicates failure Hexadecimal object file format Intel hex was chosen as the format of the files to be uploaded to the programmer The records in a hex file serve unchanged as the packets in the FTP described above no service fields need to be added The fields in Intel hex file records are shown in Appendix 1 The colon which begins each record serves as the packet signature field The load address field serves as the packet sequence number A checksum is provided as the last field in each rec
20. erflow flags are not set If the new count in either long timer is zero the corresponding overflow flag is set It is not necessary to stop Timer 0 or to disable interrupts to reload the long timers because they will not be disturbed by the Timer 0 interrupt service routine whenever their overflow flags are set Because Timer 0 free runs it is not possible to know where in a period timing of an event begins Therefore one additional count should be added to the calculated long timer count to guarantee that the timed interval is not short Long timer 0 is 16 bits allowing a maximum timed interval of over one hour Long timer 1 is 8 bits allowing a maximum timed interval of 16 seconds The programmer software is compatible with the U S Robotics Sportster 14 400 baud external modem and may require modifications if used with other modems The switches on the modem are set as follows Almer 5 87 AIMEL UP DTR normal DOWNNumeric result codes DOWNDisplay result codes DOWNSuppress command echo UP Auto answer UP CD normal UP Load NVRAM defaults DOWNSmart mode ON OOK WNDY Modem switch 7 specifies that the power on and reset configuration be loaded from NVRAM profile zero which must contain the factory default hardware flow control template Other switch settings then override the loaded configuration If NVRAM profile zero does not contain the hardware flow control template i
21. essage Local Station The local station in the test configuration consists of an IBM PC AT compatible personal computer with a Cardinal MVPV34ILC 33 600 baud internal modem Any modem may be used as long as it is compatible with the data com munications software and matches the data rate and error correction protocols of the modem at the remote site Procomm Plus for Windows version 3 0 a commercial data communications package is used to configure the modem set up communications parameters and establish a link with the remote modem Procomm Plus includes a macro language called ASPECT which allows the user to write and compile scripts which implement custom file transfer protocols A simple ASPECT script was written to read the contents of a code file and upload it to the remote programmer The ASPECT script is shown in Appendix 4 The file transfer protocol FTP implemented is a simple send and wait packet oriented protocol The FTP transmit and receive modes are diagrammed in the flowcharts in fig ures 4 and 5 respectively The computer sends each packet without flow control and waits for a response The programmer may acknowledge the packet by sending an ACK or may negatively acknowledge the packet by sending a NAK Upon receipt of an ACK the computer sends the next packet If the clone receives a NAK it resends the same packet Transmission proceeds in this manner until the entire file has been transferred The programm
22. f at least 9600 baud Remote Station Connect the programmer and modified display application to the U S Robotics Sportster 14 400 baud external modem Connect the modem to a standard analog tele phone line and set the modem switches as indicated below Modem switch settings 1 UP DTR normal 2 DOWN Numeric result codes 3 DOWN Display result codes 4 DOWN Suppress command echo 5 UP Auto answer 6 UP CD normal 7 UP Load NVRAM defaults 8 DOWN Smart mode Turn the modem on and apply power to the programmer and display application The microcontroller in the applica tion will begin executing its firmware if it contains any The programmer will initialize the modem as indicated by the activity on the modem status indicators If it should become 5 78 necessary to reinitialize the modem briefly interrupt power to the programmer Installing and Configuring Procomm Plus for Windows Version 3 0 Install Procomm Plus as instructed in the User Manual When prompted to specify the modem in use select the installed modem from the list Put the provided ASPECT script ATX WAX into the Pro comm Plus ASPECT directory If the default directories were utilized during installation the correct directory is PROWIN3 ASPECT ATX WAX is the executable ASPECT script which results from compiling the source file ATX WAS shown in Appendix 4 Source files may be edited from within Procomm Plus using the ASPECT Edi tor
23. ition of circuitry which will isolate the SPI port when RST is asserted freeing the pins for use in programming the microcontroller Circuitry which is added to support pro gramming must appear transparent to the application dur ing normal operation The code for the modified display application is shown in Appendix 2 P3 6 WR P3 7 RD DL1414T Microcontroller memm ees MiCrOCONntroller Figure 2 AT89S8252 Moving Display Application Modified for In System Programming VCC O 30 pF ak y1 6 MHz c3 T 30 pF P3 0 RXD P3 1 TXD d P3 2 INTO SHUTDN P3 3 INTT P3 4 TO S1 P3 5 T1 o o P1 0 T2 P1 1 T2EX SW SPST P12 1 3 b P1 4 SS ALE PROG MOSI P1 5 MOSI AR MISO P1 6 MISO P3 6 WR SCK___ gt P1 7 SCK P3 7 PD AT89S8252 RST Note 0 1 uF bypass caps on all ICs The Programmer The programmer shown in Figure 3 interfaces with a modem from which it receives packetized data After dis secting the data packets the programmer generates the signals required to program the data into the AT89S8252 microcontroller in the modified application Code for the programmer is shown in Appendix 3 The programmer circuitry consists of little more than an Atmel 20 pin AT89C2051 microcontroller and a Maxim MAX232 line driver receiver The microcontroller runs at 11 0592 MHz which allows the serial port to operate at a number of standard baud rates
24. lays call delay_sec jmp mO again shutdown Respond to interrupt generated by serial programmer clr ea prevent interrupts mov dptr pgm_msg point to message call show_string display message jmp wait for reset show_string DB WITH FLASH MEMORY AND SPI PORT 0 Display null terminated string pointed to by DPTR The string is left justified in the display If the length of the string exceeds the number of display positions the excess characters are ignored call clear_display begin by blanking display mov b NDEVS NELMS _ total display positions gsi clr a get char mov ca a dptr jz gs2 done if string terminator call put_char display char at position in B Almer 5 81 AIMEL inc dptr point to next char djnz b gs1 done when last position is filled gs2 ret clear_display Fill display with blanks All registers preserved push acc push b mov b NDEVS NELMS _ total display positions c1 mov a SPACE call put_char write space char djnz b c1 do all positions popb pop acc ret shift_msg Display null terminated string Each character in the string in turn enters the display from the right and is moved quickly through each element of the display to its final position The string may contain any number of characters including none If the length of the string exceeds the number of display positions the excess characters are igno
25. lication microcontroller is left in program 5 77 AIMEL ming mode preventing it from executing the incomplete or invalid firmware which it contains It is important to note that invalid packets are NEVER pro grammed into the application microcontroller To do so might over write valid program data which could not be recovered Upon receipt of an end of file packet the programmer returns its control outputs to the inactive power on state allowing the application microcontroller to begin execution of its new firmware The programmer then resumes polling for a valid packet header subject to the 30 second reset delay If a valid packet is received prior to the expiration of the 30 second delay another programming cycle begins which can only be terminated by the reception of a valid end of file packet If the reset delay expires prior to the reception of a valid end of file packet the modem will hang up and the pro grammer will return to sleep waiting for the next call In this case the application microcontroller is left in programming mode preventing it from executing its firmware To return the application to normal operation another call must be received and a valid program file downloaded terminated by an end of file packet Setting Up the Hardware Local Station Install the selected modem into the IBM PC AT compatible computer and connect it to a standard analog telephone line The modem must support a data rate o
26. nd data memory mov a ENABLE_1 send first byte of enable code call shout i mov a ENABLE 2 send second byte call shout mov a DUMMY send third byte call shout ret Allow target AT89S8252 to resume execution of its own program clr RST remove reset from target ret Load and start long timer 0 Almer 5 103 AIMEL System Timer 0 count loaded and interrupt enabled elsewhere seto LTOF seto RSO mov It0 lo 0c8h mov ItO hi 1 clr RSO clr LTOF ret init_longtimer1 Load and start long timer 1 disable counter select register bank one load 30 second count back to bank zero enable counter System Timer Zero count loaded and interrupt enabled elsewhere seto LT1F seto RSO mov Itt 17 clr RSO clr LT1F ret delay_ms disable counter select register bank one load 1 second count back to bank zero enable counter Delay for 1 ms times the value in the accumulator push acc push b mov ob 0 dd djnz b djnz b djnz acc dd pop b pop acc ret delay sec 500 us Q 12 MHz 500 us Q 12 MHz Delay for 1 s times the value in the accumulator push acc push b mov b a ddd mov a 250 call delay_ms 250 ms call delay_ms 500 ms 5 104 Microcontroller memm ees MiCrOCONntroller call delay_ms 750 ms call delay_ms 1000 ms djnz b ddd pop b pop acc ret END AMET AIMEL Appendix 4 ASPECT S
27. nter to data buffer byte counter get data from serial port Jump on error save data in buffer update checksum ees MiCrOCOONntroller rr2 rr3 rr4 rr5 write_record mov inc djnz jmp mov cjne Process checksum call jc add add add add add jnz call je call je mov clr jmp setb ret chksum a index kount rr1 rr3 a rec type a H1 rr4 get byte rr4 a chksum a data len a laddr lo a laddr hi a rec type rr4 get byte rr4 get_byte rr4 a rec_type Cc rr5 point to next location decrement byte count and loop done with data do checksum get record type jump if not type one end of file get record checksum jump on error update running checksum jump if record checksum is not zero Discard CR LF which terminates record jump on error jump on error return record type in accumulator no errors return Error data field too large invalid type or bad checksum set error flag Write the data extracted from the most recently received record into the target AT89S8252 Timing delays are enforced by software This routine assumes that the target has already been prepared for programming Returns nothing mov mov mov anl rl rl rl r2 laddr_lo r3 laddr_hi a r3 a 00011111b a a a save low byte of load address save high byte of load address get high byte of load add
28. olling for valid record header disable serial interrupts set transmit interrupt flag kludge for first use clear program mode flag enable timer 0 interrupt start 30 second timer get char 1 second timeout try again if parity error or timeout try again if not record header Found header process hex record load and dissect record jump if record is good tell sender record is bad next record jump if record is not type zero jump if target is in write mode notify target of impending doom erase target place target in write mode flag target in write mode program data into target verify program data jump if verify OK tell sender to abort clr ES seto TI clr FO seto ETO call init_longtimerO call get_char jc m8 cjne a m8 call get_record jnc m4 mov a NAK call send_char jmp m2 cjne a 0 m6 Process record type zero data jb FO m5 call shutdown call erase_chip call set_pgm seto FO call write_record call verify_record jnc m7 mov a CAN call send_char jmp m9 Process record type one end of file call clear_pgm clr FO mov a HACK call send char jmp m2 jnb LTOF m3 hang up and reset for next call take target out of write mode flag target not in write mode tell sender record OK next record poll until timer times out timer timed out or upload cancelled Almer 5 91 AIMEL call hang_
29. ord Since 7 bit ASCII coding is uti lized the eighth bit of each byte is available to be used for parity checking Since the AT89C2051 microcontroller in the programmer does not utilize external data memory necessary packet buffering must be done using internal RAM Limited mem ory precludes the use of conventional FTPs which utilize packets of 128 bytes or more The hex packet format used in this application limits packet data fields to 16 or fewer entries requiring little memory for buffering A disadvantage of the hex packet format is the use of ASCII which requires each program data byte to be expressed as two hex characters This demands that nearly twice as many bytes be transferred as might other wise be required This is not a severe limitation however since typical file transfer times are on the order of a few seconds Remote Station The remote station in the test configuration consists of the programmer and modified application previously described connected to a U S Robotics Sportster 14 400 baud external modem After power is applied the programmer resets the AT89S8252 microcontroller in the application and then sets its control outputs inactive allowing the application to run normally The programmer configures the modem to answer incoming calls and puts itself to sleep While the programmer sleeps the modem monitors the phone line waiting for an incoming call When a call is detected the modem answers and
30. ram mode held reset so that the incomplete or invalid code which it contains cannot be executed Incoming records must appear less than 30 seconds apart or the line is dropped in preparation for the next call If the remote system drops the line the programmer will wait 30 seconds before resetting Calls incoming during this time are ignored The programmer manages five lines SHUTDN RST SCK MOSI MISO which control the target AT89S8252 and 4 lines which handle the modem interface The AT89S8252 control lines occupy bits of port 1 and the modem interface lines bits of port 3 as defined in the EQUates Procedures SHOUT SHift OUT and SHIN SHift IN manage the serial transfer of data between the programmer and the target AT89S8252 The serial clock is generated and timed by software The code meets timing requirements when executed by an AT89Cx051 microcontroller with a 12 MHz clock Code modifications may be required if a faster clock is substituted Two long period timers are implemented utilizing Timer Zero and members of register bank one Timer Zero is configured in 16 bit mode and is loaded with an initial count of zero which yields the maximum delay of 65 5 ms at 12 MHz The timer is allowed to free run generating an interrupt each time the count rolls over from FFFF to 0000 At each interrupt the counts in each of the long period timers are decremented if their respective ov
31. red call clear_display begin by blanking display mov r5 NDEVS NELMS _ total display positions mov dptr usr_msg point to message ps1 mov b i first display position ps2 clr a move a a dpir get char jz ps4 done if string terminator call put char display char at position in B mov a 25 25 ms call delay_ms delay so char can be seen mov a b set up for compare clr c ready for subtraction subb a r5 compare next position to final jnc ps3 jump if char is in final position mov a SPACE call put_char blank out char 5 82 Microcontroller memm inc b next position jmp ps2 ps3 inc dptr point to next char djnz r5 ps1 final position for next char ps4 ret rotate_msg Display null terminated string The string moves through the display from right to left with the display acting as a window onto the string The string may contain any number of characters including none mov dptr Husr msg point to string clr a get first char move a a dptr jz dd1 1 blank display and exit if null string call clear_display begin by blanking display Phase I Shift the string into the display from the right until the first character is in the left most display element If the string has fewer characters than the display has elements fill the balance with blanks mov r7 0 loop counter one pass per element dd1 mov dptr usr_msg point to string mov b r7 character posi
32. ress isolate 5 bits move 5 bits to top Almer 5 99 ppt pp2 verify_record AIMEL orl a HWRITE CODE specify code write function mov temp a save adjusted high byte mov index data_buf pointer to data buffer mov kount data len byte counter mova temp send adjusted high byte of address call shout mov a f2 send low byte of address call shout mov a index send data from buffer call shout mov a 3 wait 3 ms call delay ms Next address mov a f2 get low byte of address add a 1 increment low byte movr2 a save incremented value jne pp2 Jump if no carry out of low byte carry out of low byte mov a r3 get high byte of address add a 1 increment high byte mov 13 a save incremented value anl a 00011111b isolate 5 bits rl a move 5 bits to top rl a rl a orl a HWRITE CODE specify code write function mov temp a save adjusted high byte Next data inc index point to next buffer location djnz kount ppt decrement byte count and loop ret Verify the data extracted from the latest record against that written into the target AT89S8252 Timing delays are enforced by software This routine assumes that the target has already been prepared for programming Return with carry set if verify fails 5 100 mov r2 laddr_lo save low byte of load address mov r3 laddr_hi save high byte of load address mov a r3 get high byte of
33. rites record show record rxflush purge pending receive data transmit record raw send record including CR LF comgetc rxcode 2 wait max 2 seconds for answer call show_rxcode with rxcode show received code retry 0 initialize counter 5 106 Microcontroller memm ees MiCrOCONntroller while rxcode ACK amp amp retry lt MAXRETRIES if rxcode CAN abort ordered by remote errormsg UPLOAD ABORTED BY REMOTE fclose 0 close file set aspect rxdata off exit endif termwrites Resending record M J termwrites record show record rxflush purge pending receive data transmit record raw send record comgetc rxcode 2 get response call show rxcode with rxcode show received code retry advance counter and try again endwhile if rxcode ACK errormsg EXCESSIVE RETRIES UPLOAD ABORTED fclose 0 close file set aspect rxdata off exit endif fgets 0 record read next record endwhile termwrites End of file MJ fclose 0 Close file set aspect rxdata off exit endproc proc show_rxcode param integer rxcode termmsg X rn rxcode switch rxcode case 1 termwrites Timed out M J endcase case ACK termwrites Received ACK M J endcase case NAK termwrites Received NAK M4J endcase case CAN termwrites Received CAN M J endcase Almer 5 107 AIMEL default termwrites Received garbage M J endcase endswitch endproc 5 108 Microcontroller memm Figure 4 FTP Tran
34. se is not valid valid response complete clear error flag return resend command out of retries set error flag Almer 5 95 AIMEL ss1 clr a move a a dpir get character jz ss2 check for terminator call send_char send character inc dptr point to next character jmp ss ss2 pop dph pop dpl pop acc ret send_char Wait for transmitter to clear add even parity bit to character in accumulator and transmit it Does not wait for transmitter to clear before returning jnb TI wait here for transmitter to clear clr Tl Clear transmit flag push acc save char move p get parity bit mov acc 7 C add parity bit to data mov SBUF a load character into transmitter pop acc restore char ret get_char Read a character from the serial port and check for even parity Return the character in the accumulator with parity stripped off The routine will wait for approximately 1 second before timing out Return with carry set on parity error or timeout jo RI gc2 jump if char is waiting call init_longtimer1 start 1 second timer gel jo RI gc2 exit loop when char received jnb LT1F get loop until timer times out setbc set error flag jmp gc3 return gc2 mov a SBUF get character into accumulator mov cC p carry set for odd parity error anl a 7fh Strip off parity eighth bit 5 96 Microcontroller memm ees MiCrOCOONntroller gcs3 get_byte clr
35. sition dd10 pop dph restore string pointer pop dpl inc dptr point to next char mov a 150 150 ms call delay ms delay so string can be seen jmp dd6 process next char dd11 call clear_display blank display mov a 150 150 ms call delay ms delay ret put char Display character in A at position indicated in B 5 84 Microcontroller memm ees MiCrOCOONntroller All registers preserved s0 s1 s2 s3 s4 s5 push push mov acc b p0 a move character to output port Calculate device and element from display position mov dec mov div mov cjne mov jmp cjne mov jmp cjne mov jmp cjne mov jmp jmp orl xrl mov orl mov pop pop ret delay_ms Delay for 1 ms times the value in the accumulator a b a b NELMS ab p2 0ffh a 0 s1 a 00010000b s5 a 1 s2 a 00100000b s5 a 2 s3 a 01000000b s5 a 3 s4 a 10000000b s5 init a b a 11110000b p2 a a 11110000b p2 a b acc convert to 0 n 1 elements per device A device B element clear display control port check device number device 0 select device 1 select device 2 select device 3 select undefined device restart add element selector invert device selector write strobe low reset device selector write strobe high latch data Almer 5 85 AIMEL push acc push b mov ob 0 dd
36. smit Mode Oo Get Next Record gt Oc Microcontroller Send Record Receive ACK F Receive NAK U Receive CAN X Last Record Oq Tx Attempts Exceeded Y End AIMEL 5 109 AIMEL Figure 5 FTP Receive Mode rod Y Y Abort N N Packet Q Send NAK U OK Disable Programming y Send ACK F gt O Enable Programming Programming Enabled Verify Data Send ACK F x G N Send CAN X 04 5 110 Microcontroller
37. t a temp a A a4 a 10 AIMEL get original char compare to A return error if char is below A adjust binary value Read and dissect record Two record types are accepted data and end of file If the record type is data the appropriate values are extracted and stored If the record type and checksum are valid the carry bit is cleared and the record type is returned in the accumulator Return with carry set to signal an invalid record type checksum error or other problem Errors returned by routine GET_BYTE invalid char or parity cause an immediate return with carry set rd 5 98 mov call jc mov clr subb jnc call jc mov call jc mov call jc mov cjne chksum 0 get_byte rr4 data_len a c a 16 1 rr4 get_byte rr4 laddr_hi a get_byte rr4 laddr_lo a get_byte rr4 rec_type a a 0 rr2 clear running checksum get record data length field jump on error save data length prepare for subtraction data length limited to 16 bytes jump if max size exceeded get high byte of load address field jump on error save it get low byte of load address field jump on error save it get record type field jump on error save type jump if not type zero data Process data in data type record mov index data_buf mov kount data_len call get_byte jc rr4 mov index a add a chksum Microcontroller poi
38. t may be restored with the following command sequence AT amp F1 amp W0 lt ENTER gt Some of the switch functions can be controlled by software but making use of the switches simplifies the code required to initialize the modem The only additional commands which must be issued to the modem are amp R1lgnore RTS amp AODisable ARQ result codes amp R1 causes the modem to forward incoming data to the programmer regardless of the state of RTS amp AO suppresses the extended protocol result codes Note that suppression of the codes does not affect the connection If it is desired to disable Error Control issue the command amp MO CR EQU Odh carriage return LF EQU Oah line feed ACK EQU 6h responses to remote system NAK EQU 15h CAN EQU 18h BAUD_ 1200 EQU Oe8h 1200 baud timer reload values BAUD_2400 EQU Of4h 2400 baud BAUD_9600 EQU Ofdh 9600 baud OK EQU 0 modem status codes RINGING EQU 2 CONNECT 1200 EQU 5 CONNECT 2400 EQU 10 CONNECT 9600 EQU 13 5 88 Microcontroller memm MTRIES ERASE 1 ERASE 2 ENABLE 1 ENABLE 2 DUMMY WRITE CODE READ CODE WRITE DATA READ DATA It0_lo It0 hi It1 index chksum temp kount DSR DTR RST SHUTDN_ SCK MOSI MISO flags LTOF LT1F rec_type laddr_lo laddr_hi data_len data buf stack PCON EQU 5 EQU Oach EQU 04h EQU Oach EQU 53h EQU 55h EQU 02h EQU Olh EQU 06h EQU 05h EQU r2 EQU r3
39. tion inc b adjust dd2 clr a get next char move a a dptr jz dd3 jump if string terminator call put char display char at position in B inc dptr point to next char djnz b dd2 loop until all positions written jmp dd5 next pass dd3 encountered end of string mov a SPACE pad balance of display with blanks call put char display char at position in B djnz b dd3 next position dd5 mov a 150 150 ms Almer Microcontroller 5 83 AIMEL call delay_ms delay so string can be seen inc r7 next pass cjne r7 NDEVS NELMS dd1 loop until all elements done Phase II Shift the string THROUGH the display from the right until the last character is in the left most display element If the string has fewer characters than the display has elements pad the balance with blanks mov dptr Husr msg point to string inc dptr start with the second char dd6 clr a get char move a a dptr jz dd11 blank display and exit if string end push dpl save string pointer push dph mov b NDEVS NELMS total char positions dd7 clr a get next char move a a dpir jz dd8 jump if string terminator call put_char display char at position in B inc dptr point to next char djnz b dd7 loop until all positions written jmp dd10 next pass dd8 encountered end of string mov a SPACE pad balance of display with blanks call put char display char at position in B djnz b dd8 next po
40. tion microcontroller to run normally When Figure 3 AT89S8252 Programmer programming is required the programmer again asserts RST c6 30 pF pi Y2 11 0592 MHz C7 t At 10 6 3 it cs T 10 6 3 U To Modem cg 10 16 FAI TX 30 pF AT89C2051 C10 10 6 3 C10 10 16 DTR Note 0 1 uF bypass caps on all ICs RX DSR DB25 S DTE Vv MAX232 During programming the programmer outputs serial data on the MOSI pin synchronized to a software generated clock output on the SCK pin Serial data is input on the MISO pin also synchronized to SCK The maximum fre quency of SCK must be less than 1 40th the crystal fre quency of the AT89S8252 microcontroller being pro grammed as specified in the AT89S8252 data sheet The documented code produces a maximum SCK frequency of approximately 90 KHz permitting a minimum AT89S8252 crystal frequency of approximately 3 6 MHz Remote Programming Over a Standard Telephone Line The programmer and modified application described previ ously are connected to a phone line through a modem at a remote site Using a personal computer with a modem a user can upload code containing a new message which is programmed into the AT89S8252 microcontroller in the application When programming is complete the microcon troller executes the new firmware which displays the new m
41. ts The user must verify that the hex files produced by the selected tools conform to the format documented in Appendix 1 Uploading a Hex File Launch Procomm Plus and select the correct entry from the list box in the toolbar to dial the remote site If the line is busy and remains busy for more than 30 seconds the pro grammer must be reset After a connection with the remote site has been estab lished run the ATX ASPECT script by selecting it from the list box in the toolbar When prompted by the script enter Microcontroller memm ees MiCrOCONntroller the path and file name including extension of the hex file to upload to the programmer at the remote site The pro grammer must receive the first record from the file within 30 seconds of the time the connection was established or it will hang up and the user will be required to redial During the data transfer data and status information is dis played in the Procomm Plus Terminal Window If the trans fer completes successfully the message End of File will appear in the Terminal Window The user has 30 seconds from the appearance of messages End of File or EXCESSIVE RETRIES UPLOAD ABORTED to rerun the script and upload another file if desired before the pro grammer hangs up If the message UPLOAD ABORTED BY REMOTE appears the programmer has hung up and the user must redial before uploading another file AIMEL 5 79 AIMEL Appendix
42. up break the connection clr ETO disable timer 0 interrupt jmp m1 return controller to idle serial int Process serial interrupt Interrupts due to transmit done are cleared and ignored If interrupt is due to receive data ready check for a modem connect code and set the connect flag The procedure includes code for identifying both single and double character connect codes but both may not be active simultaneously The code for identifying double character connect codes is dependent on the receive baud rate Serial interrupts are enabled elsewhere clr FO clear connect flag clr Tl Clear transmit interrupt flag jnb RI si2 exit if not receive data ready mov a SBUF get character into accumulator mov cC p carry set for odd parity error jc sit ignore char if parity error Test for single character 1200 baud connect code x anl a 7fh Strip off parity eighth bit es cjne a CONNECT_ 1200 sit ignore char if wrong code Test for double character 9600 baud connect code anl a 7fh Strip off parity eighth bit cjne a HIGH CONNECT 9600 si1 ignore wrong char clr RI reset receive flag mov a 2 expect next char in about 1 ms call delay_ms wait for next char jnb RI si2 exit if not receive data ready mov a SBUF get character into accumulator mov cC p carry set for odd parity error jc sit ignore char if parity error anl a 7fh Strip off parity eighth bit cjne a LOW CO
43. v THO 0 setb TRO start timer O setb REN enable serial reception setb EA global interrupt enable Initialize 1 O lines seto DTR seto SHUTDN_ setb MISO seto MOSI clr SCK clr RST remove reset from target ret AMEL i AIMEL modem_ init Reset and initialize the modem Return with carry set if modem fails to respond as expected clr DTR_ assert DTR to talk to modem First must ensure that the modem is in command mode mov a 1 wait 1 second call delay_sec mov dptr attn_cmd point to attention string call send_string transmit string mov a i wait 1 second call delay_sec Reset modem causing the switches to be read mov dptr reset_cmd point to reset string call modem_cmd transmit string jc nni jump on fail mov a 1 wait 1 second before next command call delay_sec Modem is powered up and on line Send required software parameters mov dptr init_cmd point to init string call modem_cmd transmit string jnc nn2 jump on pass nni Modem is misbehaving so deactivate it The controller must be reset to exit this state seto DTR deassert DTR to deactivate modem nn2 ret hang_up Force the modem to drop the line First must return the modem to command mode mov a 1 wait 1 second call delay_sec mov dptr attn_cmd point to attention string call send_string transmit string mov a 1 wait 1 second call delay_sec

Download Pdf Manuals

image

Related Search

Related Contents

Copias en línea 4.0  Points to be included in the user manual:  Avaya 1150E User Guide  Ne retirez jamais ce Manuel d`utilisation du véhicule en  "取扱説明書"  FlexScan L560T  HP 55 User's Manual  Culinaire Glass Washer Model: AT40ST  Submersible Sump Pump  MANUEL D`UTILISATION 1 • INSTALLATION !  

Copyright © All rights reserved.
Failed to retrieve file