$mod51
KEYB_DATA EQU P1.3 ;Line to which PS/2 keyboard data line is connected
KEYB_CLOCK EQU P1.2 ;Line to which PS/2 keyboard clock line is connected
KB_ACK EQU 0FAh ;Constant which represents the 'ACK' code sent back from keyboard
KB_BREAK EQU 0F0h ;Constant which represents that a key is no longer being pressed
KB_EXTENDED EQU 0E0h ;Constant which represents an extended scan code sequence
;==========================================================
;===========================================================
;SendSerial EQU 0041h
;SendSerialHexByte EQU 0044h
;SendSerialByte EQU 0047h
;==========================================================
; PROGRAM LOCATION
;
;modified to 0000h rather than 8000h.
;===========================================================
ORG 0000h
;==========================================================
; PROGRAM CODE
;
;This is the actual guts of the demonstration code.
;===========================================================
LCALL lcdi
LCALL SendSerial ;Send 'initializing' message
DB "Initializing keyboard ",13,0
LCALL PS2_GenericInit ;Initialize the keyboard
LCALL SendSerial ;Send the 'init done' message
DB "Init successful dumping PS/2 Communication ",13,0
CLR RI
MOV R7,#00
Loop:
JB RI,ExitProgram ;If a key has been pressed, exit
; LCALL PS2_GetByte ;Get a scan code from the keyboard
LCALL PS2_GetScanCode
JNC Loop ;If no key was pressed, keep waiting
;See if the key we got IS the key we're looking for
;JZ skip
LCALL datawrt
skip:PUSH ACC ;Otherwise, save the value returned by the keyboard
MOV A,#'{' ;Display a leading bracket
LCALL SendSerialByte ;Send it to the serial port
POP ACC ;Restore the value returned by the keyboard
LCALL SendSerialHexByte ;Send it to the terminal as a 2-byte hex value
MOV A,#'}' ;Display a trailing bracket
LCALL SendSerialByte ;Send it to the serial port
SJMP Loop ;Wait for the next keypress
ExitProgram:
CLR RI ;Clear serial input and exit back to SBCMON
RET
;*****************************************************************
;* Function: ByteTo2Hex *
;* Purpose: Convert a single byte into two hex digits *
;* Input: A = Byte to convert (0x00-0xFF) *
;* Output: A = High nibble (ASCII 0x30-0x39,0x41-0x46) *
;* R0 = Low nibble (ASCII 0x30-0x39, 0x41-0x46) *
;* Destroyed Registers: None *
;*****************************************************************
ByteTo2Hex:
MOV R0,A
ANL A,#0Fh
ADD A,#0F6h
JNC byte_to_bcd_2
ADD A,#07h
byte_to_bcd_2:
ADD A,#3Ah
XCH A,R0
SWAP A
ANL A,#0Fh
ADD A,#0F6h
JNC byte_to_bcd_3
ADD A,#07h
byte_to_bcd_3:
ADD A,#3Ah
RET
;*****************************************************************
;* Function: SendSerialHexByte *
;* Purpose: Sends the byte in the accumulator to the serial *
;* port as two hexadecimal nibbles. *
;* Input: ACC: Byte to send *
;* Output: None. *
;* Destroyed Registers: None *
;*****************************************************************
SendSerialHexByte:
PUSH 00h ;Save R0
PUSH ACC ;Save ACC
LCALL ByteTo2Hex ;Convert high byte to two bytes of BCD
LCALL SendSerialByte ;Send the high byte
MOV A,R0 ;Send the low byte
LCALL SendSerialByte ;Send it
POP ACC ;Restore R0
POP 00h ;Restore R0
RET
;*****************************************************************
;* Function: SendSerialByte *
;* Purpose: Sends the byte in the accumulator to the serial *
;* port and waits for it to be sent before returning. *
;* Input: ACC: Byte to send *
;* Output: None. *
;* Destroyed Registers: None *
;*****************************************************************
;++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
SendSerialByte:
CLR TI ;Prepare for transmit
MOV SBUF,A ;Send the byte out
JNB TI,$ ;Wait for byte to be sent
RET ;Done!
;*****************************************************************
;* Function: SendSerial *
;* Purpose: Sends the null-terminated string that immediately *
;* follows the LCALL that called the function to the *
;* serial port. *
;* Input: ACC: Byte to send *
;* Output: None. *
;* Destroyed Registers: None *
;*****************************************************************
SendSerial:
MOV TMOD,#22h ;Timer 1 and timer 0in Auto-reload mode
MOV TH1,#0FDh ;Reload value for 9600 baud @ 11.059 Mhz
SETB TR1 ;Turn on timer 1 for baud rate generator
MOV SCON,#52h ;Receiver Enable/Timer 1 Baud Rate 8-bit
POP DPH
POP DPL
PUSH ACC
PUSH PSW
CLR TI
SendSerial1:
CLR A
MOVC A,@A+DPTR
INC DPTR
JZ SendSerialExit
MOV SBUF,A
JNB TI,$
CLR TI
;(v1.3.1) - Removed LF-appending
;----------------------------------
CJNE A,#13,SendSerial1
MOV A,#10
MOV SBUF,A
JNB TI,$
CLR TI
;----------------------------------
SJMP SendSerial1
SendSerialExit:
POP PSW
POP ACC
PUSH DPL
PUSH DPH
RET
PS2_GenericInit:
MOV A,#0FFh ;Initializtation command
ACALL PS2_SendByte ;Send command to keyboard
ACALL PS2_GetByte ;Get a response byte, should be ACK
ACALL PS2_ChkAck ;Check to see if it was ACK
JNC PS2_GenericInit ;If it wasn't repeat and try to initialize again
MOV A,#0F4h ;Enable reporting
ACALL PS2_SendByte ;Send command to keyboard
ACALL PS2_GetByte ;Get a response byte, should be ACK
ACALL PS2_ChkAck ;Check to see if it was ACK
JNC PS2_GenericInit ;If it wasn't repeat and try to initialize again
RET
;//////////////////////////////////////////////////////////////////////////////////////////////
;PS2_MouseInit:
; MOV A,#0FFh ;Initializtation command
; ACALL PS2_SendByte ;Send command to keyboard
; ACALL PS2_GetByte ;Get a response byte, should be ACK
; ACALL PS2_ChkAck ;Check to see if it was ACK
; JNC PS2_MouseInit ;If it wasn't repeat and try to initialize again
; MOV A,#0F6h ;Set default values
; ACALL PS2_SendByte ;Send command to keyboard
; ACALL PS2_GetByte ;Get a response byte, should be ACK
; ACALL PS2_ChkAck ;Check to see if it was ACK
; JNC PS2_MouseInit ;If it wasn't repeat and try to initialize again
; MOV A,#0F4h ;Enable reporting
; ACALL PS2_SendByte ;Send command to keyboard
; ACALL PS2_GetByte ;Get a response byte, should be ACK
; ACALL PS2_ChkAck ;Check to see if it was ACK
; JNC PS2_MouseInit ;If it wasn't repeat and try to initialize again
; RET
;////////////////////////////////////////////////////////////////////////////////////////////////
;***************************************************************
;* Function: Scan code translation table *
;* Author: Craig Steiner *
;*-------------------------------------------------------------*
;* Description: The following codes are the scan codes returned*
;* by PS2_GetScanCode. The keyboard sends a byte(s) when a *
;* key is pressed and another sequence of bytes when the key *
;* is released. These sequences can be 1-3 bytes in length. *
;* The PS2_GetScanCode routine converts the keyboard scan *
;* codes into an internal representation that can be fit in *
;* a single byte. The constants below are the values that *
;* will be returned in the case of certain keypresses. In *
;* all cases, a value of 0-127 means the key was pressed *
;* while a value between 128-255 means the key was released. *
;***************************************************************
KS_KP_SLASH EQU 'a'
KS_RIGHTCTRL EQU 'b'
KS_RIGHTGUI EQU 'c'
KS_RIGHTALT EQU 'd'
KS_APPS EQU 'e'
KS_PRTSCREEN1 EQU 'f'
KS_PRTSCREEN2 EQU 'g'
KS_INSERT EQU 'h'
KS_HOME EQU 'i'
KS_PGUP EQU 'j'
KS_DELETE EQU 'k'
KS_END EQU 'l'
KS_PGDOWN EQU 'm'
KS_UPARROW EQU 'n'
KS_LEFTARROW EQU 'o'
KS_DOWNARROW EQU 'p'
KS_RIGHTARROW EQU 'r'
KS_KP_ENTER EQU 's'
KS_BACKSPACE EQU 't'
KS_TAB EQU 'u'
KS_CAPS EQU 'v'
KS_LEFTSHIFT EQU 'w'
KS_LEFTCTRL EQU 'x'
KS_LEFTGUI EQU 'y'
KS_LEFTALT EQU 'z'
KS_F1 EQU 01h
KS_F2 EQU 02h
KS_F3 EQU 03h
KS_F4 EQU 04h
KS_F5 EQU 05h
KS_F6 EQU 06h
KS_F7 EQU 07h
KS_F8 EQU 08h
KS_F9 EQU 09h
KS_F10 EQU 0Ah
KS_F11 EQU 0Bh
KS_F12 EQU 0Ch
KS_RIGHTSHIFT EQU 0Dh
KS_ENTER EQU 0Eh
KS_SCROLL EQU 0Fh
KS_NUMLOCK EQU 10h
KS_KP_ASTERISK EQU 11h
KS_KP_MINUS EQU 12h
KS_KP_PLUS EQU 13h
KS_KP_POINT EQU 14h
KS_ACPI_POWER EQU 15h
KS_ACPI_SLEEP EQU 16h
KS_ACPI_WAKE EQU 17h
KS_ESCAPE EQU 1Bh
KS_KP_0 EQU ')'
KS_KP_1 EQU '!'
KS_KP_2 EQU '@'
KS_KP_3 EQU '#'
KS_KP_4 EQU '$'
KS_KP_5 EQU '%'
KS_KP_6 EQU '^'
KS_KP_7 EQU '&'
KS_KP_8 EQU '*'
KS_KP_9 EQU '('
;***************************************************************
;* Function: PS2_GetByte *
;* Author: Craig Steiner based on code by Gabriel Lour *
;* Input: None *
;* Output Carry bit: Clear=No key returned,Set=Key returned *
;* Accumulator: Byte returned by keyboard *
;* Registers Modified: None *
;*-------------------------------------------------------------*
;* Description: Gets a single byte from the keyboard, if there *
;* is a byte to get. Returns it in the accumulator and sets *
;* carry bit. Otherwise clears the carry bit. *
;***************************************************************
PS2_GetByteSetR0:
MOV A,R0 ;We don't save Accumulator since return value can be in accumulator
PUSH ACC ;Protect R0
SJMP PS2_GetByte2 ;Use R0 that is passed in
PS2_GetByte:
MOV A,R0 ;We don't save Accumulator since return value can be in accumulator
PUSH ACC ;Protect R0
MOV R0, #50 ;Wait 50 loop cycles for data line to be lowered by keyboard
PS2_GetByte2:
SETB KEYB_DATA ;Raise data line so it can receive data
SETB KEYB_CLOCK ;Raise clock so that keyboard communication is enabled
PGB_CheckAgain:
JNB KEYB_CLOCK, PGB_KeyHit ;If clock line is now low that means keyboard is talking to us
DJNZ R0, PGB_CheckAgain ;Check R0 number of times
SJMP PGB_KeyEnd ;No keyboard response was detected in loop period
PGB_KeyHit:
JNB KEYB_DATA, PGB_StartOk ;Start bit must be 0
PGB_KeyEnd:
CLR KEYB_CLOCK ;Disable keyboard
CLR C ;Clear carry to indicate no keypress
PGB_PopExit:
XCH A,R0 ;Hold accumulator temporarily in R0
POP ACC ;Restore value of R0
XCH A,R0 ;Restore accumulator and R0
RET
PGB_StartOk:
MOV R0,#8 ;8 bits to clock into accumulator
CLR A ;Accumulator initially empty
PGB_KeyHit3:
ACALL PS2_GetBit ;Get one bit and shift into accumulator
DJNZ r0, PGB_KeyHit3 ;Execute for each of the 8 bits
PUSH ACC ;Save the value read from keyboard on the stack
CLR A
ACALL PS2_GetBit ;Get parity bit
ACALL PS2_GetBit ;Get stop bit
CLR KEYB_CLOCK
POP ACC ;Restore the byte we read
SETB C ;Set carry flag to indicate key press
SJMP PGB_PopExit ;Exit routine
;***************************************************************
;* Function: PS2_GetBit *
;* Author: Craig Steiner based on code by Gabriel Lour *
;* Input: Accumulator: Starting value of clocked-in data *
;* Output Accumulator: New value of cloced-in data *
;* Registers Modified: Carry bit *
;*-------------------------------------------------------------*
;* Description: Waits for a 1-0 transition on the clock line *
;* from the keyborad. When this happens, we have valid data *
;* on the data line so we get it and rotate it into the *
;* accumulator. *
;***************************************************************
PS2_GetBit:
JNB KEYB_CLOCK, $
JB KEYB_CLOCK, $
MOV C, KEYB_DATA
RRC A
RET
;***************************************************************
;* Function: PS2_WaitClock *
;* Author: Craig Steiner based on code by Gabriel Lour *
;* Input: None *
;* Output None *
;* Registers Modified: Nine *
;*-------------------------------------------------------------*
;* Description: Waits for a 1-0 transition on the clock line *
;* from the keyborad and returns. *
;***************************************************************
PS2_WaitClock:
JNB KEYB_CLOCK, $
JB KEYB_CLOCK, $
RET
;***************************************************************
;* Function: PS2_SendByte *
;* Author: Craig Steiner based on code by Gabriel Lour *
;* Input: Accumulator: Value to send to keyboard *
;* Output Accumulator: New value of cloced-in data *
;* Registers Modified: Carry bit *
;*-------------------------------------------------------------*
;* Description: Waits for a 1-0 transition on the clock line *
;* from the keyborad. When this happens, we have valid data *
;* on the data line so we get it and rotate it into the *
;* accumulator. *
;***************************************************************
PS2_SendByte:
XCH A,R0 ;Swap A and R0 temporarily
PUSH ACC ;This saves the value of R0 on stack
XCH A,R0 ;And this restores the accumulator to its original value
CLR KEYB_CLOCK ;Break the Keyboard
MOV R0,#00h ;Some delay (safety reasons)
DJNZ R0,$ ;Loop for 256 cycles
CLR KEYB_DATA ;Request to send
SETB KEYB_CLOCK ;Enable the Keyboard
ACALL PS2_WaitClock ;Start Bit
PUSH ACC ;Protect original value of accumulator
MOV R0,#8 ; 8bits to receive
PSB_Xmit:
RRC A ;Shift bits into carry
MOV KEYB_DATA, C ;Send highest bit out to keyboard
ACALL PS2_WaitClock ;Wait for keyboard to acknowledge
DJNZ R0,PSB_Xmit ;Loop for each bit
POP ACC ;Restore original value of accumulator
MOV C,PSW.0 ;This is Even parity
CPL C ;And Keyboard needs Odd parity
MOV KEYB_DATA,C ;Send parity bit
ACALL PS2_WaitClock ;Wait for keyboard to acknowledge bit
SETB KEYB_DATA ;Send stop bit
ACALL PS2_WaitClock ;Wait for keyobard to acknowledge bit
ACALL PS2_WaitClock ;Wait for keyboard to acknowledge bit
MOV C, KEYB_DATA ;Get the ACK bit from the keyboard, store in carry
CLR KEYB_CLOCK ;Deselect the keyboard
XCH A,R0
POP ACC
XCH A,R0 ;Restore R0
ret
;***************************************************************
;* Function: PS2_CheckAck *
;* Author: Craig Steiner based on code by Gabriel Lour *
;* Input: Accumulator: Value received from keyboard *
;* Output Carry: Clear=NAK, Set=ACK receivedn data *
;*-------------------------------------------------------------*
;* Description: Checks to see if the contents of the acc is *
;* the ACK code (FAh). If it is, it sets the carry bit. If *
;* it isn't, it clears it. *
;***************************************************************
PS2_ChkAck:
CJNE A,#KB_ACK,PCA_NAK ;If character was not ACK, clr carry to indicate failure
SETB C ;Set carry to indicate successful ACK
RET
PCA_NAK:
CLR C ;Clear carry to indicate failure
RET
;***************************************************************
;* Function: PS2_Init *
;* Author: Craig Steiner based on code by Gabriel Lour *
;* Input: None *
;* Output Carry: Clear=Failure, Set=Success *
;*-------------------------------------------------------------*
;* Description: Initializes the keyboard and indicates whether *
;* the initialization was successful or not. *
;***************************************************************
PS2_Init:
MOV A,#0FFh ;Initializtation command
ACALL PS2_SendByte ;Send command to keyboard
ACALL PS2_GetByte ;Get a response byte, should be ACK
ACALL PS2_ChkAck ;Check to see if it was ACK
JNC PS2_Init ;If it wasn't repeat and try to initialize again
MOV A,#0F4h ; Enable keyboard command
ACALL PS2_SendByte ;Send command to keyboard
ACALL PS2_GetByte ;Get a response byte, should be ACK
ACALL PS2_ChkAck ;Check to see if it was ACK
JNC PS2_Err ;If not success, abort command and exit
MOV A, #0F3h ; Set Typematic
ACALL PS2_SendByte ;Send command to keyboard
ACALL PS2_GetByte ;Get a response byte, should be ACK
ACALL PS2_ChkAck ;Check to see if it was ACK
JNC PS2_Err ;If not success, abort command and exit
MOV A, #00h ; Typematic = 250 ms / 30 cps
ACALL PS2_SendByte ;Send command to keyboard
ACALL PS2_GetByte ;Get a response byte, should be ACK
ACALL PS2_ChkAck ;Check to see if it was ACK
JNC PS2_Err ;If not success, abort command and exit
MOV A,#0 ;Keyboard starts with LEDs off, fall through to Set LEDs
PS2_SetLeds:
PUSH ACC ;Protect LED setting passed in accumulator
MOV A, #0EDh ;Set Leds command
ACALL PS2_SendByte ;Send command to keyboard
ACALL PS2_GetByte ;Get a response byte, should be ACK
ACALL PS2_ChkAck ;Check to see if it was ACK
JNC PS2_Err ;If not success, abort command and exit
POP ACC ;Restore the LED setting that was passed in
ACALL PS2_SendByte ;Send command to keyboard
ACALL PS2_GetByte ;Get a response byte, should be ACK
ACALL PS2_ChkAck ;Check to see if it was ACK
PS2_Err:
RET
;***************************************************************
;* Function: PS2_GetScanCode *
;* Author: Craig Steiner based on code by Gabriel Lour *
;* Input: None *
;* Output Carry: Clear=No key received, Set=Key received *
;* Accumulator: Scan key code *
;*-------------------------------------------------------------*
;* Description: Gets a scan code from the keyboard and returns *
;* it. A scan code is the printable alphabet and numbers in *
;* unshifted form. 0-127 means key pressed, 128+ means *
;* key released. *
;***************************************************************
PS2_GetScanCode:
LCALL PS2_GetByte ;Try to get first character
JC PGSC_GotKey ;If we got a byte, process it
PGSC_NoKey:
CLR C ;Clear carry to signify no character received
RET ;No byte received, so just exit
PGSC_GotKey:
;If we got a key then "B" is going to be used as our return
;register. It starts out clear
MOV B,#00h ;Clear our return code
MOV DPTR,#PGSC_NormalCodes ;Point initially to the normal codes
PGSC_ProcKey:
MOV R1,A ;Hold received character in R1
CJNE A,#KB_BREAK,PGSC_NotBreak ;If it's not a break code (F0) then continue
;If it is a break code then we set the high bit of 'B' to indicate that the
;key was released.
SETB B.7 ;Set high bit
PGSC_AnotherKey:
MOV R0,#20 ;Try 20 times to wait for next byte from keyboard
PGSC_AKeyLoop:
LCALL PS2_GetByte ;We then get the next byte from keyboard
JC PGSC_ProcKey ;A byte was received, so process it
DJNZ R0,PGSC_AKeyLoop ;No key detected, so keep trying
SJMP PGSC_NoKey ;No key was found after multiple tries
PGSC_NotBreak:
;Check to see if it was an extended key
CJNE A,#KB_EXTENDED,PGSC_FindCode ;If not an extended code (E0), go process it
;This means we got an extended code. If so, we set our look-up table
;to the extended scan code table and get another key and process it.
MOV DPTR,#PGSC_ExtendedCodes ;Set lookup table to extended codes
SJMP PGSC_AnotherKey ;Go get another key and process it
PGSC_FindCode:
;This now looks for the code we received in the proper table
CLR A ;Make sure offset is zero
MOVC A,@A+DPTR ;Get next scan code from DPTR
JZ PGSC_NoKey ;If zero then end of table, so exit
XRL A,R1 ;See if the key we got IS the key we're looking for
JZ PGSC_FoundKey ;If it is, so process it
;It wasn't the right key, so we increment DPTR twice to point to the
;next table entry and process that
INC DPTR
; INC DPTR
SJMP PGSC_FindCode
PGSC_FoundKey:
INC DPTR ;Point to the translation
CLR A ;No offset
MOVC A,@A+DPTR ;Get the translated character
; ORL A,B ;Combine it with B which may hold a "break" code
SETB C ;Set carry flag to indicate we have a character
RET
PGSC_NormalCodes:
;These are the translations for the normal, non-extended codes. Basically
;these are the scan codes that consist of a single byte
DB 01Ch,'A'
DB 032h,'B'
DB 021h,'C'
DB 023h,'D'
DB 024h,'E'
DB 02Bh,'F'
DB 034h,'G'
DB 033h,'H'
DB 043h,'I'
DB 03Bh,'J'
DB 042h,'K'
DB 04Bh,'L'
DB 03Ah,'M'
DB 031h,'N'
DB 044h,'O'
DB 04Dh,'P'
DB 015h,'Q'
DB 02Dh,'R'
DB 01Bh,'S'
DB 02Ch,'T'
DB 03Ch,'U'
DB 02Ah,'V'
DB 01Dh,'W'
DB 022h,'X'
DB 035h,'Y'
DB 01Ah,'Z'
DB 045h,'0'
DB 016h,'1'
DB 01Eh,'2'
DB 026h,'3'
DB 025h,'4'
DB 02Eh,'5'
DB 036h,'6'
DB 03Dh,'7'
DB 03Eh,'8'
DB 046h,'9'
DB 00Eh,'`'
DB 04Eh,'-'
DB 055h,'='
DB 05Dh,'\'
DB 066h,KS_BACKSPACE
DB 029h,' '
DB 00Dh,KS_TAB
DB 058h,KS_CAPS
DB 012h,KS_LEFTSHIFT
DB 014h,KS_LEFTCTRL
DB 011h,KS_LEFTALT
DB 059h,KS_RIGHTSHIFT
DB 05Ah,KS_ENTER
DB 076h,KS_ESCAPE
DB 005h,KS_F1
DB 006h,KS_F2
DB 004h,KS_F3
DB 00Ch,KS_F4
DB 003h,KS_F5
DB 00Bh,KS_F6
DB 083h,KS_F7
DB 00Ah,KS_F8
DB 001h,KS_F9
DB 009h,KS_F10
DB 078h,KS_F11
DB 007h,KS_F12
DB 073h,KS_SCROLL
DB 054h,'['
DB 077h,KS_NUMLOCK
DB 07Ch,KS_KP_ASTERISK
DB 07Bh,KS_KP_MINUS
DB 079h,KS_KP_PLUS
DB 071h,KS_KP_POINT
DB 070h,KS_KP_0
DB 069h,KS_KP_1
DB 072h,KS_KP_2
DB 07Ah,KS_KP_3
DB 06Bh,KS_KP_4
DB 073h,KS_KP_5
DB 074h,KS_KP_6
DB 06Ch,KS_KP_7
DB 075h,KS_KP_8
DB 07Dh,KS_KP_9
DB 05Bh,']'
DB 04Ch,';'
; DB 052h,'''
DB 041h,','
DB 049h,'.'
DB 04Ah,'/'
PGSC_ExtendedCodes:
;These are the translations for the extended codes. These are the codes
;that start with E0 and then a second character. This table lists that
;second character
DB 01Fh,KS_LEFTGUI
DB 04Ah,KS_KP_SLASH
DB 014h,KS_RIGHTCTRL
DB 027h,KS_RIGHTGUI
DB 011h,KS_RIGHTALT
DB 02Fh,KS_APPS
DB 012h,KS_PRTSCREEN1
DB 07Ch,KS_PRTSCREEN2
DB 070h,KS_INSERT
DB 06Ch,KS_HOME
DB 07Dh,KS_PGUP
DB 071h,KS_DELETE
DB 069h,KS_END
DB 07Ah,KS_PGDOWN
DB 075h,KS_UPARROW
DB 06Bh,KS_LEFTARROW
DB 072h,KS_DOWNARROW
DB 074h,KS_RIGHTARROW
DB 05Ah,KS_KP_ENTER
DB 037h,KS_ACPI_POWER
DB 03Fh,KS_ACPI_SLEEP
DB 05Eh,KS_ACPI_WAKE
DB 0
;++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
; lcd Routine
;++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
commwrt:
mov a,#00h
mov dptr,#0fff8h
movx @dptr,a
mov a,r0
mov dptr,#0fff9h
movx @dptr,a
ret
lcdi: mov r0,#38h
acall commwrt
acall delay
mov r0,#0eh
acall commwrt
acall delay
mov r0,#01h
acall commwrt
acall delay
mov r0,#06h
acall commwrt
acall delay
mov r0,#80h
acall commwrt
acall delay
ret
datawrt:
mov R1,A
mov a,#01h
mov dptr,#0fff8h
movx @dptr,a
MOV A,R1
mov dptr,#0fff9h
movx @dptr,a
ret
delay: mov r3,#10
here: mov r4,#255
here1: djnz r4,here1
djnz r3,here
ret
end
PS2 Keyboard code
RAJESHS, Tuesday, October 27, 2009I2C Bus Standard,Inter Integrated Circuit Bus Standards
RAJESHS,
History of the I2C Bus:
The I2C bus was developed in the early 1980's by Philips Semiconductors.
The original purpose was to provide an easy way to connect a CPU to peripheral chips in a TV-set.
Peripheral devices in embedded systems are often connected to the MCU as memory-mapped I/O devices, using the micro controller's parallel address and data bus.
This results in lots of wiring on the PCB's to route the address and data lines.
Furthermore, lots of control lines increases the disturbances by Electromagnetic Interference (EMI) and Electrostatic Discharge (ESD).
The bus is generally accepted in the industry as a de-facto standard.
The I2C bus has been adopted by several leading chip manufacturers like Xicor, ST Microelectronics, Infineon Technologies, Intel, Texas Instruments, Maxim, Atmel, etc..
The I2C Bus Protocol:
The I2C bus physically consists of 2 active wires and a ground connection.
The active wires, called SDA and SCL, are both bi-directional.
SDA is the Serial Data line.
SCL is the Serial Clock line.
Every device hooked up to the bus has its own unique address, no matter whether it is an MCU, LCD driver, memory, or ASIC.
Each of these chips can act as a receiver and/or transmitter, depending on the functionality of the device.
1. LCD driver is only a receiver.
2. Memory or I/O chip can be both transmitter and receiver.
The I2C bus is a multi-master bus.
Means that more than one IC capable of initiating a data transfer.
The I2C protocol specification states that, one who initiates a data transfer on the bus is considered the Bus Master and all the other Ic’s are slave.
Bus masters are always intelligent Micro controller's.
First, the MCU will issue a START condition. This acts as an 'Attention' signal to all of the connected devices.
All ICs on the bus will listen to the bus for incoming data.
The number of bytes that can be transmitted per transfer is unrestricted.
Then the MCU sends the ADDRESS of the device it wants to access, along with an indication whether the access is a Read or Write flag.
Having received the address, all IC's will compare it with their own address
If it doesn't match, they simply wait until the bus is released by the stop condition of other data transfer.
Each byte has to be followed by an acknowledgement bit.
If the address matches, however, the chip will produce a response called the ACKNOWLEDGE signal.
Once the MCU receives the acknowledge, it can start transmitting or receiving the second DATA.
When all is done, the MCU will issue the STOP condition
This is a signal that the bus has been released and that the connected ICs may expect another transmission to start any moment
The data on the SDA line must be stable during the HIGH period of the clock. The HIGH or LOW state of the data line can only change when the clock signal on the SCL line is LOW.
The start condition acts as a signal to all connected IC's that something is about to be transmitted (ADDRESS) on the bus. As a result, all connected chips will listen to the bus.
After a message has been completed, a STOP condition is sent.
This is the signal for all devices on the bus that the bus is available again.
If a chip was accessed and has received data during the last transaction, it will now process this information.
A Stop condition ALWAYS denotes the END of a transmission. Even it can be issued in the middle of a transaction or in the middle of a byte, in this case, it disregards the information sent and resumes the "listening state", waiting for a new start condition.
A HIGH to LOW transition on the SDA line while SCL is HIGH is one such unique case. This situation indicates a START condition.
A LOW to HIGH transition on the SDA line while SCL is HIGH defines a STOP condition.
START and STOP conditions are always generated by the master.
Once the start condition has been sent, a byte can be transmitted by the MASTER to the SLAVE
This first byte after a start condition will identify the slave on the bus (address) and will select the mode of operation which is specified by the LSB.
As the I2C bus gained popularity, it was soon discovered that the number of available addresses was too small.
one of the reserved addresses has been allocated to a new task to switch to 10-bit addressing mode.
If there are slaves on the bus that can operate in the extended 10-bit addressing mode, they will ALL respond with an ACK signal to the master.
The second byte that gets transmitted by the master will then be taken in and evaluated against their address.
Note:
Even in 10-bit extended addressing mode, Bit 0 of the first byte after the Start condition determines the slave access mode ('1' = read / '0' = write).
I2C has a master/slave protocol. The master initiates the communication. The sequence of events are:
1. The Master device issues a start condition. This condition informs all the slave devices to listen on the serial data line for instructions.
2. The Master device sends the address of the target slave device and a read/write flag.
3. The Slave device with the matching address responds with an acknowledgement signal.
4. Communication proceeds between the Master and the Slave on the data bus. Both the master and slave can receive or transmit data depending on whether the communication is a read or write. The transmitter sends 8-bits of data to the receiver which replies with a 1-bit acknowledgement.
When the communication is complete, the master issues a stop condition indicating that everything is done.
The I2C bus was originally developed as a multi-master bus. This means that more than one device initiating transfers can be active in the system.
When using only one master on the bus there is no real risk of corrupted data, except if a slave device is malfunctioning or if there is a fault condition involving the SDA / SCL bus lines.
This situation changes with 2 MCU's:
When MCU 1 issues a start condition and sends an address, all slaves will listen (including MCU 2 which at that time is considered a slave as well). If the address does not match the address of CPU 2, this device has to hold back any activity until the bus becomes idle again after a stop condition.
As long as the two MCU's monitor what is going on on the bus (start and stop), there is no problem.
Let's assume one of the MCU's missed the START condition and still thinks the bus is idle.
How can you know if some other device is transmitting on the bus ?
The physical bus setup helps us out.
Since the bus structure is designed in such a way (if one device pulls a line low it stays low), you can test if the bus is idle or occupied.
When a master changes the state of a line to HIGH, it MUST always check that the line really has gone to HIGH.
If it stays low then this is an indication that the bus is occupied and some other device.
If a master can't get a certain line to go high, it lost arbitration and needs to back off and wait until a stop condition.
What about the risk of data corruption ?
The problem of data corruption will occur if both the masters pulls the SDA low at the same time.
The two MCU's are accessing a slave in write mode at address 1111001.
The slave acknowledges this. So far, both masters are under the impression that they "own" the bus.
MCU1 wants to transmit 01010101 to the slave.
MCU2 wants to transmit 01100110 to the slave.
The moment the data bits do not match anymore one of them loses arbitration and backs off.
For as long as there has been no STOP present on the bus, it won't touch the bus and leave the SDA and SCL lines alone.
The moment a STOP was detected, MCU2 can attempt to transmit again to acquire the owner ship of the bus again.
All masters generate their own clock on the SCL line to transfer messages on the I2C-bus.
Data is only valid during the HIGH period of the clock.
A defined clock is therefore needed for the bit-by-bit arbitration procedure to take place.
Clock synchronization is performed using the wired-AND connection of I2C interfaces to the SCL line.
When all devices concerned have counted off their LOW period, the clock line will be released and go HIGH.
There will then be no difference between the device clocks and the state of the SCL line, and all the devices will start counting their HIGH periods.
The first device to complete its HIGH period will again pull the SCL line LOW.
NOTE:
A synchronized SCL clock is generated with its LOW period determined by the device with the longest clock LOW period.
Its HIGH period determined by the one with the shortest clock HIGH period.
Sync clock
Master clk
Device clk
Using the clock synchronizing mechanism as a handshake
The I2C protocol includes a synchronization mechanism which is used as a handshake mechanism between slow and fast devices or between masters in a multi-master session
When a slow slave (slow in terms of internal execution) is attached to the bus then problems may occur.
This lead to duplication of data and corruption.
The slave must have some means to tell the master that it is busy. It could of course simply not respond to the ACK cycle.
This would cause the master to send a stop condition and retry.
Think about an A/D converter. It might take some time for the conversion to complete.
If the master would just go on it would be reading the result of the previous conversion instead of the newly acquired data.
The synchronization mechanism is so simple, the mechanism works on the SCL line only. The slave that wants the master to wait simply pulls the SCL low as long as needed.
This is like adding "wait states" to the I2C bus cycle.
The master simply waits until it can get the SCL line to go HIGH and then just goes on with whatever it was doing .
The drawback is speed. The bus is locked at that moment. If you have rather long delays (long conversion time in our example above), then this penalizes the total bus speed a lot.
TRANSFERRING DATA
Every byte put on the SDA line must be 8-bits long.
The number of bytes that can be transmitted per transfer is unrestricted.
Each byte has to be followed by an Acknowledgement bit.
Data is transferred with the most significant bit first.
If a slave can’t receive or transmit another complete byte of data until it has performed some other function, for example servicing an internal interrupt, it can hold the clock line SCL LOW to force the master into a wait state.
Acknowledge:
The receiver must pull down the SDA line during the acknowledge clock pulse so that it remains stable LOW during the HIGH period of this clock pulse .
The Standard-mode I2C-bus specification, with its data transfer rate of up to 100 kbit/s and 7-bit addressing, has been in existence since the beginning of the 1980’s.
To meet the demands for higher speeds, as well as make available more slave address for the growing number of new devices. The following changes were made.
Fast-mode, with a bit rate up to 400 kbit/s.
High-speed mode (Hs-mode), with a bit rate up to 3.4 Mbit/s.
10-bit addressing, which allows the use of up to 1024 additional slave addresses.
PIC MicroController
RAJESHS,
PIC MicroController Day_01
Microprocessor:
Requires ‘external’ support hardware.
E.g., External RAM, ROM, Peripherals.
Microcontroller:
Very little external support hardware.
Most RAM, ROM and peripherals on chip.
“Computer on a chip”, or “System on chip” (SOC)
E.g., PIC = Peripheral Interface Controller
Microprocessor:
We’re used to the Von-Neuman ArchitectureUsed in: 80X86 (PCs), 8051, 68HC11, etc.)
Only one bus between CPU and memory
RAM and program memory share the same bus and the same memory, and so must have the same bit width
Microprocessor:
PICs use the Harvard ArchitectureUsed mostly in RISC CPUs.
Separate program bus and data bus: can be different widths!
For example, PICs use:
Data memory (RAM): a small number of 8bit registers
Program memory (ROM): 12bit, 14bit or 16bit wide (in EPROM, FLASH, or ROM)
Microprocessor:
Traditionally, CPUs are “CISC”
Complex Instruction Set Computer (CISC)
Used in: 80X86, 8051, 68HC11, etc.
Many instructions (usually > 100)
Many addressing modes
Usually takes more than 1 internal clock cycle (Tcyc) to execute
Example:
Microprocessor:
Traditionally, CPUs are “CISC”
PICs and most Harvard chips are “RISC”
Reduced Instruction Set Computer (RISC)
Used in: SPARC, ALPHA, Atmel AVR, etc.
Few instructions (usually < 50)
Only a few addressing modes
Executes 1 instruction in 1 internal clock cycle (Tcyc)
Example:
Microprocessor:
Many Microcontrollers and DSP chips are “converging”
Heading towards some mean between RISC and CISC
Large CPU are adding microcontroller like options
Small microcontrollers are getting more powerful, now able to do some DSP
General trend: Smaller packages, less power consumption, faster
PICs come with 1 of 4 CPU ‘cores’:
12bit cores with 33 instructions: 12C50x, 16C5x
14bit cores with 35 instructions: 12C67x,16Cxxx
16bit cores with 58 instructions: 17C4x,17C7xx
‘Enhanced’ 16bit cores with 77 instructions: 18Cxxx
PICs come in a huge variety of packages:
8 pin DIP : 12C50x (12bit) and 12C67x(14bit)
18pin DIP: 16C5X (12bit), 16Cxxx (14bit)
28pin DIP: 16C5X (12bit), 16Cxxx (14bit)
40pin DIP: 16Cxxx (14bit), 17C4x (16bit)
44 - 68pin: 16Cxxx (14bit), 17C4x/17Cxxx(16bit)
PICs require a clock to work.
Can use crystals, clock oscillators, or even an RC circuit.
Some PICs have a built in 4MHz RC clock
Not very accurate, but requires no external components!
All PICs can be run to a maximum spec’d speed: 12C50x 4MHz
12C67x 10MHz
16Cxxx 20MHz
17C4x / 17C7xxx 33MHz
18Cxxx 40MHz
PIC program space is different for each chip.
Some examples are:
12C508 512 12bit instructions
16C71C 1024 (1k) 14bit instructions
16F877 8192 (8k) 14bit instructions
17C766 16384 (16k) 16bit instructions
PICs have two different types of program storage:
EPROM (Erasable Programmable Read Only Memory)
Needs high voltage from a programmer to program (~13V)
Needs windowed chips and UV light to erase
PIC Examples: Any ‘C’ part: 12C50x, 17C7xx, etc.
Airtel C Programming Code
RAJESHS,
#include
#include
float main(void)
{
float A,Bb,D,G,F;
A = 440;
G = 780;
Bb = 461;
D = 586;
F = 687;
sound(G);
delay(500);
nosound();
sound(G);
delay(250);
nosound();
sound(G);
delay(250);
nosound();
sound(G);
delay(500);
nosound();
sound(2*D);
delay(500);
nosound();
sound(2*A);
delay(250);
nosound();
sound(2*Bb);
delay(250);
nosound();
sound(2*A);
delay(250);
nosound();
sound(G);
delay(250);
nosound();
sound(F);
delay(500);
nosound();
sound(2*A);
delay(500);
nosound();
sound(G);
delay(250);
nosound();
sound(2*A);
delay(250);
nosound();
sound(G);
delay(250);
nosound();
sound(F);
delay(250);
sound(G);
delay(250);
sound(2*A);
delay(250);
sound(2*Bb);
delay(500);
sound(2*A);
delay(500);
sound(G);
delay(250);
sound(F);
delay(250);
sound(D);
delay(500);
nosound();
//end 1
sound(G);
delay(500);
nosound();
sound(G);
delay(250);
nosound();
sound(G);
delay(250);
nosound();
sound(G);
delay(500);
nosound();
sound(2*D);
delay(500);
nosound();
sound(2*A);
delay(250);
nosound();
sound(2*Bb);
delay(250);
nosound();
sound(2*A);
delay(250);
nosound();
sound(G);
delay(250);
nosound();
sound(F);
delay(500);
nosound();
sound(2*A);
delay(500);
nosound();
sound(G);
delay(250);
nosound();
sound(2*A);
delay(250);
nosound();
sound(G);
delay(250);
nosound();
sound(F);
delay(250);
sound(G);
delay(250);
sound(2*A);
delay(250);
sound(2*Bb);
delay(500);
sound(2*A);
delay(500);
sound(G);
delay(250);
sound(F);
delay(250);
sound(D);
delay(500);
nosound();
//end 2
sound(2*A);
delay(250);
nosound();
sound(G);
delay(250);
nosound();
sound(F);
delay(250);
sound(G);
delay(250);
sound(2*A);
delay(250);
sound(2*Bb);
delay(500);
sound(2*A);
delay(500);
sound(G);
delay(250);
sound(F);
delay(250);
sound(D);
delay(500);
nosound();
//end 3
sound(2*A);
delay(250);
nosound();
sound(G);
delay(250);
nosound();
sound(F);
delay(250);
sound(G);
delay(250);
sound(2*A);
delay(250);
sound(2*Bb);
delay(500);
sound(2*A);
delay(500);
sound(G);Airtel C Programming Code
delay(250);
sound(F);
delay(250);
sound(D);
delay(500);
nosound();
return 0;
}
Copy paste the aboce code into your C compiler and just execute!!
SINGLE BOARD COMPUTER PROJECT REPORT
RAJESHS, Monday, October 26, 2009SYNOPSIS
The main aim of the project is to control the whole system in a single module .In this project RTC(Real Time Clock), ADC,Serial Communication, Calculator are design and develop in a single module. In this Project the Real Time Clock is to show the current Time and Date, month Year Everything display in the LCD Screen. Then the other Module ADC Part 12bit Resolution, any given analog input is given the corresponding digital output is converted, and display in the LCD Screen.
Then the Serial communication part the string “HELLO” is Serially transmitted for the baud rate 9600. In this serial communication section any wireless protocol like ZIGBEE or R.F, Blue tooth and other protocol is used to receive same Baud Rate the Original Transmitted string is receive and display in the LCD Screen.
The main part of the Project is Calculator in this calculator part the Two operations like Addition and Subtraction is successfully developed. In this calculator section single bit addition, subtraction is done with a fraction of a second. In this all application module is control by the 3*4 matrix keypad, the key 1 is pressed the calculator operation is run, key 2 is pressed ADC, Key 3 Serial Communication, Key 4 RTC Vice Versa.,
CONTENTS
CHAPTER 1 : INTRODUCTION Page No
1.1 Objective 1
1.2 General Block Diagram 1
1.3 Domain of the Project 2
1.4 Components Required 2
1.5 Introduction to Embedded System 3
CHAPTER 2 : MICROCONTROLLER
2.1General Description 5
2.2 Features 6
2.3 Block Diagram 7
2.4 Pin Diagram and Description 8
2.5 Special Function Register & Timers 11
2.6 Flash Organization & Functional Description 12
CHAPTER 3 : RAISONANCE INTEGRATED
DEVELOPMENT ENVIRONMENT (RIDE)
3.1 Multi-file Editor 16
3.2 Project Manager 16
3.3 Advanced Features 19
CHAPTER 4 : FLASH MAGIC
4.1 Introduction 21
4.2 Minimum requirements 22
4.3 Main Window 22
4.4 Five Step Programming 24
CHAPTER 5 : TEMPERATURE SENSOR – LM35
5.1 Description 31
5.2 Features 31
5.3 Sensor Operation 32
5.4 Advantages 32
CHAPTER 6 : A/D CONVERTER – MCP3202
6.1 General Description 34
6.2 Features 34
6.3 Pin Diagram 34
6.4 Functional Diagram 35
6.5 ADC Serial Communication 37
6.6 Applications 38
CHAPTER 7 : REAL TIME CLOCK DS1307
7.1 General Description 40
7.2 Features 40
7.3 Pin Diagram 40
7.4 Functional Diagram 42
7.5 Communication 43
CHAPTER 8 : SERIAL PERIPHERAL INTERFACE (SPI)
8.1 Introduction 46
8.2 SPI Bus Configuration 46
8.3 SPI Registers 48
8.4 SPI Advantages and Disadvantages 49
CHAPTER 9 : INTER –INTEGRATED CIRCUIT (I2C)
9.1 Introduction 51
9.2 I2C Bus Configuration 51
9.3 I2C Communication 52
9.4 I2C Implementation types 52
CHAPTER 10 : CIRCUIT DIAGRAM WITH OPERATION
10.1 Circuit Diagram 57
10.2 Operation 58
10.3 Program Coding 59
10.4 Conclusion 73
CHAPTER 1
INTRODUCTION
INTRODUCTION
1.1 OBJECTIVE
The objective of this project is to perform four type of task one is Real Time Clock, Adc, Serial Communication, Calculator and the other using I2C Protocol.
1.2 GENERAL BLOCK DIAGRAM
1.3 DOMAIN OF THE PROJECT
AT89S52 Microcontroller acts as the heart of the project which has its own in built memory for the controlling operation.. LM35 is used as a temperature sensor that senses the appropriate temperature level in 0 C .MCP 3202 A/D converter is used for analog signal to digital signal conversion. DS1307 is used as a real time clock, which counts seconds, minutes, hours, date, day, month and year. Keypad using to perform Calculator Function, LCD is used to display the message.
1.4 COMPONENTS REQUIRED
HARDWARE:
AT89S52 (Micro controller)
LM35
MCP 3202
DS1307
Power Supply
SOFTWARE
RIDE v6.1.6
Flash magic v3.21.116
1.5 INTRODUCTION TO EMBEDDED SYSTEM
Embedded System is one that has computer- hardware with software embedded in it as one of its most important component.
CHARACTERISTICS
Efficient reliability
Small size
Low cost
High performance
Easy upgradeability
TYPES OF EMBEDDED SYSTEMS
Small scale
Medium scale
Large scale
APPLICATIONS OF EMBEDDED SYSTEM
Household appliances including microwave ovens, washing machines, television sets, DVD players/recorders
Measurement equipment such as digital storage oscilloscopes, logic analyzers, and spectrum analyzers
Programmable logic controllers (PLCs) for industrial automation and monitoring
CHAPTER 2
AT89S52 MICRO CONTROLLER
AT89S52 MICRO CONTROLLER
2.1 GENERAL DESCRIPTION
The AT89S8252 is a low-power, high-performance CMOS 8-bit microcomputer with 8K bytes of downloadable Flash programmable and erasable read only memory and 2K bytes of EEPROM. The device is manufactured using Atmel’s high-density nonvol-atile memory technology and is compatible with the industry-standard 80C51 instruction set and pinout.
The on-chip downloadable Flash allows the program mem-ory to be reprogrammed in-system through an SPI serial interface or by a conventional nonvolatile memory programmer. By combining a versatile 8-bit CPU with downloadable Flash on a monolithic chip, the Atmel AT89S8252 is a powerful microcomputer which provides a highly-flexible and cost-effective solution to many embedded control applications.
The AT89S8252 provides the following standard features: 8K bytes of downloadable Flash, 2K bytes of EEPROM, 256 bytes of RAM, 32 I/O lines, programmable watch-dog 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 AT89S8252 is designed with static logic for operation down to zero fre-quency and supports two software selectable power saving modes. The Idle Mode stops the CPU while allowing the RAM, timer/counters, serial port, and interrupt sys-tem 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 hard-ware reset.
The downloadable Flash can be changed a single byte at a time and is accessible through the SPI serial interface. Holding RESET active forces the SPI bus into a serial programming interface and allows the program memory to be written to or read from unless Lock Bit 2 has been activated.
2.2 FEATURES
• Compatible with MCS-51™ Products 8K Bytes of In-System Reprogrammable Downloadable Flash Memory
– SPI Serial Interface for Program Downloading
– Endurance: 1,000 Write/Erase Cycles
• 2K Bytes EEPROM
– Endurance: 100,000 Write/Erase Cycles
• 4V to 6V Operating Range
• Fully Static Operation: 0 Hz to 24 MHz
• Three-level Program Memory Lock
• 256 x 8-bit Internal RAM
• 32 Programmable I/O Lines
• Three 16-bit Timer/Counters
• Nine Interrupt Sources
• Programmable UART Serial Channel
• SPI Serial Interface
• Low-power Idle and Power-down Modes
• Interrupt Recovery From Power-down
• Programmable Watchdog Timer
• Dual Data Pointer
• Power-off Flag
2.3 BLOCK DIAGRAM
2.4 PIN DIAGRAM AND DESCRIPTION
PIN DESCRIPTION
VCC :Supply voltage.
GND :Ground.
PORT 0
Port 0 is an 8-bit open drain bbi-didirectional 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 pullups. Port 0 also receives the code bytes during Flash program-ming and outputs the code bytes during program verification. External pullups are required during program verification.
PORT 1
Port 1 is an 8-bit bi-directional I/O port with internal pullups. 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 pullups 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 pullups. Some Port 1 pins provide additional functions. 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. Port 1 also receives the low-order address bytes during Flash programming and verification
PORT 2
Port 2 is an 8-bit bi-directional I/O port with internal pullups.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 pullups 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 pullups. 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 pul-lups 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.
PORT 3
Port 3 is an 8 bit bi-directional I/O port with internal pullups.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 pullups and can be used as inputs. As inputs,Port 3 pins that are externally being pulled low will source current (IIL) because of the pullups. Port 3 also receives some control signals for Flash pro-gramming and verification.
PROGRAM STORE ENABLE
PSEN is the read strobe for external program memory. When the device is executing from internal program memory, PSEN is inactive (HIGH). When the device 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.
RESET
While the oscillator is running, a HIGH logic state on this pin for two machine cycles will reset the device. If the PSEN pin is driven by a HIGH-to-LOW input transition while the RST input pin is held HIGH, the device will enter the external host mode; otherwise the device will enter the normal operation mode.
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, if lock bit 1 is programmed, EA will be internally latched on reset. EA should be strapped to VCC for internal program execu-tions. This pin also receives the 12-volt programming enable voltage (VPP) during Flash programming when 12-volt programming is selected.
ADDRESS LATCH ENABLE
ALE is the output signal for latching the low byte of the address during an access to external memory. This pin is also the programming pulse input (PROG) for flash programming. Normally the ALE is emitted at a constant rate of 1/6 the crystal frequency and can be used for external timing and clocking. One ALE pulse is skipped during each access to external data memory. However, if AO is set to ‘1’, ALE is disabled.
XTAL1
Input to the inverting oscillator amplifier and input to the internal clock operating circuit.
XTAL2
Output from the inverting oscillator amplifier.
2.5 SPECIAL FUNCTION REGISTER & TIMERS
2.5.1 SPECIAL FUNCTION REGISTER
SPI Registers
Control and status bits for the Serial Periph-eral Interface are contained in registers SPCR (shown in Table 4) and SPSR (shown in Table 5). The SPI data bits are contained in the SPDR register. Writing the SPI data register during serial data transfer sets the Write Collision bit, WCOL, in the SPSR register. The SPDR is double buff-ered for writing and the values in SPDR are not changed by Reset.
Interrupt Registers
The global interrupt enable bit and the individual interrupt enable bits are in the IE register. In addition, the individual interrupt enable bit for the SPI is in the SPCR register. Two priorities can be set for each of the six interrupt sources in the IP register.
Dual Data Pointer Registers
To facilitate accessing both internal EEPROM 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 WMCON 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 reset under software control and is not affected by RESET.
2.5.2 TIMERS
Programmable Watchdog Timer
The programmable Watchdog Timer (WDT) operates from an independent oscillator. The prescaler bits, PS0, PS1 and PS2 in SFR WMCON are used to set the period of the Watchdog Timer from 16 ms to 2048 ms. The available timer periods are shown in the following table and the actual timer periods (at VCC = 5V) are within ±30% of the nominal. The WDT is disabled by Power-on Reset and during Power-down. It is enabled by setting the WDTEN bit in SFR WMCON (address = 96H). The WDT is reset by setting the WDTRST bit in WMCON. When the WDT times out without being reset or disabled, an internal RST pulse is generated to reset the CPU.
Timer 0 and 1
Timer 0 and Timer 1 in the AT89S8252 operate the same way as Timer 0 and Timer 1 in the AT89C51, AT89C52 and AT89C55.
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 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 8. 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 oscil-lator periods, the count rate is 1/12 of the oscillator frequency.
2.6 MEMORY ORGANIZATION
Programming the Flash and EEPROM
Atmel’s AT89S8252 Flash Microcontroller offers 8K bytes of in-system reprogrammable Flash Code memory and 2K bytes of EEPROM Data memory. The AT89S8252 is normally shipped with the on-chip Flash Code and EEPROM Data memory arrays in the erased state (i.e. contents = FFH) and ready to be programmed. This device supports a High-voltage (12V) Parallel pro-gramming mode and a Low-voltage (5V) Serial programming mode. The serial programming mode pro-vides a convenient way to download the AT89S8252 inside the user’s system. The parallel programming mode is com-patible with conventional third party Flash or EPROM programmers.
The Code and Data memory arrays are mapped via sepa-rate address spaces in the serial programming mode. In the parallel programming mode, the two arrays occupy one contiguous address space: 0000H to 1FFFH for the Code array and 2000H to 27FFH for the Data array.
The Code and Data memory arrays on the AT89S8252 are programmed byte-by-byte in either programming mode. An auto-erase cycle is provided with the self-timed program-ming operation in the serial programming mode. There is no need to perform the Chip Erase operation to reprogram any memory location in the serial programming mode unless any of the lock bits have been programmed.
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 16 ms. During chip erase, a serial read from any address location will return 00H at the data outputs. In the parallel programming mode, there is no auto-erase cycle. To reprogram any non-blank byte, the user needs to use the Chip Erase operation first to erase both arrays
Programming Interface
Every code byte in the Flash and EEPROM arrays can be written, and the entire array can be erased, by using the appropriate combination of control signals. The write oper-ation cycle is self-timed and once initiated, will automatically time itself to completion.
Serial Programming Algorithm
To program and verify the AT89S8252 in the serial pro-gramming mode, the following sequence is recommended:
1. Power-up sequence: Apply power between VCC and GND pins.
Set RST pin to “H”.
If a crystal is not connected across pins XTAL1 and XTAL2, apply a 3 MHz to 24 MHz clock to XTAL1 pin and wait for at least 10 milliseconds.
2. Enable serial programming by sending the Pro-gramming Enable serial instruction to pin MOSI/P1.5. The frequency of the shift clock sup-plied at pin SCK/P1.7 needs to be less than the CPU clock at XTAL1 divided by 40.
3. The Code or Data array is programmed one byte at a time by supplying the address and data together with the appropriate Write instruction. The selected memory location is first automatically erased before new data is written. The write cycle is self-timed and typically takes less than 2.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 operation.
Power-off sequence (if needed): Set XTAL1 to “L” (if a crystal is not used).
Set RST to “L”.
Turn VCC power off.
The data RAM has 1024 bytes of internal memory.
The device can also address up to 64 Kb for external data memory.
Serial Downloading
Both the Code and Data memory arrays can be pro-grammed using the serial SPI bus 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 pro-gram/erase operations can be executed. An auto-erase cycle is built into the self-timed programming operation (in the serial mode ONLY) and there is no need to first execute the Chip Erase instruction unless any of the lock bits have been programmed. The Chip Erase opera-tion turns the content of every memory location in both the Code and Data arrays into FFH. The Code and Data memory arrays have separate address spaces
CHAPTER 3
RAISONANCE INTEGRATED DEVELOPMENT ENVIRONMENT (RIDE)
RAISONANCE INTEGRATED DEVELOPMENT ENVIRONMENT
(RIDE)
RIDE is a fully featured Integrated Development Environment that provides seamless integration and easy access to all the development tools. From editing to compiling, linking, debugging and back to the start, with a Simulator, ICE, Rom Monitor or other debugging tool, RIDE conveniently manages all aspects of the Embedded Systems development with a single user interface.
3.1 MULTI-FILE EDITOR
RIDE is based on a fast multi-document editor designed to meet the specific needs of programming. The various methods, menus, commands, and shortcuts are all fully compliant with the Microsoft® specifications for Windows 2000, XP and NT. Classic commands, such as string search and block action are integrated. Advanced features such as Matching Delimiter (parenthesis, brackets), Grep (multi-file search) and Indenter are integrated as well. The customizable color-highlighting feature is very useful to indicate specific syntactic elements as they appear in the source file: keywords, comments, identifiers, operators, and so on. The color-highlighting feature is automatically keyed to the intrinsic file type (that is, it works differently for C and assembler).This permits the user to identify quickly and easily those parts of the code responsible for syntax errors.
3.2 PROJECT MANAGER
The project manager creates links between the various files that comprise a project and the tools necessary to create that project. A project is dedicated to a particular target: 8051, XA, ST7, STR7, ST6, ST5 or other microcontrollers. The linker manages object and library files, and output format conversion as necessary. Tree-structured projects ease the management of the most complex applications (bank switching, flash, multi-processor, multi-module…).
The 'Project | Make' command directs the integrated "make" utility to build or rebuild the target programs for the current project. To avoid wasting time, each source file will be translated by its associated tool only if any of its dependencies are found to be out of date. Dependency analysis, even of directly or indirectly included files, is automatic. Options can be defined as global (for all the files) or as local (for a specific node or file). Individual attributes can be set for any file in the project. Similarities between the different tools make migration from one processor family to another immediate and easy, permitting multi-processor.
3.2.1 THE MESSAGE WINDOW AND THE ON-LINE HELP
The message window displays all warning, error, and progress messages generated during the processing of files associated with each project. Clicking on an error string in the message window automatically positions the cursor at the point of that error in the source code window.
Online Help Menu
The Online help system is context-sensitive and provides information on nearly all aspects of RIDE. A specific help file is supplied with each tool driven by the IDE ('C' Compiler, Assembler, Linker and RTOS).Online menu hints appear on the status line whenever you select a menu command.
3.2.2 THE SCRIPT LANGUAGE
Most RIDE commands can be run from a script file. Scripts are written in a C-like language, and are interpreted at execution time. With the script language, most repetitive tasks can be done automatically thus speeding up operations and reducing the probability of errors.
Scripts are very useful for Hardware Testing (board, emulator) and to initialize the system to a known status, but can be conveniently used also for other tasks such as creating very complex breakpoints or redirecting some output to a file to run a 'batch' debug session.
CONTEXT SAVING
When a project is closed, the whole associated context is saved (open file list, window size and position etc...).Settings associated with the debugger are also saves such as breakpoints, watches etc...
3.2.3 INTEGRATED HIGH-LEVEL DEBUG
RIDE provides a fully integrated source-level debugging environment. All information necessary is derived from the translators used to accomplish each step of the process. This is the heart of RIDE,
Program Window
This includes mundane aspects such as "path names", and source code specific information such as details of complex data types. With the simple click of a mouse button, the user can select among several powerful capabilities: simulate, monitor, or emulate. The fast smooth integration afforded by RIDE promotes a feeling of familiarity and ease of use, while providing a level of comfort and efficiency that reduces the most difficult and complex applications to tasks that are easily managed.
This seamless progression of the "code-translate-link-debug-test" cycle is the result of perfect communication between the programming tools and the debugger.
3.2.4. INTEGRAL SIMULATION
RIDE includes simulation engines for most 8051, XA and ST6 derivatives. The simulator/debugger is cleanly integrated into the presentation Windows. A wide range of 'views' can be selected to provide flexible direct examination of all memory spaces as well the all internal peripherals.
The simulation engines perform detailed and faithful simulations (including IDLE or Power down modes), of all peripherals—including interrupt and watchdog events—present on the selected component.
3.3 ADVANCED FEATURES
RIDE provides a rich variety of 'views' into an application. These views or windows are associated with control commands like complex breakpoints or high level trace recording.
Trace Window
CHAPTER 4
FLASH MAGIC
FLASH MAGIC
4.1 INTRODUCTION
NXP Semiconductors produce a range of Microcontrollers that feature both on-chip Flash memory and the ability to be reprogrammed using In-System Programming technology.
Flash Magic is Windows software from the Embedded Systems Academy that allows easy access to all the ISP features provided by the devices. These features include,
Erasing the Flash memory (individual blocks or the whole device)
Programming the Flash memory
Modifying the Boot Vector and Status Byte
Reading Flash memory
Performing a blank check on a section of Flash memory
Reading the signature bytes
Reading and writing the security bits
Direct load of a new baud rate (high speed communications)
Sending commands to place device in Boot loader mode
Flash Magic provides a clear and simple user interface to these features and more as described in the following sections. Under Windows, only one application may have access the COM Port at any one time, preventing other applications from using the COM Port.
Flash Magic only obtains access to the selected COM Port when ISP operations are being performed. This means that other applications that need to use the COM Port, such as debugging tools, may be used while Flash Magic is loaded. Note that in this manual third party Compilers are listed alphabetically. No preferences are indicated or implied.
4.2 MINIMUM REQUIREMENTS
Windows 95/98/ME/NT/2000/XP
Mouse
COM Port
16Mb RAM
3Mb Disk Space
4.3 MAIN WINDOW
The following is a screenshot of the main Flash Magic window. The appearance may differ slightly depending on the device selected. The window is divided up into five sections. Work your way from section 1 to section 5 to program a device using the most common functions. Each section is described in detail in the following sections. At the very bottom left of the window is an area where progress messages will be displayed and at the very bottom right is where the progress bar is displayed.
Main Window
In between the messages and the progress bar is a count of the number of times the currently selected hex file has been programmed since it was last modified or selected. Just above the progress information embedded hints are displayed. These are rotating Internet links that you can click on to go to a web page using your default browser. If you wish to quickly flick through all the hints then you can click on the fast forward button: Progress information Progress bar Section 1 includes
Embedded Hints
Menus
Programmed Count
Flash Magic User Manual
4.3.1 MENUS
There are five menus, File, ISP, Options, Tools and Help. The File menu provides access to loading and saving Hex Files, loading and saving settings files and exiting the application. The ISP menu provides access to the less commonly used ISP features. The Options menu allows access to the advanced options and includes an item to reset all options. The Tools menu provides features that support the operation and use of Flash Magic.
The Help menu contains items that link directly to useful web pages and also open the Help About window showing the version number. The Loading and Saving of Hex Files and the other ISP features are described in the following sections.
4.3.2 TOOL TIPS
Tool window
Throughout the Flash Magic user interface extensive use has been made of tool tips. These are small text boxes that appear when you place the pointer over something and keep it still for a second or two. Note that tool tips do not appear for items that are disabled (grayed out).
4.3.3 SAVING OPTIONS
The options in the main window and the Advanced Options window are automatically saved to the registry whenever Flash Magic is closed. This removes the need for an explicit save operation.
When Flash Magic is restarted the main window and the Advanced Options window will appear as you left it, so you do not have to repeatedly make the same selections every time you start the application. If you wish to reset the options to the original defaults then choose Reset from the Options menu.
4.4 FIVE STEP PROGRAMMING
For each step there is a corresponding section in the main window as described in the User Interface Tour.
4.4.1 STEP 2-CONNECTION SETTINGS
Before the device can be used the settings required to make a connection must be specified. Select the desired COM port from the drop down list or type the desired COM port directly into the box.
If you enter the COM port yourself then you must enter it in one of the following formats:
COM n
n
Any other format will generate an error. So if you want to use COM 5 (which is not present on the drop down list) you can directly type in either “COM 5” or “5”.Select the baud rate to connect at. Try a low speed first. The maximum speed that can be used depends on the crystal frequency on your hardware. You can try connecting at higher and higher speeds until connections fail. Then you have found the highest baud rate to connect at. Alternatively, some devices support high speed communications. Please refer to the High-Speed Communications section for information.
Select the device being used from the drop down list. Ensure you select the correct one as different devices have different feature sets and different methods of setting up the serial communications. Select the interface being used, if any.
Step 1
An interface is a device that connects between your PC and the target hardware. If you simply have a serial cable or USB to serial cable connecting your COM port to the target hardware, then chooses "None (ISP)".
Choosing the correct interface will automatically configure Flash Magic for that interface, along with enabling and disabling the relevant features.
Enter the oscillator frequency used on the hardware. Do not round the frequency, instead enter it as precisely as possible. Some devices do not require the oscillator frequency to be entered, so this field will not be displayed.
Once the options are set ensure the device is running the on-chip Boot loader if you are using a manual ISP entry method. Note that the connection settings affect all ISP features provided by Flash Magic.
4.4.2 STEP 2-ERASING
This step is optional, however if you attempt to program the device without first erasing at least one Flash block, then Flash Magic will warn you and ask you if you are sure you want to program the device. Select each Flash block that you wish to erase by clicking on its name. If you wish to erase all the Flash then check that option. If you check to erase a Flash block and all the Flash, then the Flash block will not be individually erased.
Step 2
If you wish to erase only the Flash blocks used by the hex file you are going to select, then check that option. For most devices erasing all the Flash also results in the Boot Vector and Status Byte being set to default values, which ensure that the Boot loader will be executed on reset, regardless of the state of the PSEN pin or other hardware requirements.
Only when programming a Hex File has been completed will the Status Byte be set to 00H to allow the code to execute. This is a safeguard against accidentally attempting to execute when the Flash is erased. On some devices erasing all the Flash will also erase the security bits.
This will be indicated by the text next to the Erase all Flash option. On some devices erasing all the Flash will also erase the speed setting of the device (the number of clocks per cycle) setting it back to the default. This will be indicated by the text next to the Erase all Flash option.
4.4.3 STEP 3-SELECTING THE HEX FILES
This step is optional. If you do not wish to program a Hex File then do not select one. You can either enter a path name in the text box or click on the Browse button to select a Hex File by browsing to it.
Also you can choose Open… from the File menu. Note that the Hex file is not loaded or cached in any way. This means that if the Hex File is modified, you do not have to reselect it in Flash Magic. Every time the Hex File is programmed it is first re-read from the location specified in the main window. The date the Hex file was last modified is shown in this section.
Step 3
This information is updated whenever the hex file is modified. The hex file does not need to be reselected. Clicking on more info or choosing Information… from the File menu will display additional information about the Hex file.
The information includes the range of Flash memory used by the Hex file, the number of bytes of Flash memory used and the percentage of the currently selected device that will be filled by programming the Hex file. If the device supports programming and execution from RAM, for example the ARM devices, then the hex file may contain records for the RAM. First the flash will be programmed followed by the RAM. Programs loaded into RAM via a hex file may be executed using such features as the Go option. See chapter 6 for more details.
4.4.4 STEP 4-OPTIONS
Flash Magic provides various options that may be used after the Hex File has been programmed. This section is optional, however Verify After Programming, Fill Unused Flash and Gen Block Checksums may only be used if a Hex File is selected (and therefore being programmed), as they all need to know either the Hex File contents or memory locations used by the Hex File.
Checking the Verify after Programming option will result in the data contained in the Hex File being read back from Flash and compared with the Hex File after programming.
Step 4
This helps to ensure that the Hex File was correctly programmed. If the device does not support verifying then this item will be disabled. Checking the Fill Unused Flash option will result in every memory location not used by the File being programmed with the value that sets all the bits to a programmed state. Once a location has been programmed with this feature it cannot be reprogrammed with any other value, preventing someone from programming the device with a small program to read out the contents of Flash or altering the application’s operation. Checking the Gen Block Checksums option will instruct Flash Magic to program the highest location in every Flash block used by the Hex File with a special “checksum adjuster value”. This value ensures that when a checksum is calculated for the whole Flash Block it will equal 55H, providing the contents of the Flash block have not be altered or corrupted. Please refer to the Block Checksums section for more information. Checking the Execute option will cause the downloaded firmware to be executed automatically after the programming is complete. Note that this will not work if using the Hardware Reset option or a device that does not support this feature.
4.4.5 STEP 5-PERFORMING THE OPERATIONS
Step 5 contains a Start button. Clicking the Start button will result in all the selected operations in the main window taking place. They will be in order:
Step 5
Erasing Flash
Programming the Hex File
Verifying the Hex File
Filling Unused Flash
Generating Checksums
Programming the clocks bit
Programming the Security Bits
Executing the firmware
Once started, progress information and a progress bar will be displayed at the bottom of the main window. In addition the Start button will change to a cancel button. Click on the cancel button to cancel the operation.
Note that if you cancel during erasing all the Flash, it may take a few seconds before the operation is cancelled. Once the operations have finished the progress information will briefly show the message “Finished…” . The Programmed Count shown next to the progress bar will increment. This shows the total number of times the hex file has been programmed. Modifying the hex file or selecting another hex file will reset the count. Alternatively, right-clicking over the count provides a menu with the option to immediately reset the count.
CHAPTER 5
TEMPERATURE SENSOR - LM35
TEMPERATURE SENSOR – LM35
The LM35 is an integrated circuit sensor that can be used to measure temperature with an electrical output proportional to the temperature in degree Celsius.
5.1 FEATURES
Calibrated directly in centigrade (o C)
Linear +10.0 mV/ o C
0.5 o C accuracy guarantee able (at +25 o C)
Rated for full -55 o C to +150o C range
Suitable for remote applications
Low cost due to wafer-level trimming
Operates from 4 to 30 volts
Less than 60 µA current drain
Low self-heating, 0.08 o C in still air
Non- linearity only ±1/4 o C typical
Low impedance output, 0.1 W for 1 mA load
5.2 DESCRIPTION
The LM35 series are precision integrated- circuit temperature sensors, whose output voltage is linearly proportional to the Celsius temperature.
The LM35 thus has an advantage over linear temperature sensors calibrated in o Kelvin, as the user is not required to subtract a large constant voltage from its output to obtain convenient centigrade scaling. The LM35’s low output impedance, linear output, and precise inherent calibration make interfacing to readout or control circuitry especially easy. It can be used with single power supplies, or with plus and minus supplies. As it draws only 60 µA from its supply, it has very low self-heating, less than 0.1 o C in still air. The LM35 is rated to operate over a -55 o C to +150 o C temperature range.
5.3 SENSOR OPERATION
In this circuit, parameter values commonly used are supply Vcc=5v or 12v, and resistance
Ra=Vcc/10-6=80 KΩ. The output voltage is converted to temperature by a simple conversion factor.
Temperature (o C) = Vout * (100 o C/ V)
LM35 Circuit
The sensor has the sensitivity of 10mV / o C and the output voltage varies linearly with temperature.
5.4 ADVANTAGES
One can measure temperature more accurately than using a thermistor.
The sensor circuitry is sealed and not subject to oxidation, etc.,
The LM35 generates a higher output voltage than thermocouples and may not require that the output voltage be amplified.
CHAPTER 6
A/D CONVERTER – MCP3202
ANALOG TO DIGITAL CONVERTER (ADC)
6.1 GENERAL DESCRIPTION
The MCP3202 is a successive approximation 12 bit Analog to Digital converter with on-board sample and hold circuitry. The MCP3202 is programmable to provide a single pseudo-differential input pair or dual single-ended inputs. Communication with the device is done using a simple serial interface compatible with the SPI protocol The device is capable of conversion rates of up to 100kbps at 5v and 50 kbps at 2.7v.Low current design of only 500nA and 375 microAmps.
6.2 FEATURES
12 bit resolution
Operating supply voltage 2.7 V to 5.5 V
On-chip sample and hold
SPI Serial interface
Low power CMOS technology
100kbps max sampling rate at Vdd =5v
50kbps max sampling rate at Vdd =2.7v
Analog inputs programmable as single-ended or differential inputs
Industrial temperature range -400c to +85 0 c
8-bit successive approximation A/D conversion
6.3 PIN DIAGRAM
6.3.1 PIN DESCRIPTIONS
1.CH0/CH1
Analog inputs for channels 0 and 1 respectively. These channels can programmed to be used as two indepen-dent channels in single ended-mode or as a single pseudo-differential input where 1 channel is IN+ and one channel is IN-.
2CS/SHDN(Chip Select/Shutdown)
The CS/SHDN pin is used to initiate communication with the device when pulled low and will end a conver-sion and put the device in low power standby when pulled high. The CS/SHDN pin must be pulled high between conversions.
3CLK (Serial Clock)
The SPI clock pin is used to initiate a conversion and to clock out each bit of the conversion as it takes place.
4DIN (Serial Data Input)
The SPI port serial data input pin is used to clock in input channel configuration data.
5DOUT (Serial Data output)
The SPI serial data output pin is used to shift out the results of the A/D conversion. Data will always change on the falling edge of each clock as the conversion takes place.
6.4 FUNCTIONAL DIAGRAM
6.4.1 DEVICE OPERATION
The MCP3202 A/D Converter employs a conventional SAR architecture. With this architecture, a sample is acquired on an internal sample/hold capacitor for 1.5 clock cycles starting on the second rising edge of the serial clock after the start bit has been received. Following this sample time, the input switch of the con-verter opens and the device uses the collected charge on the internal sample and hold capacitor to produce a serial 12-bit digital output code. Conversion rates of 100ksps are possible on the MCP3202. See Section 6.2 for information on minimum clock rates. Communication with the device is done using a 3-wire SPI-compatible interface.
6.4.2Analog Inputs:
The MCP3202 device offers the choice of using the ana-log input channels configured as two single-ended inputs or a single pseudo-differential input. Configura-tion is done as part of the serial command before each conversion begins. When used in the psuedo-differen-tial mode, CH0 and CH1 are programmed as the IN+ and IN- inputs as part of the command string transmit-ted to the device. The IN+ input can range from IN- to VREF (VREF + IN-). The IN- input is limited to ±100mV from the VSS rail. The IN- input can be used to cancel small signal common-mode noise which is present on both the IN+ and IN- inputs.
For the A/D Converter to meet specification, the charge holding capacitor (CSAMPLE) must be given enough time to acquire a 12-bit accurate voltage level during the 1.5 clock cycle sampling period. (RS) adds to the internal sampling switch (RSS) imped-ance, directly affecting the time that is required to charge the capacitor, CSAMPLE. Consequently, larger source impedances increase the offset, gain, and inte-gral linearity errors of the conversion.
Ideally, the impedance of the signal source should be near zero. This is achievable with an operational ampli-fier such as the MCP601 which has a closed loop out-put impedance of tens of ohms. When operating in the pseudo-differential mode, if the voltage level of IN+ is equal to or less than IN-, the resultant code will be 000h. If the voltage at IN+ is equal to or greater than {[VREF + (IN-)] - 1 LSB}, then the out-put code will be FFFh. If the voltage level at IN- is more than 1 LSB below VSS, then the voltage level at the IN+ input will have to go below VSS to see the 000h output code. Conversely, if IN- is more than 1 LSB above VSS, then the FFFh code will not be seen unless the IN+ input level goes above VREF level.
6.4.3 Digital Output Code
The digital output code produced by an A/D Converter is a function of the input signal and the reference volt-age. For the MCP3202, VDD is used as the reference voltage. As the VDD level is reduced, the LSB size is reduced accordingly. The theoretical digital output code produced by the A/D Converter is shown below.
Digital Output Code = 4096 * VIN / VDD
where:
VIN = analog input voltage,VDD = supply voltage,
6.5 SERIAL COMMUNICATIONS
Communication with the MCP3202 is done using a standard SPI-compatible serial interface. Initiating communication with the device is done by bringing the CS line low. See Figure 5-1. If the device was powered up with the CS pin low, it must be brought high and back low to initiate communication. The first clock received with CS low and DIN high will constitute a start bit. The SGL/DIFF bit and the ODD/SIGN bit follow the start bit and are used to select the input channel configuration. The SGL/DIFF is used to select single ended or psuedo-differential mode. The ODD/SIGN bit selects which channel is used in single ended mode, and is used to determine polarity in pseudo-differential mode. Following the ODD/SIGN bit, the MSBF bit is transmit-ted to and is used to enable the LSB first format for the device. If the MSBF bit is low, then the data will come from the device in MSB first format and any further clocks with CS low will cause the device to output zeros. If the MSBF bit is high, then the device will output the converted word LSB first after the word has been transmitted in the MSB first format.
MCP3202. The device will begin to sample the analog input on the second rising edge of the clock, after the start bit has been received. The sample period will end on the falling edge of the third clock following the start bit. MSB first. Data is always output from the device on the falling edge of the clock. If all 12 data bits have been transmitted and the device contin-ues to receive clocks while the CS is held low, (and MSBF = 1), the device will output the conversion result LSB first If more clocks are pro-vided to the device while CS is still low (after the LSB first data has been transmitted), the device will clock out zeros indefinitely. If necessary, it is possible to bring CS low and clock in leading zeros on the DIN line before the start bit. This is often done when dealing with microcontroller-based SPI ports that must send 8 bits at a time.
CONFIG
BITS CHANNEL
SELECTION GND
SGL/
DIFF ODD/
SIGN 0 1
SINGLE
ENDED MODE 1 0 -
1 1 +
PSEUDO-
DIFFERENTIAL
MODE 0 0 I I
0 1 I IN
6.6 APPLICATIONS
Closed loop control systems
Low power converter for remote data acquisition
Battery operated equipment
Acquisition of analog values in automotive, audio and
TV applications (as tuner cards)
Software defined radio and digital oscilloscopes
CHAPTER 7
REAL TIME CLOCK DS1307
REAL TIME CLOCK (RTC)
7.1 GENERAL DESCRIPTION
The DS1307 Serial Real Time Clock is a low power, full BCD clock/calendar plus 56 bytes of nonvolatile SRAM. Address and data are transferred serially via a 2-wire bi-directional bus. The clock/calendar provides seconds, minutes, hours, day, date, month, and year information. The end of the month date is automatically adjusted for months with less than 31 days, including corrections for leap year. The clock operates in either the 24-hour or 12-hour format with AM/PM indicator. The DS1307 has a built-in power sense circuit which detects power failures and automatically switches to the battery supply.
7.2 FEATURES
• Real time clock counts seconds, minutes, hours, date of the month, month, day of the week, and year
• 56 byte nonvolatile RAM for data storage
• 2-wire serial interface
• Programmable square wave output signal
• Automatic power-fail detect and switch circuitry
• Consumes less than 500 nA in battery backup mode with oscillator running
• Optional industrial temperature range -40_C to +85_C
• Available in 8-pin DIP or SOIC
7.3 PIN DIAGRAM
7.4 DESCRIPTION
VCC - Primary Power Supply
X1, X2 - 32.768 kHz Crystal Connection VBAT - +3V Battery Input
GND - Ground
SDA - Serial Data
SCL - Serial Clock
SQW/OUT - Square wave/Output Driver
7.5 FUNTIONAL BLOCK DIAGRAM:
OPREATION:
The DS1307 operates as a slave device on the serial bus. Access is obtained by implementing a START condition and providing a device identification code followed by a register address. Subsequent registers can be accessed sequentially until a STOP condition is executed. When VCC falls below 1.25 x VBAT the device terminates an access in progress and resets the device address counter. Inputs to the device will not be recognized at this time to prevent erroneous data from being written to the device from an out of tolerance system. When VCC falls below VBAT the device switches into a low current battery backup mode. Upon power up, the device switches from battery to VCC when VCC is greater than VBAT +0.2V and recognizes inputs when VCC is greater than 1.25 x VBAT.
7.5 SIGNAL DESCRIPTIONS
VCC, GND - DC power is provided to the device on these pins. VCC is the +5 volt input. When 5 volts is applied within normal limits, the device is fully accessible and data can be written and read. When a 3-volt battery is connected to the device and VCC is below 1.25 x VBAT, reads and writes are inhibited. However, the Timekeeping function continues unaffected by the lower input voltage. As VCC falls below VBAT the RAM and timekeeper are switched over to the external power supply (nominal 3.0V DC) at VBAT.
VBAT - Battery input for any standard 3-volt lithium cell or other energy source. Battery voltage must be held between 2.0 and 3.5 volts for proper operation. The nominal write protect trip point voltage at which access to the real time clock and user RAM is denied is set by the internal circuitry as 1.25 x VBAT nominal. A lithium battery with 48 mAhr or greater will back up the DS1307 for more than 10 years in the absence of power at 25 degrees C.
SCL (Serial Clock Input) - SCL is used to synchronize data movement on the serial interface.
SDA (Serial Data Input/Output) - SDA is the input/output pin for the 2-wire serial interface. The SDA pin is open drain which requires an external pullup resistor.
SQW/OUT (Square Wave/ Output Driver) - When enabled, the SQWE bit set to 1, the SQW/OUT pin outputs one of four square wave frequencies (1 Hz, 4 kHz, 8 kHz, 32 kHz). The SQW/OUT pin is open drain which requires an external pullup resistor. SQW/OUT will operate with either Vcc or Vbat applied.
X1, X2 - Connections for a standard 32.768 kHz quartz crystal. The internal oscillator circuitry is designed for operation with a crystal having a specified load capacitance (CL) of 12.5 pF.
RTC AND RAM ADDRESS MAP
The address map for the RTC and RAM registers of the DS1307 is shown in Figure 2. The real time clock registers are located in address locations 00h to 07h. The RAM registers are located in address locations 08h to 3Fh. During a multi-byte access, when the address pointer reaches 3Fh, the end of RAM space, it wraps around to location 00h, the beginning of the clock space.
CLOCK AND CALENDAR
The time and calendar information is obtained by reading the appropriate register bytes. The real time clock registers are illustrated in Figure 3. The time and calendar are set or initialized by writing the appropriate register bytes. The contents of the time and calendar registers are in the Binary-Coded Decimal (BCD) format. Bit 7 of Register 0 is the Clock Halt (CH) bit. When this bit is set to a 1, the oscillator is disabled. When cleared to a 0, the oscillator is enabled.
7.6 COMMUNICATION
Data transfer may be initiated only when the bus is not busy. During data transfer, the data line must remain stable whenever the clock line is HIGH. Changes in the data line while the clock line is high will be interpreted as control signals. Accordingly, the following bus conditions have been defined:
Bus not busy: Both data and clock lines remain HIGH.
Start data transfer: A change in the state of the data line, from HIGH to LOW, while the clock is HIGH, defines a START condition.
Stop data transfer: A change in the state of the data line, from LOW to HIGH, while the clock line is HIGH, defines the STOP condition.
Data valid: The state of the data line represents valid data when, after a START condition, the data line is stable for the duration of the HIGH period of the clock signal. The data on the line must be changed during the LOW period of the clock signal. There is one clock pulse per bit of data.
Each data transfer is initiated with a START condition and terminated with a STOP condition. The number of data bytes transferred between START and STOP conditions is not limited, and is determined by the master device. The information is transferred byte-wise and each receiver acknowledges with a ninth bit. Within the 2-wire bus specifications a regular mode (100 kHz clock rate) and a fast mode (400 kHz clock rate) are defined. The DS1307 operates in the regular mode (100 kHz) only.
Acknowledge: Each receiving device, when addressed, is obliged to generate an acknowledge after the reception of each byte. The master device must generate an extra clock pulse which is associated with this acknowledge bit.
A device that acknowledges must pull down the SDA line during the acknowledge clock pulse in such a way that the SDA line is stable LOW during the HIGH period of the acknowledge related clock pulse. Of course, setup and hold times must be taken into account. A master must signal an end of data to the slave by not generating an acknowledge bit on the last byte that has been clocked out of the slave. In this case, the slave must leave the data line HIGH to enable the master to generate the STOP condition.
Depending upon the state of the R/W bit, two types of data transfer are possible:
1. Data transfer from a master transmitter to a slave receiver. The first byte transmitted by the master is the slave address. Next follows a number of data bytes. The slave returns an acknowledge bit after each received byte. Data is transferred with the most significant bit (MSB) first.
2. Data transfer from a slave transmitter to a master receiver. The first byte (the slave address) is
transmitted by the master. The slave then returns an acknowledge bit. This is followed by the slave transmitting a number of data bytes. The master returns an acknowledge bit after all received bytes other than the last byte. At the end of the last received byte, a ’not acknowledge’ is returned.
The master device generates all of the serial clock pulses and the START and STOP conditions. A transfer is ended with a STOP condition or with a repeated START condition. Since a repeated START condition is also the beginning of the next serial transfer, the bus will not be released. Data is transferred with the most significant bit (MSB) first.
CHAPTER 8
SERIAL PERIPHERAL INTERFACE
8.1 INTRODUCTION:
SPI stands for Serial Peripheral Interfacing. It is a synchronous serial bus developed by Motorola and is present on many of their micro controllers. SPI is used to communicate with peripheral devices.Benefit of serial communications is low pin counts Many common embedded system peripherals, such as A2D and D2A converters, LCD, and temperature sensors, support serial interfaces
Two types of devise are involved in data transfer in the SPI format: master and slaves. The master device initiates data transfer and also generates the clock signal required for data transfer synchronization .SPI can achieve higher data rates. SPI has full duplex capability
8.2 SPI BUS CONFIGURATION:
Devices communicate using a master/slave relationship, in which the master initiates the data frame. When the master generates a clock and selects a slave device, data may be transferred in either or both directions simultaneously. In fact, as far as SPI is concerned, data are always transferred in both directions. It is up to the master and slave devices to know whether a received byte is meaningful or not. So a device must discard the received byte in a "transmit only" frame or generate a dummy byte for a "receive only" frame.
Single master,single slave SPI implementation
SCLK is generated by the master and input to all slaves. MOSI carries data from master to slave. MISO carries data from slave back to master. A slave device is selected when the master asserts its ÇSS signal.
Single master,Multiple slave SPI implementation
If multiple slave devices exist, the master generates a separate slave select signal for each slave.
Four main signals:
Master Out Slave In (MOSI) : data from master to slave
Master In Slave Out (MISO) : data from slave to master
Serial Clock (SCLK or SCK) : clock
Chip Select (CS) : select particular peripheral when multiple peripherals are connected to
master
8.3 SPI REGISTERS:
There are three registers unique to the serial peripheral interface which provide control,status,and data stroage
SPCR:
The Serial Peripheral Control Register (SPCR) provides control for the SPI. A pair of parameters called clock polarity (CPOL) and clock phase (CPHA) determine the edges of the clock signal on which the data are driven and sampled.
Bit 7 6 5 4 3 2 1 0
SPIE SPE DORD MSTR CPOL CPHA SPR1 SPR0
R/W R/W R/W R/W R/W R/W R/W R/W
0 0 0 0 0 0 0 0
SPIE:Serial Peripheral Interrupt Enable
SPE :Serial Peripheral System Enable
DORD:Data Order
MSTR: Master Mode Select
CPOL:Clock Polarity
CPHA:Clock Phase
SPR0:SPI Clock Rate Select0
SPR1:SPI Clock Rate Select1
SPDR:
The SPI Data register is a Read/Write register used for data transfer between the register file and the SPI shift register.Writing to the register initiates data transmission.Reading the register causes the shift register receive buffer to be read
Bit 7 6 5 4 3 2 1 0
MSB LSB
R/W R/W R/W R/W R/W R/W R/W R/W
X X X X X X X X
SPSR:
Bit 7 6 5 4 3 2 1 0
SPIF WCOL - - - - - SPI2X
R/W R/W R/W R/W R/W R/W R/W R/W
0 0 0 0 0 0 0 0
SPIF: SPI Interrupt Flag
WCOL: Write Collision
SPI2X:To double the data transmission rate
8.4 SPI ADVANTAGES AND DISADVANTAGES:
• SPI does not have an acknowledgement mechanism to confirm receipt of data. In fact, without a communication protocol, the SPI master has no knowledge of whether a slave even exists. SPI also offers no flow control.
• Slaves can be thought of as input/output devices of the master. SPI does not specify a particular higher-level protocol for master-slave dialog. In some applications, a higher-level protocol is not needed and only raw data are exchanged. An example of this is an interface to a simple codec. In other applications, a higher-level protocol, such as a command-response protocol, may be necessary. Note that the master must initiate the frames for both its command and the slave's response.
• SPI's full duplex communication capability and data rates (ranging up to several megabits per second) make it, in most cases, extremely simple and efficient for single master, single slave applications. On the other hand, it can be troublesome to implement for more than one slave, due to its lack of built-in addressing; and the complexity only grows as the number of slaves increases
CHAPTER 9
INTER –INTEGRATED CIRCUIT BUS
(I2C)
9.1 INTRODUCTION:
The name stands for “Inter - Integrated Circuit Bus” .A Small Area Network connecting ICs and other electronic systems . Synchronous Serial Signal.Multi master invented by Philips
Two wires are used to carry information between a number of devices .One wire is used for the data ,One wire is used for the clock .I2C is a true multi master bus providing arbitration and collision detection
Today, a variety of devices are available with I2C Interfaces
1.Microcontroller,
2. EEPROM,
3. Real-Timer,
4. interface chips,
5. LCD driver,
6. A/D converter.
9.2 I2C BUS CHARACTERISTICS:
• Includes electrical and timing specifications, and an
• associated bus protocol
• Two wire serial data & control bus implemented with the serial
• data (SDA) and clock (SCL) lines For reliable operation, a third line common ground is required:
• Unique start and stop condition
• Slave selection protocol uses a 7-Bit slave address .The bus specification allows an extension to 10 bits
• Bi-directional data transfer
• Acknowledgement after each transferred byte
• No fixed length of transfer
• True multi-master capability -Clock synchronization ,Arbitration procedure
• Transmission speeds up to 100Khz (classic I2C)
• Max. line capacitance of 400pF, approximately 4 meters (12 feet)
• Compatible with different IC technologies
I2C Bus Definition:
Master:
Initiates a transfer by generating start and stop conditions
Generates the clock
Transmits the slave address
Determines data transfer direction
Slave:
Responds only when addressed
Timing is controlled by the clock line .
9.3 I2C COMMUNICATION:
Bit Transfer :
In normal data transfer, the data line only changes state when the clock is low
SDA
SCL
Data line stable Change of data allowed
Data valid
Start and Stop Conditions :
A transition of the data line while the clock line is high is defined as either a start or a stop condition.
Both start and stop conditions are generated by the bus master .The bus is considered busy after a start condition, until a stop condition occurs .
SDA
SCL
Start Stop
Condition condition
I2C Addressing:
Each node has a unique 7 (or 10) bit address
Peripherals often have fixed and programmable address portions
Addresses starting with 0000 or 1111 have special functions:-
0000000 Is a General Call Address
0000001 Is a Null (CBUS) Address
1111XXX Address Extension
1111111 Address Extension – Next Bytes are the actual address
First Byte in Data Transfer on the I2C Bus:
MSB LSB ACK
R/Wr
7-bit slave address
R/Wr
0-Slave written to by master
1-Slave red by master
Ack
Generated by the slave whose address has been output
Data Transfer:
Transmitter releasesSDA
Line during 9th clock pulse
Acknowledgement from receiver
1.Start Condition-SDA is pulled low while SCL stays high
2. Slave address + R/W
3. Slave acknowledges with ACK
4. All data bytes– Each followed by ACK
5.Stop Condition- SDA is pulled High while SCL stays Low
9.4 TYPES OF I2C IMPLEMENTATION:
Byte Oriented Interface :
• Data is handled one byte at a a time
• Processor interprets a status byte when an event occurs
• For instance Philips 8xC554, 8xC591
Bit Oriented Interface:
• Processor is involved in every bus event when the interface is not Idle
“Bit Banged” :
• Implemented completely in software on 2 regular I/O pins of the microcontroller
• Works for single master systems
• Not recommended for Slave devices or Multimaster systems
9.5 I2C DEVICES:
Analog to Digital Converters (A/D, D/A):
MMI functions, battery & converters, temperature monitoring, control systems .
Bus Controller:
Telecom, consumer electronics, utomotive, Hi-Fi systems, PCs, servers
Real Time Clock (RTC)/Calendar:
Telecom, EDP,consumer electronics, clocks, automotive, Hi-Fi systems, FAX, PCs, terminals
DIP Switch:
Telecom, automotive, servers, battery & converters, control systems
LCD/LED Display Drivers:
Telecom, automotive instrument driver clusters, metering systems, POS terminals, portable items, consumer electronics
CHAPTER 10
CIRCUIT DIAGRAM WITH OPERATION
10.1 CIRCUIT DIAGRAM:
10.2 OPERATION
Many industry needs constant and regular updates on physical parameters like temperature,pressure etc.,for every small time intervals which may be difficult task for humans.Thus comes this device…..
The temperature will be sensed using a LM35 temperature sensor,which is a 3 pin IC.The analog output voltage from sensor is directly proportional to the temperature in degree celsius.It is fed to 12bit ADC MCP3202 which gives a digital output.The adc is interfaced with the microcontroller using serial peripheral interface(SPI).The IC DS1307,which is a real time clock,is interfaced with a microcontroller using I2C.The temperature along with time ,day,month and year is sent to LCD.A switch is provided to change the task,if the switch is on SPI based task is performed and displayed .If the switch is off I2C based task is performed and displays the same.
TEMPERATURE SENSOR
The temperature sensor LM35 is connected to the third pin CH1 of ADC. Where separate supply and ground is given to LM35. The supply to LM35 is given through Vref and also grouned. The LM35 is an integrated circuit sensor that can be used to measure the temperature with an electrical output proportional to the temperature in degree Celsius.
When the message is send through Microcontroller, LM35 senses the temperature and sends it as an analog input to ADC.
ANALOG TO DIGITAL CONVERTOR:
The A/D Converter MCP3202 is connected to the 6,7,8 pins of the microcontroller which are port 1.5,1.6,1.7Pins and they are MOSI,MISO,SCK.The supply to ADC is given through Vref and also grounded.The ADC Is a 12 bit converter that converts the analog signal into digital signal. This digital signal is given to the AT89S52 mirocontroller where it is communicated using SPI Protocol and displays the same in the LCD Display.
REAL TIME CLOCK:
The Real time clock DS1307 is connected to 3,4 pins of the microcontroller which are ports 1.2,1.3 pins and they are SDA and SCL.The supply to the RTC is given through Vref and also grounded.The RTC is using a Crystal of clock frequency of 32,768 khz and a battery backup of 3volts is used.The RTC reads the default date,Time,day,month and year and sends it to the AT89S52 microcontroller where it is communicated using I2C Protocol and displays the same in the LCD display
10.3 PROJECT CODING
#include
#include
#include
sbit cs = P2^2;
sbit output=P1^0;
void spi ();
void display(char *);
void dela();
char getdata(int);
void sclhigh();
void start();
void end();
void init_int();
void setclock(unsigned char,unsigned char);
void readclock();
void init_timer();
void run_timer();
void get_day(int);
int pm;
int sec =0x00;
int min = 0x35;
int hrs = 0x03;//12 hrs mode make 6th high (now time is 12)
//make 5th bit high for AM/PM indication
int day1 = 0x04;
int day = 0x14;
int month = 0x06;
int year = 0x07;
char dta[2];
char days[3],clk1[23];
int d_sec,d_min,d_hrs,i,rst1,rst2;
sbit sda = P2^3;
sbit scl = P2^4;
void rtc_4();
int release_key();
void key_press();
void debounce();
void column();
void dispay(char *);
void cal_1();
void disp(int result);
void ser_2();
void display1(char *name);
void adc_3();
void dis();
void dip(int name1);
void delay1();
void line1 ();
char a[4][3]={'1','2','3','4','5','6','7','8','9','*','0','#'};
char r=0,c=0;
int num1,num2,op;
int result,l,t;
xdata char *ptr_cmd = (xdata char *) 0x0FFF8;
xdata char *ptr_en = (xdata char *) 0x0FFF9;
void busy_check()
{
*ptr_cmd = 0x02;
while ( ( *ptr_en & 0x80 ) != 0x00 );
}
void delay()
{
unsigned int i =1000;
while ( i-- );
}
void lcd_comm()
{
*( ptr_cmd ) = 0x00;
}
void spi ()
{
SPCTL = 0X5C;
}
void line1 ()
{
lcd_comm();
*(ptr_en) = 0x80;
busy_check();
}
void init_lcd()
{
lcd_comm();
*( ptr_en ) = 0x38;
busy_check();
lcd_comm();
*(ptr_en) = 0x0e;
busy_check();
lcd_comm();
*(ptr_en) = 0x80;
busy_check();
lcd_comm();
*(ptr_en) = 0x01;
busy_check();
}
void dis(char a)
{
*(ptr_cmd) = 0x01;//Rs 1 for data write
*(ptr_en)= a;
busy_check();
}
void display()
{
*(ptr_cmd) = 0x01;
*(ptr_en) =a[r][c];
l=a[r][c];
busy_check();
}
void dip(int name1) //LCD display routine for digits display
{
*(ptr_cmd) = 0x01;
*(ptr_en) = name1;
busy_check();
delay1();
}
void disp(int result)
{
*(ptr_cmd) = 0x01;
*(ptr_en) = result;
busy_check();
}
void dispmenu()
{
lcd_comm();
*(ptr_en)=0x80;
display1("1.CAL 2.SER");
lcd_comm();
*(ptr_en)=0xC0;
display1("3.ADC 4.RTC");
}
void display1(char *name)
{
int l = strlen(name);
int i;
for(i = 0;i < l;i++)
{
*(ptr_cmd) = 0x01;
*(ptr_en) = name[i];
busy_check();
}
}
void key_press()
{
while((P3 & 0x038) == 0x038)
{
delay();
}
debounce();
}
int release_key()
{
P1=0xf0;
while((P3 & 0x38) == 0x38)
{
delay();
}
P3 = 0x0ff;
debounce();
return l;
}
void debounce()
{
P1 = 0xfe; //ground row 0 only
while((P3 & 0x38) != 0x38)
{
r=0;
column();
}
P1 = 0xfd; //ground row 1 only
while((P3 & 0x38) != 0x38)
{
r=1;
column();
}
P1 = 0xfb; //ground row 2 only
while((P3 & 0x38) != 0x38)
{
r=2;
column();
}
P1 = 0xf7; //ground row 3 only
while((P3&0x38) != 0x38)
{
r=3;
column();
}
}
void column()
{
if ((P3 & 0x30) == 0x30)
{
c=0;
l=a[r][c];
delay();
}
else if((P3 & 0x28) == 0x28)
{
c=1;
l=a[r][c];
delay();
}
else if((P3 & 0x18) == 0x18)
{
c=2;
l=a[r][c];
delay();
}
}
void dispay(char *s)
{ int l= strlen(s);
int i,c=0;
for(i=0;i<=l; i++)
{
if(c == 0)
{
if(i == 14)
{
lcd_comm();
*(ptr_en) = 0xc8;
busy_check();
c++;
}
}
*(ptr_cmd ) = 0x01;
*(ptr_en) = s[i];
busy_check();
}
}
void get_day(int dys)
{
if(dys == 01)
{
clk1[11] = 'S';
clk1[12] = 'U';
clk1[13] = 'N';
}
if(dys == 02)
{
clk1[11] = 'M';
clk1[12] = 'O';
clk1[13] = 'N';
}
if(dys == 03)
{
clk1[11] = 'T';
clk1[12] = 'U';
clk1[13] = 'S';
}
if(dys == 04)
{
clk1[11] = 'W';
clk1[12] = 'E';
clk1[13] = 'D';
}
if(dys == 05)
{
clk1[11] = 'T';
clk1[12] = 'H';
clk1[13] = 'U';
}
if(dys == 06)
{
clk1[11] = 'F';
clk1[12] = 'R';
clk1[13] = 'I';
}
if(dys == 07)
{
clk1[11] = 'S';
clk1[12] = 'A';
clk1[13] = 'T';
}
}
void init_timer()
{
TR0 = 0;
TMOD = TMOD & 0xf0;
TMOD = TMOD | 0x01;
TH0 = 0xdc;
TL0 = 0x00;
IE = IE & 0x7f;
IE = IE | 0x02;
IE = IE | 0x80;
TR0 = 1;
}
void run_timer() interrupt 1
{
i++;
if (i == 100)
{
//init_lcd();
readclock();
i = 0;
}
TR0 = 0;
TH0 = 0xdc;
TL0 = 0x00;
TR0 = 1;
}
void sclhigh()
{
scl = 1;
if(!scl)
{
dispay("ERROR");
// printf("error");
while(1);
}
}
void start()
{
sclhigh();
sda = 1;
if (!sda)
{
dispay(" gg");
// printf("gg");
while(1);
}
sda = 0;
delay();
scl = 0;
}
void end()
{
sclhigh();
sda = 0;
delay();
sda = 1;
}
int senddata(unsigned char databyte)
{
int i = 0,ret = 0,h=0;
for (i = 0;i<8;i++)
{
if ((databyte & 0x80) == 0x80) sda = 1; // if msb is 1 then send 1
else sda = 0; // else send 0 in sda line
databyte = databyte << 1; // left shift the data's
sclhigh();
delay();
scl = 0;
delay();
}
sda = 1;
sclhigh();
delay();
h = 1;
if(!sda)
{
h=0;
ret = 0;
}
else
{
dispay("2");
ret = 1;
}
scl = 0;
delay();
return(ret);
}
void dela()
{
int i =2;
while(i--);
}
void delay1()
{
int i =200;
while(i--);
}
char getdata(int ack)
{
int i;
rst1 = 0,rst2= 0;
for(i = 0;i<8;i++)
{
sclhigh();
dela();
if (i<=3)
{
rst1 *= 2;
if(sda) rst1++;
}
else
{
rst2 *= 2;
if(sda) rst2++;
}
scl = 0;
dela();
}
scl = 0;
sda = ack;
sclhigh();
dela();
scl = 0;
sda = 1;
dela();
return('A');
}
void setclock(unsigned char setbyte,unsigned char addr)
{
while (senddata(setbyte))
{
end();
start();
while (senddata(addr))
{
end();
start();
}
}
}
void readclock()
{
start(); // send start signal
while (senddata(0xd0))
{
end();
start();
}
setclock(0x00,0xd0);
end();
start();
while (senddata(0xd1))
{
end();
start();
}
d_sec = getdata(0); // sec
clk1[6] = (char) (rst1 + 48);
clk1[7] = (char) (rst2 + 48);
clk1[5]=':';
d_sec = getdata(0); // min
clk1[3] = (char) (rst1 + 48);
clk1[4] = (char) (rst2 + 48);
clk1[2] = ':';
d_sec = getdata(0); // hrs
pm=rst1&0x02;
clk1[0] = (char) ((rst1&0x01) + 48);
clk1[1] = (char) (rst2 + 48);
if(pm)
{
clk1[8] = 'P';
}
else
{
clk1[8] = 'A';
}
clk1[9]= 'M';
clk1[10] = ' ';
clk1[11] = 'S';
clk1[12] = 'U';
clk1[13] = 'N';
d_sec = getdata(0); // day1
get_day(d_sec);
d_sec = getdata(0); // day
clk1[14] = (char) (rst1 + 48);
clk1[15] = (char) (rst2 + 48);
clk1[16] = '/';
d_sec = getdata(0);// month
clk1[17] = (char) (rst1 + 48);
clk1[18] = (char) (rst2 + 48);
clk1[19] = '/';
d_sec = getdata(1);
clk1[20] = (char) (rst1 + 48);
clk1[21] = (char) (rst2 + 48);
lcd_comm();
*(ptr_en) = 0x01;
busy_check();
dispay(clk1);
for(i=0;i<=21;i++)
{
printf("%c",clk1[i]);
}
end();
}
void second_line ()
{
*ptr_cmd = 0x00;
*ptr_en = 0xC0;
busy_check ();
}
int sign ()
{
result = (~result) + 1 ;
*(ptr_cmd) = 0x01;
*ptr_en = '-';
return result;
}
void adc_3()
{
char c,d,i;
int e=0;
init_lcd ();
spi ();
cs = 0;
while(1)
{
SPDAT = 0XC0;
while (SPCFG != 0X80);
SPCFG = 0;
c = SPDAT;
SPDAT = 0XFF;
while(SPCFG != 0X80);
SPCFG = 0;
i = SPDAT;
cs = 1;
cs = 1;
cs = 0;
e = c;
e = e<<8;
e = e | i;
e = e<<1;
e = e & 0x0fff;
display1("12BIT ADC OUTPUT");//display in LCD
lcd_comm(); // LCD command routine call function
*(ptr_en) = 0xc0;// LCD display for 2nd line 1st location
delay1(); //call for delay routine
{
dip(((e%100000)/10000)+48); // ,,
display1(".");
dip(((e%10000)/1000)+48); // ,,
dip(((e%1000)/100)+48); // ,,
dip(((e%100)/10)+48); // ,,
dip((e%10)+48); // ,,
}
lcd_comm();//LCD command routine call
*(ptr_en)=0xc6;//LCD 2nd line 8th position
lcd_comm();//LCD command routine call
*(ptr_en) = 0x01;// LCD command for clear the display
delay1();//Delay routine call for some delay
}
}
void ser_2()
{
init_lcd();
display1("ser com:");
{
unsigned char m[]="hello ";
unsigned char a,x;
TMOD=0x20;// Use Timer 1 8-bit Auto Reload mode
TH1=0xE8; //Baud Rate 1200
SCON=0X50;// 8 bit,1 stop bit
TR1=1; // Start Timer 1 for Serial communication
while(1)
{
for(x=0;x<6;x++)
{
a=m[x];
SBUF=m[x];
delay();
disp(a);
while(TI==0);
TI=0;
}
}
}}
void cal_1()
{
char de=2,co=0;
while(1)
{
init_lcd();
lcd_comm();
do
{
/// (de--);
num1 = release_key ();
}
while( num1 < '0' || num1 > '9' );
*ptr_cmd = 0x01 ;
*ptr_en = num1 ;
busy_check();
num1 = num1 - 0x30;
printf(" %x ",num1);
do
{
op = release_key ();
}
while( op < '#' );
*ptr_cmd = 0x01;
if ( op == '#')
{
for(co=0;co<4;co++)
{
if(op==1)
{
*ptr_en = '+';
}
else if(op==2)
{
*ptr_en = '-';
}
else if(op==3)
{
*ptr_en = '*';
}
else
{
*ptr_en = '/';
}
}
}
busy_check();
do {
// (op--);
{
num2 = release_key ();
}
} while( num2 < '0' || num2 > '9' );
*ptr_cmd = 0x01;
*ptr_en = num2 ;
busy_check();
num2 = num2 - 0x30;
if (op == '#')
{
result = num1 + num2;
second_line ();
*(ptr_cmd) = 0x01;
*ptr_en = (result / 10 ) + 0x30;
busy_check ();
*(ptr_cmd) = 0x01;
*ptr_en = (result % 10 ) + 0x30;
busy_check ();
printf(" %d ",result);
}
else if ( op == '*' )
{
second_line ();
result = num1 - num2;
result = (result <= 9 && result >= 0 ) ? result : sign ();
*(ptr_cmd) = 0x01;
*ptr_en = (result / 10 ) + 0x30;
busy_check ();
*(ptr_cmd) = 0x01;
*ptr_en = (result % 10 ) + 0x30;
busy_check ();
printf(" %x ",result);
}
while(1){}
}
}
void rtc_4()
{
int k;
long int s=60000;
init_lcd();
printf("test");
start(); // send start signal
while(senddata(0xd0)){
end (); // send Slave address & write mode
delay1();
start();
}
setclock(0x00,0xd0);
setclock(sec,0xd0);
setclock(min,0xd0);
setclock(hrs,0xd0);
setclock(day1,0xd0);
setclock(day,0xd0);
setclock(month,0xd0);
setclock(year,0xd0);
end();
readclock();
init_timer();
while(1);
}
void main()
{
char ch;
init_lcd();
dispmenu();
while(1)
{
ch=release_key();
switch(ch)
{
case'1':cal_1();
break;
case'2':ser_2();
break;
case'3':adc_3();
break;
case'4':rtc_4();
break;
default:printf("exit\n");
}
}
}
*******************End of Main Program********************
10.4 CONCLUSION
In future, I could use this way for controlling the temperature also and the RTC for setting the time intervals also and Scientific Calculator is also Implement, and normal Serial Communication replace wireless communication Zigbee and R.F is used. Since this communication through the SPI and I2C are wire based we would like to perform in wireless technologies also which will be more effective, Further it can be used for controlling and monitoring all other Parameters used in industries, appliances, etc.
BIBLIOGRAPHY
REFERENCE BOOKS
The 8051 Microcontroller and Embedded Systems - Muhammad Ai Mazidi & Co.
Embedded Systems – Raj Kamal.
Embedded Software Primer – David E Simon.
Microcontrollers and Microprocessors
WEBSITES
www.gsmworld.com
www.iec.org
www.google.com
www.raisonance.com