;
; Combination lock box assembler.asm
;
; Created: 6/10/2018 3:24:23 PM
; Author : James Coghlan
;

.INCLUDE “M32ADEF.INC” ;ADD Atmega32 definition

.ORG 0x00 ; code segment area

.EQU LCD_PORT = PORTB //Label PORTB with LCD_PORT title, any instance of LCD_PORT used with be replaced with PORTB value
.EQU LCD_DDR = DDRB //Label DDRB with LCD_DDR title
.EQU LCD_PIN = PINB //Label PINB with LCD_PIN title
.EQU LCD_RS = 0 //Label LCD_RS with 0 for PB0
.EQU LCD_RW = 1 //Label LCD_RW with 1 for PB1
.EQU LCD_EN = 2 //Label LCD_EN with 2 for PB2

.EQU KEY_PORT = PORTC //Label PORTC with KEY_PORT title
.EQU KEY_PIN = PINC //Label PINC with KEY_PIN title
.EQU KEY_DDR = DDRC //Label DDRC with KEY_DDR title

//Setting up stack pointer register
LDI R21, HIGH(RAMEND) //Load immediate HIGH(RAMEND) to R21
OUT SPH, R21 //Store register R21 to SPH
LDI R21, LOW(RAMEND) //Load immediate LOW (RAMEND) to R21
OUT SPL, R21 //Store register R21 to SPL

LDI R20, 0xF0 //Load immediate F0 to R20
OUT KEY_DDR, R20 //Setting KEY DDR to R20 which = 0xF0 4 bits output and 4 bits input

CALL LCD_Init //Call the initialise LCD
CALL MSGDISPLAY //Call the message display, which prints a string

HERE:
CALL KEYPADSCAN //call the Keypad scanning
CALL LCDWRITE //call the lcdwrite
RJMP HERE //Loops back to Keypad press checking

MSG:
.DB “INPUT CODE:”, 0 //Stored message string in z registers

;*******************************************************
LCD_Init:
LDI R21, 0xFF
OUT LCD_DDR, R21 ; LCD Data port is output

LDI R16, 0x33 ; init. LCD for 4 bit data
CALL COMMWRITE:
CALL DELAY_2ms
LDI R16, 0x32 ; init. LCD for 4 bit data
CALL COMMWRITE:
CALL DELAY_2ms
LDI R16, 0x28 ;init. LCD 2 lines, 5×7 matrix
CALL COMMWRITE:
CALL DELAY_2ms
LDI R16, 0x0E ; display on curser on
CALL COMMWRITE:
CALL DELAY_2ms
LDI R16, 0x01 ; clear lcd
CALL COMMWRITE:
CALL DELAY_2ms
LDI R16, 0x06 ; shift curser right
CALL COMMWRITE:
RET

;********************************************************
MSGDISPLAY:
LDI R31, HIGH(MSG