Exemplo n.º 1
0
void exec_cmd(char *cmd){
	comm_flush();
	if(stricmp(cmd,"b")==0){
		xprintf(INFO "resetting to bootloader" " (%s:%d)\n",_F_,_L_);
		SCB->VTOR = (BOOTLOADER_START & 0x1FFFFF80);
		RTC_WriteGPREG(LPC_RTC, 2, 0xbbbbbbbb);
		WDT_Init (WDT_CLKSRC_PCLK, WDT_MODE_RESET);
		WDT_Start(1);
		NVIC_EnableIRQ(WDT_IRQn);
	}
	else if(stricmp(cmd,"r")==0){
		xprintf(INFO "reseting" " (%s:%d)\n",_F_,_L_);
		WDT_Init(WDT_CLKSRC_PCLK, WDT_MODE_RESET);
		WDT_Start(1);
		NVIC_EnableIRQ(WDT_IRQn);
		while(1);//lockup, wdt will reset board
		//WDT_ClrTimeOutFlag();
	}
	else if(stricmp(cmd,"t")==0){
		xprintf(INFO "tests running" " (%s:%d)\n",_F_,_L_);
	}
	else if(stricmp(cmd,"q")==0){
		xprintf(INFO "q" " (%s:%d)\n",_F_,_L_);
	}
	else if(stricmp(cmd,"")==0){
		xprintf(INFO "\r\nr-Resets board\r\nb-Resets to bootloader\r\nt-led test\r\n" " (%s:%d)\n",_F_,_L_);
	}
	else{
		xprintf(INFO "Command not found (cmd=%s)" " (%s:%d)\n",cmd,_F_,_L_);
	}
	return;
}
Exemplo n.º 2
0
void main(void) //using 0
{			   
	EA = 0;
	
	
	PLLCON&=PLLCON_VAL;//настройка частоты процессора
	
	RestoreCalibrate();
	RestoreSettings();
//	ChannelsInit();//инициализация настроек каналов
	Protocol_Init();	
	Timer1_Initialize(); //таймер шедулера 200Гц	
	ADC_Initialize();
	UART_Init();


	WDT_Init(WDT_2000);//включить сторожевой таймер

	PT_INIT(&pt_sort);

	startMenu();
	EA=1;


	while(1)
	{		
		ulongsort_process(&pt_sort);
		DisplayProcess(&pt_display);  
		WDT_Process(&pt_wdt);
		KeyboardProcess(&pt_keyboard);	    
	}
}
Exemplo n.º 3
0
void main(void) //using 0
{			   
	EA = 0;
	
	//CFG845=0x1;//enable xram
	
	PLLCON&=PLLCON_VAL;//настройка частоты процессора
//-------printf--------
//    T3CON = T3CON_VAL;
//
//    T3FD = T3FD_VAL;
//    SCON =0x52; //0x53;
//---------------------
	
	Timer1_Initialize(); //таймер генерации частоты

	Frequency_Init();
	DAC_Init();
	WDT_Init(WDT_2000);//включить сторожевой таймер

	EA=1;

	while(1)
	{	
	  Frequency_Measure_Process();
	  WDT_Clear();
	}
}
Exemplo n.º 4
0
void main(void) //using 0
{			   
	EA = 0;
	
	//CFG845=0x1;//enable xram
	
	PLLCON&=PLLCON_VAL;//настройка частоты процессора
//	ChannelsInit();//инициализация настроек каналов

	
	Timer1_Initialize(); //
	Timer2_Initialize();

	Dol_Init();

	WDT_Init(WDT_2000);//включить сторожевой таймер

	I2C_Slave_Init();
	EA=1;

	while(1)
	{		
	  Frequency_Handler();//обработчик измерения частоты
	  WDT_Clear();
	}
}
Exemplo n.º 5
0
void WDT_NMI(void)
{
    WDT_InitTypeDef WDT_InitStruct;
    WDT_InitStruct.DetectTime = WDT_DETECT_TIME_EXP_25;

    WDT_InitStruct.OverflowOutput = WDT_NMIINT;


    LED_Init();
    Delay(5000U);
    LED_On(LED1 | LED2);
    WDT_Init(&WDT_InitStruct);
    WDT_Enable();

    while (1) {
        if (fIntNMI == 1U) {
            fIntNMI = 0U;
            LED_On(LED3);
            Delay(500U);
            LED_Off(LED3);
            Delay(500U);
            WDT_Disable();
        } else {
            /* Do nothing */
        }
#ifdef DEMO2
        Delay(500U);
        WDT_WriteClearCode();
        LED_On(LED2);
        Delay(500U);
        LED_Off(LED2);
#endif
    }
}
Exemplo n.º 6
0
void main(void) //using 0
{			   
	EA = 0;
	
	
	PLLCON&=PLLCON_VAL;//настройка частоты процессора
	
	RestoreCalibrate();
	
	ChannelsInit();//инициализаци¤ настроек каналов
	Protocol_Init();	
	Timer1_Initialize(); //таймер шедулера 200√ц	
	ADC_Initialize();
	UART_Init();

	WDT_Init(WDT_2000);//включить сторожевой таймер
	
	PT_INIT(&pt_sort);


	EA=1;

	while(1)
	{	
		ProtoProcess(&pt_proto);
	
		ulongsort_process(&pt_sort);
		WDT_Process(&pt_wdt);	    
	}
}
Exemplo n.º 7
0
void main(void) //using 0
{			   	
	EA = 0;
		
	PLLCON&=PLLCON_VAL;//настройка частоты процессора

	if(!BUTTON1)
	{
		SHOW_VOLTAGE=1;
	}
	
	Timer1_Initialize(); //таймер шедулера 200Гц
	
	ADC_Initialize();

	ChannelsInit();
	UART_Init();

	WDT_Init(WDT_250);//включить сторожевой таймер



	EA=1;
	PT_INIT(&pt_display);
	PT_INIT(&pt_led);
	PT_INIT(&pt_key);
	PT_INIT(&pt_blink);

 	if(!SHOW_VOLTAGE)
	{
	   if(skd.SKD_Set.SKD_Settings.diap_high>=100.0 || skd.SKD_Set.SKD_Settings.diap_low<-100.0) //передвигаем десятичную точку
	   {
	   		LED_SetPoint(INDICATOR_1,2);
	   }
	   else
	   {
	   		LED_SetPoint(INDICATOR_1,3);
	   }
		LED_Set_Brightness(INDICATOR_1,0);
		//LED_Out_Float(INDICATOR_1,0.0);
	}
	else
	{
		LED_SetPoint(INDICATOR_1,4);
		LED_Set_Brightness(INDICATOR_1,0);
		LED_Out_Float(INDICATOR_1,0.0);	
	}
	Protocol_Init();
	while(1)
	{		
		LED_Process(&pt_led);
		Display_Out_Process(&pt_display);
		Keyboard_Process(&pt_key);
		ProtoProcess(&pt_proto);
		LED_BlinkTask(&pt_blink);
		WDT_Clear();
	}
}
Exemplo n.º 8
0
void check_boot_request (void)
{
  if (digital_read (4, (1<<29)) == 0)
  {
    WDT_Init (WDT_CLKSRC_PCLK, WDT_MODE_RESET);
    WDT_Start (10);
    while (1);
  }
}
Exemplo n.º 9
0
/*
**-----------------------------------------------------------------------------
**
**  Abstract:
**	This function initializes every macro.
**
**  Parameters:
**	None
**
**  Returns:
**	None
**
**-----------------------------------------------------------------------------
*/
void systeminit(void)
{
	CG_ReadResetSource();
	CLOCK_Init();
	TAU0_Init();
	WDT_Init();
	CRC0CTL = 0x00U;
	IAWCTL = 0x00U;
}
Exemplo n.º 10
0
void qWDT_Start(uint32_t timeout){
	NVIC_EnableIRQ(WDT_IRQn);

	// Initialize WDT, IRC OSC, interrupt mode, timeout = 5000000us = 5s
	WDT_Init(WDT_CLKSRC_IRC, WDT_MODE_INT_ONLY);
	// Start watchdog with timeout given
	WDT_Start(timeout);


}
Exemplo n.º 11
0
void main(void) //using 0
{			   
	unsigned char i=0;
	EA = 0;


	
	ChannelsInit();//инициализаци¤ настроек каналов
	Protocol_Init();
	Timer0_Initialize();	
	Timer1_Initialize(); //таймер шедулера 200√ц	



	ADC_Initialize();
	EA=1;
	for(i=0;i<MID_NUM<<1;i++)
	{
		unsigned int delay=300;
		SCONV=1;
		while(delay)
		{
			delay--;
		}
	}

	ADC_MID_1=PHASE_1_RESULT;
	ADC_MID_2=PHASE_2_RESULT;

	UART_Init();
	Dol_Init();
	Timer2_Initialize();


	WDT_Init(WDT_2000);//включить сторожевой таймер


//	RestoreCalibrate();

//	PT_INIT(&pt_i2c_read);
//	PT_INIT(&pt_freq_measure);
//	PT_INIT(&pt_sort);
	PT_INIT(&pt_out);

	

	while(1)
	{	
		ProtoProcess(&pt_proto);
		OutProcess(&pt_out);	    
	}
}
Exemplo n.º 12
0
/*********************************************************************//**
 * @brief		c_entry: Main program body
 * @param[in]	None
 * @return 		int
 **********************************************************************/
int c_entry (void)
{
    /* Initialize debug via UART0
     * – 115200bps
     * – 8 data bit
     * – No parity
     * – 1 stop bit
     * – No flow control
     */
    debug_frmwrk_init();

    // print welcome screen
    print_menu();

    // Init WDT, IRC OSC, interrupt mode, timeout = 2000000 us = 2s
    WDT_Init(WDT_CLKSRC_IRC, WDT_MODE_INT_ONLY);

    _DBG_("Press '1' to enter system in Deep Sleep mode");
    while(_DG !='1');

    NVIC_EnableIRQ(WDT_IRQn);
    WDT_Start(WDT_TIMEOUT);

    _DBG_("Enter Deep Sleep mode!");
    _DBG_("Wait 2s for WDT wake-up system...");

    /*---------- Disable and disconnect the main PLL0 before enter into Deep-Sleep
     * or Power-Down mode <according to errata.lpc1768-16.March.2010> ------------
     */
    LPC_SC->PLL0CON &= ~(1<<1); /* Disconnect the main PLL (PLL0) */
    LPC_SC->PLL0FEED = 0xAA; /* Feed */
    LPC_SC->PLL0FEED = 0x55; /* Feed */
    while ((LPC_SC->PLL0STAT & (1<<25)) != 0x00); /* Wait for main PLL (PLL0) to disconnect */
    LPC_SC->PLL0CON &= ~(1<<0); /* Turn off the main PLL (PLL0) */
    LPC_SC->PLL0FEED = 0xAA; /* Feed */
    LPC_SC->PLL0FEED = 0x55; /* Feed */
    while ((LPC_SC->PLL0STAT & (1<<24)) != 0x00); /* Wait for main PLL (PLL0) to shut down */
    /*------------Then enter into PowerDown mode ----------------------------------*/

    // Enter target power down mode
    CLKPWR_DeepSleep();
    SystemInit();
    debug_frmwrk_init();
    _DBG_("\n\rSystem wake-up!\n\r");
    while(1);
    return 1;
}
Exemplo n.º 13
0
int c_entry(void)
{
	// Init LED port
	LED_Init();

	/*
	 * Initialize debug via UART
	 */
	debug_frmwrk_init();

	// print welcome screen
	print_menu();

	// Read back TimeOut flag to determine previous timeout reset
	if (WDT_ReadTimeOutFlag()){
		_DBG_(info1);
		// Clear WDT TimeOut
		WDT_ClrTimeOutFlag();
	} else{
		_DBG_(info2);
	}

	// Initialize WDT, IRC OSC, interrupt mode, timeout = 2000000 microsecond
	WDT_Init(WDT_CLKSRC_IRC, WDT_MODE_RESET);
	// Start watchdog with timeout given
	WDT_Start(WDT_TIMEOUT);

	// set timer 100 ms
	Timer_Wait(100);

	while (1){
		// Wait for 100 millisecond
		while ( !(TIM_GetIntStatus(LPC_TIM0,0)));
		TIM_ClearIntPending(LPC_TIM0,0);
		//turn on led
		FIO_ByteSetValue(2, 0, LED_PIN);

		// Wait for 100 millisecond
		while ( !(TIM_GetIntStatus(LPC_TIM0,0)));
		TIM_ClearIntPending(LPC_TIM0,0);
		//turn off led
		FIO_ByteClearValue(2, 0, LED_PIN);
	}

	return 0;
}
Exemplo n.º 14
0
//-----------------------------------------------------------------------------
// main()
//-----------------------------------------------------------------------------
void main(void)
{
    U32 transfer_data;

    WDT_Init();
    Oscillator_Init();
    Port_Init();

    // These pins are grounded on the CoreSight debug connector
    P1_4 = 0;
    P1_2 = 0;

    // There is no debug port connection at this point
    DP_Type = DP_TYPE_NONE;

    SWD_Initialize();
    SWD_Configure(DP_TYPE_SWD);
    SWD_Connect();

    transfer_data = 0x00000000;

    // Read the IDCODE from the connected device
    SWD_DAP_Move(0, DAP_IDCODE_RD, &transfer_data);

    // The return value from DAP_IDCODE_RD for SiM3U1xx devices is 0x2BA01477

    // Write the CTRLSTAT register to enable the debug hardware
    transfer_data = 0x50000000;
    SWD_DAP_Move(0, DAP_CTRLSTAT_WR, &transfer_data);
    SWD_ClearErrors();
    connect_and_halt_core();
    programming_sram();

    transfer_data = 0x00000000;
    SWD_DAP_Move(0, DAP_CTRLSTAT_WR, &transfer_data);
    SWD_Disconnect();

    while (1)
    {
    }
}
Exemplo n.º 15
0
void
xs_wdt_start(xsMachine *the)
{
    int index = xsToInteger(xsArg(0));
    WDT_Config_Type cfg;

    cfg.timeoutVal = index;
    cfg.mode = WDT_MODE_RESET;
    cfg.resetPulseLen = WDT_RESET_PULSE_LEN_2;
    WDT_Init(&cfg);

    CLK_ModuleClkEnable(CLK_WDT);
#if defined(CONFIG_CPU_MW300)
    /* For 88MW300, APB1 bus runs at 50MHz whereas for 88MC200 it runs at
     * 25MHz, hence following clk divider is added to keep timeout same.
     */
    CLK_ModuleClkDivider(CLK_WDT, 1);
#endif
    WDT_Enable();
    wdt_enable = 1;
}
Exemplo n.º 16
0
/* WDT_NMI function */
void WDT_NMI(void)
{
    WDT_InitTypeDef WDT_InitStruct;
    WDT_InitStruct.DetectTime = WDT_DETECT_TIME_EXP_25;
    WDT_InitStruct.OverflowOutput = WDT_NMIINT;

    SystemInit();

    /* WDT and LED configuration */
    TSB_PM->CR = (uint32_t) 0xF0;
    TSB_PM->PUP = (uint32_t) 0xF0;
	TSB_PM->DATA = (uint32_t)0xFF;
	
    WDT_Init(&WDT_InitStruct);
    WDT_Enable();

    while (1) {
#ifdef DEMO2
        Delay(500U);
        WDT_WriteClearCode();
        TSB_PM_DATA_PM6 = !TSB_PM_DATA_PM6;
#endif
    }
}
Exemplo n.º 17
0
// the loop routine runs over and over again forever:
void loop() {
  byte lclocktick=0;
 //       int j;
	//    analogWrite(9, 60);
	//  TCCR2A = _BV(COM2A1) | _BV(COM2B1) | _BV(WGM21) | _BV(WGM20);
	//  TCCR2B = _BV(CS22);
	//  OCR2A = 180;
	//  OCR2B = 50;

	//  digitalWrite(led, HIGH);   // turn the LED on (HIGH is the voltage level)
	if(!(laserstate||lightstate||command_pending))
	{
              
            if(sleepcounter==0)
            {
                attachInterrupt(0, int0, LOW);

		WDT_Stop();
                set_led(led,&ledstate,0);
               set_led(led2,&ledstate2,0);
//                delay(100);
		go_sleep();
                int0f();
		WDT_Init();
            }
	}
        else
            sleepcounter=SLEEPIDLESECS;
        if(clocktick)
        {
          cli();
            lclocktick=clocktick;
            clocktick=0;
          sei();
       	set_led(led,&ledstate,0);

            wdtcounter+=lclocktick;
            sleepcounter--;
           if(!(wdtcounter%BATCHECKSECS))
               checkbat=1;
            if(laserstate)
            		lasercounter++;
            
             if(lightstate)
			lightcounter++;


        }

	if(command_pending==2)
	{
		btnpress();

		command_pending=0;
            

	}
	if(command_pending==1&&millis()-timepressed>LONGBUTTONPRESS)
		int0r();
//	toggle_led(led2,&ledstate2);

	if(laserstate&&(lasercounter>LASER_MAX_ON))
	{
		set_laser(0);
                laserstate=0;

	}
	if(lightstate&&(lightcounter>LIGHT_MAX_ON))
	{
              set_lights(0);
              lightstate=0;
	}

        if(checkbat)
        {
          check_bat();
          checkbat=0;
        }
        if(volts<VBATTHRESH)
        {
             if(lclocktick)
         	    toggle_led(led2,&ledstate2);   
        }
        else   
            set_led(led2,&ledstate2,0);      
        if(volts<VBATTHRESH_CRIT)
        {
          if(!(wdtcounter%BATCHECKCRITSECS))
          {
   //         for(j=0;j<3;j++)
   //         {
              set_lights(0);
              delay(100);
              set_lights(lightstate);
               delay(100);
   //         }
            
          }
          
        }            


	//delay(100);
	//  digitalWrite(led, LOW);    // turn the LED off by making the voltage LOW
	//  delay(500);               // wait for a second
}
Exemplo n.º 18
0
void MAIN_vInit(void)
{
  // USER CODE BEGIN (Init,2)

  // USER CODE END

  //// -----------------------------------------------------------------------
  //// Begin of Important Settings for the Start-Up File
  //// -----------------------------------------------------------------------
  ///  All following settings must be set in the start-up file. You can use 
  ///  DAvE's project file (*.dpt) to include this register values into your 
  ///  compiler EDE.

    ///  ---------------------------------------------------------------------
    ///  Initialization of the SYSCON Register:
    ///  ---------------------------------------------------------------------
    ///  - 256 words system stack
    ///  - Internal ROM area mapped to segment 1
    ///  - the segmentation is enabled (CSP is saved/restored during 
    ///  interrupt entry/exit)
    ///  - Internal ROM disabled
    ///  - the pin #BHE is enabled
    ///  - the pins #WR and #BHE retain their normal functions
    ///  - system clock output CLKOUT is disabled
    ///  - latched #CS mode
    ///  - pin #RSTIN is pulled low during the internal reset sequence
    ///  - the on-chip X-Peripherals are enabled and can be accessed
    ///  - accesses to the XBUS peripherals are done internally

    //// this register must be set in the start-up file
    //// SYSCON  =  0x101C

    ///  ---------------------------------------------------------------------
    ///  Initialization of the SYSCON1 Register:
    ///  ---------------------------------------------------------------------

    //// this register must be set in the start-up file
    //// SYSCON1  =  0x0000

    ///  ---------------------------------------------------------------------
    ///  Initialization of the SYSCON2 Register:
    ///  ---------------------------------------------------------------------

    //// this register must be set in the start-up file
    //// SYSCON2  =  0x0000

    ///  ---------------------------------------------------------------------
    ///  Initialization of the SYSCON3 Register:
    ///  ---------------------------------------------------------------------

    //// this register must be set in the start-up file
    //// SYSCON3  =  0x0000

    ///  ---------------------------------------------------------------------
    ///  --- initialization of the BUSCON 0-4 and ADRRSEL Registers 1-4 ---
    ///  ---------------------------------------------------------------------


    ///  ---------------------------------------------------------------------
    ///  ---------- external bus 0 is enabled ----------
    ///  ---------------------------------------------------------------------
    ///  - 16-bit Multiplexed Bus
    ///  - memory cycle time control: 15 waitstates
    ///  - With read/write delay: activate command 1 TCL after falling edge 
    ///  of ALE
    ///  - chip select mode: address chip select
    ///  - memory tristate control: 1 waitstate
    ///  - ALE lengthening control: lengthened ALE signal
    ///  - Address windows are switched immediately
    ///  - Normal #WR signal

    //// this register must be set in the start-up file
    //// BUSCON0  =  0x06C0




  //// -----------------------------------------------------------------------
  //// End of Important Settings for the Start-Up File
  //// -----------------------------------------------------------------------




  //   -----------------------------------------------------------------------
  //   Initialization of the Peripherals:
  //   -----------------------------------------------------------------------

  //   initializes the Parallel Ports
  IO_Init();

  //   initializes the Asynchronous/Synchronous Serial Interface (ASC0)
  ASC0_Init();

  //   initializes the General Purpose Timer Unit (GPT1)
  GPT1_vInit();

  //   initializes the Watchdog Timer (WDT)
  WDT_Init();

  //   initializes the Real Timer Clock (RTC)
  RTC_Init();

  //   initializes the Analog / Digital Converter (ADC)
  ADC_vInit();

  //   initializes the Capture / Compare Unit 2 (CAPCOM2)
  CC2_Init();

  //   initializes the Capture / Compare Unit 6 (CAPCOM6)
  CC6_Init();

  //   initializes the On-Chip CAN Interface 1 (CAN1)
  CAN1_Init();

  // USER CODE BEGIN (Init,3)

  // USER CODE END

  //   globally enable interrupts
  PSW_IEN        =  1;          

} //  End of function MAIN_vInit
Exemplo n.º 19
0
void Setup() {
	/* Initialize LCD */
	lcd_initialize();

	/* Clear LCD */
	lcd_clear();

	/* Display message on LCD */

	lcd_buffer_print(LCD_LINE2, "    TEST   ");

	/* Initialize motors */
	Motors_Init();
	/* Turn on motors relay */
	Motors_On();
	/* Send arm signal to motors */
	Motor_Arm(MOTOR_UPPER);
	Motor_Arm(MOTOR_BOTTOM);

	/* Initialize servos */
	Servos_Init();

	/* Initialize sonar */
	sonarInitialize(); //must be initialized before IIC, otherwise it will not work
	/* Setup the 12-bit A/D converter */
	S12ADC_init();


	/* Initialize I2C with control */
	riic_ret_t iic_ret = RIIC_OK;
	iic_ret |= riic_master_init();
	while (RIIC_OK != iic_ret) {
		nop(); /* Failure to initialize here means demo can not proceed. */
	}


	/* Setup Compare Match Timer */
	CMT_init();

	/* Initialize PID structure used for PID properties */
	PID_Init(&z_axis_PID, 0.7, 0.05, 0.30, dt, 0, 0.5);	//0.7 0.05 0.15
	PID_Init(&Pitch_PID, 1, 0, 0.01, dt, -30, 30);
	PID_Init(&Roll_PID, 1, 0, 0.01, dt, -30, 30);

	Init_AVG(0, &pitchAVG);
	Init_AVG(0, &rollAVG);

	/* Make the port connected to SW1 an input */
	PORT4.PDR.BIT.B0 = 0;

	/*MPU6050 Initialization*/
	MPU6050_Test_I2C();
	Setup_MPU6050();
	Calibrate_Gyros();
//	Calibrate_Accel();

	/*Kalman Initialization*/
	init_Kalman();

	//MS5611-01BA01 init
//    MS5611_Init();

	desiredState.key.motor_diff_us = 0;
	desiredState.key.abs.pos.z = 0.20;
	altitudeValue = 200;
	mainWDT = WDT_Init(500, Fallback);
	WDT_Start(&mainWDT);
	sonarWDT = WDT_Init(60, Sonar_Fallback);
	WDT_Start(&sonarWDT);
}
Exemplo n.º 20
0
/* This is your main function! You should have an infinite loop in here that
 * does all the important stuff your node was designed for */
int main(void) {

#if defined(DOUBLE_BUFFER_EXAMPLE)
#define BUFFER_SIZE 128
	/* variables for double buffer example */
	char buf_1[BUFFER_SIZE];
	char buf_2[BUFFER_SIZE];
	char *current_buf;
	struct UART_buffer_descriptor buf_desc_1, buf_desc_2;
#endif

#if defined(WAVESCULPTOR_EXAMPLE)
	float velocity = 2.0; // velocity in metres per second
	float bus_current = 1.0; // perentage of bus current max
	float motor_current = 1.0;
#endif

	setup();

	/* Initialise the watchdog timer. If the node crashes, it will restart automatically */
	WDT_Init(); 

	/* Initialise Scandal, registers for the config messages, timesync messages and in channels */
	scandal_init();

	/* Set LEDs to known states */
	red_led(0);
	yellow_led(1);

	/* Initialise UART0 */
	UART_Init(115200);

	/* Wait until UART is ready */
	scandal_delay(100);

	/* Display welcome header over UART */
	UART_printf("Welcome to the template project! This is coming out over UART0\n\r");
	UART_printf("A debug LED should blink at a rate of 1HZ\n\r");

	red_led(1);

	sc_time_t one_sec_timer = sc_get_timer();

#if defined(IN_CHANNEL_EXAMPLE)
	UART_printf("If you configure the in channel 0, a message should print upon receipt of such a channel message\n\r");
	sc_time_t in_timer = sc_get_timer();
	scandal_register_in_channel_handler(0, &in_channel_0_handler);
#endif

#if defined(DOUBLE_BUFFER_EXAMPLE)
	UART_printf("This shows an example of double buffer reading from the UART. Enter the text 'time' and press enter\n\r> ");
	UART_init_double_buffer(&buf_desc_1, buf_1, BUFFER_SIZE,
								&buf_desc_2, buf_2, BUFFER_SIZE);
#endif

#if defined(WAVESCULPTOR_EXAMPLE)
	sc_time_t ws_timer = sc_get_timer();
	/* register for wavesculptor bus and temp messages */
	scandal_register_ws_bus_callback(&ws_bus_handler);
	scandal_register_ws_temp_callback(&ws_temp_handler);
#endif

	/* This is the main loop, go for ever! */
	while (1) {
		/* This checks whether there are pending requests from CAN, and sends a heartbeat message.
		 * The heartbeat message encodes some data in the first 4 bytes of the CAN message, such as
		 * the number of errors and the version of scandal */
		handle_scandal();

#if DOUBLE_BUFFER_EXAMPLE
		current_buf = UART_readline_double_buffer(&buf_desc_1, &buf_desc_2);

		/* UART_readline_double_buffer will return a pointer to the current buffer. */
		if (current_buf != NULL) {
			if (strncmp("time", current_buf, 4) == 0) {
				UART_printf("The time is: %d\r\n> ", (int)sc_get_timer());
			}
		}
#endif

#if defined(WAVESCULPTOR_EXAMPLE)
		/* Send the wavesculptor drive commands every 100ms.
		 * To make this more 'realtime', we should be doing this with a timer interrupt */
		if(sc_get_timer() >= ws_timer + 100) {
			scandal_send_ws_drive_command(DC_DRIVE, velocity, motor_current);
			scandal_send_ws_drive_command(DC_POWER, 0.0, bus_current);
			scandal_send_ws_id(DC_BASE, "TRIb", 4);

			/* Update the timer */
			ws_timer = sc_get_timer();
		}
#endif

		/* Send a UART and CAN message and flash an LED every second */
		if(sc_get_timer() >= one_sec_timer + 1000) {
			/* Send the message */
			UART_printf("1 second timer %u\n\r", (unsigned int)sc_get_timer());

			/* Send a channel message with a blerg value at low priority on channel 0 */
			scandal_send_channel(TELEM_LOW, /* priority */
									0,      /* channel num */
									0xaa   /* value */
			);

			/* Twiddle the LEDs */
			toggle_red_led();

			/* Update the timer */
			one_sec_timer = sc_get_timer();
		}

#if defined(IN_CHANNEL_EXAMPLE)
		/* The old way of checking for an incoming message that you've registered for.
		 * This is a silly way to do this. A better way is to use the scandal_register_in_channel_handler
		 * feature. Your function will get called when a new message comes in */
		if(scandal_get_in_channel_rcvd_time(TEMPLATE_TEST_IN) > in_timer) {

			UART_printf("I received a channel message in the main loop on in_channel 0, value %u at time %d\n\r", 
				(unsigned int)scandal_get_in_channel_value(TEMPLATE_TEST_IN), 
				(int)scandal_get_in_channel_rcvd_time(TEMPLATE_TEST_IN)
			);

			if(scandal_get_in_channel_value(TEMPLATE_TEST_IN) == 1) {
				toggle_red_led();
			} else {
				toggle_yellow_led();
			}

			in_timer = scandal_get_in_channel_rcvd_time(TEMPLATE_TEST_IN);
		}
#endif

		/* Tickle the watchdog so we don't reset */
		WDT_Feed();
	}
}
Exemplo n.º 21
0
int main(void)
{
	
	Port_Init();
	DDRE |= (1<<3);
	DDRA |= (1<<6);
	LCDInit(LS_NONE);
	
	DDRC |= (1<<3);
	PORTC |= (1<<3);
	cal_point_1 = eeprom_read_dword(0);
	cal_point_2 = eeprom_read_dword((uint32_t*)5);
	target_feedback = (cal_point_1 + cal_point_2)/2;
	cli();
	TIMSK |= ((1 << TICIE1)| (1 << TOIE1));   //Set capture interrupt
	TCCR1B |= ((1 << ICES1) | (1<<CS10));
	TCCR3A = ((1<<COM3A1));
	TCCR3B = ((1<<CS30) | (1<<WGM33));
	ICR3 = 1000;
	OCR3A = 0;
	sei(); 
	LCDClear();
	//LCDWriteString("Powering On...");
	red_light();
	WDT_Init();
	OCR3A = (int)pwm_duty_cycle;
	_delay_ms(100);
	/*int warm_up_timer = 10;
	while(warm_up_timer > 0)
	{
		if (feedback_speed < (target_feedback - 7))
		{
			if (feedback_speed > (target_feedback - 100))
			{
				pwm_duty_cycle += 1;
			}
		}
		if (feedback_speed > (target_feedback + 7))
		{
			if(feedback_speed < (target_feedback + 100))
			{
				pwm_duty_cycle -= 1;
			}
			
		}
		if (feedback_speed < (target_feedback - 100) )
		{
			pwm_duty_cycle += 3;
		}
		if (feedback_speed > (target_feedback + 100))
		{
			pwm_duty_cycle -= 3;
		}
		if(pwm_duty_cycle > 499){pwm_duty_cycle = 499;}
		if(pwm_duty_cycle < 0 ){pwm_duty_cycle = 0;}
		
		wdt_reset();
		_delay_ms(100);
		LCDClear();
		char feedback_speed_string[4];
		snprintf(feedback_speed_string,4,"%d",feedback_speed);
		LCDWriteString(feedback_speed_string);
		warm_up_timer -= 1;
	}
	*/
	
	
	
	
    while(1)
    {
		feedback_speed = (new_feedback_speed);
        if (page == 0)
		{
			wdt_reset();
			real_speed = ((double) feedback_speed / (double) target_feedback)*4.5f;
			average_speed = (real_speed+average_speed*4.0f)/5.0f;
			int avg_speed_int = (int)average_speed;
			float avg_speed_float = average_speed - avg_speed_int;
			int avg_speed_dec = avg_speed_float*10;
			snprintf(avg_speed_string,4,"%01d.%01d",avg_speed_int,avg_speed_dec);
			LCDClear();
			LCDWriteString("Airflow: ");
			LCDWriteString(avg_speed_string);
			LCDWriteString(" m/s");
			LCDWriteStringXY(0,1,"Target: 4.5 m/s");
			wdt_reset();
			_delay_ms(100);
			wdt_reset();
			
			// speed control section
			if (feedback_speed < (target_feedback - 10))
			{
				if (feedback_speed > (target_feedback - 200))
				{
					pwm_duty_cycle += 0.25;
				}
			}
			if (feedback_speed > (target_feedback + 10))
			{
				if(feedback_speed < (target_feedback + 200))
				{
					pwm_duty_cycle -= 0.25;
				}
				
			}
			if (feedback_speed < (target_feedback - 200) )
			{
				pwm_duty_cycle += 4;
			}
			if (feedback_speed > (target_feedback + 200))
			{
				pwm_duty_cycle -= 4;
			}
			if (feedback_speed < (target_feedback - 60))
			{
				errors += 20;
			}
			if (feedback_speed > (target_feedback + 60))
			{
				errors += 20;
			}
			if (feedback_speed < (target_feedback + 40))
			{
				if (feedback_speed > (target_feedback - 40))
				{
					errors = 0;
				}
			}
			if (errors > 250) 
			{
				errors = 250;
				
			}
			if (pwm_duty_cycle > 999) {pwm_duty_cycle = 999;}
			if (pwm_duty_cycle < 0){pwm_duty_cycle = 0;}
				
		
			
			OCR3A = (int)pwm_duty_cycle;
			wdt_reset();
		}
		
		
		
		
		
		if (page == 1)
		{
			LCDClear();
			LCDWriteString("Calibration Mode");
			if(cal_number == 0)
			{
				LCDWriteStringXY(0,1,"Cal. Point 1");
			}
			if(cal_number == 1)
			{
				LCDWriteStringXY(0,1,"Cal. Point 2");
			}
			if(cal_number == 2)
			{
				LCDWriteStringXY(0,1,"Press %1 To Save");
			    _delay_ms(50);
				LCDWriteStringXY(0,1,"Press %2 To Save");
				_delay_ms(50);
				wdt_reset();
			}
			wdt_reset();
			_delay_ms(150);
			wdt_reset();
			
		}
		
		
		
		
		if (!(PINA & (1<<3)))
		{
			page++;
			while(!(PINA & (1<<3)))
			{
				wdt_reset();
			} //right
			_delay_ms(25);
			if (page > 1)
			{
				page = 0;
			}
		}
		
		
		
		if (!(PINA & (1<<0))) //up
		{
			if (page == 1)
			{
				cal_speed += 5;
				if (cal_speed > 1000)
				{
					cal_speed = 1000;
				}
				OCR3A = cal_speed;
				wdt_reset();
			}	
			_delay_ms(25);	
		}
		
		
		
		
		if (!(PINA & (1<<4))) //down
		{
			if (page == 1)
			{
				cal_speed -= 5 ;
				if (cal_speed < 0)
				{
					cal_speed = 0;
				}
				OCR3A = cal_speed;
				wdt_reset();
			}
			_delay_ms(25);
		}
		
		
		
		
		if (!(PINA & (1<<2))) //center
		{
			wdt_reset();
			if (page == 1)
			{			
				switch (cal_number)
				{
					case 0:
					cal_point_1 = feedback_speed;
					cal_number = 1;
					break;
					
					case 1:
					cal_point_2 = feedback_speed;
					cal_number = 2;
					break;
					
					case 2:
					wdt_reset();
					eeprom_write_dword(0,cal_point_1);
					eeprom_write_dword((uint32_t*)5,cal_point_2);
					wdt_reset();
					page = 0;
					cal_number = 0;
					break;
					
				}
			}
			
			
			while(!(PINA & (1<<2)))
			{
				wdt_reset();
			}
			_delay_ms(25);
		}
		if (!(PINA & (1<<1))) //left
		{
			page--;
			while(!(PINA & (1<<3)))
			{
				wdt_reset();
			}
			_delay_ms(25);
			if (page < 0)
			{
				page = 1;
			}
		}
		if (errors == 0)
		{
			green_light();
		}
		if(errors >= 250)
		{
			red_light();
		}
		
		
    }
}
Exemplo n.º 22
0
//***********************************************************************
//			主程序
//***********************************************************************
void main(void)
{
  unsigned char qq;
 // unsigned char adxl_state;
  unsigned char mmc_state;
    unsigned char eeprom_state;
  for (qq=0;qq<0xf0;qq++)
  {
  _NOP();
  }
  WDT_Init();                                   //看门狗设置
 //  _DINT();
  Clock_Init();                                 //系统时钟设置
  delay_ms(100);                                //延时100ms
  Port_Init();                                  //系统初始化,设置IO口属性
  GM8125_Init(0);
  delay_ms(100); 
  DeBug_Print_Str("System Start!\r\n");  
  TimerA_init();
 
  mmc_state = mmc_test();
  if ( mmc_state == 1)
  {
   DeBug_Print_Str("MMC Verify Success!\r\n");  
   cardSize =  MMC_ReadCardSize();
   SDsizeDisplay(cardSize); 
   SD_File_Create();
  }
  else
  {
      DeBug_Print_Str("MMC Verify Failure!\r\n");  
  }
    //延时100ms
 _EINT(); 

   eeprom_state = eeprom_test();
   if ( eeprom_state == 1)
  {
     DeBug_Print_Str("EEPROM Verify Success!\r\n");  

  }
  else
  {
      DeBug_Print_Str("EEPROM Verify Failure!\r\n");  
  }
   
      Init_ADXL345();                 	//初始化ADXL345
      devid=Single_Read_ADXL345(0X00);	//读出的数据为0XE5,表示正确
      if(devid!=0XE5)
      {				
          DeBug_Print_Str("No ADXL345\r\n");	
      }
      else
      {			
      	  DeBug_Print_Str("ADXL345 init Success!\r\n");	    
      } 

  while(1)
  {
    /*
     adxl_state = ADXL345_Work(&X_data,&Y_data,&Z_data);
     if (adxl_state == FALSE)
     {
         DeBug_Print_Str("Adxl345 no work!\r\n");	
     }
     
     delay_ms(5);
     ProcessingData();
     delay_ms(5);
     */
    
    while (0 == ConnectFlag)
    {
         gprs_band_rate();
         DeBug_Print_Str("GPRS BandRate Set OK!\r\n"); 
         delay_ms(1000);
         gprs_check_china_mobile();
         DeBug_Print_Str("GPRS Check China Mobile OK!\r\n"); 
         delay_ms(1000);
         ConnectFlag = gprs_connect_server();//while (connect ok)
         if (1 == ConnectFlag)
         {
           DeBug_Print_Str("GPRS Connect Server is OK!\r\n"); 
           LogFlag=0;   //登上服务器后将logon标志置零
         }
         else
         {
            DeBug_Print_Str("GPRS Connect Server Fail!\r\n"); 
         }
         delay_ms(1000);  
    }
    
     while(1 == ConnectFlag)
    {
      DoRcv();
      if(LogFlag)
      {
        SendData(); 
      }
     
      delay_ms(1000);  
    }  
    
      //delay_ms(1000);  

  }
}
Exemplo n.º 23
0
/*
 * main.c
 */
int main(void) {
    //WDTCTL = WDTPW | WDTHOLD;	// Stop watchdog timer
	Clock_Init();
    WDT_Init();
    WX315_Init();
	led_init();
	Init_HC05();
	TimerA_Init();
	Key_Init();
	MQ2_Init();
	Ir_Init();
	Sound_Init();

//	//__bis_SR_register(LPM0_bits + GIE);
	_EINT();

	led0_off();//默认开蓝牙使能
	delay_ms(1000);

	while(1){
		if(temp_tx_flag==1){
			for(i=0;i<8;i++){
				UartPutchar(ch[i]);
			}
			temp_tx_flag=0;
		}
		if(flag_mq2==1){
			flag_mq2=0;
			UartPutchar('V');//Vapour 烟雾传感器 有漏气 向APP发送指令'V'
		}
		if(flag_ir==1){
			flag_ir=0;
			UartPutchar('I');//Ir 红外传感器 有漏气 向APP发送指令'I'
		}
		if(flag_sound==1){
			flag_sound=0;
			UartPutchar('S');//Sound 声音传感器 有大风 向APP发送指令'S'
		}
		switch(uart_temp){

			 		//color
			 		case 'r':
			 			RGB_r();
			 			uart_temp=' ';
			 			break;
			 		case 'o':
			 			RGB_o();
			 			uart_temp=' ';
			 			break;
			 		case 'y':
			 			RGB_y();
			 			uart_temp=' ';
			 			break;
			 		case 'g':
			 			RGB_g();
			 			uart_temp=' ';
			 			break;
			 		case 'b':
			 			RGB_b();
			 			uart_temp=' ';
			 			break;
			 		case 'p':
			 			RGB_p();
			 			uart_temp=' ';
			 			break;
			 		case 'w':
			 			RGB_w();
			 			uart_temp=' ';
			 			break;
			 		case 'd'://关灯 dieout
			 			RGB_d();
			 			uart_temp=' ';
			 			break;
			 			//***********************************************************
			 		case 'm'://开窗 m motor
			 			Window_m();
			 			uart_temp=' ';
			 			break;
			 		case 'n'://关窗
			 			Window_n();
			 			uart_temp=' ';
			 			break;
			 			//***********************************************************
			 		case 'u'://加热 u up
			 			TempNew_u();
			 			uart_temp=' ';
			 			break;
			 		case 'v'://制冷
			 			TempNew_v();
			 			uart_temp=' ';
			 			break;
			 		case 'x'://停止加热
			 			TempNew_x();
			 			uart_temp=' ';
			 			break;
			 		case 'z'://停止制冷
			 			TempNew_z();
			 			uart_temp=' ';
			 			break;
			 			//************************************************************
			 		case 'c'://回家模式
			 			Home_Mode_Backhome();
			 			break;
			 		case 'e'://浪漫模式
			 			Home_Mode_Romatic();
			 			break;
			 		case 'f'://离家模式
			 			Home_Mode_Awayhome();
			 			break;


			 		default:break;
			 		}
	}

	
	//return 0;
}