예제 #1
0
/////////////////////////////////////////////////////////////////////////////
// Reads the EEPROM content during boot
// If EEPROM content isn't valid (magic number mismatch), clear EEPROM
// with default data
/////////////////////////////////////////////////////////////////////////////
s32 PRESETS_Init(u32 mode)
{
  s32 status = 0;

  // init EEPROM emulation
  if( (status=EEPROM_Init(0)) < 0 ) {
#if DEBUG_VERBOSE_LEVEL >= 1
    DEBUG_MSG("[PRESETS] EEPROM initialisation failed with status %d!\n", status);
#endif
  }

  // check for magic number in EEPROM - if not available, initialize the structure
  if( status < 0 ||
      PRESETS_Read32(PRESETS_ADDR_MAGIC01) != EEPROM_MAGIC_NUMBER ) {
#if DEBUG_VERBOSE_LEVEL >= 1
    DEBUG_MSG("[PRESETS] magic number not found - initialize EEPROM!\n");
#endif

    // enforce formatting
    EEPROM_Init(1);

    // clear EEPROM
    int addr;
    for(addr=0; addr<PRESETS_EEPROM_SIZE; ++addr)
      status |= PRESETS_Write16(addr, 0x00);

    status |= PRESETS_StoreAll();

    // finally write magic numbers
    if( status >= 0 )
      status |= PRESETS_Write32(PRESETS_ADDR_MAGIC01, EEPROM_MAGIC_NUMBER);
  }

  if( status >= 0 ) {
#if DEBUG_VERBOSE_LEVEL >= 1
    DEBUG_MSG("[PRESETS] reading configuration data from EEPROM!\n");
#endif

    u8 midimon_setup = PRESETS_Read16(PRESETS_ADDR_MIDIMON);
    status |= MIDIMON_InitFromPresets((midimon_setup>>0) & 1, (midimon_setup>>1) & 1, (midimon_setup>>2) & 1);

    status |= UIP_TASK_InitFromPresets(PRESETS_Read16(PRESETS_ADDR_UIP_USE_DHCP),
				       PRESETS_Read32(PRESETS_ADDR_UIP_IP01),
				       PRESETS_Read32(PRESETS_ADDR_UIP_NETMASK01),
				       PRESETS_Read32(PRESETS_ADDR_UIP_GATEWAY01));

    u8 con = 0;
    for(con=0; con<PRESETS_NUM_OSC_RECORDS; ++con) {
      int offset = con*PRESETS_OFFSET_BETWEEN_OSC_RECORDS;
      status |= OSC_SERVER_InitFromPresets(con,
					   PRESETS_Read32(PRESETS_ADDR_OSC0_REMOTE01 + offset),
					   PRESETS_Read16(PRESETS_ADDR_OSC0_REMOTE_PORT + offset),
					   PRESETS_Read16(PRESETS_ADDR_OSC0_LOCAL_PORT + offset));
    }
  }
예제 #2
0
/***********************************************************************
		module		:	[EEPROM]
		function		:	[EEPROM写]
  		return		:	[0:写入成功
  						-1:写入失败]
		comment	:	[全局普通函数]
		machine		:	[EH-0818]
		language	:	[CHN]
 		keyword		:	[EEPROM]
		date			:	[11/07/27]
 		author		:	[chen-zhengkai]
************************************************************************/
char eeprom_write(unsigned char* writeBuffer, unsigned short sizeLen, int romOffset)
{
	unsigned short idx = 0;
	char ret = 0;
	EEPROM_Init(EEPROM_ON);
	for (idx = 0; idx < sizeLen; idx++) {
		if (EEPROM_Write_Byte(idx+romOffset, writeBuffer[idx])) {	//写入失败
			ret = -1;	//写入失败
			break;
		}
	}
	EEPROM_Init(EEPROM_OFF);
	return ret;
}
예제 #3
0
/***********************************************************************
		module		:	[EEPROM]
		function		:	[EEPROM读]
  		return		:	[0:读取成功
  						-1:读取失败]
		comment	:	[全局普通函数]
		machine		:	[EH-0818]
		language	:	[CHN]
 		keyword		:	[EEPROM]
		date			:	[11/07/27]
 		author		:	[chen-zhengkai]
************************************************************************/
char eeprom_read(unsigned char* readBuffer, unsigned short sizelen, int romOffset)
{
	unsigned short idx = 0;
	char ret = 0;
	EEPROM_Init(EEPROM_ON);
	for (idx = 0; idx < sizelen; idx++) {
		if (EEPROM_Read_Byte(idx+romOffset, &readBuffer[idx])) {	//读取失败
			ret = -1;	//读取失败
			break;
		}
	}
	EEPROM_Init(EEPROM_OFF);
	return ret;
}
예제 #4
0
int main(void)
{
	delay_init();	    	
	NVIC_PriorityGroupConfig(NVIC_PriorityGroup_2); 
	uart_init(115200);	 //串口初始化为115200
	Uart2_Init(115200);
	OLED_Init();
	LED_Init();
	OLED_Clear(); 	
	KEY_Init();//IO初始化
	TIM3_Int_Init(499,7199);//10Khz的计数频率,计数到500为50ms  
	NET_Init();
	ConnectToDevice();
	delay_ms(300);
	LED2 = 0;
	delay_ms(100);
	LED2 = 1;
	EEPROM_Init();
	// ReadLedStatusFromFlash();
	StartToUploadFlag = 1;
	while(1) 
	{		
		MainMenuIntoSubMenu();
		SwitchDetect();
	}
}
예제 #5
0
/* initialize for touch & calibration */
int touch_calibration_init(void)
{
    rt_uint8_t magic = 0;
    calculate_data_t data;
    struct rtgui_calibration_ops *ops;

    ops = calibration_get_ops();

    /* initialization the eeprom  on chip  */
    EEPROM_Init();
    /* initialization the touch driver */
    rtgui_touch_hw_init("spi10");
    /* set callback to save calibration data */
    calibration_set_after(calibration_data_save);
    /* initialization rtgui tonch server */
    rtgui_touch_init(ops);
    /* restore calibration data */
    EEPROM_Read(0, CALIBRATION_DATA_PAGE, &magic, MODE_8_BIT, 1);
    if (CALIBRATION_DATA_MAGIC != magic)
    {
        rt_kprintf("touch is not calibration,now calibration it please.\n");
        calibration_init(RT_NULL);
    }
    else
    {
        EEPROM_Read(CALIBRATION_DATA_OFFSET, CALIBRATION_DATA_PAGE, &data, MODE_8_BIT, sizeof(calculate_data_t));
        calibration_set_data(&data);
    }
    /* power down the EEPROM */
    EEPROM_PowerDown(ENABLE);
    return 0;
}
예제 #6
0
void HAL_EEPROM_Init(void)
{
    /* Unlock the Flash Program Erase controller so EEPROM_Init can
     * format EEPROM in case it is invalid */
    FLASH_Unlock();
    EEPROM_Init();
    FLASH_Lock();
}
/*********************************************************************************
  *Function		: EEPROMClass::EEPROMClass()
  *Description	: Arduino Compatibility EEPROM methods
  *Input		: none
  *Output		: none
  *Return		: none
  *author		: lz
  *date			: 2015-2-1
  *Others		: none
**********************************************************************************/
EEPROMClass::EEPROMClass()
{
    EEPROM_Init();
    for (uint16_t i = 0 ; i < EEPROM_SIZE ; i++)
    {
        EepromAddressTab[i] = i;
    }
}
예제 #8
0
void test_eeprom(void) {
	volatile unsigned int i;
    volatile unsigned char x;

	EEPROM_Init(EEPROM_ADDR);

	for(i=0; i < 1;i++ ) {
		  ascii(message[i]);
		  EEPROM_ByteWrite(i, message[i]);
		  EEPROM_AckPolling();
	}

	for(i=0; i < 1;i++ ) {
		  x=EEPROM_RandomRead(i);
		  ascii(x);
	}
}
예제 #9
0
main() {
	
	// Select the internal 4MHz oscillator
	OSCCONbits.IRCF = 0b1101;		// 4MHz clock select
	OSCCONbits.SCS = 0b11;			// Internal oscillator
	OSCCONbits.SPLLEN = 0;			// x4 PLL disabled

	SBUS_Init();
	EEPROM_Init();
	Macros_Init();
	PWM_Init();
	PushButtons_Init();
	NightSense_Init();
	Seq_Init();						// Start out at the first sequence
	
//	opMode = LIGHTING_MODE;	
 	override = FALSE;
예제 #10
0
void init_main()
{
	/*Initialize modules*/
	timer_init();
	led_init();

	/*Initialize peripherals*/
	USART_Init(1);
	TIMERS_Init();
	EEPROM_Init();
	ws2812Init();
	ledStringInit();
	ledEffectInit();
	adcInit();
	ExtIntInit();
	ISR_init();

}
예제 #11
0
int main(void) {
	volatile unsigned int i;
    volatile unsigned char x;
    WDTCTL = WDTPW + WDTHOLD;                 // Stop watchdog timer

    EEPROM_Init(0x50);

	for(i=0; i < 3;i++ ) {
		  ascii(message[i]);
		  EEPROM_ByteWrite(i, message[i]);
		  EEPROM_AckPolling();
	}

	for(i=0; i < 3;i++ ) {
		  x=EEPROM_RandomRead(i);
		  ascii(x);
	}
 }
예제 #12
0
파일: main.c 프로젝트: yguo89/RTOS
// *************** SetupHardware *************** 
// Configures the necessary hardware for the board 
// Inputs: none
// Outputs: none
void SetupHardware( void )
{
    /* If running on Rev A2 silicon, turn the LDO voltage up to 2.75V.  This is
       a workaround to allow the PLL to operate reliably. */
    if( DEVICE_IS_REVA2 )
    {
        SysCtlLDOSet( SYSCTL_LDO_2_75V );
    }
	
	/* Set the clocking to run from the PLL at 50 MHz */
	SysCtlClockSet( SYSCTL_SYSDIV_4 | SYSCTL_USE_PLL | SYSCTL_OSC_MAIN |
	                SYSCTL_XTAL_8MHZ );								
					
    // Initialize GPIO driver
	GPIO_InitTasks();

    // Initialize uartstdio for UART0, which is used for communicating over USB and
	// debugging. UART0 uses port A pins 0-1.
	#if ENABLE_UART_PRINTF	 	
	UART_Init();
	#endif	
	
	// Initialize SPI0 for sensor ports
	// SPI1 is initialized by transceiver code
	// XXX What does EEPROM_Init() do besides SPI_Init(0)?
	EEPROM_Init();
			 	 
	// Enable Buttons and/or LEDs depending on target board
#if EVAL_BOARD == 1 
	GPIO_Init( BUTTON_PORT, UP_BUTTON|DOWN_BUTTON|LEFT_BUTTON|RIGHT_BUTTON|SEL_BUTTON,
			   GPIO_DIR_MODE_IN, GPIO_STRENGTH_2MA, GPIO_PIN_TYPE_STD_WPU ); 
	LED_Init(DEBUG_LED);
#else				
	LED_Init(LED1);
	LED_Init(LED2);	
	LED_Init(LED3);	
	LED_Init(LED4);	
#endif
}
예제 #13
0
/*
** ===================================================================
**     Method      :  PE_low_level_init (component MC9S08PA16_32)
**
**     Description :
**         Initializes components and provides common register 
**         initialization. The method is called automatically as a part 
**         of the application initialization code.
**         This method is internal. It is used by Processor Expert only.
** ===================================================================
*/
void PE_low_level_init(void)
{
  #ifdef PEX_RTOS_INIT
    PEX_RTOS_INIT();                   /* Initialization of the selected RTOS. Macro is defined by the RTOS component. */
  #endif
  /* SCG_C1: FTM2=1,??=0,FTM0=1,??=0,??=0,??=0,MTIM0=1,RTC=1 */
  setReg8(SCG_C1, 0xA3U);               
  /* SCG_C2: ??=0,??=0,DBG=1,NVM=1,IPC=1,CRC=1,??=0,??=0 */
  setReg8(SCG_C2, 0x3CU);               
  /* SCG_C3: ??=0,??=0,SCI1=1,SCI0=1,??=0,SPI0=1,IIC=1,??=0 */
  setReg8(SCG_C3, 0x36U);               
  /* SCG_C4: ACMP=1,??=0,ADC=1,??=0,IRQ=1,??=0,??=0,KBI0=1 */
  setReg8(SCG_C4, 0xA9U);               
  /* Common initialization of the CPU registers */
  /* SYS_SOPT2: TXDME=0 */
  clrReg8Bits(SYS_SOPT2, 0x80U);        
  /* PORT_PTBOE: PTBOE1=1,PTBOE0=0 */
  clrSetReg8Bits(PORT_PTBOE, 0x01U, 0x02U); 
  /* PORT_PTBIE: PTBIE1=0,PTBIE0=1 */
  clrSetReg8Bits(PORT_PTBIE, 0x02U, 0x01U); 
  /* PORT_PTBD: PTBD1=1 */
  setReg8Bits(PORT_PTBD, 0x02U);        
  /* PORT_PTCOE: PTCOE7=1,PTCOE6=0 */
  clrSetReg8Bits(PORT_PTCOE, 0x40U, 0x80U); 
  /* PORT_PTCIE: PTCIE7=0,PTCIE6=1 */
  clrSetReg8Bits(PORT_PTCIE, 0x80U, 0x40U); 
  /* PORT_PTCD: PTCD7=1 */
  setReg8Bits(PORT_PTCD, 0x80U);        
  /* PORT_PTAD: PTAD0=0 */
  clrReg8Bits(PORT_PTAD, 0x01U);        
  /* PORT_PTAPE: PTAPE0=0 */
  clrReg8Bits(PORT_PTAPE, 0x01U);       
  /* PORT_PTAOE: PTAOE0=1 */
  setReg8Bits(PORT_PTAOE, 0x01U);       
  /* PORT_PTAIE: PTAIE0=0 */
  clrReg8Bits(PORT_PTAIE, 0x01U);       
  /* PORT_PTDD: PTDD0=0 */
  clrReg8Bits(PORT_PTDD, 0x01U);        
  /* PORT_PTDPE: PTDPE0=0 */
  clrReg8Bits(PORT_PTDPE, 0x01U);       
  /* PORT_PTDOE: PTDOE0=1 */
  setReg8Bits(PORT_PTDOE, 0x01U);       
  /* PORT_PTDIE: PTDIE0=0 */
  clrReg8Bits(PORT_PTDIE, 0x01U);       
  /* SYS_SOPT3: CLKOE=0,BUSREF=0 */
  clrReg8Bits(SYS_SOPT3, 0x0FU);        
  /* IPC_ILRS9: ILRn3=0,ILRn2=0,ILRn1=0,ILRn0=0 */
  setReg8(IPC_ILRS9, 0x00U);            
  /* IPC_ILRS8: ILRn3=0,ILRn2=0,ILRn1=0,ILRn0=0 */
  setReg8(IPC_ILRS8, 0x00U);            
  /* IPC_ILRS7: ILRn3=0,ILRn2=0,ILRn1=0,ILRn0=2 */
  setReg8(IPC_ILRS7, 0x02U);            
  /* IPC_ILRS6: ILRn3=2,ILRn2=2,ILRn1=2,ILRn0=2 */
  setReg8(IPC_ILRS6, 0xAAU);            
  /* IPC_ILRS5: ILRn3=2,ILRn2=0,ILRn1=0,ILRn0=0 */
  setReg8(IPC_ILRS5, 0x80U);            
  /* IPC_ILRS4: ILRn3=2,ILRn2=0,ILRn1=2,ILRn0=2 */
  setReg8(IPC_ILRS4, 0x8AU);            
  /* IPC_ILRS3: ILRn3=0,ILRn2=0,ILRn1=0,ILRn0=0 */
  setReg8(IPC_ILRS3, 0x00U);            
  /* IPC_ILRS2: ILRn3=0,ILRn2=0,ILRn1=0,ILRn0=0 */
  setReg8(IPC_ILRS2, 0x00U);            
  /* IPC_ILRS1: ILRn3=2,ILRn2=2,ILRn1=0,ILRn0=0 */
  setReg8(IPC_ILRS1, 0xA0U);            
  /* IPC_ILRS0: ILRn3=0,ILRn2=0,ILRn1=0,ILRn0=0 */
  setReg8(IPC_ILRS0, 0x00U);            
  /* IPC_SC: IPCE=1,??=0,PSE=0,PSF=0,PULIPM=0,??=0,IPM=0 */
  setReg8(IPC_SC, 0x80U);               
      /* Initialization of the PORT module */
  /* ### Shared modules init code ... */
  /* ### Asynchro serial "AS_CCTALK" init code ... */
  AS_CCTALK_Init();
  /* ### Free running 8-bit counter "FC_CCTALK" init code ... */
  FC_CCTALK_Init();
  /* ### TimerInt "TI_CCTALK" init code ... */
  TI_CCTALK_Init();
  /* ###  WatchDog "WDOG" init code ... */
  WDOG_Init();
  /* WDOG_CNT: CNT=0xA602 */
  setReg16(WDOG_CNT, 0xA602U);          
  /* WDOG_CNT: CNT=0xB480 */
  setReg16(WDOG_CNT, 0xB480U);          
  /* ### Asynchro serial "AS_DATABUS" init code ... */
  AS_DATABUS_Init();
  /* ### BitIO "LED_RUN" init code ... */
  /* ### BitIO "LED_CCTALK" init code ... */
  /* ### Free running 8-bit counter "FC_DATABUS" init code ... */
  FC_DATABUS_Init();
  /* ### TimerInt "TI_LEDS" init code ... */
  TI_LEDS_Init();
  /* ### IntEEPROM "EEPROM" init code ... */
  EEPROM_Init();
  /* ### Free running 8-bit counter "FC_HOPPER" init code ... */
  FC_HOPPER_Init();
  /* Common peripheral initialization - ENABLE */
  /* FTM0_SC: CLKS=1 */
  clrSetReg8Bits(FTM0_SC, 0x10U, 0x08U); 
  /* FTM2_SC: CLKS=1 */
  clrSetReg8Bits(FTM2_SC, 0x10U, 0x08U); 
  CCR_lock = (byte)0;
  __EI();                              /* Enable interrupts */
}
예제 #14
0
void main(void)
{
          unsigned int position=0;
          int error=0,perror=0;
          long int iterm=0;

          //Declaration related to PID control systems.
          unsigned char com_data[7];

          unsigned int servo_output=1500;
          int correction;
          
          unsigned char lap=0;
          
          unsigned int totalsum;
          int start_count=0;  //variable to be removed...
          
          // DC pid control variables
          static int error_dc,perror_dc=0;     //error can be +ve or -ve
          int correction_dc=0;          //+ve or -ve
          unsigned char speed_dc = 40;
          unsigned char count=0; 
          
                              
          Leds_and_Switches_Init();
          EEPROM_Init();
          //EEPROM_reset();
          EEPROM_read();
          
          dc_motor_init();                     // Current pwm duty is 85         
          ISR_init();
          ATD_init();
          pulse_counter_init();
          servo_init();
          //uart0_9600_init();            //To be removed in the final version of the software.
          TI1_Enable();
                                        
          while(1)
          {
                    //This function compensates the sen_data array and puts the result into com_data array.                    
                    compensate_value(sen_data,com_data);
                    
                    // Placing it here, will increase the lag between value read and action taken.. hence
                    // making the system unresponsive ...
                    ATD0CTL5_SCAN=0;          //This will start a new conversion ....
                                        
                     // CODE FOR DC_PID CONTROL.. 
                    if(dc_newval_flag)
                    {
                              dc_newval_flag=0;                  
                              perror_dc=error_dc;
                              error_dc = setpoint - pulse_count;
                              correction_dc =(int) (((KP_DC*error_dc )/DIV10)+ (KD_DC*(error_dc-perror_dc)/DIV10));
                                                      
                              if(speed_dc + correction_dc>=200)
                              {
                                        speed_dc=200;
                              }
                              else if(speed_dc + correction_dc <=0)
                              {
                                        speed_dc =0;
                              }
                              else
                              {
                                        // A type of integrator
                                        speed_dc +=correction_dc;
                              }
                              dc_motor_speed(speed_dc);
                    }

	//START STOP DETEECTION
	//119	15	116	221	134	52	189           
                     totalsum = com_data[4]+com_data[5]+com_data[6]+com_data[0]+com_data[1]+com_data[2]+com_data[3];
                                          
                     if(totalsum>START_OR_CROSS && totalsum<SURE_START)    //either CROSS or start ...
                     {
                              //SUM OF SENSORS IS LARGE OS EITHER A CROSS OR START..
                              //LED1=LED_ON ;

                               if(start_count>delay_dc)
                               {
                                        if(lap>=2)
                                        {
                                                  dc_motor_stop();
                                                  //TSCR1_TEN = 0;                       // Stop timer
                                                  //dc_newval_flag=0;
                                        }
                                        else
                                        {
                                                  lap++;
                                        }
                                        
                               }                            
                                        
                    }
                    
                    //        CAN       BE        COMMENTED           IN        FINAL     VERSION   OF        CODE
                    else if(totalsum<ALL_WHITE)
                    {
                              //LED2=LED_ON ;                    
                              //do nothing..
                    }
                                                                       
                    else 
                    {
                              //LED3=LED_ON ;
                              start_count=0;                //for start/cross detection
                              
                              sort_array(com_data);
                                                                                        
                            /*To find the correction, we have three branches .... */
                                                                                        
                              //GUARD 1
                              if(index ==0 && com_data[index]<GUARD_VAL)
                              {          
                                        //LEFT
                                        //maore the 1500
                                        correction =MAX_CORRECTION;
                                        //LED4=LED_ON;
                              }
                              
                              //GUARD 2
                              else if(index==6 && com_data[index]<GUARD_VAL)
                              {
                                        //RIGHT
                                             // less than 1500
                                        correction =MIN_CORRECTION;
                                        //LED4=LED_ON;
                              }     
                              
                              else
                              {
                                        //LED3=LED_OFF;
                                        position =  (index << 9) + (com_data[index+1]-com_data[index-1]) ;
                                        perror=error;       //stores previous error
                                        error = 1536 - position;
                                                                      
                                        //PID        		               
                                        correction = (int)((int)((kp*error)/DIV100)  + (int)((ki *iterm)/DIV1000) + (int)(kd*(error-perror)/DIV1000));
                                        //anti wind up circutary
                                      
                                        if (correction >= MAX_CORRECTION)
                                        {
                                                  correction = MAX_CORRECTION;
                                        }    

                                        else if (correction <= MIN_CORRECTION)
                                        {
                                                  correction = MIN_CORRECTION;
                                        }
                                        else
                                        {
                                                  // limits bound on iterm.
                                                  if (iterm>=ITERM_LIMIT) 
                                                  {
                                                            //To buffer the fast responses of propotional control, we have the integral control.
                                                            iterm = ITERM_LIMIT;
                                                            //LED4=~LED4;
                                                  }

                                                  else if (iterm<=-ITERM_LIMIT)
                                                  {
                                                            //To buffer the fast responses of propotional control, we have the integral control.
                                                            iterm = -ITERM_LIMIT;
                                                            //LED4=~LED4;
                                                  }

                                                  else
                                                  {
                                                            iterm += error/20;
                                                  }                                                            
                                        }
                                                                                                                                                                
                              }
                              
                             /* PID of dc motor should be applied based on the result of the pid of SERVO ie ""correction""
                                  As the frequency of action of DC PID is slow,, 65 ms, so the lag is enough to drive the car out of track..
                                  DIRECT ACCESS TO DC MOTOR SHOULD BE MADE .. while settiing thr """setpoint"""
                             */
                                                           
                              // correction will be handled from the guards also...
                              if(correction > SHARP_TURN || (-correction) > SHARP_TURN)
                              {                               
                                        //dc_motor_speed(10);
                                        setpoint=2;
                              }
                              
                              else if ((correction>MIDDLE_TURN && correction <SHARP_TURN) || (correction < -MIDDLE_TURN && correction >-SHARP_TURN))
                              {                                 
                                        //dc_motor_speed(20);
                                        setpoint=3;
                              }
                              
                              else 
                              {
                                        //dc_motor_speed(50);
                                        setpoint =4;
                              }

                                          
                              servo_output = (unsigned int)(SET_POINT-correction);
                              servo_set(servo_output);
                    }
          }                              
}
예제 #15
0
void main(void)
{
          unsigned int position=0;
          int error=0,perror=0;
          long int iterm=0;

          //Declaration related to PID control systems.
          unsigned char com_data[7];

          unsigned int servo_output=1500;
          int correction;
          
          unsigned char lap=0;
          
          unsigned int totalsum;
          int start_count=0;  //variable to be removed...
                              
          Leds_and_Switches_Init();
          EEPROM_Init();
          //EEPROM_reset();
          EEPROM_read();
          
          dc_motor_init();                     // Current pwm duty is 85         
          ISR_init();
          ATD_init();
          pulse_counter_init();
          servo_init();
          //uart0_9600_init();            //To be removed in the final version of the software.
        //  TI1_Enable();
                                        
          while(1)
          {
                    //This function compensates the sen_data array and puts the result into com_data array.                    
                    compensate_value(sen_data,com_data);

                    // Placing it here, will increase the lag between value read and action taken.. hence
                    // making the system unresponsive ...
                    ATD0CTL5_SCAN=0;          //This will start a new conversion ....

	//START STOP DETEECTION
	//119	15	116	221	134	52	189           
                     totalsum = com_data[4]+com_data[5]+com_data[6]+com_data[0]+com_data[1]+com_data[2]+com_data[3];
                                          
                     if(totalsum>START_OR_CROSS && totalsum<SURE_START)    //either CROSS or start ...
                     {
                              //SUM OF SENSORS IS LARGE OS EITHER A CROSS OR START..
                              //LED1=LED_ON ;

                               if(start_count>delay_dc)
                               {
                                        if(lap>=2)
                                        {
                                                  dc_motor_stop();
                                                  //TSCR1_TEN = 0;                       // Stop timer
                                                  //dc_newval_flag=0;
                                        }
                                        else
                                        {
                                                  lap++;
                                        }
                                        
                               }                            
                                        
                    }
                    
                    //        CAN       BE        COMMENTED           IN        FINAL     VERSION   OF        CODE
                    else if(totalsum<ALL_WHITE)
                    {
                              //LED2=LED_ON ;                    
                              //do nothing..
                    }
                                                                       
                    else 
                    {
                              //LED3=LED_ON ;
                              start_count=0;                //for start/cross detection
                              
                              sort_array(com_data);
                                                                                        
                            /*To find the correction, we have three branches .... */
                                                                                        
                              //GUARD 1
                              if(index ==0 && com_data[index]<GUARD_VAL)
                              {          
                                        //LEFT
                                        //maore the 1500
                                        correction =MAX_CORRECTION;
                                        //LED4=LED_ON;
                              }
                              
                              //GUARD 2
                              else if(index==6 && com_data[index]<GUARD_VAL)
                              {
                                        //RIGHT
                                             // less than 1500
                                        correction =MIN_CORRECTION;
                                        //LED4=LED_ON;
                              }     
                              
                              else
                              {
                                        //LED3=LED_OFF;
                                        position =  (index << 9) + (com_data[index+1]-com_data[index-1]) ;
                                        perror=error;       //stores previous error
                                        error = 1536 - position;
                                                                      
                                        //PID        		               
                                        correction = (int)((int)((kp*error)/DIV100)  + (int)((ki *iterm)/DIV1000) + (int)(kd*(error-perror)/DIV1000));
                                        //anti wind up circutary
                                      
                                        if (correction >= MAX_CORRECTION)
                                        {
                                                  correction = MAX_CORRECTION;
                                        }    

                                        else if (correction <= MIN_CORRECTION)
                                        {
                                                  correction = MIN_CORRECTION;
                                        }
                                        else
                                        {
                                                  // limits bound on iterm.
                                                  if (iterm>=ITERM_LIMIT) 
                                                  {
                                                            //To buffer the fast responses of propotional control, we have the integral control.
                                                            iterm = ITERM_LIMIT;
                                                            //LED4=~LED4;
                                                  }

                                                  else if (iterm<=-ITERM_LIMIT)
                                                  {
                                                            //To buffer the fast responses of propotional control, we have the integral control.
                                                            iterm = -ITERM_LIMIT;
                                                            //LED4=~LED4;
                                                  }

                                                  else
                                                  {
                                                            iterm += error/20;
                                                  }                                                            
                                        }
                                                                                                                                                                
                              }
                                                            
                              servo_output = (unsigned int)(SET_POINT-correction);
                              servo_set(servo_output);
                    }
          }                              
}
예제 #16
0
void HAL_EEPROM_Init(void)
{
    EEPROM_Init();
}
예제 #17
0
파일: presets.c 프로젝트: glocklueng/MIOS32
/////////////////////////////////////////////////////////////////////////////
// Reads the EEPROM content during boot
// If EEPROM content isn't valid (magic number mismatch), clear EEPROM
// with default data
/////////////////////////////////////////////////////////////////////////////
s32 PRESETS_Init(u32 mode)
{
  s32 status = 0;

  // init EEPROM emulation
  if( (status=EEPROM_Init(0)) < 0 ) {
#if DEBUG_VERBOSE_LEVEL >= 1
    DEBUG_MSG("[PRESETS] EEPROM initialisation failed with status %d!\n", status);
#endif
  }

  // check for magic number in EEPROM - if not available, initialize the structure
  u32 magic = PRESETS_Read32(PRESETS_ADDR_MAGIC01);
  if( status < 0 ||
      (magic != EEPROM_MAGIC_NUMBER &&
       magic != EEPROM_MAGIC_NUMBER_OLDFORMAT1 &&
       magic != EEPROM_MAGIC_NUMBER_OLDFORMAT2 &&
       magic != EEPROM_MAGIC_NUMBER_OLDFORMAT3 &&
       magic != EEPROM_MAGIC_NUMBER_OLDFORMAT4) ) {
#if DEBUG_VERBOSE_LEVEL >= 1
    DEBUG_MSG("[PRESETS] magic number not found (was 0x%08x) - initialize EEPROM!\n", magic);
#endif

    // clear EEPROM
    if( (status=EEPROM_Init(1)) < 0 ) {
#if DEBUG_VERBOSE_LEVEL >= 1
      DEBUG_MSG("[PRESETS] EEPROM clear failed with status %d!\n", status);
#endif
      return status;
    }

    // write all-0
    int addr;
    for(addr=0; addr<PRESETS_EEPROM_SIZE; ++addr)
      status |= PRESETS_Write16(addr, 0x00);

    status |= PRESETS_StoreAll();
  }

  if( magic == EEPROM_MAGIC_NUMBER_OLDFORMAT1 ||
      magic == EEPROM_MAGIC_NUMBER_OLDFORMAT2 ||
      magic == EEPROM_MAGIC_NUMBER_OLDFORMAT3 ||
      magic == EEPROM_MAGIC_NUMBER_OLDFORMAT4 ) {

#if DEBUG_VERBOSE_LEVEL >= 1
    DEBUG_MSG("[PRESETS] new format detected: clearing upper part of EEPROM...\n");
#endif

    // clear EEPROM
    int addr;
    for(addr=0x100; addr<PRESETS_EEPROM_SIZE; ++addr)
      status |= PRESETS_Write16(addr, 0x00);
  }

  if( status >= 0 ) {
#if DEBUG_VERBOSE_LEVEL >= 1
    DEBUG_MSG("[PRESETS] reading configuration data from EEPROM!\n");
#endif

    u8 midimon_setup = PRESETS_Read16(PRESETS_ADDR_MIDIMON);
    status |= MIDIMON_InitFromPresets((midimon_setup>>0) & 1, (midimon_setup>>1) & 1, (midimon_setup>>2) & 1);

    u8 num_srio = PRESETS_Read16(PRESETS_ADDR_NUM_SRIO);
    if( num_srio )
      MIOS32_SRIO_ScanNumSet(num_srio);


    status |= UIP_TASK_InitFromPresets(PRESETS_Read16(PRESETS_ADDR_UIP_USE_DHCP),
				       PRESETS_Read32(PRESETS_ADDR_UIP_IP01),
				       PRESETS_Read32(PRESETS_ADDR_UIP_NETMASK01),
				       PRESETS_Read32(PRESETS_ADDR_UIP_GATEWAY01));

    u8 con = 0;
    for(con=0; con<PRESETS_NUM_OSC_RECORDS; ++con) {
      int offset = con*PRESETS_OFFSET_BETWEEN_OSC_RECORDS;
      status |= OSC_SERVER_InitFromPresets(con,
					   PRESETS_Read32(PRESETS_ADDR_OSC0_REMOTE01 + offset),
					   PRESETS_Read16(PRESETS_ADDR_OSC0_REMOTE_PORT + offset),
					   PRESETS_Read16(PRESETS_ADDR_OSC0_LOCAL_PORT + offset));
    }

    int kb;
    keyboard_config_t *kc = (keyboard_config_t *)&keyboard_config[0];
    for(kb=0; kb<KEYBOARD_NUM; ++kb, ++kc) {
      int offset = kb*PRESETS_OFFSET_BETWEEN_KB_RECORDS;
      kc->midi_ports = PRESETS_Read16(PRESETS_ADDR_KB1_MIDI_PORTS + offset);
      kc->midi_chn = PRESETS_Read16(PRESETS_ADDR_KB1_MIDI_CHN + offset);

      u16 note_offsets = PRESETS_Read16(PRESETS_ADDR_KB1_NOTE_OFFSET + offset);
      kc->note_offset = (note_offsets >> 0) & 0xff;
      kc->din_key_offset = (note_offsets >> 8) & 0xff;

      kc->num_rows = PRESETS_Read16(PRESETS_ADDR_KB1_ROWS + offset);
      kc->dout_sr1 = PRESETS_Read16(PRESETS_ADDR_KB1_DOUT_SR1 + offset);
      kc->dout_sr2 = PRESETS_Read16(PRESETS_ADDR_KB1_DOUT_SR2 + offset);
      kc->din_sr1 = PRESETS_Read16(PRESETS_ADDR_KB1_DIN_SR1 + offset);
      kc->din_sr2 = PRESETS_Read16(PRESETS_ADDR_KB1_DIN_SR2 + offset);

      u16 misc = PRESETS_Read16(PRESETS_ADDR_KB1_MISC + offset);
      kc->din_inverted          = (misc & (1 << 0)) ? 1 : 0;
      kc->break_inverted        = (misc & (1 << 1)) ? 1 : 0;
      kc->scan_velocity         = (misc & (1 << 2)) ? 1 : 0;
      kc->scan_optimized        = (misc & (1 << 3)) ? 1 : 0;
      kc->scan_release_velocity = (misc & (1 << 4)) ? 1 : 0;
      kc->make_debounced        = (misc & (1 << 5)) ? 1 : 0;
      kc->break_is_make         = (misc & (1 << 6)) ? 1 : 0;

      kc->delay_fastest                    = PRESETS_Read16(PRESETS_ADDR_KB1_DELAY_FASTEST + offset);
      kc->delay_slowest                    = PRESETS_Read16(PRESETS_ADDR_KB1_DELAY_SLOWEST + offset);

      if( magic != EEPROM_MAGIC_NUMBER_OLDFORMAT1 && magic != EEPROM_MAGIC_NUMBER_OLDFORMAT2 ) {
	kc->delay_fastest_black_keys         = PRESETS_Read16(PRESETS_ADDR_KB1_DELAY_FASTEST_BLACK_KEYS + offset);
	kc->delay_fastest_release            = PRESETS_Read16(PRESETS_ADDR_KB1_DELAY_FASTEST_RELEASE + offset);
	kc->delay_fastest_release_black_keys = PRESETS_Read16(PRESETS_ADDR_KB1_DELAY_FASTEST_RELEASE_BLACK_KEYS + offset);
	kc->delay_slowest_release 	   = PRESETS_Read16(PRESETS_ADDR_KB1_DELAY_SLOWEST_RELEASE + offset);
      }

      if( magic == EEPROM_MAGIC_NUMBER_OLDFORMAT1 ) {
	u16 ain_assign = PRESETS_Read16(0xcb + offset);
	kc->ain_pin[KEYBOARD_AIN_PITCHWHEEL] = (ain_assign >> 0) & 0xff;
	kc->ain_pin[KEYBOARD_AIN_MODWHEEL]   = (ain_assign >> 8) & 0xff;

	u16 ctrl_assign = PRESETS_Read16(0xcc + offset);
	kc->ain_ctrl[KEYBOARD_AIN_PITCHWHEEL] = (ctrl_assign >> 0) & 0xff;
	kc->ain_ctrl[KEYBOARD_AIN_MODWHEEL]   = (ctrl_assign >> 8) & 0xff;
      } else if( magic == EEPROM_MAGIC_NUMBER_OLDFORMAT2 || magic == EEPROM_MAGIC_NUMBER_OLDFORMAT3 ) {
예제 #18
0
int main(void) {
	char buf[22];
	int len;

	PLLCFG = (1<<5) | (4<<0); //PLL MSEL=0x4 (+1), PSEL=0x1 (/2) so 11.0592*5 = 55.296MHz, Fcco = (2x55.296)*2 = 221MHz which is within 156 to 320MHz
	PLLCON = 0x01;
	PLLFEED = 0xaa;
	PLLFEED = 0x55; // Feed complete
	while(!(PLLSTAT & (1<<10))); // Wait for PLL to lock
	PLLCON = 0x03;
	PLLFEED = 0xaa;
	PLLFEED = 0x55; // Feed complete
	VPBDIV = 0x01; // APB runs at the same frequency as the CPU (55.296MHz)
	MAMTIM = 0x03; // 3 cycles flash access recommended >40MHz
	MAMCR = 0x02; // Fully enable memory accelerator
	
	Sched_Init();
	IO_Init();
	Set_Heater(0);
	Set_Fan(0);
	Serial_Init();
	I2C_Init();
	EEPROM_Init();
	NV_Init();

	if( NV_GetConfig(REFLOW_BEEP_DONE_LEN) == 255 ) {
		NV_SetConfig(REFLOW_BEEP_DONE_LEN, 10); // Default 1 second beep length
	}

	printf("\nInitializing improved reflow oven...");
	LCD_Init();
	LCD_BMPDisplay(logobmp,0,0);

	// Setup watchdog
	WDTC = PCLKFREQ / 3; // Some margin (PCLKFREQ/4 would be exactly the period the WD is fed by sleep_work)
	WDMOD = 0x03; // Enable
	WDFEED = 0xaa;
	WDFEED = 0x55;

	uint8_t resetreason = RSIR;
	RSIR = 0x0f; // Clear it out
	printf("\nReset reason(s): %s%s%s%s", (resetreason&(1<<0))?"[POR]":"", (resetreason&(1<<1))?"[EXTR]":"",
			(resetreason&(1<<2))?"[WDTR]":"", (resetreason&(1<<3))?"[BODR]":"");

	// Request part number
	command[0] = IAP_READ_PART;
	iap_entry(command, result);
	const char* partstrptr = NULL;
	for(int i=0; i<NUM_PARTS; i++) {
		if(result[1] == partmap[i].id) {
			partstrptr = partmap[i].name;
			break;
		}
	}
	// Read part revision
	partrev=*(uint8_t*)PART_REV_ADDR;
	if(partrev==0 || partrev > 0x1a) {
		partrev = '-';
	} else {
		partrev += 'A' - 1;
	}
	len = snprintf(buf,sizeof(buf),"%s rev %c",partstrptr,partrev);
	LCD_disp_str((uint8_t*)buf, len, 0, 64-6, FONT6X6);
	printf("\nRunning on an %s", buf);

	LCD_FB_Update();
	Keypad_Init();
	Buzzer_Init();
	ADC_Init();
	RTC_Init();
	OneWire_Init();
	Reflow_Init();

	Sched_SetWorkfunc( MAIN_WORK, Main_Work );
	Sched_SetState( MAIN_WORK, 1, TICKS_SECS( 2 ) ); // Enable in 2 seconds

	Buzzer_Beep( BUZZ_1KHZ, 255, TICKS_MS(100) );

	while(1) {
		int32_t sleeptime;
		sleeptime=Sched_Do( 0 ); // No fast-forward support
		//printf("\n%d ticks 'til next activity"),sleeptime);
	}
	return 0;
}
예제 #19
0
파일: main2.c 프로젝트: yguo89/RTOS
// going to print to the console generally instead of transmitting
//  in order to help with debugging
static void DriverEEPROM(void)
{
	unsigned char  *driver_ptr = (unsigned char*)0x20000800;
    unsigned char  *verify_ptr = (unsigned char*)0x20002000;
    unsigned short  driver_size = 0x800;     // can we determine this at run time??
 	unsigned short  eeprom_addr = 0x0800;
    int i, errors = 0;
    tBoolean success = true;
    char uartGetBuff[2];
    
    Transceiver_TX_Queue = xQueueCreate ( 4, sizeof( Message ) );
    
	// Initialize UART stdio
	UART_Init();  

	// Initialize GPIO driver
	GPIO_InitTasks();
										  
    // Initialize EEPROM
    EEPROM_Init();			
    EEPROM_Open( CS_PORT, CS_PIN );
    
	UARTprintf( "\n\nWriting to EEPROM...\n" );

	// Copy the driver from internal RAM to the external EEPROM
    EEPROM_WriteBurst( eeprom_addr, driver_ptr, driver_size );
    
    UARTprintf( "Verifying write...\n" );
    
	// Read the driver from external EEPROM
    EEPROM_ReadBurst(eeprom_addr, verify_ptr, driver_size);
    EEPROM_Close( CS_PORT, CS_PIN );
    
	// Verify the contents of both drivers are the same
    for(i = 0; i < driver_size; i++)
	{
        if(driver_ptr[i] != verify_ptr[i]) {
            success = false;
            errors++;
        }
    }

    if(success)
	{
	    UARTprintf( "Successfully wrote driver 2 to eeprom: %d bytes\n", driver_size );
    }
	else
	{
		UARTprintf( "Verify failed, %d errors :(\n", errors );
	}

	// XXX Why does this not work???
	GPIO_Init( GPIO_PORT_B, GPIO_PIN_1, GPIO_STRENGTH_2MA, GPIO_DIR_MODE_IN, GPIO_PIN_TYPE_STD_WPD );
	GPIO_SetInterruptTask( GPIO_PORT_B, GPIO_PIN_1, GPIO_RISING_EDGE, 2, intTask );

	// Run simple command-line interface to test the sensor driver
	UARTprintf( "\n" );
  	while(1)
  	{
        // Simple command line interface to test sensor:
        //  - 'i' calls sensor_init()
        //  - 'c' calls sensor_config()
        //  - 't' calls sensor_task()
        UARTgets(uartGetBuff, 2);    // get letter
        switch(uartGetBuff[0])
		{
            case 'i':
                DriverJumpTable[0](&SensorPort1); 
                break;
            case 'c':
                DriverJumpTable[1](&SensorPort1); 
                break;
			case 't':
                DriverJumpTable[2](&SensorPort1);	 
				break;
            case 'h':
				UARTprintf( "Usage:\n" );
				UARTprintf( "i - calls sensor_init()\n" );	
				UARTprintf( "c - calls sensor_config()\n" );
				UARTprintf( "t - calls sensor_task()\n" );
				break;
			default:   
				UARTprintf( "\n" );
        }
  	}
}
예제 #20
0
파일: main.c 프로젝트: Talljoe/qmk_firmware
/* Main thread
 */
int main(void) {
  /* ChibiOS/RT init */
  halInit();
  chSysInit();

#ifdef STM32_EEPROM_ENABLE
  EEPROM_Init();
#endif

  // TESTING
  // chThdCreateStatic(waThread1, sizeof(waThread1), NORMALPRIO, Thread1, NULL);

  keyboard_setup();

  /* Init USB */
  init_usb_driver(&USB_DRIVER);

  /* init printf */
  init_printf(NULL,sendchar_pf);

#ifdef MIDI_ENABLE
  setup_midi();
#endif

#ifdef SERIAL_LINK_ENABLE
  init_serial_link();
#endif

#ifdef VISUALIZER_ENABLE
  visualizer_init();
#endif


  host_driver_t* driver = NULL;

  /* Wait until the USB or serial link is active */
  while (true) {
#if defined(WAIT_FOR_USB) || defined(SERIAL_LINK_ENABLE)
    if(USB_DRIVER.state == USB_ACTIVE) {
      driver = &chibios_driver;
      break;
    }
#else
    driver = &chibios_driver;
    break;
#endif
#ifdef SERIAL_LINK_ENABLE
    if(is_serial_link_connected()) {
      driver = get_serial_link_driver();
      break;
    }
    serial_link_update();
#endif
    wait_ms(50);
  }

  /* Do need to wait here!
   * Otherwise the next print might start a transfer on console EP
   * before the USB is completely ready, which sometimes causes
   * HardFaults.
   */
  wait_ms(50);

  print("USB configured.\n");

  /* init TMK modules */
  keyboard_init();
  host_set_driver(driver);

#ifdef SLEEP_LED_ENABLE
  sleep_led_init();
#endif

  print("Keyboard start.\n");

  /* Main loop */
  while(true) {

#if !defined(NO_USB_STARTUP_CHECK)
    if(USB_DRIVER.state == USB_SUSPENDED) {
      print("[s]");
#ifdef VISUALIZER_ENABLE
      visualizer_suspend();
#endif
      while(USB_DRIVER.state == USB_SUSPENDED) {
        /* Do this in the suspended state */
#ifdef SERIAL_LINK_ENABLE
        serial_link_update();
#endif
        suspend_power_down(); // on AVR this deep sleeps for 15ms
        /* Remote wakeup */
        if(suspend_wakeup_condition()) {
          usbWakeupHost(&USB_DRIVER);
        }
      }
      /* Woken up */
      // variables has been already cleared by the wakeup hook
      send_keyboard_report();
#ifdef MOUSEKEY_ENABLE
      mousekey_send();
#endif /* MOUSEKEY_ENABLE */

#ifdef VISUALIZER_ENABLE
      visualizer_resume();
#endif
    }
#endif

    keyboard_task();
#ifdef CONSOLE_ENABLE
    console_task();
#endif
#ifdef VIRTSER_ENABLE
    virtser_task();
#endif
#ifdef RAW_ENABLE
    raw_hid_task();
#endif
  }
}
예제 #21
0
void main(void)
{
                              
          Leds_and_Switches_Init();
          EEPROM_Init();
          //EEPROM_reset();
          EEPROM_read();
          
          dc_motor_init();                     // Current pwm duty is 85         
          ISR_init();
          ATD_init();
          servo_init();
                               
while(1)
{
          while(START)
          {
                    //This function compensates the sen_data array and puts the result into com_data array.                    
                    compensate_value(sen_data,com_data);
                    
                    // Placing it here, will increase the lag between value read and action taken.. hence
                    // making the system unresponsive ...
                    ATD0CTL5_SCAN=0;          //This will start a new conversion ....
                                        
	//START STOP DETEECTION
	//119	15	116	221	134	52	189           
                     totalsum = com_data[4]+com_data[5]+com_data[6]+com_data[0]+com_data[1]+com_data[2]+com_data[3];
                                          
                     if(totalsum>START_OR_CROSS && totalsum<SURE_START)    //either CROSS or start ...
                     {
                              //SUM OF SENSORS IS LARGE OS EITHER A CROSS OR START..
                              //LED1=LED_ON ;

                               if(start_count>delay_dc) //&& correction < CORR_LIMIT)   GOT THE LOGIC
                               {
                                        if(lap>=2)
                                        {
                                                  //START=0;
                                                  //dc_motor_stop();
                                                  //TSCR1_TEN = 0;                       // Stop timer
                                                  //dc_newval_flag=0;
                                        }
                                        else
                                        {
                                           //       lap++;
                                        }
                                        
                               }
                               
                               else                            
                               {
                                        start_count++;
                               }
                                        
                    }
                    
                    //        CAN       BE        COMMENTED           IN        FINAL     VERSION   OF        CODE
                    else if(totalsum<ALL_WHITE)
                    {
                              //LED2=LED_ON ;                    
                              //do nothing..
                    }
                                                                       
                    else 
                    {
                              //LED3=LED_ON ;
                              start_count=0;                //for start/cross detection                              
                              sort_array(com_data);
                                                                                        
                            /*To find the correction, we have three branches .... */
                                                                                        
                              //GUARD 1
                              /* if(index ==0 && com_data[index]<GUARD_VAL)
                              {          
                                        //LEFT
                                        //maore the 1500
                                        correction =MAX_CORRECTION;
                                        //LED4=LED_ON;
                              }
                              
                              //GUARD 2
                              else if(index==6 && com_data[index]<GUARD_VAL)
                              {
                                        //RIGHT
                                             // less than 1500
                                        correction =MIN_CORRECTION;
                                        //LED4=LED_ON;
                              }     
                              
                              else */
                              {
                                        //LED3=LED_OFF;
                                        
                                        if(index==0)
                                        {
                                                  //position = 0;     //as com_data[0] > com_data[1]
                                                  position = 2 *com_data[1];
                                        }
                                        else if (index==6)
                                        {
                                                  //position = 3072;       //as com_data[] > com_data[] 
                                                  position = 3072 - 2*com_data[5];
                                        }
                                        else
                                        {
                                                  position =  (index << 9) + (com_data[index+1]-com_data[index-1]);
                                        }

                                        perror=error;       //stores previous error
                                        error = (long)1536 - (long)position;
                                                                      
                                        //PID        		               
                                        correction = (int)((int)((kp*error)/DIV1000)  + (int)((ki *iterm)/DIV10000) + (int)(kd*(error-perror)/DIV10000));
                                        //anti wind up circutary
                                      
                                        if (correction >= MAX_CORRECTION)
                                        {
                                                  correction = MAX_CORRECTION;
                                        }    

                                        else if (correction <= MIN_CORRECTION)
                                        {
                                                  correction = MIN_CORRECTION;
                                        }
                                        else
                                        {
                                                            // limits bound on iterm.
                                                            if ((iterm+error)>=ITERM_LIMIT) 
                                                            {
                                                                      //To buffer the fast responses of propotional control, we have the integral control.
                                                                      iterm = ITERM_LIMIT;
                                                                      //LED4=~LED4;
                                                            }

                                                            else if ((iterm+error)<=-ITERM_LIMIT)
                                                            {
                                                                      //To buffer the fast responses of propotional control, we have the integral control.
                                                                      iterm = -ITERM_LIMIT;
                                                                      //LED4=~LED4;
                                                            }

                                                            else
                                                            {
                                                                      if ( icount <200)
                                                                      {                        
                                                                                iterm += error/20;
                                                                                icount ++;
                                                                      }                                                            

                                                                      else
                                                                      {
                                                                                icount=0;
                                                                                if(error < RESET_ITERM || (-error) > RESET_ITERM  )
                                                                                {
                                                                                          iterm=0;
                                                                                }
                                                                      }
                                                            }
                                                  }
                                        }
                                                                                                                                                                
                              }
                              
                             /* PID of dc motor should be applied based on the result of the pid of SERVO ie ""correction""
                                  As the frequency of action of DC PID is slow,, 65 ms, so the lag is enough to drive the car out of track..
                                  DIRECT ACCESS TO DC MOTOR SHOULD BE MADE .. while settiing thr """setpoint"""
                             */
                                                           
                              // correction will be handled from the guards also...
                              if(correction > SHARP_TURN || (-correction) > SHARP_TURN)
                              {                               
                                        //dc_motor_speed(10);
                                        //setpoint=2;
                                        //kp=8;
                              }
                              
                              else if ((correction>MIDDLE_TURN && correction <SHARP_TURN) || (correction < -MIDDLE_TURN && correction >-SHARP_TURN))
                              {                                 
                                        //dc_motor_speed(20);
                                        //setpoint=3;
                                        //kp=12;
                              }
                              
                              else 
                              {
                                        //dc_motor_speed(50);
                                        //setpoint =4;
                              }

                                          
                              servo_output = (unsigned int)(SET_POINT-correction);
                              servo_set(servo_output);
                    }
          }                              
}