Ejemplo n.º 1
0
/** @brief Function for main application entry.
 */
int main(void)
{  
    gpiote_init();
    ppi_init();
    timer2_init();

    // Enable interrupt on Timer
    NVIC_EnableIRQ(TIMER2_IRQn);
    __enable_irq();

    // Enabling constant latency as indicated by PAN 11 "HFCLK: Base current with HFCLK 
    // running is too high" found at Product Anomaly document found at
    // https://www.nordicsemi.com/eng/Products/Bluetooth-R-low-energy/nRF51822/#Downloads
    //
    // @note This example does not go to low power mode therefore constant latency is not needed.
    //       However this setting will ensure correct behaviour when routing TIMER events through 
    //       PPI (shown in this example) and low power mode simultaneously.
    NRF_POWER->TASKS_CONSTLAT = 1;

    // Start the timer.
    NRF_TIMER2->TASKS_START = 1;
    while (true)
    {
        // Do nothing.
    }
}
Ejemplo n.º 2
0
void main_init(void) {
  uint8_t itmp;

  serial_init();
 
  PORTD |= 7<<PD5;
  DDRD |= 15<<PD4;
  fdevopen((void*)serial_putc, (void*)serial_get); 
  
  serial_set_echo(SERIAL_ECHO_OFF);

  for(itmp=0; itmp<20; itmp++) printf("\r\n");
  printf("Initialization\r\n");

  printf("Initializing delay timer (2)...\r\n");
  timer2_init();
  adc_init();
  
  timer2_wait(STD_DELAY);

  printf("Disable JTAG...\r\n");
  cli();
  MCUCSR |= (1<<JTD);
  MCUCSR |= (1<<JTD); // 2 mal in Folge ,vgl. Datenblatt fuer mehr Information
  sei();
  timer2_wait(STD_DELAY);

  initial_power_check();

  printf("EEPROM Check:");
  if(eeprom_is_config_valid()==1) printf(COLOR_GREEN" Valid!"COLOR_OFF);
  else printf(COLOR_RED" Invalid!"COLOR_OFF);
  printf("\r\n");
}
Ejemplo n.º 3
0
/*==================================================================================
* 函 数 名: Set_System
* 参    数: None
* 功能描述:  初始化系统
* 返 回 值: None
* 备    注: 
* 作    者: gaodb
* 创建时间: 2012.10
==================================================================================*/
void Set_System(void)
{  
    rcc_init();
		
    peri_clk_init();  
		
  	NVIC_Configuration();  
  	
    pins_init();  
    
    systick_init();
		
    timer2_init();
    timer4_init(); 
    
    RAY12_ADC_Init();
    
    LCD_Config();    
    DispInit();
    
    uart1_init(BAUD_RATE_57600);	
		uart2_init(BAUD_RATE_57600);
		
		dac1_init();
		
    sys_variable_init();
}
Ejemplo n.º 4
0
/**
 * @brief Function for application main entry.
 */
int main(void)
{
    gpiote_init();
    bsp_configuration();
    ppi_init();
    timer2_init();

    // Enabling constant latency as indicated by PAN 11 "HFCLK: Base current with HFCLK 
    // running is too high" found at Product Anomaly document found at
    // https://www.nordicsemi.com/eng/Products/Bluetooth-R-low-energy/nRF51822/#Downloads
    //
    // @note This example does not go to low power mode therefore constant latency is not needed.
    //       However this setting will ensure correct behaviour when routing TIMER events through 
    //       PPI (shown in this example) and low power mode simultaneously.
    NRF_POWER->TASKS_CONSTLAT = 1;

    // Enable interrupt on Timer 2.
    NVIC_EnableIRQ(TIMER2_IRQn);
    __enable_irq();

    // Workaround for PAN-73: Use of an EVENT from any TIMER module to trigger a TASK in GPIOTE or 
    // RTC using the PPI could fail under certain conditions.
    *(uint32_t *)0x4000AC0C = 1;    
    // Start the timer.
    NRF_TIMER2->TASKS_START = 1;

    while (true)
    {
        // Do nothing.
    }
}
Ejemplo n.º 5
0
int main( void )
{
    uint16_t mtr_cnt[4] = {0,0,0,0};
	
	cli();

	palsetimer_init(); /* タイマ1インプットキャプチャ設定 */
	timer2_init();     /* タイマ2割り込み設定 */
	dig_init();        /* 出力ポート指定、初期化 */
    sei();             /* SREG の設定 - 割り込み有効 */

	rpm   = 4321;
	count = 0;
	wait_time = 0;                /* タイマークリア */

	while(1)
	{
		dig_putrpm();             /* 前の RPM を1sec表示。その間にモーターカウント。 */

		/* RPM を算出
		 * 実測値より、5パルスあたり1回転のため、
		 * rpm = mtr_cnt × 60 ÷ (5*サンプリングsec)
		 */
		mtr_cnt[sec_cnt] = count;
		count = 0;                /* 1secのカウント開始 */
		rpm = (mtr_cnt[0] + mtr_cnt[1] + mtr_cnt[2] + mtr_cnt[3]) * (60/(5*RPM_SAMPLING_SEC));
		
		sec_cnt++;
		sec_cnt &= 0x3;           /* 0-3を繰り返す */

	}


}
Ejemplo n.º 6
0
void board_init(void)
{
  /* SysTick end of count event each 10ms */
  RCC_GetClocksFreq(&RCC_Clocks);
  SysTick_Config(RCC_Clocks.HCLK_Frequency / 100);
  timer2_init();
  timer14_init();
  Usart_Init(USART2,9600);
  send_data(USART2, "uart2 is OK!\r\n", strlen("uart2 is OK!\r\n"));
  //不同的传感器的引脚及用到的板级外设不同
  //sensor_init();
#if defined (BEEP)
  //蜂鸣器用作调试设备
  beep_init();
  Delay(20);
  BEEP_OFF();
#endif
#if defined (DEBUG)
  //串口用作调试端口
  Usart_Init(DEBUG_UART,115200);
  send_data(DEBUG_UART, "uart is OK!\r\n", strlen("uart is OK!\r\n"));
#endif
#if defined (EEPROM)
  //24cxx IIC接口初始化
  IIC_Init();
#endif
} 
Ejemplo n.º 7
0
Archivo: main.c Proyecto: edwios/IoT
void main(void)
{
  u8 TxFlag=0;
  u8 RxFlag=0;

  InitSfr();                                               //PIC16 Register Initialization
  PowerUpDelay();                                          //Power on delay  
  InitPort();                                              //PIC16 IO port Initialization
  timer1_init();
  timer2_init();
  LCD_Init();                                              //LCD initialize
  BeepOff();                                               //Close buzzer
  ModuleSelectModeEntryCheck();                            //Confirm whether you can enter module select mode
  Uart_init();
  PowerOnMusic();                                          //Power on music
  
  while(1)
  { 
    MenuConfig();                                          //Menu config & display
    if(gb_ModuleWorkEnableFlag)
    {
      RFM22B_Running(gb_SystemMode,gb_ModuleWorkMode,gb_ParameterChangeFlag,&TxFlag,&RxFlag,&gb_RF_RSSI);
        
      if(TxFlag==1)                                        //Sent successfully
      {
        TxFlag=0; 
        gw_SendDataCount++;
        if(gw_SendDataCount>9999){gw_SendDataCount=0;}
      }
      if(RxFlag==1)                                        //Successfully received
      {
        RxFlag=0; 
        gw_ReceiveDataCount++;
        if(gw_ReceiveDataCount>9999){gw_ReceiveDataCount=0;}
      }
          
            
      if(gb_ParameterChangeFlag==1){gb_ParameterChangeFlag=0;}    //clear parameter flag
      if(gb_ModuleWorkMode!=C_ModuleWorkMode_FSK && gb_ModuleWorkMode!=C_ModuleWorkMode_OOK && gb_ModuleWorkMode!=C_ModuleWorkMode_LoRa)
      {
        gb_StatusTx=0;
        gb_StatusRx=0;
      }
    }
    else
    {
      gb_StatusTx=0;
      gb_StatusRx=0;
    }
    if(gb_ErrorFlag!=1)
    {  
      TxLED_Deal();                                        //Tx LED display deal
      RxLED_Deal();                                        //Rx LED display deal 
    }
  }
}
Ejemplo n.º 8
0
/**
 * @brief Function for application main entry.
 */
int main(void)
{
    timer0_init(); // Timer used to blink the LEDs.
    timer1_init(); // Timer to generate events on even number of seconds.
    timer2_init(); // Timer to generate events on odd number of seconds.
    ppi_init();    // PPI to redirect the event to timer start/stop tasks.

    uint32_t err_code;
    const app_uart_comm_params_t comm_params =
     {
         RX_PIN_NUMBER,
         TX_PIN_NUMBER,
         RTS_PIN_NUMBER,
         CTS_PIN_NUMBER,
         APP_UART_FLOW_CONTROL_ENABLED,
         false,
         UART_BAUDRATE_BAUDRATE_Baud115200
     };

    APP_UART_FIFO_INIT(&comm_params,
                    UART_RX_BUF_SIZE,
                    UART_TX_BUF_SIZE,
                    uart_error_handle,
                    APP_IRQ_PRIORITY_LOW,
                    err_code);

    APP_ERROR_CHECK(err_code);

    // Enabling constant latency as indicated by PAN 11 "HFCLK: Base current with HFCLK 
    // running is too high" found at Product Anomaly document found at
    // https://www.nordicsemi.com/eng/Products/Bluetooth-R-low-energy/nRF51822/#Downloads
    //
    // @note This example does not go to low power mode therefore constant latency is not needed.
    //       However this setting will ensure correct behaviour when routing TIMER events through 
    //       PPI (shown in this example) and low power mode simultaneously.
    NRF_POWER->TASKS_CONSTLAT = 1;
    
    // Start clock.
    nrf_drv_timer_enable(&timer0);
    nrf_drv_timer_enable(&timer1);
    nrf_drv_timer_enable(&timer2);

    // Loop and increment the timer count value and capture value into LEDs. @note counter is only incremented between TASK_START and TASK_STOP.
    while (true)
    {

        printf("Current count: %d\n\r", (int)nrf_drv_timer_capture(&timer0,NRF_TIMER_CC_CHANNEL0));

        /* increment the counter */
        nrf_drv_timer_increment(&timer0);

        nrf_delay_ms(100);
    }
}
Ejemplo n.º 9
0
int main() {
	ioinit();
	timer2_init();
	timer2_overflow_hook = timer2_hook;
	timer1_init();
	
	_delay_ms(100);
	spi_init();

	sound_reset();
	
	usart_init(1);//	usart_init(23); 	// 9600bps

  	spdif_configure();
	ad1955_configure();
	ad1955_mute();
#define NO_NOISE_MEASURE
#ifdef NOISE_MEASURE
	ad1955_unmute();
	cli();
	set_sleep_mode(SLEEP_MODE_PWR_DOWN);
	for(;;) {
	sleep_mode();
	}
#endif	
	
	spdif_selectChannel(1);
	
   	spdif_dumpRegisters();
	
	printf("\n\nSVODAC V%s\n", idstring);

	for (;;) {
		if (main_state_machine() == STATE_READY) {
			if ((REQUEST_STATUS & _BV(REQUEST_MUTE)) != 0) {
				ad1955_mute();
			} else 	if ((REQUEST_STATUS & _BV(REQUEST_UNMUTE)) != 0) {
				ad1955_unmute();
			} 
			
			if ((REQUEST_STATUS & _BV(REQUEST_STOP)) != 0) {
				//printf("STOP");
				spdif_stop();
			} else if ((REQUEST_STATUS & _BV(REQUEST_RUN)) != 0) {
				//printf("RUN");
				spdif_run();
			}
			REQUEST_STATUS = 0;
			sleep_mode();
		}
	}

	return 0; // make happy
}
Ejemplo n.º 10
0
void SERVO_init(void){
	//timer0 initlization for auto scan.
	timer0_comp_init();
	timer2_init();
	SERVO_DDR |= (_BV(SERVO_ENA)|_BV(SERVO_DIR)|_BV(SERVO_PUL));
	SERVO_PORT |= (_BV(SERVO_ENA));
	SERVO_enable();
	
	servo_position_buffer = ucHoldingBuf[P_SERVO_POSITION_REG];

	timer2_enable();
}
Ejemplo n.º 11
0
/*------------------------------------------------------------------------
	SPI制御レジスタをマスターモードで初期化する.
    -d0 | fOSC/2  ... 6MHz
    -d1 | fOSC/4  ... 3MHz
    -d2 | fOSC/8  ... 1.5MHz
    -d3 | fOSC/16 ... 750kHz
    -d4 | fOSC/32 ... 375kHz
    -d5 | fOSC/64 ... 187kHz
    -d6 | fOSC/128...  93kHz
    -d7以降はリニアに遅くなります. 
 *------------------------------------------------------------------------
 */
void timer2_interval(uchar spi_delay)
{
	if	   (spi_delay==0) {timer2_init(0,2-1);}		//-d0 | fOSC/2  ... 6MHz
	else if(spi_delay==1) {timer2_init(0,4-1);}		//-d1 | fOSC/4  ... 3MHz
	else if(spi_delay==2) {timer2_init(0,8-1);}		//-d2 | fOSC/8  ... 1.5MHz
	else if(spi_delay==3) {timer2_init(1,4-1);}		//-d3 | fOSC/16 ... 750kHz
	else if(spi_delay==4) {timer2_init(1,8-1);}		//-d4 | fOSC/32 ... 375kHz
	else if(spi_delay==5) {timer2_init(2,4-1);}		//-d5 | fOSC/64 ... 187kHz
	else if(spi_delay>=6) {
		timer2_init(2,spi_delay);					//-d6〜|fOSC/128 ... 93kHz
	}
}
Ejemplo n.º 12
0
/********************************************************************
 *	初期化関数
 ********************************************************************
 */
static void	InitializeSystem(void)
{
#if RAM_SERIAL
	extern void set_serial_number(void);

	set_serial_number();
#endif
#if defined(__18F14K50)
	// 入力ピンをデジタルモードにする.
	ANSEL=0;
	ANSELH=0;
#endif
    ADCON1 = 0x0F;			//Need to make sure RB4 can be used as a digital input pin

#if	1
	// HIDaspx , PICwriter用 portb,portcを全入力にする.
	TRISB = 0xFF;
	TRISC = 0xFF;
#endif

#if	defined(USE_USB_BUS_SENSE_IO)
	tris_usb_bus_sense = INPUT_PIN;
#endif

#if	defined(USE_SELF_POWER_SENSE_IO)
	tris_self_power	= INPUT_PIN;
#endif
	mInitializeUSBDriver();
	UserInit();

#if	USE_PS2KEYBOARD		// PS/2キーボードI/F を使用する.
	kbd_init();
#endif

#if	TIMER2_INTERRUPT

//	timer2_init(0x80 |(15<<3)| 2,255);	// 割り込みON,postscale 1/16,prescale 1/16,1/256 = 183.10 H
//	timer2_init(0x80 |(14<<3)| 2,249);	// 割り込みON,postscale 1/15,prescale 1/16,1/250 = 200Hz
//	timer2_init(0x80 |(14<<3)| 2, 49);	// 割り込みON,postscale 1/15,prescale 1/16,1/50 = 1000Hz
	timer2_init(0x80 |(14<<3)| 2,  4);	// 割り込みON,postscale 1/15,prescale 1/16,1/5  =  10kHz

	// 割り込み許可.
	InitTimer2InterruptLow();			// Timer2割り込みを low Priorityに設定する.

#else

	INTCONbits.GIEL = 0; 		// Low  Priority 割り込みを禁止.
	INTCONbits.GIEH = 0; 		// High Priority 割り込みを禁止.
#endif
}
Ejemplo n.º 13
0
// ------------------------------------------------------------------------
// main
// ------------------------------------------------------------------------
void c_main()
{
  io_printf (IO_STD, "starting dumped packet bouncer\n");

  timer_init (TICK_PERIOD);  // setup timer to maybe turn on bouncing

  cc_init ();                // setup comms. cont. interrupt when not full

  router_init ();            // setup router to interrupt when dumping

  #ifdef DEBUG
    timer2_init ();          // setup timer2 for profiling
  #endif

  cpu_sleep ();		     // Send core to sleep
}
Ejemplo n.º 14
0
uint16_t MPU6000::init()
{
    if (_initialised) return _product_id;
    _initialised = true;
    SPI.begin();
    SPI.setClockDivider (SPI_CLOCK_DIV16); // 1MHZ SPI rate  
    
    // we need to stop the barometer from holding the SPI bus
    pinMode (40, OUTPUT);
    digitalWrite (40, HIGH);
     
    hardware_init();
    timer2_init ();
    timer2_start ();
    return _product_id;
}
Ejemplo n.º 15
0
int main(void)
{
  /* Intitialization */
  gpiote_init();
  ppi_init();
  timer2_init();

  /* Enable interrupt on Timer 2*/
  NVIC_EnableIRQ(TIMER2_IRQn);
  __enable_irq();

  /* Start clock */
  NRF_TIMER2->TASKS_START = 1;
  while (true)
  {
  }
}
Ejemplo n.º 16
0
void init_devices2 (void)
{
 DDRA=0x00;
DDRB&=~_BV(4);
DDRD&=~_BV(6);

PORTA=0xFF;
PORTB|=_BV(4);
PORTD|=_BV(6);
 cli();    //Clears the global interrupts
  DDRA |= (1 << PA7); // making servo contol pins as output
  DDRD |= (1 << PD7);
 uart0_init();
 port_init();
 left_position_encoder_interrupt_init();
 right_position_encoder_interrupt_init();
 timer2_init();
 adc_init();
 sei();          //Enables the global interrupts
}
Ejemplo n.º 17
0
int
main (void)
{
    IRMP_DATA irmp_data;
        
    irmp_init();                                                            // initialize irmp
    timer2_init();                                                          // initialize timer2

    for (;;)
    {
        if (irmp_get_data (&irmp_data))
        {
            // ir signal decoded, do something here...
            // irmp_data.protocol is the protocol, see irmp.h
            // irmp_data.address is the address/manufacturer code of ir sender
            // irmp_data.command is the command code
            // irmp_protocol_names[irmp_data.protocol] is the protocol name (if enabled, see irmpconfig.h)
        }
    }
}
Ejemplo n.º 18
0
void block_detect()
{
			stop();	
			ssss =SREG;
			cli();
			timer0_init();
			TIMSK |= (1 << OCIE0) | (1 << TOIE0); // timer 0 compare match and overflow interrupt enable 
			sei();
			SREG = ssss;
			drop_down();
			_delay_ms(2000);
			pickup();
			//drop_down();
			
			ssss =SREG;
			cli();
			timer2_init();
			sei();
			ssss = SREG;
			forward();	
}
Ejemplo n.º 19
0
void My_System_Init(void)
{
uint8_t flag, i=0;
	NVIC_Configuration();
	delay_init(72);	   	 		//延时初始化	
	for(i=0;i<5;i++)
		delay_Ms_Loop(1000);	//上电短延时	确保供电稳定
	
	LED_Init();	
	LEDALL_ON;
	timer2_init();					//PWM输出定时器初始化
	timer3_init();					//PWM输出定时器初始化
	IIC_Init();
	uart_init(38400); 	    //调试用串口初始化
	My_usart2_init(38400);	//蓝牙用串口初始化
	printf("欢迎使用启天科技BUTTERFLY四旋翼\r\n");
	printf("QQ群:471023785\r\n");
	LEDALL_OFF;
	MPU6050_Init();					//6050初始化
	SPI1_INIT();						//SPI初始化,用于nRF模块
	flag = NRF_CHECK();			//检查NRF模块是否正常工作
	if(flag != 1)
	{
		while(1)
		{
			LEDALL_OFF;
			delay_Ms_Loop(200);
			LEDALL_ON;
			delay_Ms_Loop(200);
		}
	}
	NRF24L01_INIT();						//nRF初始化
	SetRX_Mode();								//设置为接收模式
	NRF24L01_INIT();						//nRF初始化
	NRF_GPIO_Interrupt_Init();	//nRF使用的外部中断的引脚初始化
	tim4_init();								//定时中断,作为系统的控制频率	
	adcInit();									//ADC初始化,测量电池电压
}
Ejemplo n.º 20
0
/*!
 * \fn main()
 * \brief just to test PWM module
 * \return none
 */
int main()
{
	PCA0MD = 0x00;
	PORT_Init();
	OSCILLATOR_Init();
	PCA0_Init();
	timer_0_1_init();
	timer2_init();
	IN1 = 0;
	IN2 = 1;
	IN3 = 0;
	IN4 = 1;
	EA = 1;
	//set_pwm_0_duty_cycle(20);
	//set_pwm_1_duty_cycle(16);
	while (1)
	{
		//set_pwm_0_duty_cycle(700);
		//set_pwm_1_duty_cycle(660);
		set_wheel_1_speed(50);
		set_wheel_0_speed(50);
	}
}
Ejemplo n.º 21
0
int main(void) {
    uint16_t adc_data = 0;
    
    sei(); // Enable interrupts
    fosc_cal(); // Set calibrated 1MHz system clock
    portb_init(); // Set up port B
    usart_init(); // Set up the USART
    timer2_init();  // Set up, stop, and reset timer2
    timer0_init();
    usart_puts("Initialize ADC\r\n");
    adc_init();
    usart_puts("Initialize LCD\r\n");
    lcd_init(); // From LDC_driver
    usart_puts("Start main loop\r\n");
    lcd_puts("Hello",0); // From LCD_functions
    timer2_start(); // Start stimulus
    adc_mux(1); // Switch to the voltage reader at J407
    for(;;) {
        adc_read(&adc_data);
        adc_report(adc_data);
        OCR0A = (uint8_t)(adc_data);
    }// end main for loop
} // end main
Ejemplo n.º 22
0
int main()
{
	/* Semaphore creation */
	vSemaphoreCreateBinary(ahrs_task_semaphore);

	/* Peripheral initialization */
	NVIC_PriorityGroupConfig(NVIC_PriorityGroup_4);
	led_init();
	debug_port_init();
	usart3_init(57600);
	i2c1_init();
	timer2_init();

	//Make sure all the peripheral is finished the initialization
	delay_ms(1000);

	/* Device initialization */
	while(mpu6050_init());

	led_on(LED1); //Initialization is finished

	/* Task creation */
	//Attitude and Heading Reference System (AHRS) task
	xTaskCreate(ahrs_task, (portCHAR *)"AHRS task",
		4096, NULL, tskIDLE_PRIORITY + 2, NULL);

	//USART plot task
	xTaskCreate(usart_plot_task, (portCHAR *)"USART plot task",
		2048, NULL, tskIDLE_PRIORITY + 1, NULL);


	/* Start schedule */
	vTaskStartScheduler();

	return 0;
}
Ejemplo n.º 23
0
/*-------------------------------------------------------------------------------------------------------------------------------------------
 * main function
 *-------------------------------------------------------------------------------------------------------------------------------------------
 */
int
main ()
{
    static uint_fast8_t     last_ldr_value = 0xFF;
    struct tm               tm;
    LISTENER_DATA           lis;
    ESP8266_INFO *          esp8266_infop;
    uint_fast8_t            esp8266_is_up = 0;
    uint_fast8_t            code;

#if SAVE_RAM == 0
    IRMP_DATA               irmp_data;
    uint32_t                stop_time;
    uint_fast8_t            cmd;
#endif
    uint_fast8_t            status_led_cnt              = 0;
    uint_fast8_t            display_flag                = DISPLAY_FLAG_UPDATE_ALL;
    uint_fast8_t            show_temperature            = 0;
    uint_fast8_t            time_changed                = 0;
    uint_fast8_t            power_is_on                 = 1;
    uint_fast8_t            night_power_is_on           = 1;
    uint_fast8_t            ldr_value;
    uint_fast8_t            ap_mode = 0;

    SystemInit ();
    SystemCoreClockUpdate();                                                // needed for Nucleo board

#if defined (STM32F103)                                                     // disable JTAG to get back PB3, PB4, PA13, PA14, PA15
    RCC_APB2PeriphClockCmd(RCC_APB2Periph_AFIO, ENABLE);                    // turn on clock for the alternate function register
    GPIO_PinRemapConfig(GPIO_Remap_SWJ_JTAGDisable, ENABLE);                // disable the JTAG, enable the SWJ interface
#endif

    log_init ();                                                            // initilize logger on uart

#if SAVE_RAM == 0
    irmp_init ();                                                           // initialize IRMP
#endif
    timer2_init ();                                                         // initialize timer2 for IRMP, DCF77, EEPROM etc.
    delay_init (DELAY_RESOLUTION_1_US);                                     // initialize delay functions with granularity of 1 us
    board_led_init ();                                                      // initialize GPIO for green LED on disco or nucleo board
    button_init ();                                                         // initialize GPIO for user button on disco or nucleo board
    rtc_init ();                                                            // initialize I2C RTC
    eeprom_init ();                                                         // initialize I2C EEPROM

    if (button_pressed ())                                                  // set ESP8266 into flash mode
    {
        board_led_on ();
        esp8266_flash ();
    }

    log_msg ("\r\nWelcome to WordClock Logger!");
    log_msg ("----------------------------");
    log_str ("Version: ");
    log_msg (VERSION);

    if (rtc_is_up)
    {
        log_msg ("rtc is online");
    }
    else
    {
        log_msg ("rtc is offline");
    }

    if (eeprom_is_up)
    {
        log_msg ("eeprom is online");
        read_version_from_eeprom ();
        log_printf ("current eeprom version: 0x%08x\r\n", eeprom_version);

        if ((eeprom_version & 0xFF0000FF) == 0x00000000)
        {                                                               // Upper and Lower Byte must be 0x00
            if (eeprom_version >= EEPROM_VERSION_1_5_0)
            {
#if SAVE_RAM == 0
                log_msg ("reading ir codes from eeprom");
                remote_ir_read_codes_from_eeprom ();
#endif
                log_msg ("reading display configuration from eeprom");
                display_read_config_from_eeprom ();

                log_msg ("reading timeserver data from eeprom");
                timeserver_read_data_from_eeprom ();
            }

            if (eeprom_version >= EEPROM_VERSION_1_7_0)
            {
                log_msg ("reading night timers from eeprom");
                night_read_data_from_eeprom ();
            }
        }
    }
    else
    {
        log_msg ("eeprom is offline");
    }

    ldr_init ();                                                            // initialize LDR (ADC)
    display_init ();                                                        // initialize display

    dcf77_init ();                                                          // initialize DCF77

    night_init ();                                                          // initialize night time routines

    short_isr = 1;
    temp_init ();                                                           // initialize DS18xx
    short_isr = 0;

    display_reset_led_states ();
    display_mode                = display_get_display_mode ();
    animation_mode              = display_get_animation_mode ();
    auto_brightness             = display_get_automatic_brightness_control ();

    if (eeprom_is_up)
    {
        if (eeprom_version != EEPROM_VERSION)
        {
            log_printf ("updating EEPROM to version 0x%08x\r\n", EEPROM_VERSION);

            eeprom_version = EEPROM_VERSION;
            write_version_to_eeprom ();
#if SAVE_RAM == 0
            remote_ir_write_codes_to_eeprom ();
#endif
            display_write_config_to_eeprom ();
            timeserver_write_data_to_eeprom ();
            night_write_data_to_eeprom ();
            eeprom_version = EEPROM_VERSION;
        }
    }

    ds3231_flag = 1;

#if SAVE_RAM == 0
    stop_time = uptime + 3;                                                 // wait 3 seconds for IR signal...
    display_set_status_led (1, 1, 1);                                       // show white status LED

    while (uptime < stop_time)
    {
        if (irmp_get_data (&irmp_data))                                     // got IR signal?
        {
            display_set_status_led (1, 0, 0);                               // yes, show red status LED
            delay_sec (1);                                                  // and wait 1 second
            (void) irmp_get_data (&irmp_data);                              // flush input of IRMP now
            display_set_status_led (0, 0, 0);                               // and switch status LED off

            log_msg ("calling IR learn function");
            if (remote_ir_learn ())                                         // learn IR commands
            {
                remote_ir_write_codes_to_eeprom ();                         // if successful, save them in EEPROM
            }
            break;                                                          // and break the loop
        }
    }
#endif

    display_set_status_led (0, 0, 0);                                       // switch off status LED

    esp8266_init ();
    esp8266_infop = esp8266_get_info ();

    while (1)
    {
        if (! ap_mode && esp8266_is_up && button_pressed ())                // if user pressed user button, set ESP8266 to AP mode
        {
            ap_mode = 1;
            log_msg ("user button pressed: configuring esp8266 as access point");
            esp8266_is_online = 0;
            esp8266_infop->is_online = 0;
            esp8266_infop->ipaddress[0] = '\0';
            esp8266_accesspoint ("wordclock", "1234567890");
        }


        if (status_led_cnt)
        {
            status_led_cnt--;

            if (! status_led_cnt)
            {
                display_set_status_led (0, 0, 0);
            }
        }

        if ((code = listener (&lis)) != 0)
        {
            display_set_status_led (1, 0, 0);                               // got net command, light red status LED
            status_led_cnt = STATUS_LED_FLASH_TIME;

            switch (code)
            {
                case LISTENER_SET_COLOR_CODE:                               // set color
                {
                    display_set_colors (&(lis.rgb));
                    log_printf ("command: set colors to %d %d %d\r\n", lis.rgb.red, lis.rgb.green, lis.rgb.blue);
                    break;
                }

                case LISTENER_POWER_CODE:                                   // power on/off
                {
                    if (power_is_on != lis.power)
                    {
                        power_is_on = lis.power;
                        display_flag = DISPLAY_FLAG_UPDATE_ALL;
                        log_msg ("command: set power");
                    }
                    break;
                }

                case LISTENER_DISPLAY_MODE_CODE:                            // set display mode
                {
                    if (display_mode != lis.mode)
                    {
                        display_mode = display_set_display_mode (lis.mode);
                        display_flag = DISPLAY_FLAG_UPDATE_ALL;
                        log_printf ("command: set display mode to %d\r\n", display_mode);
                    }
                    break;
                }

                case LISTENER_ANIMATION_MODE_CODE:                          // set animation mode
                {
                    if (animation_mode != lis.mode)
                    {
                        animation_mode = display_set_animation_mode (lis.mode);
                        animation_flag = 0;
                        display_flag = DISPLAY_FLAG_UPDATE_ALL;
                        log_printf ("command: set animation mode to %d\r\n", animation_flag);
                    }
                    break;
                }

                case LISTENER_DISPLAY_TEMPERATURE_CODE:                     // set animation mode
                {
                    show_temperature = 1;
                    log_msg ("command: show temperature");
                    break;
                }

                case LISTENER_SET_BRIGHTNESS_CODE:                          // set brightness
                {
                    if (auto_brightness)
                    {
                        auto_brightness = 0;
                        last_ldr_value = 0xFF;
                        display_set_automatic_brightness_control (auto_brightness);
                    }
                    display_set_brightness (lis.brightness);
                    display_flag = DISPLAY_FLAG_UPDATE_NO_ANIMATION;
                    log_printf ("command: set brightness to %d, disable autmomatic brightness control per LDR\r\n", lis.brightness);
                    break;
                }

                case LISTENER_SET_AUTOMATIC_BRIHGHTNESS_CODE:               // automatic brightness control on/off
                {
                    if (lis.automatic_brightness_control)
                    {
                        auto_brightness = 1;
                        log_msg ("command: enable automatic brightness control");
                    }
                    else
                    {
                        auto_brightness = 0;
                        log_msg ("command: disable automatic brightness control");
                    }

                    last_ldr_value = 0xFF;
                    display_set_automatic_brightness_control (auto_brightness);
                    break;
                }

                case LISTENER_TEST_DISPLAY_CODE:                            // test display
                {
                    log_msg ("command: start display test");
                    display_test ();
                    break;
                }

                case LISTENER_SET_DATE_TIME_CODE:                           // set date/time
                {
                    if (rtc_is_up)
                    {
                        rtc_set_date_time (&(lis.tm));
                    }

                    if (hour != (uint_fast8_t) lis.tm.tm_hour || minute != (uint_fast8_t) lis.tm.tm_min)
                    {
                        display_flag = DISPLAY_FLAG_UPDATE_ALL;
                    }

                    wday   = lis.tm.tm_wday;
                    hour   = lis.tm.tm_hour;
                    minute = lis.tm.tm_min;
                    second = lis.tm.tm_sec;

                    log_printf ("command: set time to %s %4d-%02d-%02d %02d:%02d:%02d\r\n",
                                wdays_en[lis.tm.tm_wday], lis.tm.tm_year + 1900, lis.tm.tm_mon + 1, lis.tm.tm_mday,
                                lis.tm.tm_hour, lis.tm.tm_min, lis.tm.tm_sec);
                    break;
                }

                case LISTENER_GET_NET_TIME_CODE:                            // get net time
                {
                    net_time_flag = 1;
                    log_msg ("command: start net time request");
                    break;
                }

                case LISTENER_IR_LEARN_CODE:                                // IR learn
                {
#if SAVE_RAM == 0
                    log_msg ("command: learn IR codes");

                    if (remote_ir_learn ())
                    {
                        remote_ir_write_codes_to_eeprom ();
                    }
#endif
                    break;
                }

                case LISTENER_SAVE_DISPLAY_CONFIGURATION:                   // save display configuration
                {
                    display_write_config_to_eeprom ();
                    log_msg ("command: save display settings");
                    break;
                }
            }
        }

        if (auto_brightness && ldr_poll_brightness (&ldr_value))
        {
            if (ldr_value + 1 < last_ldr_value || ldr_value > last_ldr_value + 1)           // difference greater than 2
            {
                log_printf ("ldr: old brightnes: %d new brightness: %d\r\n", last_ldr_value, ldr_value);
                last_ldr_value = ldr_value;
                display_set_brightness (ldr_value);
                display_flag = DISPLAY_FLAG_UPDATE_NO_ANIMATION;
            }
        }

        if (!esp8266_is_up)                                                 // esp8266 up yet?
        {
            if (esp8266_infop->is_up)
            {
                esp8266_is_up = 1;
                log_msg ("esp8266 now up");
            }
        }
        else
        {                                                                   // esp8266 is up...
            if (! esp8266_is_online)                                        // but not online yet...
            {
                if (esp8266_infop->is_online)                               // now online?
                {
                    char buf[32];
                    esp8266_is_online = 1;

                    log_msg ("esp8266 now online");
                    sprintf (buf, "  IP %s", esp8266_infop->ipaddress);
                    display_banner (buf);
                    display_flag = DISPLAY_FLAG_UPDATE_ALL;

                    net_time_flag = 1;
                }
            }
        }

        if (dcf77_time(&tm))
        {
            display_set_status_led (1, 1, 0);                       // got DCF77 time, light yellow = green + red LED

            status_led_cnt = 50;

            if (rtc_is_up)
            {
                rtc_set_date_time (&tm);
            }

            if (hour != (uint_fast8_t) tm.tm_hour || minute != (uint_fast8_t) tm.tm_min)
            {
                display_flag = DISPLAY_FLAG_UPDATE_ALL;
            }

            wday        = tm.tm_wday;
            hour        = tm.tm_hour;
            minute      = tm.tm_min;
            second      = tm.tm_sec;

            log_printf ("dcf77: %s %4d-%02d-%02d %02d:%02d:%02d\r\n",
                         wdays_en[tm.tm_wday], tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday, tm.tm_hour, tm.tm_min, tm.tm_sec);
        }

        if (ds3231_flag)
        {
            if (rtc_is_up && rtc_get_date_time (&tm))
            {
                if (hour != (uint_fast8_t) tm.tm_hour || minute != (uint_fast8_t) tm.tm_min)
                {
                    display_flag = DISPLAY_FLAG_UPDATE_ALL;
                }

                wday        = tm.tm_wday;
                hour        = tm.tm_hour;
                minute      = tm.tm_min;
                second      = tm.tm_sec;

                log_printf ("read rtc: %s %4d-%02d-%02d %02d:%02d:%02d\r\n",
                             wdays_en[tm.tm_wday], tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday, tm.tm_hour, tm.tm_min, tm.tm_sec);
            }

            ds3231_flag = 0;
        }

        if (auto_brightness && ldr_conversion_flag)
        {
            ldr_start_conversion ();
            ldr_conversion_flag = 0;
        }

        if (net_time_flag)
        {
            if (esp8266_infop->is_online)
            {
                display_set_status_led (0, 0, 1);                       // light blue status LED
                status_led_cnt = STATUS_LED_FLASH_TIME;
                timeserver_start_timeserver_request ();                 // start a timeserver request, answer follows...
            }

            net_time_flag = 0;
            net_time_countdown = 3800;                                  // next net time after 3800 sec
        }

        if (show_time_flag)                                             // set every full minute
        {
#if WCLOCK24H == 1
            display_flag = DISPLAY_FLAG_UPDATE_ALL;
#else
            if (minute % 5)
            {
                display_flag = DISPLAY_FLAG_UPDATE_MINUTES;             // only update minute LEDs
            }
            else
            {
                display_flag = DISPLAY_FLAG_UPDATE_ALL;
            }
#endif
            show_time_flag = 0;
        }

        if (power_is_on == night_power_is_on && night_check_night_times (power_is_on, wday, hour * 60 + minute))
        {
            power_is_on         = ! power_is_on;
            night_power_is_on   = ! night_power_is_on;
            display_flag        = DISPLAY_FLAG_UPDATE_ALL;
            log_printf ("Found Timer: %s at %02d:%02d\r\n", power_is_on ? "on" : "off", hour, minute);
        }

        if (show_temperature)
        {
            uint_fast8_t temperature_index;

            show_temperature = 0;

            if (ds18xx_is_up)
            {
                short_isr = 1;
                temperature_index = temp_read_temp_index ();
                short_isr = 0;
                log_printf ("got temperature from DS18xxx: %d%s\r\n", temperature_index / 2, (temperature_index % 2) ? ".5" : "");
            }
            else if (rtc_is_up)
            {
                temperature_index = rtc_get_temperature_index ();
                log_printf ("got temperature from RTC: %d%s\r\n", temperature_index / 2, (temperature_index % 2) ? ".5" : "");
            }
            else
            {
                temperature_index = 0xFF;
                log_msg ("no temperature available");
            }

            if (temperature_index != 0xFF)
            {
                display_temperature (power_is_on, temperature_index);

#if WCLOCK24H == 1                                                          // WC24H shows temperature with animation, WC12H rolls itself
                uint32_t    stop_time;

                stop_time = uptime + 5;

                while (uptime < stop_time)
                {
                    if (animation_flag)
                    {
                        animation_flag = 0;
                        display_animation ();
                    }
                }
#endif
                display_flag = DISPLAY_FLAG_UPDATE_ALL;                     // force update
            }
        }

        if (display_flag)                                                   // refresh display (time/mode changed)
        {
            log_msg ("update display");

#if WCLOCK24H == 1
            if (display_mode == MODES_COUNT - 1)                            // temperature
            {
                uint_fast8_t temperature_index;

                if (ds18xx_is_up)
                {
                    short_isr = 1;
                    temperature_index = temp_read_temp_index ();
                    short_isr = 0;
                    log_printf ("got temperature from DS18xxx: %d%s\r\n", temperature_index / 2, (temperature_index % 2) ? ".5" : "");
                }
                else if (rtc_is_up)
                {
                    temperature_index = rtc_get_temperature_index ();
                    log_printf ("got temperature from RTC: %d%s\r\n", temperature_index / 2, (temperature_index % 2) ? ".5" : "");
                }
                else
                {
                    temperature_index = 0x00;
                    log_msg ("no temperature available");
                }

                display_clock (power_is_on, 0, temperature_index - 20, display_flag);    // show new time
            }
            else
            {
                display_clock (power_is_on, hour, minute, display_flag);    // show new time
            }
#else
            display_clock (power_is_on, hour, minute, display_flag);        // show new time
#endif
            display_flag = DISPLAY_FLAG_NONE;
        }

        if (animation_flag)
        {
            animation_flag = 0;
            display_animation ();
        }

        if (dcf77_flag)
        {
            dcf77_flag = 0;
            dcf77_tick ();
        }

#if SAVE_RAM == 0
        cmd = remote_ir_get_cmd ();                                         // get IR command

        if (cmd != REMOTE_IR_CMD_INVALID)                                   // got IR command, light green LED
        {
            display_set_status_led (1, 0, 0);
            status_led_cnt = STATUS_LED_FLASH_TIME;
        }

        if (cmd != REMOTE_IR_CMD_INVALID)                                   // if command valid, log command code
        {
            switch (cmd)
            {
                case REMOTE_IR_CMD_POWER:                         log_msg ("IRMP: POWER key");                  break;
                case REMOTE_IR_CMD_OK:                            log_msg ("IRMP: OK key");                     break;
                case REMOTE_IR_CMD_DECREMENT_DISPLAY_MODE:        log_msg ("IRMP: decrement display mode");     break;
                case REMOTE_IR_CMD_INCREMENT_DISPLAY_MODE:        log_msg ("IRMP: increment display mode");     break;
                case REMOTE_IR_CMD_DECREMENT_ANIMATION_MODE:      log_msg ("IRMP: decrement animation mode");   break;
                case REMOTE_IR_CMD_INCREMENT_ANIMATION_MODE:      log_msg ("IRMP: increment animation mode");   break;
                case REMOTE_IR_CMD_DECREMENT_HOUR:                log_msg ("IRMP: decrement hour");             break;
                case REMOTE_IR_CMD_INCREMENT_HOUR:                log_msg ("IRMP: increment hour");             break;
                case REMOTE_IR_CMD_DECREMENT_MINUTE:              log_msg ("IRMP: decrement minute");           break;
                case REMOTE_IR_CMD_INCREMENT_MINUTE:              log_msg ("IRMP: increment minute");           break;
                case REMOTE_IR_CMD_DECREMENT_BRIGHTNESS_RED:      log_msg ("IRMP: decrement red brightness");   break;
                case REMOTE_IR_CMD_INCREMENT_BRIGHTNESS_RED:      log_msg ("IRMP: increment red brightness");   break;
                case REMOTE_IR_CMD_DECREMENT_BRIGHTNESS_GREEN:    log_msg ("IRMP: decrement green brightness"); break;
                case REMOTE_IR_CMD_INCREMENT_BRIGHTNESS_GREEN:    log_msg ("IRMP: increment green brightness"); break;
                case REMOTE_IR_CMD_DECREMENT_BRIGHTNESS_BLUE:     log_msg ("IRMP: decrement blue brightness");  break;
                case REMOTE_IR_CMD_INCREMENT_BRIGHTNESS_BLUE:     log_msg ("IRMP: increment blue brightness");  break;
                case REMOTE_IR_CMD_DECREMENT_BRIGHTNESS:          log_msg ("IRMP: decrement brightness");       break;
                case REMOTE_IR_CMD_INCREMENT_BRIGHTNESS:          log_msg ("IRMP: increment brightness");       break;
                case REMOTE_IR_CMD_GET_TEMPERATURE:               log_msg ("IRMP: get temperature");            break;
            }
        }

        switch (cmd)
        {
            case REMOTE_IR_CMD_POWER:
            {
                power_is_on = ! power_is_on;

                display_flag        = DISPLAY_FLAG_UPDATE_ALL;
                break;
            }

            case REMOTE_IR_CMD_OK:
            {
                display_write_config_to_eeprom ();
                break;
            }

            case REMOTE_IR_CMD_DECREMENT_DISPLAY_MODE:                      // decrement display mode
            {
                display_mode = display_decrement_display_mode ();
                display_flag = DISPLAY_FLAG_UPDATE_ALL;
                break;
            }

            case REMOTE_IR_CMD_INCREMENT_DISPLAY_MODE:                      // increment display mode
            {
                display_mode = display_increment_display_mode ();
                display_flag = DISPLAY_FLAG_UPDATE_ALL;
                break;
            }

            case REMOTE_IR_CMD_DECREMENT_ANIMATION_MODE:                    // decrement display mode
            {
                animation_mode = display_decrement_animation_mode ();
                display_flag = DISPLAY_FLAG_UPDATE_ALL;
                break;
            }

            case REMOTE_IR_CMD_INCREMENT_ANIMATION_MODE:                    // increment display mode
            {
                animation_mode = display_increment_animation_mode ();
                display_flag = DISPLAY_FLAG_UPDATE_ALL;
                break;
            }

            case REMOTE_IR_CMD_DECREMENT_HOUR:                              // decrement hour
            {
                if (hour > 0)
                {
                    hour--;
                }
                else
                {
                    hour = 23;
                }

                second          = 0;
                display_flag    = DISPLAY_FLAG_UPDATE_ALL;
                time_changed    = 1;
                break;
            }

            case REMOTE_IR_CMD_INCREMENT_HOUR:                              // increment hour
            {
                if (hour < 23)
                {
                     hour++;
                }
                else
                {
                    hour =  0;
                }

                second          = 0;
                display_flag    = DISPLAY_FLAG_UPDATE_ALL;
                time_changed    = 1;
                break;
            }

            case REMOTE_IR_CMD_DECREMENT_MINUTE:                            // decrement minute
            {
                if (minute > 0)
                {
                    minute--;
                }
                else
                {
                    minute = 59;
                }

                second          = 0;
                display_flag    = DISPLAY_FLAG_UPDATE_ALL;
                time_changed    = 1;
                break;
            }

            case REMOTE_IR_CMD_INCREMENT_MINUTE:                            // increment minute
            {
                if (minute < 59)
                {
                    minute++;
                }
                else
                {
                    minute = 0;
                }

                second          = 0;
                display_flag    = DISPLAY_FLAG_UPDATE_ALL;
                time_changed    = 1;
                break;
            }

            case REMOTE_IR_CMD_DECREMENT_BRIGHTNESS_RED:                    // decrement red brightness
            {
                display_decrement_color_red ();
                display_flag        = DISPLAY_FLAG_UPDATE_NO_ANIMATION;
                break;
            }

            case REMOTE_IR_CMD_INCREMENT_BRIGHTNESS_RED:                    // increment red brightness
            {
                display_increment_color_red ();
                display_flag        = DISPLAY_FLAG_UPDATE_NO_ANIMATION;
                break;
            }

            case REMOTE_IR_CMD_DECREMENT_BRIGHTNESS_GREEN:                  // decrement green brightness
            {
                display_decrement_color_green ();
                display_flag        = DISPLAY_FLAG_UPDATE_NO_ANIMATION;
                break;
            }

            case REMOTE_IR_CMD_INCREMENT_BRIGHTNESS_GREEN:                  // increment green brightness
            {
                display_increment_color_green ();
                display_flag        = DISPLAY_FLAG_UPDATE_NO_ANIMATION;
                break;
            }

            case REMOTE_IR_CMD_DECREMENT_BRIGHTNESS_BLUE:                   // decrement blue brightness
            {
                display_decrement_color_blue ();
                display_flag        = DISPLAY_FLAG_UPDATE_NO_ANIMATION;
                break;
            }

            case REMOTE_IR_CMD_INCREMENT_BRIGHTNESS_BLUE:                   // increment blue brightness
            {
                display_increment_color_blue ();
                display_flag        = DISPLAY_FLAG_UPDATE_NO_ANIMATION;
                break;
            }

            case REMOTE_IR_CMD_AUTO_BRIGHTNESS_CONTROL:                     // toggle auto brightness
            {
                auto_brightness = ! auto_brightness;
                last_ldr_value = 0xFF;
                display_set_automatic_brightness_control (auto_brightness);
                display_flag = DISPLAY_FLAG_UPDATE_NO_ANIMATION;
                break;
            }

            case REMOTE_IR_CMD_DECREMENT_BRIGHTNESS:                        // decrement brightness
            {
                if (auto_brightness)
                {
                    auto_brightness = 0;
                    last_ldr_value = 0xFF;
                    display_set_automatic_brightness_control (auto_brightness);
                    display_flag = DISPLAY_FLAG_UPDATE_NO_ANIMATION;
                }

                display_decrement_brightness ();
                display_flag = DISPLAY_FLAG_UPDATE_NO_ANIMATION;
                break;
            }

            case REMOTE_IR_CMD_INCREMENT_BRIGHTNESS:                        // increment brightness
            {
                if (auto_brightness)
                {
                    auto_brightness = 0;
                    last_ldr_value = 0xFF;
                    display_set_automatic_brightness_control (auto_brightness);
                    display_flag = DISPLAY_FLAG_UPDATE_NO_ANIMATION;
                }

                display_increment_brightness ();
                display_flag = DISPLAY_FLAG_UPDATE_NO_ANIMATION;
                break;
            }

            case REMOTE_IR_CMD_GET_TEMPERATURE:                             // get temperature
            {
                show_temperature    = 1;
                break;
            }

            default:
            {
                break;
            }
        }
#endif // SAVE_RAM == 0

        if (time_changed)
        {
            if (rtc_is_up)
            {
                tm.tm_hour = hour;
                tm.tm_min  = minute;
                tm.tm_sec  = second;
                rtc_set_date_time (&tm);
            }

            time_changed = 0;
        }
    }

    return 0;
}
Ejemplo n.º 24
0
/*************************************************************************
* Description: Initialization for Timer
* Returns: none
* Notes: none
*************************************************************************/
void timer_init(
    void)
{
    timer2_init();
}
Ejemplo n.º 25
0
Archivo: avr.c Proyecto: olcai/sommar
int main(void)
{
  const char* str;

  /* initialize stuff commen for both base and node */
  config_load();
  lcd_init();
  rtc_init();
  adc_init();
  uart_init();
  
  //Timer2 används för att hålla våran radio-timeslot (kanske bara behövs när vi är nod?.
  timer2_init();

  /* set portC as output and all leds off */
  DDRC = 0xFF;
  PORTC = 0xff;

  /* lets initialize modules specific for the mode */
  if(config.flags.mode == CONFIG_MODE_BASE)
  {
    suart_init();
    str = "\n00init\nSystem is now online!\n";
    while(*str)
    {
      while(suart_putc(*str) == FALSE);
      str++;
    }
  }
  else
  {
    response_wait_time = atoi(config.group) * 4;
//    response_wait_time = 16;
  }

  /* in our answer the two first byte is always the group number */
  memcpy((void*)answer, (void*)config.group, CONFIG_GRP_LEN);

  /* all is initialized, lets roll */
  sei();
  
  /* configure the mode button pin as input */
  MODE_BUTTON_DDR &= ~_BV(MODE_BUTTON_PIN);

  /* loop until the mode button pin is low */
  while(bit_is_set(MODE_BUTTON_PORT, MODE_BUTTON_PIN))
  {
    uint8_t buffer[UART_FIFO_SIZE];

    /* uart data (radio), parse it */
    if(uart.stopchars)
    {
      uart.stopchars--;

      /* copy it to our stack */
      uint8_t i = 0;
      while ((buffer[i] = uart_getc()) != PROTOCOL_STOPCHAR)
        i++;
      /* 
       * node -> parse it
       * base -> pass along to the suart (to computer)
       */
      
      if(config.flags.mode == CONFIG_MODE_BASE)
      {
        int j;
        for(j=0;j<i;j++)
          while(suart_putc(buffer[j]) == FALSE);
      }
      else {
        if (cmd_parse(buffer, i)) {
          // enable the send timer
          TCNT2 = 0;
          TIMSK |= _BV(OCIE2);
        }
      }
    }

    /*
     * suart data (from computer)
     * We only get this as base, so answer the command
     * if it's addressed to us, and send to all nodes.
     */
    if(suart.stopchars) {
      suart.stopchars--;
      uint8_t i = 0;
      while ((buffer[i] = suart_getc()) != PROTOCOL_STOPCHAR)
        i++;
      if (cmd_parse(buffer, i)) {
        i = 0;
        if (command_parsed == 1) {
          do {
            suart_putc(answer[i]);
          } while (answer[i++] != PROTOCOL_STOPCHAR);
          command_parsed = 0;
        }
      }
      //Send to radio
      i = 0;
      do {
        uart_putc(buffer[i]);
      } while (buffer[i++] != PROTOCOL_STOPCHAR);
    }
  }

  /* we are closing down, do not disturb */
  cli();

  /* this is safe because we know that the mode is just one bit */
  config.flags.mode = !config.flags.mode;
  config_save();
  rtc_save();

  /* use the watchdog to get a nice clean reset */
  wdt_enable(WDTO_15MS);
  while(1);
}
int main(void)
{
	int temp = 0;					// Read temperature
	//int sp_temp_get;
	float temp_real = 0;			// Real format temperature		
	//int t_sample = 100;				// Time period samples read ms
	//int t_control = 1000;			// Time period control system ms
	
	uint16_t t_sample = 0;				// Time period samples read ms
	int t_control = 0;			// Time period control system ms
	
	//long millis_ant1;				// Aux timer
	//long millis_ant2;				// Aux timer
	uint16_t out_pwm;				// Out PWM control
	double y_temp[PmA+2] = {0};								// Array out incremental y(k), y(k-1), y(k-2), y(k-3)
	double u_temp[PmB+3] = {0};								// Array process input incremental u(k), u(k-1), u(k-2), u(k-3), u(k-4)
	double t_temp[5] = {1.0, -0.3, 0.1, 0.1, 0.1};			// Array parameters adaptive mechanism a1k, a2k, b1k, b2k, b3k		
	double sp_temp[2] = {0};								// Set point process sp(k)
	double yp_temp[2] = {0};								// Array process out yp(k)		
	
	cli();							// Disable interrupts
	conductor_block();				// Calculate parameters conductor block
	usart_init();					// Initialize USART
	UCSR0B |= (1 << RXCIE0);		// Enable interrupt RX (If enabled do not use functions get_xx)
	adc_Setup();					// Initialize ADC
	timer1_init();					// Timer system without interrupts
	//timer0_init();				// Initialize timer0 system ms
	timer2_init();					// Initialize timer2 PWM
	sei();
	
	DDRD |= (1 << PIND3);			// Out PWM OC2B PIND3 Digital PIN 3
	
	temp = adc_read(0);				// Initialize temperature readers
	//millis_ant1 = millis;			// Initialize period samples
	//millis_ant2 = millis;			// Initialize period control	
	
	//eeprom_update_float(&eeprom_float,f);
	
	//float eeprom_float_read;
	
	//eeprom_float_read = eeprom_read_float(&eeprom_float);
	//put_float(eeprom_float_read);

	
	//put_string("\n Input SP temperature: ");
	//sp_temp_get = get_int();
	
    while(1)
    {		
        
		// Samples read
		//if ((millis - millis_ant1) >= t_sample){
			//millis_ant1 = millis;
		t_sample = TCNT1;									// Catch sample time for integer angle gyro		
		T_CNT = T_SAMPLE * 1000L/64;						// Number count temp1.  1 Count Temp1 64us => T_sample = Value_CNT1 = ms/64us 
		if (t_sample >= T_CNT){								// Attitude calculates Read IMU (Accel and Gyro)
			TCNT1 = 0;										// Restart sample time
			t_control++;									// Increment time Period control
			temp = lpf(adc_read(0), temp, 0.1);						
		}
		
		//if ((millis - millis_ant2) >= t_control){		
			//millis_ant2 = millis;
			
		if (t_control >= T_CONTROL){						//Control action balancer
			t_control = 0;	
			temp_real = temp * 110.0 / 1023.0;	// solo en el control
	
			//Adaptive predictive balancer process			
			sp_temp[0] = sp_temp_get;											// Set point
			yp_temp[0] = temp_real;												// Process out y(k).
									
			adaptive(sp_temp, t_temp, y_temp, u_temp, yp_temp, UP_PWM);	// Call adaptive function
			out_pwm = u_temp[0];									// Out Controller adaptive
			if (out_pwm > UP_PWM) out_pwm = UP_PWM;							// Upper limit out
				else if (out_pwm < 0) out_pwm = 0;
			//out_pwm = 0;														// Off control			
			OCR2B = 255 - out_pwm;												// Out PWM
			
			put_float(temp_real);
			put_string(" ");
			put_int(OCR2B);
			put_string(" ");
			put_int(sp_temp_get);
			//put_string(" ");
			//put_float(NL);
			//put_string(" ");
			//put_float(GainA);
			//put_string(" ");
			//put_float(GainB);
			//put_string(" ");
			//put_int(T_SAMPLE);
			//put_string(" ");
			//put_int(T_CONTROL);			
			put_string("\n");
			
		}		
		//TODO:: Please write your application code    
    }
}
Ejemplo n.º 27
0
int main(void)
{

    // for 74HC595 port setting for LCD
    SoftSPI_Init();
    
    // for 74HC595 port setting for LED array
    SoftSPI_LED_Init();
    
    // Initialize LCD
	lcd_init();
	
    // Timer for PWM driver initialize
    timer0_init();
    
    // TachoMeter counter initialize
    timer1_init();

    // delay counter initialize
    timer2_init();
    
    // PWM output port definition
    DDRD |= (1<<PD6);
    
	// USART initialize
	USARTinit(UBRR);
	
	// Ext. Interupt setting
	ExtInterrupt_init();
    
    // TicToc initialize
    tictoc_init(FOSC, Ndiv1);
    
    // Tacho Meter Initialize
    TachoMeter_init(FOSC,Ndiv1);
    
    // Bar-Meter Initialize
    BarMeter_init();
    
    // Facemark character Initialize
    FaceMark_init();
    
    // Set Initial Target IDs
    set_initial_t_id();
    
	// Declarations
	unsigned char*   opening_message0 = "Multi-Function Meter";
    unsigned char*   opening_message1 = "     Timer Test     ";
    unsigned char*   opening_message2 = "   Firmware Rev.6   ";
    
	uint8_t         n, m;					// 'for' loop variables
    
	uint8_t         index = 0;				// LCD displaying data index
	
	uint16_t		maxv = 2352;			// maximum decimal angle data value from 'Defi Link Unit II'
    
	uint8_t         id;						// ID index for processing
    
	uint8_t         valid_packet[Ndata];	// Validtity indicator
	
	uint8_t			low4bits[4];			// Extracted lower 4 bits from byte data
	uint16_t        dec_ang;				// Angle data (decimal)
	float           dec_nrm;				// Angle data (decimal)
	float			value[Ndata];			// Decoded value
    uint16_t        mult_factor[3];		// Multiplying factor for hexadecimal to decimal decoding
    
	uint8_t         digits_int[5];			// Digits integer data
	unsigned char	digits_char[5];			// Digits character data for display
    
	float           div_factor;				// Dividing factor for integer
	uint8_t         digits_valid;			// Indicate digits in integer are valid or invalid
    
    // value = eq_grad * dec_nrm + eq_intercept
    // Gradient-term of decoding equation
	uint16_t eq_grad[] = {
        3,	// Turbo
        9000,	// Tacho
        10,	// Oil pres.
        6,	// Fuel pres.
        900,	// Ext. Temp.
        100,	// Oil Temp.
        100	// Water Temp.
    };
    
    // Intercept-term of decoding equation
    int16_t eq_intercept[] = {
        -1,	// Turbo
        0,	// Tacho
        0,	// Oil pres.
        0,	// Fuel pres.
        200,	// Ext. Temp.
        50,	// Oil Temp.
        20	// Water Temp.
    };
    
    // Definition of number of significant figure
	uint8_t   Nsig[] = {				// Number of significant figures
        3,	// Turbo
        4,	// Tacho
        3,	// Oil pres.
        3,	// Fuel pres.
        4,	// Ext. Temp.
        3,	// Oil Temp.
        3	// Water Temp.
    };
    
    // Deifinition of number of integer figure
	uint8_t	Nint[] = {				// Number of integr digits
        1,	// Turbo
        4,	// Tacho
        2,	// Oil pres.
        1,	// Fuel pres.
        4,	// Ext. Temp.
        3,	// Oil Temp.
        3	// Water Temp.
    };
    
    uint8_t	SIGN[] = {				// Show +/-, enable showing is '1'
        1,	// Turbo
        0,	// Tacho
        0,	// Oil pres.
        0,	// Fuel pres.
        0,	// Ext. Temp.
        0,	// Oil Temp.
        0	// Water Temp.
    };
    
	uint8_t	Nspace[7];				// Number of space between character and digits
    float   Resolution[7];


    RxName[0]		=   "BOOST";
    RxName[1]		=   "TACHO";
    RxName[2]		=   "OIL.P";
    RxName[3]		=   "FUEL.P";
    RxName[4]		=   "EXT.T";
    RxName[5]		=   "OIL.T";
    RxName[6]		=   "WATER.T";

/*
	RxName[0]		=   "Boost";
	RxName[1]		=   "Tacho";
	RxName[2]		=   "Oil.P";
	RxName[3]		=   "Fuel.P";
	RxName[4]		=   "ExTmp";
	RxName[5]		=   "Oil.T";
	RxName[6]		=   "Water.T";
*/
    
/*
	RxName[0]	=   "BS";
	RxName[1]	=   "TC";
	RxName[2]	=   "OP";
	RxName[3]	=   "FP";
	RxName[4]	=   "ET";
	RxName[5]	=   "OT";
	RxName[6]	=   "WT";
*/
    
/*
	RxName[0]	=   "Boost";
	RxName[1]	=   "Tacho";
	RxName[2]	=   "Oil press";
	RxName[3]	=   "Fuel press";
	RxName[4]	=   "Ext. Temp.";
	RxName[5]	=   "Oil Temp.";
	RxName[6]	=   "Water Temp.";
*/
    
    // Definition of Resolution for processing and number of space for display
    for(n=0;n<7;n++){
        Resolution[n] = 1;
        for(m=0;m<Nsig[n]-Nint[n];m++){
            Resolution[n] = Resolution[n] / 10;
        }
        RxNameLength[n] = StrLength(RxName[n]);
        Nspace[n]       = DISP_W - RxNameLength[n] - ( Nsig[n] + (Nsig[n]!=Nint[n]) + SIGN[n] );
    }
    
    
	mult_factor[0] = 1;
	mult_factor[1] = 16;
	mult_factor[2] = 256;
    
    
//    delay_cnt = (unsigned long int)( ( WAIT*1.0 ) * ( (1.0*FOSC)/(1.0*Ndiv2) ) / 256.0 / 1000.0 );
    delay_cnt = (unsigned long int)( ( WAIT*1.0 ) * ( (1.0*FOSC)/1000.0/(1.0*Ndiv2) ) / 256.0 );
    
/*
    // opening @ LED array
    for(n=0;n<=8;n++){
        send_bits_595_LED(0x01 << n);
        _delay_ms(60);
    }

    // opening @ LCD
	_delay_ms(50);
	lcd_locate(1,0);
	for(n=0;n<LCD_W;n++){
		lcd_set_char(opening_message0[n]);
		_delay_ms(20);
	}
    lcd_locate(2,0);
    for(n=0;n<LCD_W;n++){
        lcd_set_char(opening_message1[n]);
        _delay_ms(20);
    }
    lcd_locate(3,0);
    for(n=0;n<LCD_W;n++){
        lcd_set_char(opening_message2[n]);
        _delay_ms(20);
    }
    
    // opening @ LED array
    for(n=0;n<=8;n++){
        send_bits_595_LED(~( 0xff << n ));
        _delay_ms(30);
    }
    _delay_ms(250);
    for(n=0;n<=8;n++){
        send_bits_595_LED( 0xff >> n );
        _delay_ms(30);
    }
    _delay_ms(50);
    for(n=0;n<2;n++){
        send_bits_595_LED(0xff);
        _delay_ms(75);
        send_bits_595_LED(0x00);
        _delay_ms(75);
    }
    
    // Clear Opening
	for(m=0;m<4;m++){
		lcd_locate(m,0);
		for(n=0;n<LCD_W;n++){
			lcd_set_char(0x20);
			_delay_ms(15);
		}
	}
*/
    
    // Initialize data display for Defi Link Tap
    for ( index = 0; index < Ndata; index++ ){
        data_updated[index] = 1;
    }
    
    // Enable Interrupt
    sei();

    // Timer Test
    DDRC = 0b00000001;
    PORTC = 0b00000001;
    // Timer Test
    
	////// Main Process start //////
	while(1){
        
        if(lcd_update){
            DisplayItemInfo();
            lcd_locate((chg_index&0x03)>>1,8-(1-chg_index%2));
            lcd_update = 0;
		}

        ////// Measure Process //////
        
        //// Defi Link Tap ////
		for ( index = 0; index < Ndata; index++ ){
			
            if( data_updated[index] == 1 ){
                data_updated[index] = 0;
                
                // Rx data read
                id = t_id[index];
                
                // Judge data validity
                for( n = 1; n < 4; n++ ){
                    if( ( ( (data[index][n] >= '0') & (data[index][n] <= '9') )
                         |( (data[index][n] >= 'A') & (data[index][n] <= 'F') ) ) ){
                        valid_packet[index] = 1;
                    }else{
                        valid_packet[index] = 0;
                        break;
                    }
                }
                // end of judge
                
                if ( valid_packet[index] == 1 ) {
                    // Change char to angle-dec
                    dec_ang = 0;
                    for( n = 1; n < 4; n++){ // data[0] is neglected because of it is control data
                        if  ( (data[index][n] & 0xf0) == 0x30 ){
                            low4bits[n] = (unsigned int)(data[index][n] & 0x0f);
                        }else if ( (data[index][n] & 0xf0) == 0x40 ){
                            low4bits[n] = (unsigned int)(data[index][n] & 0x0f) + 9;
                        }else{
                            break;
                        }
                        dec_ang = dec_ang + low4bits[n] * mult_factor[3-n];
                    }
                    // end of Change char to angle-dec
                    
                    // Change angle-dec to normlized-dec
                    dec_nrm = (float)dec_ang / (float)maxv;
                    // end of Change angle-dec to normlized-dec
                    
                    // Change dec to ISO
                    value[index] = dec_nrm * eq_grad[id] + eq_intercept[id];
                    // end of change dec to ISO
                }

            }
		}
        
        rpm = TachoMeter();
        
/*
        //debug
        if( rpm > 8000 ){
            rpm = 0;
        }else{
            rpm = rpm + 10;
        }
        //debug
*/
        
        // Fuel Pump Driver
        OCR0A = FuelPumpDriver(rpm, value[2],value[3]);
        // value[2] ... Fuel Pressure
        // value[3] ... Boost

        
        ////// Display Process //////
        if(    ( ( (0xffff - timer2_cnt_last) > delay_cnt ) && ( (timer2_cnt - timer2_cnt_last)             > delay_cnt ) )
            || ( ( (0xffff - timer2_cnt_last) < delay_cnt ) && ( (timer2_cnt + (0xffff - timer2_cnt_last))  > delay_cnt ) ) ){

            timer2_cnt_last = timer2_cnt;

            // Timer Test
            PORTC = ~PORTC;
            // Timer Test
            

            //// Defi Link Tap ////
            for ( index = 0; index < Ndata; index++ ){
                
                // Rx data read
                id = t_id[index];

                // clear value area of LCD
                lcd_locate(index,RxNameLength[id]);
                for (n=0;n<=(DISP_W-RxNameLength[id])-1;n++) {
                    lcd_set_char(' ');
                }
                // end of clear value area
                
                // pad blank area of LCD
                lcd_locate(index,RxNameLength[id]);
                for (n=0;n<Nspace[id];n++){
                    lcd_set_char(' ');
                }
                // end of pad blank area of LCD
                
                // display value
                if ( valid_packet[index] == 1 ) {
                    lcd_set_numeric(value[index],Nint[id],Nsig[id]-Nint[id],SIGN[id]);
                }else if( valid_packet[index] == 0 ){
                    for(n=0;n<(Nsig[id]!=Nint[id])+SIGN[id];n++){
                        lcd_set_char(' ');
                    }
                    for(n=0;n<Nsig[id];n++){
                        lcd_set_char('*');
                    }
                }
                // end of display value

            }
            

            // Display Facemark
            lcd_locate(2,13);
            if((unsigned int)rpm < 3000){
                shobon();
            }else if((unsigned int)rpm < 5000){
                shakin();
            }else{
                kuwa();
                lcd_set_str("  ");
            }

 
            // Update Indicator
            lcd_locate(2,12);
            lcd_set_char(0xff);
 
            
        }else{

            // Clear Update Indicator
            lcd_locate(2,12);
            lcd_set_char(' ');
            
        }
        
        //// Real-Time Update items
        

        // Display RPM
        lcd_locate(0,12);
        lcd_set_numeric((unsigned int)rpm,5,0,0);
        lcd_set_str("RPM");
        
        // Display RPM @ Bar Meter
        lcd_locate(3,12);
        BarMeter_disp((unsigned int)rpm);

        
	}

    return 0;
}
Ejemplo n.º 28
0
void heart_init(void)
{
	timer2_init();
}
Ejemplo n.º 29
0
static void led3_thread_entry(void* parameter)
{
	
	rt_kprintf ( "\r\n led3_thread_entry!!\r\n");
    irmp_init();                                                            // initialize irmp
	  irsnd_init();        
    timer2_init();                                                          // initialize timer2
	rt_kprintf ( "\r\n 红外收发系统初始化完成!\r\n");
    for (;;)
    {
			char *str;
		//	rt_kprintf ( "IRMP  is going!!!\r\n");
			 rt_thread_delay(1);
			if(RT_EOK== (rt_mb_recv(&dfs_mb,(rt_uint32_t*)&str,RT_WAITING_NO)))
			{rt_kprintf("接收到控制邮件,数据为 %s",str);
				//   TIM_Cmd(TIM2, ENABLE);
							if(strcmp(str,"getremote")==0)
								hot_remote_state=1;
								if(strcmp(str,"sendremote")==0)	
									hot_remote_send=1;
			}
        if (irmp_get_data (&irmp_data))
        {
          rt_kprintf("接收红外信号编码方式: %s",irmp_protocol_names[irmp_data.protocol]);
          rt_kprintf(" 编码地址: 0x%2X",irmp_data.address);
          rt_kprintf(" 命令: 0x%2X",irmp_data.command);
          rt_kprintf(" 标志位: 0x%2X\r\n",irmp_data.flags );
			if(1==hot_remote_state)	
			{
			hot_remote_state=2;
			irmp_data1=irmp_data;
			rt_mb_send(&mb,(rt_uint32_t)get_remot1_mp3);//发送邮件
				 rt_kprintf("红外接收完成第一次\n" );
			}
		else if(2==hot_remote_state)
			{
			if(irmp_data1.command==irmp_data.command)
				{
					 rt_kprintf("红外接收完成第二次,验证通过\n" );
				rt_mb_send(&mb,(rt_uint32_t)get_remot2_mp3);//发送邮件
				hot_remote_state=0;
					//  TIM_Cmd(TIM2, DISABLE);
				}
			else {
				 rt_kprintf("红外接收完成第二次,验证不通过,再次接收红外数据\n" );
				rt_mb_send(&mb,(rt_uint32_t)check_fail_mp3);//发送邮件
				hot_remote_state=1;
				}
			}
        }
				if(hot_remote_send)	
		{   
		hot_remote_send=0;
		//	 TIM_Cmd(TIM2, ENABLE);
			/*	irmp_data.protocol = IRMP_SAMSUNG32_PROTOCOL;                             // use NEC protocol
        irmp_data.address  = 0x0e0e;                                        // set address to 0x00FF
        irmp_data.command  = 0xf30c;                                        // set command to 0x0001
        irmp_data.flags    = 0;                                             // don't repeat frame*/
        irsnd_send_data (&irmp_data, TRUE);                                 // send frame, wait for completion			// don't repeat frame
			rt_mb_send(&mb,(rt_uint32_t)sen_remot_mp3);
		  rt_kprintf("发送红外数据完成\n");
		  rt_kprintf("发射红外信号编码方式: %s",irmp_protocol_names[irmp_data.protocol]);
          rt_kprintf(" 编码地址: 0x%2X",irmp_data.address);
          rt_kprintf(" 命令: 0x%2X",irmp_data.command);
          rt_kprintf(" 标志位: 0x%2X\r\n",irmp_data.flags );
		//  TIM_Cmd(TIM2, DISABLE);
		}
    }
}
Ejemplo n.º 30
0
void board_init(void)
{
	timer0_init();
	timer2_init();
	interrupt_init();
}