示例#1
0
void ui_clockhandler()
{
//Get time
    struct rtc_time* time=rtc_gettime();

//Draw time
    cli_setrect(0);
    cli_positioncursor(video_getcollumns()-13,0);
    cli_puts("            ");
    cli_positioncursor(video_getcollumns()-13,0);
    cli_putu32(time->hour,10);
    cli_positioncursor(video_getcollumns()-10,0);
    cli_putch(':');
    cli_positioncursor(video_getcollumns()-8,0);
    cli_putu32(time->minute,10);
    cli_positioncursor(video_getcollumns()-5,0);
    cli_putch(':');
    cli_positioncursor(video_getcollumns()-3,0);
    cli_putu32(time->seccond,10);

    cli_setrect(&ui_CLIRect);
    cli_positioncursor(0,0);


}
示例#2
0
void vLcdPcf (void *pvParameters)
{
   char strMsgDebug[64];
   RTC_t stDate;
   
   
   PCF8574_I2C_Init();
   LcdPcf_Init();
    
   LcdPcf_Backlight(1);
  
   while(1)
   {
      rtc_gettime(&stDate);
      sprintf(strMsgDebug, "%02d/%02d/%02d  ", stDate.mday, stDate.month, stDate.year);
      
      LcdPcf_Goto(1,0);
      prit_lcd(strMsgDebug);
      
      sprintf(strMsgDebug, "%02d:%02d:%02d", stDate.hour, stDate.min, stDate.sec);
      LcdPcf_Goto(2,0);
      prit_lcd(strMsgDebug);
      osDelay(100);
   }
}
示例#3
0
文件: main.c 项目: li1794/CNC-STM32
void setTime(void)
{
	RTC_t rtc;
	int c = -1, pos = 0, v = 0;
	
	win_showMsgWin();
	scr_setScroll(false);
	rtc_gettime(&rtc);
	scr_puts("D-ENTER C-CANCEL A-Up B-Down");
	scr_puts("\n'*' -Left '#' -RIGHT");
	scr_printf("\n\nTime: %02d.%02d.%02d %02d:%02d:%02d", rtc.mday, rtc.month, rtc.year - 2000, rtc.hour, rtc.min, rtc.sec);
	do
	{
		switch (pos)
		{
		case 0: v = rtc.mday; break;
		case 1: v = rtc.month; break;
		case 2: v = rtc.year - 2000; break;
		case 3: v = rtc.hour; break;
		case 4: v = rtc.min; break;
		case 5: v = rtc.sec; break;
		}
		if (c == KEY_STAR)	pos = pos <= 0 ? 5 : pos - 1;
		if (c == KEY_DIES) pos = pos >= 5 ? 0 : pos + 1;

		scr_gotoxy(0, 4);
		scr_fontColorNormal();
		scr_printf(" New: %02d.%02d.%02d %02d:%02d:%02d", rtc.mday, rtc.month, rtc.year - 2000, rtc.hour, rtc.min, rtc.sec);
		scr_fontColorInvers();
		scr_gotoxy(pos * 3 + 6, 3);
		scr_printf("%02d", v);
		while ((c = kbd_getKey()) < 0);

		if (c == KEY_A) v++;
		if (c == KEY_B)	v--;

		switch (pos) {
		case 0:
			if (v >= 1 && v <= 31) rtc.mday = v;
			break;
		case 1:
			if (v >= 1 && v <= 12) rtc.month = v;
			break;
		case 2:
			if (v >= 12 && v <= 30) rtc.year = v + 2000;
			break;
		case 3:
			if (v >= 0 && v <= 23) rtc.hour = v;
			break;
		case 4:
			if (c >= 0 && v <= 59)	rtc.min = v;
			break;
		case 5:
			if (v >= 0 && v <= 59)	rtc.sec = v;
			break;
		}
	} while (c != KEY_C && c != KEY_D);

	if (c == KEY_D) rtc_settime(&rtc);
}
示例#4
0
文件: rtc.c 项目: fachat/XD2031
int main(int argc, char** argv) {
    char line[MAX_LINE + 1]; int had_a_comment = 1;

    RTC_t time_before; rtc_gettime(&time_before);
    int8_t res;
    char* output[32];

    while(fgets(line, MAX_LINE, stdin) != NULL) {
        line[strlen(line) - 1] = 0; // drop '\n'
        if(line[0] == '#') {
            if(!had_a_comment) puts("\n");
            puts(line);
            had_a_comment=1;
            continue;
        } else {
            if(!had_a_comment) puts("\n");
            had_a_comment=0;
            printf("Test: '%s'\n", line);
        }
        // --------------------------------------
        res = rtc_time(line, output);
        if(res == -1 ) {
	    printf("before: "); rtc_timestamp(&time_before);
	    printf(" after: "); rtc_timestamp(&time_after);
        } else if(res > 0) {
            printf("***** ERROR %d *****\n", res);
        } else if(res < -1) {
            printf("***** ERROR %d *****\n", res);
        }
    }

    return 0;
}
示例#5
0
int
tryPush( XObj self, XObj sessn, int times, int length )
{
    xkern_return_t xkr;
    int i;
    Msg_s	savedMsg, request;
    int c = 0;
    PState 	*ps = (PState *)self->state;
#if MACH_KERNEL
    tvalspec_t  time_val_before, time_val_after;
#endif /* MACH_KERNEL */
    
    xkr = msgConstructContig(&savedMsg, self->path,
				 (u_int)length,
				 TEST_STACK_SIZE);
    if (xkr == XK_FAILURE) {
	sprintf(errBuf, "Could not construct a msg of length %d\n", 
		length + TEST_STACK_SIZE);
	Kabort(errBuf);
    }
    msgConstructContig(&request, self->path, 0, 0);
    semInit(&ps->sema, 0);
    ps->flushing = FALSE;
    ps->partialcount = times - 1;
#if  MACH_KERNEL
    rtc_gettime(&ps->starttime);
    rtc_gettime(&ps->partialtime);
#else
    xGetTime(&ps->starttime);
#endif /* MACH_KERNEL */
    for (i = 0; i < ps->groupsize; i++) {
	msgAssign(&request, &savedMsg);
	xkr = xPush(sessn, &request);
	if( xkr == XK_FAILURE ) {
	    printf( "Dgram Push error %d\n" , xkr ); 
	    goto abort;
	}
    }
    evSchedule(ps->evdgram, dgram_abort, self, 30000000);
    semWait(&ps->sema);
    evCancel(ps->evdgram);
    
 abort:
    msgDestroy(&savedMsg);
    msgDestroy(&request);
    return (times - ps->partialcount);
}
static int sunxi_rtc_read_time(struct device *dev, struct rtc_time *tm)
{
	struct platform_device *pdev = to_platform_device(dev);
	struct sunxi_rtc *rtc_dev = platform_get_drvdata(pdev);
	int ret = 0;

	mutex_lock(&rtc_dev->mutex);
	ret = rtc_gettime(rtc_dev, tm);
	mutex_unlock(&rtc_dev->mutex);
	return ret;
}
示例#7
0
xkern_return_t
clientDemux( XObj self, XObj lls, Msg dg )
{

    PState 	*ps = (PState *)self->state;
    Msg_s       reply;
#if  MACH_KERNEL
    tvalspec_t  singletime;
#else 
    XTime       endtime;
#endif /* MACH_KERNEL */

    if (ps->flushing == TRUE)
	return XK_SUCCESS;

    if (--ps->partialcount == 0) {
	semSignal(&ps->sema);
	ps->flushing = TRUE;
#if  MACH_KERNEL
#if 0
	rtc_gettime(&ps->nettime);
	SUB_TVALSPEC(&ps->nettime, &ps->starttime);
	dgramtest_record((void *)&ps->nettime);
#endif /* 0 */
#else 
	xGetTime(&endtime);
	xSubTime(&ps->nettime, endtime, ps->starttime);
#endif /* MACH_KERNEL */
	return XK_SUCCESS;
    }
#if  MACH_KERNEL
    rtc_gettime(&singletime);
    SUB_TVALSPEC(&singletime, &ps->partialtime);
    dgramtest_record((void *)&singletime);
    rtc_gettime(&ps->partialtime);
#endif /* MACH_KERNEL */
    msgConstructCopy(&reply, dg);
    (void)xPush(lls, &reply);
    msgDestroy(&reply);
    return XK_SUCCESS;
}
示例#8
0
文件: adc.c 项目: olcai/sommar
void adc_rtc_tick(void) {
  /* 
   * rtc körs varje sekund, så det blir direktmappning mellan sample_counter
   * och tidsintervallet (som också är i sekunder)
   */
  if (++sample_counter == config.interval) {
    sample_counter = 0;
   
    // nu gör vi det lätt för oss och sparar tiden vi hämtade värdet här
    rtc_gettime((uint8_t*)adc.data_time[0]);

    adc_dosample();
  }
}
示例#9
0
void LoggerBase::logCsvMessage(const char* pInfoType, const char* pMessage,
                              const char* pFilename, const char* pFuncName, int lineNum)
{
    semTake();
    {
        const char comma[] = ",";
        const char parens[] = "()";
        const char newline[] = "\n";

        char buff[40] = { 0 };
        rtc_t time = rtc_gettime();
        sprintf(buff, "%u/%u,%02d:%02d:%02d,%u,%s,",
                (unsigned)time.month, (unsigned)time.day, (unsigned)time.hour,
                (unsigned)time.min, (unsigned)time.sec, getTimestamp(),
                pInfoType
                );
        log(buff);

        log(pMessage);
        log(comma);

        // Find the back-slash or forward-slash to get filename only, not absolute or relative path
        if(0 != pFilename) {
            char* pSlash = strrchr(pFilename, '/');
            // If forward-slash not found, find back-slash
            if(0 == pSlash) pSlash = strrchr(pFilename, '\\');
            if(0 != pSlash) pFilename = pSlash+1;

            log(pFilename);
        }
        log(comma);

        if(0 != pFuncName) {
            log(pFuncName);
            log(parens);
        }
        log(comma);

        if(0 != lineNum) {
            sprintf(buff, "%i", lineNum);
            log(buff);
        }
        log(newline);
    }
    semGive();
}
示例#10
0
//! Update the explorer panel with currently set config values
void CAN_UserResetPanelValues(void){
	CANMsg_t TxMsg;
	u32_t tmp_u32;
	RTC rtc;
	
	HW_GetDOUT(&tmp_u32);

	TxMsg.Id = SYM_OUT_IO;
	TxMsg.Len = 1;
	TxMsg.Type = CAN_MSG_STANDARD;
	TxMsg.Data.Data8[0] =  (HW_GPS_GetPowerState()<<1) | ((u8_t)tmp_u32) ;
	CAN_UserWrite(&TxMsg);

	TxMsg.Id = SYM_OUT_GYRO;
	TxMsg.Len = 1;
	MEMS_L3GD20_GetRange(&TxMsg.Data.Data8[0]);
	CAN_UserWrite(&TxMsg);
	
	TxMsg.Id = SYM_OUT_ACC_SCALE;
	TxMsg.Len = 1;
	MEMS_BMC050_GetAccRange(&TxMsg.Data.Data8[0]);
	CAN_UserWrite(&TxMsg);

	TxMsg.Id = SYM_OUT_ACC_FAST_CALIBRATION;
	TxMsg.Len = 4;
	MEMS_BMC050_GetAccCalTargets(&TxMsg.Data.Data8[0],
			&TxMsg.Data.Data8[1],
			&TxMsg.Data.Data8[2]);
	TxMsg.Data.Data8[3] = 0;
	CAN_UserWrite(&TxMsg);

	rtc_gettime(&rtc);
	TxMsg.Id = SYM_OUT_RTC_SET_TIME;
	TxMsg.Len = 8;
	TxMsg.Data.Data8[0] = rtc.sec;
	TxMsg.Data.Data8[1] = rtc.min;
	TxMsg.Data.Data8[2] = rtc.hour;
	TxMsg.Data.Data8[3] = rtc.wday;
	TxMsg.Data.Data8[4] = rtc.mday;
	TxMsg.Data.Data8[5] = rtc.month;
	TxMsg.Data.Data16[3] = rtc.year;
	CAN_UserWrite(&TxMsg);
	
	return;
}
示例#11
0
bool example_alarm::run(void *p)
{
    static int print_first_sixty_secs = 0;
    ++print_first_sixty_secs;

    /**
     * Note that we use MAX delay while checking for mAlarmSec because if a second
     * hasn't elapsed, then by definition, minute won't elapse.
     */
    if (xSemaphoreTake(mAlarmSec, portMAX_DELAY)) {
        if (print_first_sixty_secs <= 60) {
            printf("tick %i -- ", (int)rtc_gettime().sec);
        }
    }
    if (xSemaphoreTake(mAlarmMin, 0)) {
        puts("A minute has elapsed!");
    }

    return true;
}
示例#12
0
/*
 * Universal (Posix) time tick. This is called from the clock
 * interrupt path at splclock() interrupt level.
 */
void
utime_tick(void)
{
	register int	delta;

	delta = tick;
	if (timedelta < 0) {
		delta -= tickdelta;
		timedelta += tickdelta;
	} else
	if (timedelta > 0) {
		delta += tickdelta;
		timedelta -= tickdelta;
	}
	time_value_add_usec(&time, delta);
	update_mapped_time(&time);
#if PTIME_MACH_RT
	(void) rtc_gettime((tvalspec_t *)&last_utime_tick);
#endif	/* PTIME_MACH_RT */
}	
示例#13
0
//------------------------------------------------------------------------------
//! void CAN_UserSendRTCTime(void)
//------------------------------------------------------------------------------
//! @brief	Sends current RTC time
//------------------------------------------------------------------------------
void CAN_UserSendRTCTime(void){
	RTC rtc;
	CANMsg_t TxMsg;

 	rtc_gettime(&rtc);

	TxMsg.Id = SYM_RTC_TIME;
	TxMsg.Len = 8;
	TxMsg.Type = CAN_MSG_STANDARD;
	TxMsg.Data.Data8[0] = rtc.sec;
	TxMsg.Data.Data8[1] = rtc.min;
	TxMsg.Data.Data8[2] = rtc.hour;
	TxMsg.Data.Data8[3] = rtc.wday;
	TxMsg.Data.Data8[4] = rtc.mday;
	TxMsg.Data.Data8[5] = rtc.month;
	TxMsg.Data.Data16[3] = rtc.year;

	CAN_UserWrite(&TxMsg);

	return;
}
示例#14
0
/*
 * Read the Universal (Posix) time.
 */
kern_return_t
host_get_time(
	host_t		host,
	time_value_t	*current_time)	/* OUT */
{
#if	PTIME_MACH_RT
	tvalspec_t	now_tick;
	tvalspec_t	last_tick;
#endif	/* PTIME_MACH_RT */

	if (host == HOST_NULL)
		return(KERN_INVALID_HOST);

#if	PTIME_MACH_RT
	/*
	 * If we are interrupted during the following calculation,
	 * we have to do it over.  If last_utime_tick changes, then
	 * we have been interrupted.
	 */
	do {
	    last_tick.tv_nsec = last_utime_tick.tv_nsec;
	    last_tick.tv_sec  = last_utime_tick.tv_sec;
	    do {
		current_time->seconds = mtime->seconds;
		current_time->microseconds = mtime->microseconds;
	    } while (current_time->seconds != mtime->check_seconds);
	    
	    (void) rtc_gettime(&now_tick);
	    SUB_TVALSPEC(&now_tick, &last_tick);
	    time_value_add_usec(current_time, now_tick.tv_nsec/NSEC_PER_USEC);
	} while ( last_tick.tv_nsec != last_utime_tick.tv_nsec );
#else	/* PTIME_MACH_RT */
	do {
	    current_time->seconds = mtime->seconds;
	    current_time->microseconds = mtime->microseconds;
	} while (current_time->seconds != mtime->check_seconds);
#endif	/* PTIME_MACH_RT */

	return (KERN_SUCCESS);
}
示例#15
0
/**
 * Initializes the minimal system including CPU Clock, UART, and Flash accelerator
 * Be careful of the order of operations!!!
 */
void low_level_init(void)
{
    rtc_init();
    m_rtc_boot_time = rtc_gettime();

    /**
     * Configure System Clock based on desired clock rate @ sys_config.h
     * Setup default interrupt priorities that will work with FreeRTOS
     */
    sys_clock_configure();
    configure_flash_acceleration(sys_get_cpu_clock());
    configure_interrupt_priorities();
    __enable_irq();

    // Setup UART with minimum I/O functions
    uart0_init(UART0_DEFAULT_RATE_BPS);
    sys_set_outchar_func(uart0_putchar);
    sys_set_inchar_func(uart0_getchar);

    /**
     *  If buffers are set to 0, so printf/scanf will behave correctly!
     *  If not set, then printf/scanf will have weird buffering/flushing effects
     */
    setvbuf(stdout, 0, _IONBF, 0);
    setvbuf(stdin,  0, _IONBF, 0);

    /**
     * Set the semaphore for the malloc lock.
     * Initialize newlib fopen() fread() calls support
     */
    syscalls_init();

    /**
     * Enable watchdog to allow us to recover in case of:
     *  - We attempt to run an application and it's not there
     *  - Application we ran crashes
     */
    sys_watchdog_enable();
    print_boot_info();
}
示例#16
0
/**
 * Initializes the minimal system including CPU Clock, UART, and Flash accelerator
 * Be careful of the order of the operations!!!
 */
void low_level_init(void)
{
    rtc_init();
    g_rtc_boot_time = rtc_gettime();

    /* Configure System Clock based on desired clock rate @ sys_config.h */
    sys_clock_configure();
    configure_flash_acceleration(sys_get_cpu_clock());

    /* Setup default interrupt priorities that will work with FreeRTOS */
    configure_interrupt_priorities();

    /* These methods shouldn't be needed but doing it anyway to be safe */
    NVIC_SetPriorityGrouping(0);
    __set_BASEPRI(0);
    __enable_fault_irq();
    __enable_irq();

    /* Setup UART with minimal I/O functions */
    uart0_init(SYS_CFG_UART0_BPS);
    sys_set_outchar_func(uart0_putchar);
    sys_set_inchar_func(uart0_getchar);

    /**
     * Turn off I/O buffering otherwise sometimes printf/scanf doesn't behave
     * correctly due to strange buffering and/or flushing effects.
     */
    setvbuf(stdout, 0, _IONBF, 0);
    setvbuf(stdin,  0, _IONBF, 0);

    /* Initialize newlib fopen() fread() calls support */
    syscalls_init();

    /* Enable the watchdog to allow us to recover in an event of system crash */
    sys_watchdog_enable();

    /* Uart and printf() are initialized, so print our boot-up message */
    print_boot_info();
}
示例#17
0
const char* getMMYYExtension(const char* pFilename)
{
    static char filename[16] = {0};

    // Short filenames have 12 character limit not including null
    char *p = &filename[0];
    for(int i=0; i<7 && pFilename[i] != '\0'; i++) {
        *p++ = pFilename[i];
    }

    RTC time = rtc_gettime();
    time.year -= 2000;

    //*p++ = '.';
    *p++ = (time.month / 10) + '0';
    *p++ = (time.month % 10) + '0';
    *p++ = (time.year / 10) + '0';
    *p++ = (time.year % 10) + '0';
    *p++ = '\0';

    return filename;
}
示例#18
0
void rtcInit()
{
  RTC_InitTypeDef RTC_InitStruct;

  RCC_APB1PeriphClockCmd(RCC_APB1Periph_PWR, ENABLE);
  PWR_BackupAccessCmd(ENABLE);
  RCC_LSEConfig(RCC_LSE_ON);
  while(RCC_GetFlagStatus(RCC_FLAG_LSERDY) == RESET);
  RCC_RTCCLKConfig(RCC_RTCCLKSource_LSE);
  RCC_RTCCLKCmd(ENABLE);
  RTC_WaitForSynchro();

  // RTC time base = LSE / ((AsynchPrediv+1) * (SynchPrediv+1)) = 1 Hz*/
  RTC_InitStruct.RTC_HourFormat = RTC_HourFormat_24;
  RTC_InitStruct.RTC_AsynchPrediv = 127;
  RTC_InitStruct.RTC_SynchPrediv = 255;
  RTC_Init(&RTC_InitStruct);
  
  struct gtm utm;
  rtc_gettime(&utm);
  g_rtcTime = gmktime(&utm);
}
/**
 * Initializes the minimal system including CPU Clock, UART, and Flash accelerator
 * Be careful of the order of operations!!!
 */
void low_level_init(void)
{
    rtc_init();
    g_rtc_boot_time = rtc_gettime();

    /**
     * Configure System Clock based on desired clock rate @ sys_config.h
     * Setup default interrupt priorities that will work with FreeRTOS
     */
    sys_clock_configure();
    configure_flash_acceleration(sys_get_cpu_clock());
    configure_interrupt_priorities();
    __enable_irq();

    // Setup UART with minimum I/O functions
    uart0_init(UART0_DEFAULT_RATE_BPS);
    sys_set_outchar_func(uart0_putchar);
    sys_set_inchar_func(uart0_getchar);

    /**
     * Turn off I/O buffering otherwise sometimes printf/scanf doesn't behave
     * correctly due to strange buffering and/or flushing effects.
     */
    setvbuf(stdout, 0, _IONBF, 0);
    setvbuf(stdin,  0, _IONBF, 0);

    // Initialize newlib fopen() fread() calls support
    syscalls_init();

    /**
     * Enable watchdog to allow us to recover in case of:
     *  - We attempt to run an application and it's not there
     *  - Application we ran crashes
     */
    sys_watchdog_enable();
    print_boot_info();
}
示例#20
0
文件: main.c 项目: li1794/CNC-STM32
/***************************************************
 *	Show status
 */
void showStatusString(void)
{
	static uint8_t sec = 0, limits = 0;

	if (Seconds() != sec)
	{	// Display every second
		scr_setfullTextWindow();
		scr_gotoxy(2, TEXT_Y_MAX - 1);
		scr_fontColor(White, Black);
#if (USE_RTC == 1)
		RTC_t rtc;
		rtc_gettime(&rtc);
		scr_printf("%02d.%02d.%02d %02d:%02d:%02d ", rtc.mday, rtc.month, rtc.year - 2000, rtc.hour, rtc.min, rtc.sec);
#else
		scr_printf("%02d:%02d:%02d ", ((Seconds() / 3600) % 24), ((Seconds() / 60) % 60), (Seconds() % 60));
#endif

#if (USE_EXTRUDER == 1)
		scr_fontColor(_smParam.maxSpindleTemperature > extrudT_getTemperatureReal() ? Green : Red, Black);
		scr_printf("t:%dC", extrudT_getTemperatureReal());
#endif
		SystemStatus(sec);

		// scr_clrEndl();
		sec = Seconds();
		limits = 0xFF;
	}

	if (limits != limits_chk())
	{
		limits = limits_chk();
		scr_Rectangle(283, 224, 293, 239, limitX_chk() ? Red : Green, true);
		scr_Rectangle(296, 224, 306, 239, limitY_chk() ? Red : Green, true);
		scr_Rectangle(309, 224, 319, 239, limitZ_chk() ? Red : Green, true);
	}
}
示例#21
0
int main(void)
{

//  u16 len = 0;			    
//  len = menuDisplay(bufExtBin);
//  if (len)
//	signUSBMass = 0;

  signUSBMass = 0;
//***********************************DEBUG********************************************/

      
//***********************************END OF DEBUG********************************************/

    /* Configure IO connected to USB PWR DET *********************/	
    RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOD,ENABLE );
	GPIO_InitStructure.GPIO_Pin = GPIO_Pin_3;
  	GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN_FLOATING;
  	GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
  	GPIO_Init(GPIOD, &GPIO_InitStructure);

    if((GPIO_ReadInputData(GPIOD) & 0x08))   // USB is present after switch - work MASS Storage
      {
	     signUSBMass = 1;
      }

	signUSBMass = 0;   //debugga

#if 1  	  //that's for temporary off USB - for debugging
  
  NVIC_Configuration();
  Set_System();
  Set_USBClock();
  USB_Interrupts_Config();
  USB_Init();
  if(signUSBMass)
     while (bDeviceState != CONFIGURED);

#endif 
//
#if 1
  if(!signUSBMass)
   {
    if (SysTick_Config(SystemCoreClock / 1000))  //1ms
     { 
       /* Capture error */ 
       while (1);
     }

  	 /* Flash unlock */
     FLASH_Unlock();
     /* Clear All pending flags */
     FLASH_ClearFlag(FLASH_FLAG_BSY | FLASH_FLAG_EOP | FLASH_FLAG_PGERR | FLASH_FLAG_WRPRTERR);	

//***********************************DEBUG********************************************/

     
//***********************************END OF DEBUG********************************************/

  /* Enable CRC clock */
  RCC_AHBPeriphClockCmd(RCC_AHBPeriph_CRC, ENABLE);
    
  ledDioGPIOInit();
  //LED_MIDDLE = 1;
  //GPIO_ResetBits(LED_MID_PORT, LED_MID_PORT_PIN);
  BKPInit();
  //debugga

  /*
  u32 mileage = 0;
  mileage         = BKPReadReg(BKP_DR_MSG_NUMBER1)  | ( (u32)(BKPReadReg(BKP_DR_MSG_NUMBER2) << 16)  );
  mileage++;
  BKPWriteReg(BKP_DR_MSG_NUMBER1,mileage);BKPWriteReg(BKP_DR_MSG_NUMBER2,mileage >> 16);
  mileage         = BKPReadReg(BKP_DR_MSG_NUMBER1)  | ( (u32)(BKPReadReg(BKP_DR_MSG_NUMBER2) << 16)  );
  mileage = 0;
  BKPWriteReg(BKP_DR_MSG_NUMBER1,mileage);BKPWriteReg(BKP_DR_MSG_NUMBER2,mileage >> 16);
  mileage         = BKPReadReg(BKP_DR_MSG_NUMBER1)  | ( (u32)(BKPReadReg(BKP_DR_MSG_NUMBER2) << 16)  );
  if(mileage)
	signUSBMass = 0;   //debugga
  */

  Delay(1000);

  //rs485Init();

  //Delay(1000);

  ais326dq_init();
  ais326dq_data(&ais326dq_out);

  adcInit();

  gpsInit();

  gprsModemInit();
  
  gprsModemOn();
#ifndef BRIDGE_USB_GSM
  setupGSM();
  ftpGSMPrepare();
  packetsIni();
#endif
  rtc_init();
  rtc_gettime(&rtc);
  initSD();

  /* reading settings */
  readConfig();
  /* Log  */
  saveSDInfo((u8 *)"TURN ON BLOCK ",strlen((u8 *)"TURN ON BLOCK "), SD_SENDED, SD_TYPE_MSG_LOG );
  saveSDInfo((u8 *)readRTCTime(&rtc),strlen((const char *)readRTCTime(&rtc)), SD_SENDED, SD_TYPE_MSG_LOG );

  }	 //if(!signUSBMass)
#endif

  //u8 tempCnt;
  while (1)
  {
    if(!signUSBMass)
	 {
	     gpsHandling();
		 #ifndef BRIDGE_USB_GSM
		    loopGSM();
			loopFTP();
            UpdatingFlash();
			naviPacketHandle();
			rcvPacketHandle();
            rcvPacketHandleUSB();
		 #endif 
		 buttonScan();
		 accelScan();
		 
//		 if(getButtonUserPressed())
//		  {
//		    led_mid(BOARD_LED_XOR);
//		    ais326dq_data(&ais326dq_out);
//		  }

		 //rs485Analyse();
		 handleFOS();
         adcScan();

  	 }  /* if(!signUSBMass)  */
  }
}
示例#22
0
int main(void)
{
	uint8_t system_state=0, i2c_resets=0, si446x_resets=0;//used to track button press functionality and any errors
	uint8_t sensors=0;
	uint32_t repetition_counter=0;			//Used to detect any I2C lockup
	uint8_t L3GD20_Data_Buffer_old[8];		//Used to test for noise in the gyro data (indicating that it is working)
	uint8_t UplinkFlags=0,CutFlags=0;
	uint16_t UplinkBytes=0;				//Counters and flags for telemetry
	uint32_t last_telemetry=0,cutofftime=0,indtest=0,badgyro=0,permission_time=0,countdown_time=0,last_cuttest=0;
	uint16_t sentence_counter=0;
	uint8_t silab;
	//Cutdown config stuff here, atm uses hardcoded polygon defined in polygon.h
	static const int32_t Geofence[UK_GEOFENCE_POINTS*2]=UK_GEOFENCE;
	RTC_t RTC_time;
        _REENT_INIT_PTR(&my_reent);
        _impure_ptr = &my_reent;
	SystemInit();					//Sets up the clk
	setup_gpio();					//Initialised pins, and detects boot source
	DBGMCU_Config(DBGMCU_IWDG_STOP, ENABLE);	//Watchdog stopped during JTAG halt
	RCC_APB1PeriphClockCmd(RCC_APB1Periph_PWR | RCC_APB1Periph_BKP, ENABLE);/* Enable PWR and BKP clocks */
	PWR_BackupAccessCmd(ENABLE);/* Allow access to BKP Domain */
	uint16_t shutdown_lock=BKP_ReadBackupRegister(BKP_DR3);	//Holds the shutdown lock setting
	uint16_t reset_counter=BKP_ReadBackupRegister(BKP_DR2); //The number of consecutive failed reboot cycles
	PWR_BackupAccessCmd(DISABLE);
	if(RCC->CSR&RCC_CSR_IWDGRSTF && shutdown_lock!=SHUTDOWNLOCK_MAGIC) {//Watchdog reset, turn off
		RCC->CSR|=RCC_CSR_RMVF;			//Reset the reset flags
		shutdown();
	}
	if(USB_SOURCE==bootsource) {
		RCC->CFGR &= ~(uint32_t)RCC_CFGR_PPRE1_DIV16;
		RCC->CFGR |= (uint32_t)RCC_CFGR_PPRE1_DIV4;//Swap the ABP1 bus to run at 12mhz rather than 4 if we booted from USB, makes USB fast enough
	}
	SysTick_Configuration();			//Start up system timer at 100Hz for uSD card functionality
	Watchdog_Config(WATCHDOG_TIMEOUT);		//Set the watchdog
	Watchdog_Reset();				//Reset watchdog as soon as possible incase it is still running at power on
	rtc_init();					//Real time clock initialise - (keeps time unchanged if set)
	Usarts_Init();
	ISR_Config();
	rprintfInit(__usart_send_char);			//Printf over the bluetooth
	if(USB_SOURCE==bootsource) {
		Set_System();				//This actually just inits the storage layer
		Set_USBClock();
		USB_Interrupts_Config();
		USB_Init();
		uint32_t nojack=0x000FFFFF;		//Countdown timer - a few hundered ms of 0v on jack detect forces a shutdown
		while (bDeviceState != CONFIGURED) {	//Wait for USB config - timeout causes shutdown
			if((Millis>10000 && bDeviceState == UNCONNECTED)|| !nojack)	//No USB cable - shutdown (Charger pin will be set to open drain, cant be disabled without usb)
				shutdown();
			if(GET_VBUS_STATE)		//Jack detect resets the countdown
				nojack=0x0FFFFF;
			nojack--;
			Watchdog_Reset();		//Reset watchdog here, if we are stalled here the Millis timeout should catch us
		}
		PWR_BackupAccessCmd(ENABLE);		/* Allow access to BKP Domain */
		BKP_WriteBackupRegister(BKP_DR3,0x0000);//Wipe the shutdown lock setting
		PWR_BackupAccessCmd(DISABLE);
		while(1) {
			if(!(Millis%1000) && bDeviceState == SUSPENDED) {
				Delay(100);
				if(!GET_VBUS_STATE)
					shutdown();
			}
			Watchdog_Reset();
			__WFI();			//Sleep mode
		}
	}
        if(!GET_PWR_STATE && !(CoreDebug->DHCSR&0x00000001) && shutdown_lock!=SHUTDOWNLOCK_MAGIC) {//Check here to make sure the power button is still pressed, if not, sleep if no debug and not in always on flight mode
                shutdown();                             //This means a glitch on the supply line, or a power glitch results in sleep
        }
	// check to see if battery has enough charge to start
	ADC_Configuration();				//We leave this a bit later to allow stabilisation
	{
	uint32_t t=Millis;
	while(Millis<(t+100)){__WFI();}			//Sensor+inst amplifier takes about 100ms to stabilise after power on
	}
	if(Battery_Voltage<BATTERY_STARTUP_LIMIT) {	//We will have to turn off
		if(reset_counter<10)
			shutdown();
	}
	Watchdog_Reset();				//Card Init can take a second or two
	// system has passed battery level check and so file can be opened
	{//Context
	uint8_t silabs_header[5]={};
	uint8_t* silabs_header_=NULL;			//Pointer to the array (if all goes ok)
	if((f_err_code = f_mount(0, &FATFS_Obj)))Usart_Send_Str((char*)"FatFs mount error\r\n");//This should only error if internal error
	else {						//FATFS initialised ok, try init the card, this also sets up the SPI1
		if(!(f_err_code=f_open(&FATFS_logfile,(const TCHAR*)"time.txt",FA_OPEN_EXISTING|FA_READ|FA_WRITE))){//Try to open time file get system time
			if(!f_stat((const TCHAR *)"time.txt",&FATFS_info)) {//Get file info
				if(FATFS_info.fsize<5) {	//Empty file
					RTC_time.year=(FATFS_info.fdate>>9)+1980;//populate the time struct (FAT start==1980, RTC.year==0)
					RTC_time.month=(FATFS_info.fdate>>5)&0x000F;
					RTC_time.mday=FATFS_info.fdate&0x001F;
					RTC_time.hour=(FATFS_info.ftime>>11)&0x001F;
					RTC_time.min=(FATFS_info.ftime>>5)&0x003F;
					RTC_time.sec=(FATFS_info.ftime<<1)&0x003E;
					rtc_settime(&RTC_time);
					rprintfInit(__fat_print_char);//printf to the open file
					printf("RTC set to %d/%d/%d %d:%d:%d\n",RTC_time.mday,RTC_time.month,RTC_time.year,\
					RTC_time.hour,RTC_time.min,RTC_time.sec);
				}				
			}
			f_close(&FATFS_logfile);	//Close the time.txt file
		}
		// load settings if file exists
		Watchdog_Reset();			//Card Init can take a second or two
		if(!f_open(&FATFS_logfile,(const TCHAR *)"settings.dat",FA_OPEN_EXISTING | FA_READ)) {
			UINT br;
			int8_t rtc_correction;
			f_read(&FATFS_logfile, (void*)(&rtc_correction),sizeof(rtc_correction),&br);
			//Use the setting to apply correction to the RTC
                        if(br && (rtc_correction<30) && (rtc_correction>-92) && rtc_correction ) {
                                PWR_BackupAccessCmd(ENABLE);/* Allow access to BKP Domain */
                                uint16_t tweaked_prescale = (0x0001<<15)-2;/* Try to run the RTC slightly too fast so it can be corrected either way */
                                RTC_WaitForSynchro();   /* Wait for RTC registers synchronization */
                                if( RTC->PRLL != tweaked_prescale ) {/*Note that there is a 0.5ppm offset here (correction 0==0.5ppm slow)*/
                                        RTC_SetPrescaler(tweaked_prescale); /* RTC period = RTCCLK/RTC_PR = (32.768 KHz)/(32767-2+1) */
                                        RTC_WaitForLastTask();
                                }
                                BKP_SetRTCCalibrationValue((uint8_t) ((int16_t)31-(21*(int16_t)rtc_correction)/(int16_t)20) );
                                BKP_RTCOutputConfig(BKP_RTCOutputSource_None);/* Ensure any output is disabled here */
                                /* Lock access to BKP Domain */
                                PWR_BackupAccessCmd(DISABLE);
                        }
                        else if(br && ((uint8_t)rtc_correction==0x91) ) {/* 0x91 magic flag sets the RTC clock output on */
                                PWR_BackupAccessCmd(ENABLE);/* Allow access to BKP Domain */
                                BKP_RTCOutputConfig(BKP_RTCOutputSource_CalibClock);/* Output a 512Hz reference clock on the TAMPER pin*/
                                PWR_BackupAccessCmd(DISABLE);
                        }
			if(br) {
				f_read(&FATFS_logfile, (void*)(&shutdown_lock),sizeof(shutdown_lock),&br);/*This needs to be set with the same magic flag value*/
				if(br==2) {
                                	PWR_BackupAccessCmd(ENABLE);/* Allow access to BKP Domain */
					BKP_WriteBackupRegister(BKP_DR3,shutdown_lock);//Wipe the shutdown lock setting
                               		PWR_BackupAccessCmd(DISABLE);
				}
			}
			if(br==2) {			//Read was successful, next try to read 5 bytes of packet header
				f_read(&FATFS_logfile, (void*)(silabs_header),5,&br);
				if(br!=5)
					silabs_header_=silabs_header;
			}
			f_close(&FATFS_logfile);	//Close the settings.dat file
		}
#ifndef SINGLE_LOGFILE
		rtc_gettime(&RTC_time);			//Get the RTC time and put a timestamp on the start of the file
		rprintfInit(__str_print_char);		//Print to the string
		printf("%02d-%02d-%02dT%02d-%02d-%02d-%s.csv",RTC_time.year,RTC_time.month,RTC_time.mday,RTC_time.hour,RTC_time.min,RTC_time.sec,"Log");//Timestamp name
		rprintfInit(__usart_send_char);		//Printf over the bluetooth
#endif
		Watchdog_Reset();			//Card Init can take a second or two
		if((f_err_code=f_open(&FATFS_logfile,(TCHAR*)LOGFILE_NAME,FA_CREATE_ALWAYS | FA_WRITE))) {//Present
			Delay(10000);
			if((f_err_code=f_open(&FATFS_logfile,(TCHAR*)LOGFILE_NAME,FA_CREATE_ALWAYS | FA_WRITE))) {//Try again
				printf("FatFs drive error %d\r\n",f_err_code);
				if(f_err_code==FR_DISK_ERR || f_err_code==FR_NOT_READY)
					Usart_Send_Str((char*)"No uSD card inserted?\r\n");
			}
		}
		else {
			Watchdog_Reset();		//Card Init can take a second or two
			print_string[strlen(print_string)-4]=0x00;//Wipe the .csv off the string
			strcat(print_string,"_gyro.wav");
			if((f_err_code=f_open(&FATFS_wavfile_gyro,(TCHAR*)LOGFILE_NAME,FA_CREATE_ALWAYS | FA_WRITE))) {//Present
				printf("FatFs drive error %d\r\n",f_err_code);
				if(f_err_code==FR_DISK_ERR || f_err_code==FR_NOT_READY)
					Usart_Send_Str((char*)"No uSD card inserted?\r\n");
			}
			else {					//We have a mounted card
				f_err_code=f_lseek(&FATFS_logfile, PRE_SIZE);// Pre-allocate clusters
				if (f_err_code || f_tell(&FATFS_logfile) != PRE_SIZE)// Check if the file size has been increased correctly
					Usart_Send_Str((char*)"Pre-Allocation error\r\n");
				else {
					if((f_err_code=f_lseek(&FATFS_logfile, 0)))//Seek back to start of file to start writing
						Usart_Send_Str((char*)"Seek error\r\n");
					else
						rprintfInit(__str_print_char);//Printf to the logfile
				}
				if(f_err_code)
					f_close(&FATFS_logfile);//Close the already opened file on error
				else
					file_opened=1;		//So we know to close the file properly on shutdown
				if(file_opened==1) {
					Watchdog_Reset();	//Card Init can take a second or two
					if (f_err_code || f_tell(&FATFS_wavfile_gyro) != PRE_SIZE)// Check if the file size has been increased correctly
						Usart_Send_Str((char*)"Pre-Allocation error\r\n");
					else {
						if((f_err_code=f_lseek(&FATFS_logfile, 0)))//Seek back to start of file to start writing
							Usart_Send_Str((char*)"Seek error\r\n");
						else
							rprintfInit(__str_print_char);//Printf to the logfile
					}
					if(f_err_code)
						f_close(&FATFS_wavfile_gyro);//Close the already opened file on error
					else
						file_opened|=2;	//So we know to close the file properly on shutdown
				}
			}
		}
	}
	f_err_code|=write_wave_header(&FATFS_wavfile_gyro, 4, 100, 16);//4 channels, last channel is for the current rpm
	Watchdog_Reset();				//Card Init can take a second or two
	//Setup and test the silabs radio
	silab=si446x_setup(silabs_header_);
	if(silab!=0x44) {				//Should return the device code
		print_string[0]=0x00;
		printf("Silabs: %02x\n",silab);
		f_puts("Silabs detect error, got:",&FATFS_logfile);
		f_puts(print_string,&FATFS_logfile);
		shutdown_filesystem(ERR, file_opened);//So we log that something went wrong in the logfile
		shutdown();
	}
	}//Context
示例#23
0
int main(void)
{
	uint32_t data_counter=0;			//used as data timestamp
	uint8_t deadly_flashes=0,system_state=0,repetition_counter=0;
	int16_t sensor_data, sensor_raw_data[3]={};	//used for handling data passed back from sensors
	int16_t sfe_sensor_ref_buff[2][3],sfe_sensor_ref_buff_old[2][3];//used to detect and fix I2C bus lockup
	RTC_t RTC_time;
	wave_stuffer Gyro_wav_stuffer={0,0},Accel_wav_stuffer={0,0};//Used to controlling wav file bit packing
	SystemInit();					//Sets up the clk
	setup_gpio();					//Initialised pins, and detects boot source
	DBGMCU_Config(DBGMCU_IWDG_STOP, ENABLE);	//Watchdog stopped during JTAG halt
	if(RCC->CSR&RCC_CSR_IWDGRSTF) {			//Watchdog reset, turn off
		RCC->CSR|=RCC_CSR_RMVF;			//Reset the reset flags
		shutdown();
	}
	SysTick_Configuration();			//Start up system timer at 100Hz for uSD card functionality
	Watchdog_Config(WATCHDOG_TIMEOUT);		//Set the watchdog
	Watchdog_Reset();				//Reset watchdog as soon as possible incase it is still running at power on
	rtc_init();					//Real time clock initialise - (keeps time unchanged if set)
	Usarts_Init();
	ISR_Config();
	rprintfInit(__usart_send_char);			//Printf over the bluetooth
	if(USB_SOURCE==bootsource) {
		Set_System();				//This actually just inits the storage layer
		Set_USBClock();
		USB_Interrupts_Config();
		USB_Init();
		uint32_t nojack=0x000FFFFF;		//Countdown timer - a few hundered ms of 0v on jack detect forces a shutdown
		while (bDeviceState != CONFIGURED) {	//Wait for USB config - timeout causes shutdown
			if(Millis>10000 || !nojack)	//No USB cable - shutdown (Charger pin will be set to open drain, cant be disabled without usb)
				shutdown();
			if(GET_CHRG_STATE)		//Jack detect resets the countdown
				nojack=0x0FFFFF;
			nojack--;
			Watchdog_Reset();		//Reset watchdog here, if we are stalled here the Millis timeout should catch us
		}
		USB_Configured_LED();
		EXTI_ONOFF_EN();			//Enable the off interrupt - allow some time for debouncing
		while(1) {				//If running off USB (mounted as mass storage), stay in this loop - dont turn on anything
			if(Millis%1000>500)		//1Hz on/off flashing
				switch_leds_on();	//Flash the LED(s)
			else
				switch_leds_off();
			Watchdog_Reset();
			__WFI();			//Sleep until something arrives
		}
	}
	else {
		if(!GET_PWR_STATE)			//Check here to make sure the power button is still pressed, if not, sleep
			shutdown();			//This means a glitch on the supply line, or a power glitch results in sleep
		EXTI_ONOFF_EN();			//Enable the off interrupt - allow some time for debouncing
		ADC_Configuration();			//At present this is purely here to detect low battery
		do {
			battery_voltage=Battery_Voltage;//Have to flush adc for some reason
			Delay(25000);
		} while(fabs(Battery_Voltage-battery_voltage)>0.01 || !battery_voltage);
		I2C_Config();				//Setup the I2C bus
		Sensors=detect_sensors(0);		//Search for connected sensors
		if(battery_voltage<BATTERY_STARTUP_LIMIT)
			deadly_flashes=1;
		if(!(Sensors&(1<<FOREHEAD_ACCEL)))	//Check for any missing sensors
			deadly_flashes=2;
		if(!(Sensors&(1<<(FOREHEAD_GYRO-1))))
			deadly_flashes=3;
		if(!(Sensors&(1<<(SFE_1_ACCEL-1))))
			deadly_flashes=4;
		if(!(Sensors&(1<<(SFE_1_MAGNO-1))))
			deadly_flashes=5;
		if(!(Sensors&(1<<(SFE_1_GYRO-1))))
			deadly_flashes=6;
		if(!(Sensors&(1<<(SFE_2_ACCEL-3))))
			deadly_flashes=7;
		if(!(Sensors&(1<<(SFE_2_MAGNO-3))))
			deadly_flashes=8;
		if(!(Sensors&(1<<(SFE_2_GYRO-3))))
			deadly_flashes=9;
		if((f_err_code = f_mount(0, &FATFS_Obj)))Usart_Send_Str((char*)"FatFs mount error\r\n");//This should only error if internal error
		else if(!deadly_flashes){		//FATFS and the I2C initialised ok, try init the card, this also sets up the SPI1
			if(!f_open(&FATFS_logfile,"time.txt",FA_OPEN_EXISTING | FA_READ | FA_WRITE)) {//Try and open a time file to get the system time
				if(!f_stat((const TCHAR *)"time.txt",&FATFS_info)) {//Get file info
					if(!FATFS_info.fsize) {//Empty file
						RTC_time.year=(FATFS_info.fdate>>9)+1980;//populate the time struct (FAT start==1980, RTC.year==0)
						RTC_time.month=(FATFS_info.fdate>>5)&0x000F;
						RTC_time.mday=FATFS_info.fdate&0x001F;
						RTC_time.hour=(FATFS_info.ftime>>11)&0x001F;
						RTC_time.min=(FATFS_info.ftime>>5)&0x003F;
						RTC_time.sec=(FATFS_info.ftime<<1)&0x003E;
						rtc_settime(&RTC_time);
						rprintfInit(__fat_print_char);//printf to the open file
						printf("RTC set to %d/%d/%d %d:%d:%d\n",RTC_time.mday,RTC_time.month,RTC_time.year,\
						RTC_time.hour,RTC_time.min,RTC_time.sec);
					}				
				}
				f_close(&FATFS_logfile);//Close the time.txt file
			}
			rtc_gettime(&RTC_time);		//Get the RTC time and put a timestamp on the start of the file
			rprintfInit(__str_print_char);	//Print to the string
			//timestamp name
			printf("%d-%02d-%02dT%02d-%02d-%02d",RTC_time.year,RTC_time.month,RTC_time.mday,RTC_time.hour,RTC_time.min,RTC_time.sec);
			rprintfInit(__usart_send_char);	//Printf over the bluetooth
			f_err_code = f_mkdir(print_string); //Try to make a directory where the logfiles will live
			if(f_err_code) {
				printf("FatFs drive error %d\r\n",f_err_code);
				if(f_err_code==FR_DISK_ERR || f_err_code==FR_NOT_READY)
					Usart_Send_Str((char*)"No uSD card inserted?\r\n");
				repetition_counter=1;
			}
			else
				f_err_code=f_chdir(print_string);//enter our new directory
			if(f_err_code) {
				if(!repetition_counter)
					printf("FatFs drive error entering direcotry %d\r\n",f_err_code);
				repetition_counter=1;
			}
			else {
				strcat(print_string,".csv");
				f_err_code=f_open(&FATFS_logfile,print_string,FA_CREATE_ALWAYS | FA_WRITE);//Try to open the main 100sps csv logfile
			}
			if(f_err_code) {
				if(!repetition_counter)
					printf("FatFs drive error creating logfile %d\r\n",f_err_code);
				repetition_counter=1;
			}
			else {	
				print_string[strlen(print_string)-4]=0x00;	//Wipe the .csv off the string
				strcat(print_string,"_accel.wav");
				f_err_code=f_open(&FATFS_wavfile_accel,print_string,FA_CREATE_ALWAYS | FA_WRITE);//Try to open the accel wav logfile
			}
			if(f_err_code) {
				if(!repetition_counter)
					printf("FatFs drive error creating accel wav file %d\r\n",f_err_code);
				repetition_counter=1;
			}
			else {	
				print_string[strlen(print_string)-9]=0x00;	//Wipe the accel.wav off the string
				strcat(print_string,"gyro.wav");
				f_err_code=f_open(&FATFS_wavfile_gyro,print_string,FA_CREATE_ALWAYS | FA_WRITE);//Try to open the gyro wav logfile
			}
			if(f_err_code) {
				if(!repetition_counter)
					printf("FatFs drive error creating gyro wav file %d\r\n",f_err_code);
			}
			else {				//We have a mounted card
				print_string[0]=0x00;	//Wipe the string
				f_err_code=f_lseek(&FATFS_logfile, PRE_SIZE);// Pre-allocate clusters
				if (f_err_code || f_tell(&FATFS_logfile) != PRE_SIZE)// Check if the file size has been increased correctly
					Usart_Send_Str((char*)"Pre-Allocation error\r\n");
				else {
					if((f_err_code=f_lseek(&FATFS_logfile, 0)))//Seek back to start of file to start writing
						Usart_Send_Str((char*)"Seek error\r\n");
					else
						rprintfInit(__str_print_char);//Printf to the logfile
				}
				if(f_err_code)
					f_close(&FATFS_logfile);//Close the already opened file on error
				else
					file_opened=0x01;//So we know to close the file properly on shutdown - bit mask for the files
				if(!f_err_code) {
					f_err_code=f_lseek(&FATFS_wavfile_accel, PRE_SIZE);// Pre-allocate clusters
					if (f_err_code || f_tell(&FATFS_wavfile_accel) != PRE_SIZE)// Check if the file size has been increased correctly
						Usart_Send_Str((char*)"Pre-Allocation error\r\n");
					else {
						if((f_err_code=f_lseek(&FATFS_wavfile_accel, 0)))//Seek back to start of file to start writing
							Usart_Send_Str((char*)"Seek error\r\n");
					}
					if(f_err_code)
						f_close(&FATFS_wavfile_accel);//Close the already opened file on error
					else
						file_opened|=0x02;//So we know to close the file properly on shutdown - bit mask for the files
				}
				if(!f_err_code) {
					f_err_code=f_lseek(&FATFS_wavfile_gyro, PRE_SIZE);// Pre-allocate clusters
					if (f_err_code || f_tell(&FATFS_wavfile_gyro) != PRE_SIZE)// Check if the file size has been increased correctly
						Usart_Send_Str((char*)"Pre-Allocation error\r\n");
					else {
						if((f_err_code=f_lseek(&FATFS_wavfile_gyro, 0)))//Seek back to start of file to start writing
							Usart_Send_Str((char*)"Seek error\r\n");
					}
					if(f_err_code)
						f_close(&FATFS_wavfile_gyro);//Close the already opened file on error
					else
						file_opened|=0x04;//So we know to close the file properly on shutdown - bit mask for the files
				}
			}
		}
		repetition_counter=0;			//Reset this here	
		//We die, but flash out a number of flashes first
		if(f_err_code || deadly_flashes) {	//There was an init error
			for(;deadly_flashes;deadly_flashes--) {
				RED_LED_ON;
				Delay(200000);
				RED_LED_OFF;
				Delay(200000);
				Watchdog_Reset();
			}
			RED_LED_ON;
			Delay(400000);
			shutdown();			//Abort after a (further )single red flash
		}
	}
示例#24
0
int main(void)
{
	uint32_t ppg;					//PPG channel
	uint32_t data_counter=0;			//used as data timestamp
	uint8_t system_state=0;				//used to track button press functionality
	float sensor_data;				//used for handling data passed back from sensors
	RTC_t RTC_time;
        _REENT_INIT_PTR(&my_reent);
        _impure_ptr = &my_reent;
	SystemInit();					//Sets up the clk
	setup_gpio();					//Initialised pins, and detects boot source
	DBGMCU_Config(DBGMCU_IWDG_STOP, ENABLE);	//Watchdog stopped during JTAG halt
	if(RCC->CSR&RCC_CSR_IWDGRSTF) {			//Watchdog reset, turn off
		RCC->CSR|=RCC_CSR_RMVF;			//Reset the reset flags
		shutdown();
	}
	SysTick_Configuration();			//Start up system timer at 100Hz for uSD card functionality
	Watchdog_Config(WATCHDOG_TIMEOUT);		//Set the watchdog
	Watchdog_Reset();				//Reset watchdog as soon as possible incase it is still running at power on
	rtc_init();					//Real time clock initialise - (keeps time unchanged if set)
	Usarts_Init();
	ISR_Config();
	rprintfInit(__usart_send_char);			//Printf over the bluetooth
	if(USB_SOURCE==bootsource) {
		Set_System();				//This actually just inits the storage layer
		Set_USBClock();
		USB_Interrupts_Config();
		USB_Init();
		uint32_t nojack=0x000FFFFF;		//Countdown timer - a few hundered ms of 0v on jack detect forces a shutdown
		while (bDeviceState != CONFIGURED) {	//Wait for USB config - timeout causes shutdown
			if(Millis>10000 || !nojack)	//No USB cable - shutdown (Charger pin will be set to open drain, cant be disabled without usb)
				shutdown();
			if(GET_VBUS_STATE)		//Jack detect resets the countdown
				nojack=0x0FFFFF;
			nojack--;
			Watchdog_Reset();		//Reset watchdog here, if we are stalled here the Millis timeout should catch us
		}
		USB_Configured_LED();
		EXTI_ONOFF_EN();			//Enable the off interrupt - allow some time for debouncing
		while(1) {				//If running off USB (mounted as mass storage), stay in this loop - dont turn on anything
			if(Millis%1000>500)		//1Hz on/off flashing
				switch_leds_on();	//Flash the LED(s)
			else
				switch_leds_off();
			Watchdog_Reset();
		}
	}
	if(!GET_PWR_STATE)				//Check here to make sure the power button is still pressed, if not, sleep
		shutdown();				//This means a glitch on the supply line, or a power glitch results in sleep
	for(uint8_t n=0;n<PPG_CHANNELS;n++)
		init_buffer(&(Buff[n]),PPG_BUFFER_SIZE);//Enough for ~0.25S of data
	setup_pwm();					//Enable the PWM outputs on all three channels
	Delay(100000);					//Sensor+inst amplifier takes about 100ms to stabilise after power on
	ADC_Configuration();				//We leave this a bit later to allow stabilisation
	calibrate_sensor();				//Calibrate the offset on the diff pressure sensor
	EXTI_ONOFF_EN();				//Enable the off interrupt - allow some time for debouncing
	I2C_Config();					//Setup the I2C bus
	uint8_t sensors_=detect_sensors();		//Search for connected sensors
	sensor_data=GET_BATTERY_VOLTAGE;		//Have to flush adc for some reason
	Delay(10000);
	if(!(sensors_&~(1<<PRESSURE_HOSE))||GET_BATTERY_VOLTAGE<BATTERY_STARTUP_LIMIT) {//We will have to turn off
		Watchdog_Reset();			//LED flashing takes a while
		if(abs(Reported_Pressure)>PRESSURE_MARGIN)
			Set_Motor(-1);			//If the is air backpressure, dump to rapidly drop to zero pressure before turnoff
		if(file_opened)
			f_close(&FATFS_logfile);	//be sure to terminate file neatly
		red_flash();
		Delay(400000);
		red_flash();				//Two flashes means battery abort -----------------ABORT 2
		if(sensors_&~(1<<PRESSURE_HOSE))
			shutdown();
		Delay(400000);
		red_flash();				//Three flashes means no sensors abort ------------ABORT 3
		shutdown();
	}
	if((f_err_code = f_mount(0, &FATFS_Obj)))Usart_Send_Str((char*)"FatFs mount error\r\n");//This should only error if internal error
	else {						//FATFS initialised ok, try init the card, this also sets up the SPI1
		if(!f_open(&FATFS_logfile,"time.txt",FA_OPEN_EXISTING | FA_READ | FA_WRITE)) {//Try and open a time file to get the system time
			if(!f_stat((const TCHAR *)"time.txt",&FATFS_info)) {//Get file info
				if(!FATFS_info.fsize) {	//Empty file
					RTC_time.year=(FATFS_info.fdate>>9)+1980;//populate the time struct (FAT start==1980, RTC.year==0)
					RTC_time.month=(FATFS_info.fdate>>5)&0x000F;
					RTC_time.mday=FATFS_info.fdate&0x001F;
					RTC_time.hour=(FATFS_info.ftime>>11)&0x001F;
					RTC_time.min=(FATFS_info.ftime>>5)&0x003F;
					RTC_time.sec=(FATFS_info.ftime<<1)&0x003E;
					rtc_settime(&RTC_time);
					rprintfInit(__fat_print_char);//printf to the open file
					printf("RTC set to %d/%d/%d %d:%d:%d\n",RTC_time.mday,RTC_time.month,RTC_time.year,\
					RTC_time.hour,RTC_time.min,RTC_time.sec);
				}				
			}
			f_close(&FATFS_logfile);	//Close the time.txt file
		}
#ifndef SINGLE_LOGFILE
		rtc_gettime(&RTC_time);			//Get the RTC time and put a timestamp on the start of the file
		rprintfInit(__str_print_char);		//Print to the string
		printf("%d-%d-%dT%d-%d-%d.txt",RTC_time.year,RTC_time.month,RTC_time.mday,RTC_time.hour,RTC_time.min,RTC_time.sec);//Timestamp name
		rprintfInit(__usart_send_char);		//Printf over the bluetooth
#endif
		if((f_err_code=f_open(&FATFS_logfile,LOGFILE_NAME,FA_CREATE_ALWAYS | FA_WRITE))) {//Present
			printf("FatFs drive error %d\r\n",f_err_code);
			if(f_err_code==FR_DISK_ERR || f_err_code==FR_NOT_READY)
				Usart_Send_Str((char*)"No uSD card inserted?\r\n");
		}
		else {					//We have a mounted card
			f_err_code=f_lseek(&FATFS_logfile, PRE_SIZE);// Pre-allocate clusters
			if (f_err_code || f_tell(&FATFS_logfile) != PRE_SIZE)// Check if the file size has been increased correctly
				Usart_Send_Str((char*)"Pre-Allocation error\r\n");
			else {
				if((f_err_code=f_lseek(&FATFS_logfile, 0)))//Seek back to start of file to start writing
					Usart_Send_Str((char*)"Seek error\r\n");
				else
					rprintfInit(__str_print_char);//Printf to the logfile
			}
			if(f_err_code)
				f_close(&FATFS_logfile);//Close the already opened file on error
			else
				file_opened=1;		//So we know to close the file properly on shutdown
		}
	}
示例#25
0
//------------------------------------------------------------------------------
//! void CAN_UserProcessMsg(void)
//------------------------------------------------------------------------------
//! @brief	Processes incoming CAN messages
//------------------------------------------------------------------------------
void CAN_UserProcessMsg(void){
	RTC rtc;
	CANMsg_t msg;
	u8_t res=0;
	static u8_t toggle_led=0;
	CRCInit_t cfg= CRC32_CONFIG;
	u32_t cnt=0;


	res = CAN_UserRead(&msg);
	if(!res)
		return;

#if 0
	if(toggle_led){
		HW_SetLED (HW_LED_STATUS_2, HW_LED_GREEN);
		toggle_led = 0;
	}else{
		HW_SetLED (HW_LED_STATUS_2, HW_LED_ORANGE);
		toggle_led = 1;
	}
#endif

	if(msg.Id<INCOMING_CAN_ID_MIN || msg.Id>INCOMING_CAN_ID_MAX)
		return;

	switch(msg.Id){
	case SYM_OUT_IO:
		HW_SetDOUTn(HW_DOUT_1, (msg.Data.Data8[0] & 0x01));

		if (msg.Data.Data8[0] & 0x02)
			HW_GPS_PowerOn();
		else
			HW_GPS_PowerOff();
		break;

	case SYM_OUT_POWEROFF:
		if(msg.Data.Data8[0]&0x01)
			HW_SwitchOFF();
		break;

	case SYM_OUT_GYRO:
		MEMS_L3GD20_SetRange(msg.Data.Data8[0]&0x03);
		break;

	case SYM_OUT_ACC_SCALE:
		MEMS_BMC050_SetAccRange(msg.Data.Data8[0]&0x7);
		break;

	case SYM_OUT_SAVE_CFG:
		// only write configuration if LSB in lowest byte is set
		if(!(msg.Data.Data8[0]&0x1))
			break;

		MEMS_BMC050_GetAccCalTargets(	&cfg_data.Acc.cmp_target_x,
										&cfg_data.Acc.cmp_target_y,
										&cfg_data.Acc.cmp_target_z);
		MEMS_BMC050_GetAccRange(&cfg_data.Acc.range);
#if STORE_ACC_COMPENSATION_PERMANENT
		cfg_data.Acc.flags |= ACC_USE_EEPROM_RAW_COMPENSATION_VALUES;
		cfg_data.Acc.flags |= ACC_USE_EEPROM_FILT_COMPENSATION_VALUES;

		MEMS_BMC050_GetAccCalFiltValues(&cfg_data.Acc.cmp_filt_x,
										&cfg_data.Acc.cmp_filt_y,
										&cfg_data.Acc.cmp_filt_z);
		MEMS_BMC050_GetAccCalRawValues(	&cfg_data.Acc.cmp_raw_x,
										&cfg_data.Acc.cmp_raw_y,
										&cfg_data.Acc.cmp_raw_z);
#else
		cfg_data.Acc.flags = 0;
#endif

		MEMS_L3GD20_GetRange(&cfg_data.Gyro.range);

		res = CRC_Init(&cfg);
		if(res != CRC_ERR_OK)
			break;

		cnt = sizeof(cfg_data)-sizeofmember(S_CONFIG_DATA_t, crc32);
		res = CRC_CalcCRC((void*) &cfg_data, cnt, t_crc_8_bit, &cfg_data.crc32);
		if(res != CRC_ERR_OK)
					break;

		if(EEPROM_Write(EEPROM_INT, EEPROM_CFG_ADDR, &cfg_data,
				sizeof(cfg_data))!= EEPROM_ERR_OK){
			// write failed
		}
		if(EEPROM_FlushCache(EEPROM_INT)!= EEPROM_ERR_OK){
			// flush failed
		}
		break;

	case SYM_OUT_RTC_SET_TIME:
		rtc.sec = msg.Data.Data8[0] ;
		rtc.min	= msg.Data.Data8[1] ;
		rtc.hour = msg.Data.Data8[2] ;
		rtc.wday = msg.Data.Data8[3] ;
		rtc.mday = msg.Data.Data8[4] ;
		rtc.month = msg.Data.Data8[5] ;
		rtc.year = msg.Data.Data16[3] ;
		rtc_settime(&rtc);
		break;

	case SYM_OUT_RTC_ADOPT_GPS_TIME:
		if(!(msg.Data.Data8[0]&0x1))
			break;

		// only copy values if they are valid
		if((MAX7W_Readings.Validity & GPS_TIME_VALID)!=GPS_TIME_VALID)
			break;
		if((MAX7W_Readings.Validity & GPS_DATE_VALID)!=GPS_DATE_VALID)
			break;

		// get old values to keep day of week that was set before
		rtc_gettime(&rtc);

		rtc.sec = MAX7W_Readings.Time_Sec;
		rtc.min	= MAX7W_Readings.Time_Min;
		rtc.hour = MAX7W_Readings.Time_Hrs;
		rtc.mday = MAX7W_Readings.Date_DayOfMonth;
		rtc.month = MAX7W_Readings.Date_Month;
		rtc.year = MAX7W_Readings.Date_Year;
		rtc_settime(&rtc);
		break;

	case SYM_OUT_ACC_FAST_CALIBRATION:
		MEMS_BMC050_SetAccCalTargets(&msg.Data.Data8[0], &msg.Data.Data8[1], &msg.Data.Data8[2]);
		if(msg.Data.Data8[3]&0x1)
			MEMS_BMC050_StartFastAccCompensation();
		break;

	default:
		break;
	}

	return;
}
示例#26
0
int main(void)
{
//***********************************DEBUG********************************************/
#if 0

nmeaPOS p1,p2;
nmeaINFO info;
info.lat = 5547.1206;
info.lon = 4906.2111;
nmea_info2pos(&info, &p1);
info.lat = 5547.1221;
info.lon = 4906.208;
nmea_info2pos(&info, &p2);

m += 23;

u32 t    = nmea_distance(&p1, &p2);
if(m)
#endif
//***********************************END OF DEBUG********************************************/
  NVIC_Configuration();	//for  all peripheria
  if (SysTick_Config(SystemCoreClock / 1000))  //1ms
     { 
       /* Capture error */ 
       while (1);
     }
  Delay(500);


  USBIniPin();
  	  
  signUSBMass = USBDetectPin();
  signUSBMass = 0;  //deb
  #if not defined (VER_3)
    USBCommonIni(); 
  #endif
  if(signUSBMass)
    {
	 #if defined (VER_3)
	 USBCommonIni();
	 #endif
     while (bDeviceState != CONFIGURED);
	}
  else //if(!signUSBMass)
   {

  	 /* Flash unlock */
     FLASH_Unlock();
     /* Clear All pending flags */
     FLASH_ClearFlag(FLASH_FLAG_BSY | FLASH_FLAG_EOP | FLASH_FLAG_PGERR | FLASH_FLAG_WRPRTERR);	

//***********************************DEBUG********************************************/

     
//***********************************END OF DEBUG********************************************/
  /* Enable CRC clock */
  RCC_AHBPeriphClockCmd(RCC_AHBPeriph_CRC, ENABLE);
    
  ledDioGPIOInit();
  led_dn(BOARD_LED_ON);
  led_mid(BOARD_LED_ON);
#if defined (VER_3)
  led_up(BOARD_LED_ON);
  ibuttonInit();
  rfmodemInit();
#endif
  Delay(1000);
  alarmInit();
  BKPInit();

  //timer6Init();

  //rs485Init();
#if not defined (VER_3)
  ais326dq_init();
#endif

  //ais326dq_data(&ais326dq_out);
  /*ADC*/
  adcInit();
  /*GPS*/
  gpsInit();

  /* reading settings */
  readConfig();
  /*MODEM*/
  gprsModemInit();
  gprsModemOn(innerState.activeSIMCard);
//***********************************DEBUG********************************************/
  //GSMSpeaker(1);
//***********************************END OF DEBUG********************************************/

#ifndef BRIDGE_USB_GSM
  setupGSM();
  ftpGSMPrepare();
  packetsIni();
#endif

  led_dn(BOARD_LED_OFF);
  led_mid(BOARD_LED_OFF);
#if defined (VER_3)
  led_up(BOARD_LED_OFF);
#endif

  rtc_init();
  rtc_gettime(&rtc);

#if 1			  /* WATCH DOG */
  /* IWDG timeout equal to 3.27 sec (the timeout may varies due to LSI frequency dispersion) */
  /* Enable write access to IWDG_PR and IWDG_RLR registers */
  IWDG_WriteAccessCmd(IWDG_WriteAccess_Enable);
  /* IWDG counter clock: 40KHz(LSI) / 32 = 1.25 KHz */
  IWDG_SetPrescaler(IWDG_Prescaler_64);	//32
  /* Set counter reload value to 0xFFF */
  IWDG_SetReload(0xFFF);
  /* Reload IWDG counter */
  IWDG_ReloadCounter();
  /* Enable IWDG (the LSI oscillator will be enabled by hardware) */
  IWDG_Enable();
  setTimerIWDG(ONE_SEC);
#endif

  initSD();
#if defined (VER_3)
  //DACInit();
#endif

  /* Log  */
  saveSDInfo((u8 *)"TURN ON BLOCK ",strlen((u8 *)"TURN ON BLOCK "), SD_SENDED, SD_TYPE_MSG_LOG );
  //saveSDInfo((u8 *)readRTCTime(&rtc),strlen((const char *)readRTCTime(&rtc)), SD_SENDED, SD_TYPE_MSG_LOG );
#if defined (VER_3)  
  //DACSpeaker(1);
  //wp_play("0:/sound.wav");
  //DACSpeaker(0);
#endif 

  }	 //if(!signUSBMass)

  while (1)
  {
    if(!signUSBMass)
	  {
		 monitorWatchDog();

		 #ifndef BRIDGE_USB_GPS
	     if(!innerState.bootFTPStarted)
	         gpsHandling();
		 #endif

		 #ifndef BRIDGE_USB_GSM
		 if(!innerState.flagTmpDebug)
		    loopGSM();
			loopFTP();
            UpdatingFlash();
			if(!innerState.bootFTPStarted)
			   naviPacketHandle();
			rcvPacketHandle();
            rcvPacketHandleUSB();
		 #endif 

		 #if !defined (VER_3)
			 buttonScan();
		     accelScan();
		 #endif
		 
		 //rs485Analyse();
		 handleFOS();
		 executeDelayedCmd();
#if defined (VER_3)
		 #if 0 
		 if(innerState.flagDebug)
		 {
  			DACSpeaker(1);
	        /* Start DAC Channel1 conversion by software */
		    //a += 300;
    		//DAC_SetChannel1Data(DAC_Align_12b_R, 4000);
    		//DAC_SetChannel1Data(DAC_Align_12b_L, a);  //for saw
    		//DAC_SetChannel1Data(DAC_Align_8b_R, a);
			
			//DAC_SetChannel1Data(DAC_Align_12b_R, 4095);
			//DAC_SetChannel1Data(DAC_Align_12b_R, 0);
			//for (a = 0; a<4095; ++a)
			//for(;;)
			//  DAC_SetChannel1Data(DAC_Align_12b_R, 0);

			//DAC_SetChannel1Data(DAC_Align_12b_R, 0);
			//for ( ; ; )
			//{
			//   DAC_SoftwareTriggerCmd(DAC_Channel_1, ENABLE);
			//}
 

	        DAC_SoftwareTriggerCmd(DAC_Channel_1, ENABLE);  //debugga
		 }
		 else
		 {
		     DACSpeaker(0);
		 }
	  #endif
#endif
	 }
	else
	  handleUSBPresent();
  }	   //while(1)
}