Beispiel #1
0
//MAIN FUNCTION **************************************************************
void main(void)
{
    char keypad;
    char tensDigit; 
    char onesDigit; 
    char numAsDecimal; 
    
    initMethods(); 
    putchar('\r');  // Dummy write to serial port
    printf("\nStart\r\n");

    Counts = 0;
    while (Counts < 1); // Wait a long time (1s) for keypad & LCD to initialize

    lcd_clear();
    lcd_print("Calibration:\nHello world!\n012_345_678:\nabc def ghij");
    
    
    while (1)
    {
        keypadInput = read_keypad(); //read the keypad
        if (keypadInput != -1) { //if keypad pressed
            tensDigit = keypadInput; while(read_keypad() != -1); pause(); //store press as tens digit
            
            do {
                onesDigit = read_keypad(); //set the result of read_keypad to ones digit
            } while (onesDigit == -1) //stop once ones digit equals an input value
            while(read_keypad() != -1); pause(); //wait until key is released, then pause for one second
             
            numAsDecimal = twoDigitNum(tensDigit, onesDigit); 
            displayInput(numAsDecimal); 
        }
    }
Beispiel #2
0
int multi_view_mode(char previous) {
    sensor_changer(&sensor_selector, &previous);
    lcd_display_top_row("Mult");
    lcd_display_bottom_row();
    //use sweep_num to see what stage of 'turning' the object is at

    char a = read_keypad(33);
    if (a == 'A'&& previous != a) {
        SYSTICK_IntCmd(DISABLE);
        clear_display(59);
        char a = read_keypad(33);
        previous = keypad_check(a, previous);
        return 0;
    }
    else if (a == 'B'&& previous != a) {
        SYSTICK_IntCmd(DISABLE);
        clear_display(59);
        char a = read_keypad(33);
        previous = keypad_check(a, previous);
        return 1;
    }
    else if (a == 'C'&& previous != a) {
        servoreset();
        SYSTICK_IntCmd(ENABLE);
        clear_display(59);
        char a = read_keypad(33);
        previous = keypad_check(a, previous);
        return 2;
    }
    else if (a == 'D'&& previous != a) {
        servoreset();
        SYSTICK_IntCmd(ENABLE);
        char a = read_keypad(33);
        previous = keypad_check(a, previous);
        return 3;
    }
    else {
        keypad_change_servo_speed(&turnspeed, a, &previous);
        keypad_change_servo_start_pos(&servo_start, a, &previous);
        keypad_change_servo_stop_pos(&servo_stop, a, &previous);
        keypad_change_sample_rate(&samplerate, a, &previous);
        keypad_activate_interrupt(a, &previous);
        average_calculator(us_dist_arr, ir_dist_arr, array_counter, &us_avg, &ir_avg);
        previous = keypad_check(a, previous);

        //distanceircalc();
        //RTC_AlarmIntConfig((LPC_RTC_TypeDef *) LPC_RTC, RTC_TIMETYPE_SECOND, ENABLE);
        //RTC_SetAlarmTime((LPC_RTC_TypeDef *) LPC_RTC, RTC_TIMETYPE_SECOND, 1);
        return 3;
    }
}
Beispiel #3
0
unsigned char get_keypress(void)
{
	char tempval = 0;
	unsigned char tempnum = 0;
	tempval = read_keypad();
	while(tempval == -1)
	{
		tempval = read_keypad();
	}
	tempnum = tempval - 48;
	while(tempval != -1)
	{
		tempval = read_keypad();
	}
	return tempnum;
}
//------------------------------------------------------------------------------
//choose gain
//------------------------------------------------------------------------------
void choose_gain(void) // This function reads desired steering gain from the keypad
{					// Desired gain is chosen by incrementing it by pressing button 8 and decrementing it by pressing button 2
	lcd_clear();
	while (keypad != 35) 
	{
		lcd_clear();
		lcd_print("\rPress 2 to increase gain, press 8 to decrease gain");
		lcd_print("\rGain is: %d", k); // print gain
		keypad = read_keypad();
		pause();
		if (keypad == 50) 
		{
			k++;
		}
		else if (keypad == 56) 
		{
			k--; 
		}
	}
	lcd_clear();
	lcd_print("\rYour gain is: %d\n", k);

	keypad = 0;

}
//-----------------------------------------------------------------------------
// Choose speed
//-----------------------------------------------------------------------------
//*************************MODIFIED NO AD!!!
void pick_speed(void){
	lcd_clear();
	lcd_print("\nenter speed 1-5\n");
	lcd_print("0=full back, 3 = neut, etc\n");
	keypad = read_keypad();
	pause();
	if(keypad != -1)
	{
		lcd_clear();
		lcd_print("\nyour value was%c", keypad);
		if(keypad ==0)
		{
			lcd_print("Wire Connection/XBR0 Error");
		}
	}
	speed_motor = 50*keypad;
	/*
	lcd_clear();
	lcd_print("To set speed, adjust pMeter now");
	lcd_print("\n3 seconds to do so");
	pause();
	lcd_clear();
	lcd_print("To set speed, adjust pMeter now");
	lcd_print("\n2 seconds to do so");
	pause();
	lcd_clear();
	lcd_print("To set speed, adjust pMeter now");
	lcd_print("\n1 seconds to do so");
	pause();
	*/
}//end pick motor speed
Beispiel #6
0
int tape_measure_mode(char previous) {
    sensor_changer(&sensor_selector, &previous);
    count = 18;
    lcd_display_top_row("Tape");
    lcd_display_bottom_row();


    char a = read_keypad(33);
    if (a == 'A'&& previous != a) {
        SYSTICK_IntCmd(DISABLE);
        clear_display(59);
        char a = read_keypad(33);
        previous = keypad_check(a, previous);
        return 0;
    }
    else if (a == 'B'&& previous != a) {
        SYSTICK_IntCmd(DISABLE);
        char a = read_keypad(33);
        previous = keypad_check(a, previous);
        return 1;
    }
    else if (a == 'C'&& previous != a) {
        servoreset();
        SYSTICK_IntCmd(ENABLE);
        clear_display(59);
        char a = read_keypad(33);
        previous = keypad_check(a, previous);
        return 2;
    }
    else if (a == 'D'&& previous != a) {
        servoreset();
        SYSTICK_IntCmd(ENABLE);
        clear_display(59);
        char a = read_keypad(33);
        previous = keypad_check(a, previous);
        return 3;
    }
    else {
        //distanceircalc();
        //RTC_AlarmIntConfig((LPC_RTC_TypeDef *) LPC_RTC, RTC_TIMETYPE_SECOND, DISABLE);
        PWM_MatchUpdate((LPC_PWM_TypeDef *) LPC_PWM1,2,18,PWM_MATCH_UPDATE_NOW);
        keypad_change_sample_rate(&samplerate, a, &previous);
        average_calculator(us_dist_arr, ir_dist_arr, array_counter, &us_avg, &ir_avg);
        previous = keypad_check(a, previous);
        return 1;
    }
}
Beispiel #7
0
char get_kpd_input() {	//gets keyboard input
	char check = read_keypad();
	pause();
	while(check == -1) {
		check = read_keypad();
		pause();
	}

	keypad = check;

	while(check != -1) {
		check = read_keypad();
		pause();
	}
	
	return keypad;	
}//end get kpd input
Beispiel #8
0
 /*----------------------------------------------------------------------------
*      Thread  'LED_Thread': Toggles LED
 *---------------------------------------------------------------------------*/
	void Thread_keypad (void const *argument) {
		while(1){
				osMutexWait(mutex, 100);
				keypad_value = read_keypad();
				osMutexRelease(mutex);
				osDelay(1000);
			}
	}
void main()
{
	char c;
  int i=0,flag=0;
  char password[4]={"1234"};
	char input[4];
  Lcd8_Init();
  while(1)
  {
    Lcd8_Set_Cursor(1,1);
    Lcd8_Write_String("Enter Password:"******"*");
			i++;
		}

		for(i=0;i<4;i++)
		{
			if(password[i]!=input[i])
			{
				flag=1;
				break;
			}
		}
		delay(1000);
		Lcd8_Clear();
		Lcd8_Set_Cursor(1,1);
		if(flag==1)
		{			
			Lcd8_Write_String("Wrong Password!");
		}
		else
		{			
			Lcd8_Write_String("Correct Password");
		}	
		delay(2000);
   /* Lcd8_Write_String("Times:");
    while(!(c = read_keypad()));
    p=c;
    while(p==c)
    {
      i++;
      Lcd8_Set_Cursor(1,14);
      Lcd8_Write_Char(c);
      Lcd8_Set_Cursor(2,7);
      Lcd8_Write_Char(i+48);
      delay(100);
      while(!(c = read_keypad()));
    }
    i=0; */
		//while(!read_keypad());
    Lcd8_Clear();
   }
}
Beispiel #10
0
int main(void){
	unsigned char digit;		//where digit to be printed will be held
	unsigned char digit_old = '0'; //where the previous digit will be held

	DDRA = 0xF0;         // set PORTA[7:4] OUT, PORTA[3:0] IN
   PORTA = 0xFF;		// turn on PULLUP res for PORTA[3:0] and A[7:4] HIGH
	DDRB = 0xFF;         // set PORTB for output
   PORTB = 0x00;        // turn ON all LEDs initially

	while(1){
		digit = read_keypad(digit_old);
		digit_old = digit;	//store old digit incase no button is pressed on next cycle
		display_7led(digit);
	}
	return 1;
}
Beispiel #11
0
//-----------------------------------------------------------------------------
// Choose Gain
//-----------------------------------------------------------------------------
void choose_gain(void) {
	char keypad;
	lcd_clear();
	lcd_print("\nTo set gain press a number, n");
	lcd_print("\nThe gain will be 0.n");
	keypad = read_keypad();
	pause();
	if(keypad != -1)
	{
		lcd_print("\nYou selected 0.%c", keypad);
		ratio = ((keypad - 0x30)/10);
		//ratio needs to be a float or something to hold a decimal
		//doesn't need to be read too often, xdata?
		if(keypad ==0)
		{
			lcd_print("Wire Connection/XBR0 Error")
		}
	}
Beispiel #12
0
int calibration_mode(char previous) {
    sensor_changer(&sensor_selector, &previous);
    count = 18;
    PWM_MatchUpdate((LPC_PWM_TypeDef *) LPC_PWM1,2,18,PWM_MATCH_UPDATE_NOW);


    char a = read_keypad(33);
    /*
    Selector to change the mode using the keypad keys A,B,C and D. Replicated in the rest of the modes too.
    When the system is started for the first time, it starts in calibration mode and requests its values unless one of the
    B, C or D keys is held at startup.
    */
    if (a == 'A'&& previous != a) {
        SYSTICK_IntCmd(DISABLE);
        char a = read_keypad(33);
        previous = keypad_check(a, previous);
        return 0;
    }
    else if (a == 'B'&& previous != a) {
        SYSTICK_IntCmd(DISABLE);
        clear_display(59);
        char a = read_keypad(33);
        previous = keypad_check(a, previous);
        return 1;
    }
    else if (a == 'C'&& previous != a) {
        servoreset();
        SYSTICK_IntCmd(ENABLE);
        clear_display(59);
        char a = read_keypad(33);
        previous = keypad_check(a, previous);
        return 2;
    }
    else if (a == 'D'&& previous != a) {
        servoreset();
        SYSTICK_IntCmd(ENABLE);
        clear_display(59);
        char a = read_keypad(33);
        previous = keypad_check(a, previous);
        return 3;
    }
    else {
        int ir_calib_arr[3];
        int us_calib_arr[3];
        int ir_reported;
        int us_reported;
        int ir_calib_val;
        int us_calib_val;
        int u = 0;
        char write[2];
        strcpy(write, "");
        /*
        Code to get values from the keypad. The user places an object at a set distance away from the head, enters how far it is from
        the head, then finalises this value with the # key. If a mistake is made, the screen can be cleared with the A key,
        Then repostions it closer or further and enters the new distance.
        This is repeated once more to obtain three different calibration values.
        */
        while(calib_tracker <3) {
            if (u == 1000) {
                sensor_changer_cali_mode(&sensor_selector, &previous);
                int addr = 0x80;
                int i;
                for(i=0; i < strlen("Input actual dist: "); i++) {
                    addr = alloc_lcd_addr(addr, i, "Input actual dist: ");
                }
                for(i=0; i < strlen(write); i++) {
                    addr = alloc_lcd_addr(addr, i, write);
                }
                char x;
                x = read_keypad(33);
                if (x == previous) {
                    previous = x;
                }
                else if (x != 'Z' && x != previous) {
                    if (x == 'A') {
                        clear_display(59);
                        strcpy(write, "");
                        previous = x;
                    }
                    else if (isalpha(x) || x == '*' || isdigit(x)) {
                        addr = 0x80;
                        append(write, x);
                        clear_display(59);
                        for(i=0; i < strlen("Input actual dist: "); i++) {
                            addr = alloc_lcd_addr(addr, i, "Input actual dist: ");
                        }
                        for(i=0; i < strlen(write); i++) {
                            addr = alloc_lcd_addr(addr, i, write);
                        }
                        previous = x;
                    }
                    else if(x == '#') {
                        clear_display(59);
                        int act_val = atoi(write);
                        int anglemax = ((servo_stop-8)*9);
                        int anglemin = ((servo_start-8)*9);
                        int angle = ((count-8)*9);
                        char port3[90] = "";
                        sprintf(port3, ";%i;%i;%i;%i;%i;%i;%i;%i;%i;%i;%i;%i;\n\r", ir_raw, us_raw, ir_dist, us_dist, angle, anglemax, anglemin, act_val, sweep_num, multicheck, mode, newmulti);
                        write_usb_serial_blocking(port3 ,90);
                        ir_reported = ir_dist;
                        char port[3] = "";
                        sprintf(port, "%i", ir_reported);
                        //write_usb_serial_blocking("ir_report: ", 11);
                        //write_usb_serial_blocking(port, 3);
                        //write_usb_serial_blocking("\n\r", 2);
                        us_reported = us_dist;
                        char port1[3] = "";
                        sprintf(port1, "%i", us_reported);
                        //write_usb_serial_blocking("us_report: ", 11);
                        //write_usb_serial_blocking(port1, 3);
                        //write_usb_serial_blocking("\n\r", 2);
                        ir_calib_val = (act_val - ir_reported);
                        us_calib_val = (act_val - us_reported);
                        ir_calib_arr[calib_tracker] = ir_calib_val;
                        us_calib_arr[calib_tracker] = us_calib_val;
                        calib_tracker++;
                        strcpy(write, "");
                        previous = x;
                    }
                }
                else if (x == 'Z' && previous != 'Z') {
                    previous = 'Z';
                }
            }
            else {
                u++;
            }
        }
        /*
        If the calibration values have been entered, but the calibration is not yet complete, this calculates the calibration adjustments
        for both IR and US, then sets calibrated_flag to stop them from being recalculated.
        */
        if (calibrated_flag == 0) {
            for (calib_tracker = 0; calib_tracker <3; calib_tracker++) {
                ir_calib_total += ir_calib_arr[calib_tracker];
                us_calib_total += us_calib_arr[calib_tracker];
            }
            calibrated_flag = 1;
            ir_calibration_adjust = ir_calib_total/3;
            us_calibration_adjust = us_calib_total/3;
            char port1[3] = "";
            sprintf(port1, "%i", ir_calib_total);
            /*write_usb_serial_blocking("IR total: ", 8);
            write_usb_serial_blocking(port1, 3);
            write_usb_serial_blocking("\n\r", 2);*/
            char port2[3] = "";
            sprintf(port2, "%i", us_calib_total);
            /*write_usb_serial_blocking("US total: ", 8);
            write_usb_serial_blocking(port2, 3);
            write_usb_serial_blocking("\n\r", 2);*/
            char port3[3] = "";
            sprintf(port3, "%i", ir_calibration_adjust);
            /*write_usb_serial_blocking("IR adjust: ", 9);
            write_usb_serial_blocking(port3, 3);
            write_usb_serial_blocking("\n\r", 2);*/
            char port4[3] = "";
            sprintf(port4, "%i", us_calibration_adjust);
            /*write_usb_serial_blocking("US adjust: ", 9);
            write_usb_serial_blocking(port4, 3);
            write_usb_serial_blocking("\n\r", 2);*/
        }

        lcd_display_top_row("Cali");
        lcd_display_bottom_row();
        //distanceircalc();
        //RTC_AlarmIntConfig((LPC_RTC_TypeDef *) LPC_RTC, RTC_TIMETYPE_SECOND, DISABLE);
        //keypad_change_sample_rate(&samplerate, a, &previous);
        average_calculator(us_dist_arr, ir_dist_arr, array_counter, &us_avg, &ir_avg);
        previous = keypad_check(a, previous);
        return 0;
    }
}
Beispiel #13
0
void *read_keypad_wrapper(void *input) {
	keypad_input_t *_input = (keypad_input_t *)input;
	read_keypad(&_input->n, &_input->inputs);
}
Beispiel #14
0
	void mode_change_thread(void const * argument){
		wirelessTransmit_TX(motor_init);
		keypad_column_init();		
		osDelay(100);
		
		/*read column*/
		int8_t key_column = readKeyColumn();
		keypad_row_init();
		
		/*read row*/
		int8_t key_row = readKeyRow();
		
		mode = read_keypad(key_column, key_row);
			
		while(1){
			mode = read_keypad(key_column, key_row);
				while(mode == 'e'){
						wirelessTransmit_TX(motor_init);
						keypad_column_init();		
						osDelay(100);
						
						/*read column*/
						int8_t key_column = readKeyColumn();
						keypad_row_init();
						
						/*read row*/
						int8_t key_row = readKeyRow();
						
						mode = read_keypad(key_column, key_row);
				}
				if (mode == 'A'){
				printf (">>>>>>>>Entering Mode_1 Real Time Tilting<<<<<<<<\n");
				char mode1[7] = "Mode 1";
				LCD_clear_display();
				LCD_DISPLAY_UPDATE_POS(0x80, mode1);
				wirelessTransmit_TX(mode_A);
				
				tilt_thread = osThreadCreate(osThread(tilt_detection_thread),NULL);
				tilt_transmit_thread = osThreadCreate(osThread(transmitTiltAngles),NULL);
							
				uint8_t readreg=read_Status_Register(WIRELESS_STATUS_VERSION);
				
					mode_selection = 1;
					
			}else if (mode == 'B'){
				printf (">>>>>>>>Entering Mode_2 Movement Sequence Input<<<<<<<<\n");
				wirelessTransmit_TX(mode_B);
//				printf ("A: positive sign(must be entered). B: negative sign. C: terminate input\n");
//				printf ("IMPORTANT: To input <30,-60,10> <-45,65,8>...<20,-30,5> You shall enter the key as following:\n");
//				printf ("A30B60A10B45A65A08...A20B30A05C\n");
				
				keypad_thread = osThreadCreate(osThread(keypad), NULL);
				
				
				mode_selection = 2;
				
				
			}else if (mode == 'C'){
				printf (">>>>>>>>Entering Mode_3 Record and Play Option<<<<<<<<\n");
				wirelessTransmit_TX(mode_C);
				mode_selection = 3;
				
			}
			
			osSignalWait(SIGNAL_MODE_CHANGE, osWaitForever);
			if(mode_selection == 1 ){
				osThreadTerminate(tilt_transmit_thread);
				osThreadTerminate(tilt_thread);
			}
			else if(mode_selection == 2){
				osThreadTerminate(keypad_thread);
			}
			else{
			
			}
			
			mode_selection=0;
		}
}
Beispiel #15
0
void keypad(void const *argument){
	printf("keypad thread entered!\n");		
	int8_t num = -1;
	int8_t k = 0;;
	
	char ch;
	
	
	
//	while(1){
//		keypad_column_init();		
//		osDelay(200);
//		
//		/*read column*/
//		int8_t key_column = readKeyColumn();
//		keypad_row_init();
//		
//		/*read row*/
//		int8_t key_row = readKeyRow();
//		
//		/*read number*/
//		num = read_keypad(key_column, key_row);
	
//		if (num != -1)
//			printf ("%d\n", num);
//		else{
//			ch = read_symble(key_column, key_row);
//			if (ch != 'e'){
//					printf ("%c\n", ch);
//			}
//		
		while (ch != 'D'){
			keypad_column_init();		
			osDelay(250);
			
			/*read column*/
			int8_t key_column = readKeyColumn();
			keypad_row_init();
			
			/*read row*/
			int8_t key_row = readKeyRow();
			
			ch = read_keypad(key_column, key_row);
			
			
		
			
			
			if (ch != 'e' ){	
//				sequence[k] = ch;
//				printf("sequence[%d]: %c\n", k,sequence[k] );
//				k++;
				
				//if (ch == 'D'){
					sequence[0] = ch;
					sequence[1] = 'D';
					printf ("before sendSequence: %s\n", sequence);
					LCD_clear_display();
					LCD_DISPLAY_UPDATE_POS(0x80, sequence);
					sendSequence(sequence);
					//transmit_sequence_thread = osThreadCreate(osThread(transmitSequence), NULL);
					
					
					
					
				//}
				
				
			}
		}
		
//		
//		
	
}
int main(){

	first_time_boot(); //first time boot parameters
	read_config(); //nuskaitom config is eeprom	
	
	
	//------------- I/O nustatymai ------------------
	
	//LED
	PORTDDR(LED_PORT) |= _BV(LED1_BIT); 
	LED_PORT &= ~_BV(LED1_BIT); 
	PORTDDR(LED_PORT) |= _BV(LED2_BIT); 
	LED_PORT &= ~_BV(LED2_BIT); 
	PORTDDR(LED_PORT) |= _BV(LED3_BIT); 
	LED_PORT &= ~_BV(LED3_BIT); 

	PORTDDR(LCD_LED_PORT) |= _BV(LCD_LED_BIT); //LCD pasvietimas
	LCD_LED_PORT |= _BV(LCD_LED_BIT); //ijungiam LCD pasvietimas

	//USART
	DDRD|=_BV(PD1); //TX
	PORTD|=_BV(PD1);
	DDRD&=~_BV(PD0); //RX

	//ROT ENCODER
	DDRD&=~_BV(PD3); //INT1 
	PORTD|=_BV(PD3);
	DDRD&=~_BV(PD4); 
	PORTD|=_BV(PD4);
	//ROT ENCODER BUTTON
	DDRB&=~_BV(PB6); 
	PORTB|=_BV(PB6);


	//PIR
	DDRD&=~_BV(PD2); //INT0
//	PORTD|=_BV(PD2);

	//PWM OUT
	DDRB|=_BV(PB3); 
 
	//----------------- initai -----------------------------

	init_uart(UBRR_VAL);
	lcd_init(LCD_DISP_ON);
	INT_init();
	ADC_init();

	timer_init_0();
	timer_init_1();

	start_timer1();
//	TIMSK |=(_BV(OCIE1A)); //iddle timmer on


	apie();	
	
	
	//puslapiai();


	//Nustatom PWM mode
//	TCCR2=0x6B;     //6E;

//	OCR2=EEPROM_read(24); // OCR2 is EEPROM




	
	work_mode=EEPROM_read(25);
	wmode(work_mode);
	
	show_work_mode();
	
#if debug_mode
send_string("OCR2 eeprome: ");
send_string(itoa(OCR2, buff, 10));
send_string("\n\r");
#endif

	//naudojam ADC nuskaitymui
	
//	start_timer0();
	
	_delay_ms(200);
	LCD_LED_PORT &= ~_BV(LCD_LED_BIT); //isjungiam LCD pasvietima	

sei();

//fade_in();

//fade_out();




	


while(5){


	PORTDDR(LED_PORT)^= (1<<LED3_BIT);
//	_delay_ms(50);

//-------------------- to go into main menu 00--------------------

//		if (bit_is_clear(PINB, PB6)){	
//		lcd_light=1;
//		}
		
		
		if(meniu==0 && config==0 && read_keypad()==1){
			
		#if debug_mode 
		PORTDDR(LED_PORT)^= (1<<LED2_BIT);
		send_string("nuspausta knopke\n\r");	
		#endif
		
		if(lcd_light==0) {	
							clock_second=0;
							clock_millisecond=0;
							lcd_light=1;
							LCD_LED_PORT |= _BV(LCD_LED_BIT); //ijungiam LCD pasvietima	
						 }
		else{

		LCD_LED_PORT |= _BV(LCD_LED_BIT); //ijungiam LCD pasvietima	

		meniu=1; 
		menu_page=0; 
		sub_menu_page=0;
	
		lcd_light=0; 

		puslapiai();
		
		}		

		#if debug_mode 
		debug_meniu();	
		#endif
			
		}
	
//-------------------- main and sub menu routine --------------
	
	while(meniu!=0 && config==0){

	
		if(read_keypad()==1){

			if(meniu==1 && config==0){
				
					if(menu_page<4){ //2inis configas (on/off tipo)
						meniu=2;
						sub_menu_page=0; 
						puslapiai_2();
					
						#if debug_mode 
						debug_meniu();					
						#endif
					}				

					else if (menu_page==4){	//isejimas i configa		
						meniu=3;
						config=1;
						read_config(); //nuskaitom config parametrus is eeprom
						puslapiai_config();										

						#if debug_mode 
						debug_meniu();	
						#endif
					}
					//exit meniu punktas
					else if (menu_page==5){ //iseijimas i work_mode();
						meniu=0;
						config=0;

						show_work_mode();

						LCD_LED_PORT &= ~_BV(LCD_LED_BIT); //isjungiam LCD pasvietima

						#if debug_mode 
						debug_meniu();	
						#endif		
					}

					else meniu=meniu;
			}
//-------------------- end of main menu routine --------------

	
//-------------------- start of sub menu routine --------------		
		
		else if (meniu==2 && config==0){ //2inis configas
		
			if(sub_menu_page==1) { //OFF vektorius visiems meniu			
				if(menu_page!=4){ 
				meniu=1; 
				work_mode=0;	 //OFF - wmode
				EEPROM_write(25, work_mode);
				wmode(work_mode);		
				puslapiai(); 
				
				#if debug_mode 
				debug_meniu();	
				#endif	
				}
		

			}
			
			else if (sub_menu_page==0){ //ON vektorius
				if(menu_page==0){		//ON/OFF meniu punkte
				work_mode=1;			//ON - wmode
				EEPROM_write(25, work_mode);
				meniu=0;
				wmode(work_mode);
				show_work_mode();
				

				_delay_ms(200);
				LCD_LED_PORT &= ~_BV(LCD_LED_BIT); //isjungiam LCD pasvietima
				
				#if debug_mode 
				debug_meniu();	
				#endif	
				}
				
				else if (menu_page==1){		//PIR meniu punktas
				work_mode=2;				//PIR - wmode
				EEPROM_write(25, work_mode);
				meniu=0;
				show_work_mode();
				wmode(work_mode);				
				

				_delay_ms(200);
				LCD_LED_PORT &= ~_BV(LCD_LED_BIT); //isjungiam LCD pasvietima
				}				

				else if (menu_page==2){		//PIR/LDR meniu punktas
				work_mode=3;				//PIR/LDR - wmode
				EEPROM_write(25, work_mode);
				meniu=0;
				show_work_mode();
				wmode(work_mode);				
				

				_delay_ms(200);
				clock_second=0;
				clock_millisecond=0;
				lcd_light=1;
				
				//LCD_LED_PORT &= ~_BV(LCD_LED_BIT); //isjungiam LCD pasvietima
				
				#if debug_mode 
				debug_meniu();	
				#endif	
				}

				else if (menu_page==3){		//LDR meniu punktas
				work_mode=4;				//LDR - wmode
				EEPROM_write(25, work_mode);
				meniu=0;
				show_work_mode(); 
				wmode(work_mode);
				
				

				_delay_ms(200);
				LCD_LED_PORT &= ~_BV(LCD_LED_BIT); //isjungiam LCD pasvietima
				
				#if debug_mode 
				debug_meniu();	
				#endif	
				}
			}

			else meniu=meniu;
		}
		}
	}
//-------------------- end of sub menu routine --------------



//-------------------------- config ---------------------
	while(meniu!=0 && config==1){

		
		if(read_keypad()==1){	

		#if debug_mode
		PORTDDR(LED_PORT)^= (1<<LED1_BIT);
		send_string("nuspausta knopke confige\n\r");
		#endif

			//config meniu vaiksciojimas: arba iseinam i main meniu arba nueinam i sub config meniu
			if(meniu==3 && config==1){
			
					//exit meniu punktas
					if (config_menu_page==config_menu_page_max){ //iseijimas i work_mode();
						meniu=1;
						config=0;
						config_menu_page=0;	
						puslapiai();

						#if debug_mode 
						debug_meniu();	
						#endif		
					}
					
					//nuejimas i sub config meniu (minPWM, maxPWM, timeOUT ir LDRth nustatymai)
					else if (config_menu_page!=config_menu_page_max){
					meniu=3;
					config=2;
					
					//nuostato nustatymas (pasiziurim, kelintas fadein[] elementas atinka minPWM/maxPWM reiksme EEProme
					if (config_menu_page==0) nuostatas=nuostato_radimas(minPWM);
					else if (config_menu_page==1) nuostatas=nuostato_radimas(maxPWM);
					else nuostatas=nuostatas;

					puslapiai_config_2();
					
					#if debug_mode
					debug_meniu();
					#endif
				//	break;
					}

			
			}

			else config=config;
		}

	}

//---------------------- end of config -----------------------

//---------------------- sub config routine -------------------------

	while(meniu!=0 && config==2){

		
		if(read_keypad()==1){	

		#if debug_mode
		PORTDDR(LED_PORT)^= (1<<LED1_BIT);
		send_string("nuspausta knopke sub confige\n\r");
		#endif

		//isejimas is sub configo
		
		meniu=3;
		config=1;
		nuostatas=0;
		puslapiai_config();

		write_config();
		//OCR2=EEPROM_read(24);
		timer2_set(EEPROM_read(24));
		wmode(work_mode); //kad liktu tikrasis work_mode
		}

		else config=config;
	}

//---------------------- end of sub config routine ------------------

}

}
//-----------------------------------------------------------------------------
// Main Function
//-----------------------------------------------------------------------------
void main(void)
{
  desired_range = 150;
  // initialize board
  Sys_Init();
  putchar(' '); //the quotes in this line may not format correctly
  PCA_Init();
  ADC_Init();
  Interrupt_Init();
  Port_Init();
  XBR0_Init();
  SMB_Init();
  putchar('\r');

  //print beginning message
  printf("En taro Adun, Executor!\r\n");

  // set the PCA output to a neutral setting
  steering_neutral();
  ranger_neutral();

  wait();                                       /* Let stuff warm up */

  // Get the PD constants and target heading from the keypad
  compass_kp              = read_gain()/10.;
  desired_heading         = read_heading();
  compass_kd              = read_gain_high();

  ranger_kp		           = read_gain_thrust()/10.;
  ranger_kd		           = read_gain_thrust_high();

  //Write the settings to the record
  printf ( "Compass KP = %d, Compass KD = %d, Desired Heading = %d, Ranger KP = %d, Ranger KD = %d, Desired Range = %d\r\n", 
      compass_kp,
      compass_kd, 
      desired_heading, 
      ranger_kp, 
      ranger_kd, 
      desired_range );

  printf ( "Time, heading, range\r\n ");

  PCA0CPL1 =   0xFFFF - 3200;
  PCA0CPH1 = ( 0xFFFF - 3200 ) >> 8 ;

  // Start at time 0.
  time = 0;

  while(1)                                      /* Infinite loop is go */
  {	
    if ( nCounts == 50 )
    {
      // Update the LCD loop
      lcd_clear();
      lcd_print( "Batt level: %d\n", get_battery_voltage() );
      lcd_print("Heading :%d\n", heading/10);
      lcd_print("Alt: %d", range );
      if (SS)
        lcd_print("PAUSED\n");
      else
        lcd_print("\n");
      lcd_print("# forHead, * forGain");
      
      }
    if ( read_keypad() != -1 )
    {
      // Check the keypad
      pause();
      if ( getKey() == '#' )
      {
        // If # was pressed, get a new heading
        steering_neutral();
        ranger_neutral();				
        desired_heading = read_heading();
        time = 0;
        printf ( "Compass KP = %d, Compass KD = %d, Desired Heading = %d, Ranger KP = %d, Ranger KD = %d, Desired Range = %d\r\n", 
            compass_kp,
            compass_kd, 
            desired_heading, 
            ranger_kp, 
            ranger_kd, 
            desired_range );

        printf ( "Time, heading, range\r\n ");
      }
      else if( getKey() == '*' )
      {
        // If * was pressed, get new gain contants
        steering_neutral();
        ranger_neutral();	
        compass_kp = read_gain()/10.;
        compass_kd = read_gain_high();
        ranger_kp  = read_gain_thrust()/10.;
        ranger_kd  = read_gain_thrust_high();
        time = 0;
        printf ( "Compass KP = %d, Compass KD = %d, Desired Heading = %d, Ranger KP = %d, Ranger KD = %d, Desired Range = %d\r\n", 
            compass_kp,
            compass_kd, 
            desired_heading, 
            ranger_kp, 
            ranger_kd, 
            desired_range );

        printf ( "Time, heading, range\r\n ");
      }
    }
    else
      pause();
    if(SS)			//while the SS is off
    {
      //printf("The slide switch is OFF \r\n");
      steering_neutral();
      ranger_neutral();
    }
    if(!SS)		//SS is On
    {
      //printf("The Slide switch is On \r\n");
      if ( new_heading )
        printf("%lu,%d,%d\r\n",
            time,
            compass_old_error, 
            ranger_old_error );
      if (new_heading)    //wait for 40ms
      {	
        heading=read_compass();
        //printf("The heading result is %d\r\n", heading);
        new_heading=0;
        Steering_Servo(  );
      }
      if (new_range)
      {
        ReadRanger(  );
        Speed_Cont(  );		//adjust motor speed
        new_range=0;		//reset ranger flag
      }
    }	
  }
}
int main (void)
{
	enum states state;
	state = idle; //initial state is in idle

	DDRA  = 0xF0;		// P.A[7:4] OUT P.A[3:0] IN
	PORTA = 0xFF;		// P.A[3:0] Pullup P.A[7:4] set HIGH
	DDRB  = 0xFF;		// P.B for 7seg
	PORTB = 0xFF;		//
	DDRC  = 0xFF;		// Port C for debugging purposes
	PORTC = 0x00;
	timer_init();		// initialize timer
	sei();				// enable global interrupts

	current_floor=1;
	while(1)
	{
		display_7led(current_floor);
		switch (state)
		{

		case idle:
		{
//			display_7led(1);//debug
			up_amount = 0;
			floor_selection_pointer = 0;
			delay_time=0;
//			call_flag=0;
//			sel_flag = 0;
			floor_clear();
			read_keypad(0);
			if(call_flag==1)
			{
				state=move_x;
			}
			if (sel_flag==1)
			{
				if(current_floor!=4)
					dir_flag=1; //move up before going down if not on 4th floor
				else
					dir_flag=0; //move down if on 4th floor
				state=delay_select;
			}
			break;
		}

		case move_x:
		{
//			display_7led(2);//debug

			if(call_flag==1)	// if a call operation, move then go to idle
			{
				move_elevator(call_floor_distance);	// move to called floor
				call_floor_distance = 0;
//				call_flag=0; 			// reset call flag
				state=open;
			}
			else
			{
				move_elevator(call_floor_distance);
				floor_amount_moved++;
				state=open;
				call_floor_distance = 0;
			}
			break;
		}
		case open:
		{
//			display_7led(3);//debug

			move_door(1);		// open the door
			state=delay_close;
			break;
		}
		case delay_close:
		{
//			display_7led(4);//debug

			delay_flag = 1;		//begin counting delay_time
			if(delay_time == 2)	// wait 3 sec before closing door
			{
				state = closing;	// close door;
				delay_flag = 0;		// turn off delay flag
				delay_time = 0;		// reset delay_time
			}
			break;
		}
		case delay_select:	//
		{
//			display_7led(5);//debug
//			move_door(1);//debug
//			sel_flag=0;			// turn off select flag
//			read_keypad(1);
			delay_flag = 1;		// begin counting delay_time
//			if (sel_flag ==1)
//			{
//				delay_time = 0;	// reset delay_time if button is pressed
//				sel_flag=0;
//			}
			if (delay_time >= 2)	// after grace period, move next state
			{
				state=adj_distance;	// begin to adj distances
				delay_flag = 0;
				delay_time =0;
			}

			break;
		}
		case closing:
		{
//			display_7led(6);//debug

			move_door(0); 		// close the door
			if((call_flag==1)||(floor_amount_moved>=floor_amount_selected))
			{
				call_flag=0;
				floor_clear();
				floor_selection_pointer=0;
				state = idle;
			}
			else if (floor_amount_moved<floor_amount_selected)
			{
				up_amount--;
				if (up_amount<=0)
					dir_flag=0;	// start moving down after done going up
				state = adj_distance;
			}
			break;
		}
		case adj_distance:
		{
//			move_door(1);//debug
//			display_7led(7);//debug

			floor_adj();		// adjust the distances in array
			state = move_x;		// move to next floor
			break;
		}
		default:
			;
		} //end of switch

//		_delay_ms(250);
//		display_7led(9);
//		_delay_ms(250);


	} //end of while


}