示例#1
0
int main(void)
{
    /* Chip fixes provided by energymicro in errata 
    CHIP_Init();  I will see If needed ;)
    */

    /* Clock management unit initialization and configuration */
    initCMU();

    /* Real time clock initialization and configuration */
    initRTC();

    /* Voltage comparator initialization and configuration */
    initVCMP();

    /* General purpose IO initialization and configuration */
    initGPIO();

    /* Nested vector interrupt controller initialization and configuration */
    /* initNVIC(); disabled at the moment */

    /* SysTick clock initialization and configuraion 
     initSysTick(); SysTick doesn't work in deep sleep ;/
     */

    /* Clear reset causes */
    clearResetCauses();

    /* Configure deep sleep mode with event handling */
    SCB->SCR |= SCB_SCR_SEVONPEND_Msk |
                SCB_SCR_SLEEPDEEP_Msk;

    /* Enter debug mode If PA0 port is low during strtup */
    if (!(GPIO->P[GPIO_PORT_A].DIN & (GPIO_MASK_PIN(GPIO_PIN_0))))
        while(1);

    while(1)
    {
        /* Wait for event - no NVIC used */
        __WFE();

        /* Switch HFRCO to LFRCO since after event in most of cases will be
           executed in this while(1). Select proper prescalers 
        */
        enableLFRCO();

        /* Read pending interrupts and event handling */
        if (NVIC->ISPR[(uint32_t)PAGE0] & (uint32_t)(RTC_IRQn & 0x1F)) 
            RTC_EventHandler();

        if (NVIC->ISPR[(uint32_t)PAGE1] & (uint32_t)(VCMP_IRQn & 0x1F))
            VCMP_EventHandler();

        if (NVIC->ISPR[(uint32_t)PAGE0] & (uint32_t)(GPIO_ODD_IRQn & 0x1F))
            GPIO_ODD_EventHandler();

        if (NVIC->ISPR[(uint32_t)PAGE0] & (uint32_t)(GPIO_EVEN_IRQn & 0x1F))
            GPIO_EVEN_EventHandler();
    }
}
示例#2
0
static void setupHardware(void) {
	SystemInit();
	SystemCoreClockUpdate();//CLKPWR_ConfigPPWR()
	//allPinsAsOut();
	//delay_ms(500);
	powerSectionInit();

#ifdef USE_MODULE_GSM
	GSM_Init();
#endif

	sensorControlInit();
	setActiveChannel(1);
#ifdef USE_MODULE_SENSORS
	//DS18B20_Init();
	initSHT21();
#endif

	//debugLed();
	//displayInitialization();
	//qtouchKeyboardInitialization();

#ifdef USE_MODULE_RTC
	initRTC();
#endif
}
示例#3
0
// Init the clock modules
void ClockMaster::clockSetup(Alarm *alarm) {
  Serial.begin(9600);
  initRTC();
  dht.begin();
  tft.begin();
  initScreen();
  alarm->initAlarm(getTime());
}
示例#4
0
void SignalingWebSocketServer::start() {
	sem_init(&sem, 0, 0);
	th = std::thread([&](){
		initRTC();
		sem_post(&sem);
		this->run();
	});
	sem_wait(&sem);
}
示例#5
0
文件: main.c 项目: ctag/cpe495
/*
 * ======== main ========
 */
void main(void)
{
    WDT_A_hold(WDT_A_BASE); //Stop watchdog timer

    // Minimum Vcore setting required for the USB API is PMM_CORE_LEVEL_2
    PMM_setVCore(PMM_CORE_LEVEL_2);
    USBHAL_initPorts();           // Config GPIOS for low-power (output low)
    USBHAL_initClocks(8000000);   // Config clocks. MCLK=SMCLK=FLL=8MHz; ACLK=REFO=32kHz
    USB_setup(TRUE,TRUE);  // Init USB & events; if a host is present, connect
    initRTC();             // Start the real-time clock

    __enable_interrupt();  // Enable interrupts globally

    int prevLeft = getLeft();
    int prevRight = getRight();
    int left;
    int right;

    while (1)
    {
        // Enter LPM0, which keeps the DCO/FLL active but shuts off the
        // CPU.  For USB, you can't go below LPM0!
        __bis_SR_register(LPM0_bits + GIE);

        // If USB is present, sent the time to the host.  Flag is set every sec

        left = getLeft();
        right = getRight();
        timeStr[0] = '[';
        itoa(left, &timeStr[1], 10);
        itoa(right, &timeStr[2], 10);
        timeStr[3] = ']';
        timeStr[4] = '\n';
        timeStr[5] = '\0';
//
//        if (bSendTimeToHost)
//        {
//            bSendTimeToHost = FALSE;
//            convertTimeBinToASCII(timeStr);

            // This function begins the USB send operation, and immediately
            // returns, while the sending happens in the background.
            // Send timeStr, 9 bytes, to intf #0 (which is enumerated as a
            // COM port).  1000 retries.  (Retries will be attempted if the
            // previous send hasn't completed yet).  If the bus isn't present,
            // it simply returns and does nothing.
            if (USBCDC_sendDataInBackground(timeStr, 6, CDC0_INTFNUM, 1000))
            {
              _NOP();  // If it fails, it'll end up here.  Could happen if
                       // the cable was detached after the connectionState()
            }           // check, or if somehow the retries failed
//        }
    }  //while(1)
}  //main()
示例#6
0
/** Configures the board hardware and chip peripherals for the demo's functionality. */
void SetupHardware(void)
{
	/* Disable clock division */
	clock_prescale_set(clock_div_1);

	initRTC();
#ifdef USB_CDC
	initUSBSerial();
#endif
	sei();
	USB_Init();
}
示例#7
0
void initKernel() {
	printLine("--- START KERNEL INITIALIZATION ---");
	printLine("GDT: Computer running in Portected Mode.");
	printLine("SYS: Running with 32-Bit architecture.");

	initIDT();
	initRTC();

	printLine("--- END KERNEL INITIALIZATION ---");

	/*char buffer[10];
	itoa(getDay(), buffer, 10);

	printLine(buffer);
*/
}
/**************************************************************************//**
 * @brief  Main function
 *****************************************************************************/
int main(void)
{
  /* Initialize chip */
  CHIP_Init();

  SegmentLCD_Init(true);

  initRTC();
  initGPIO();

  /* Initial LCD content */
  SegmentLCD_Number(time);

  while (1)
  {
    /* Go to EM2 */
    EMU_EnterEM2(true);
    /* Wait for interrupts */
  }
}
int main()
{
    uint32_t Counter=0;
    initClockHSI16();
    configPins(); 
    initUART(9600);
    initRTC();
    initADC();    
    enable_interrupts();
    while(1)
    {
        
        resume_from_low_power(); // Interrupt woke up CPU - restore systems to full wakefulness
        // Awake now, do some control or other task.  
        GPIOB_ODR |= BIT3;  // Turn on LED
        testADC();          // read ADC channel 0 and output result to USART2
        drain(); // wait for any pending serial transmissions to end otherwise will exit sleep prematurely
        GPIOB_ODR &= ~BIT3; // Turn off LED
        low_power_mode();   // off to sleep to save power  
        
    } 
    return 0;
}
int main(void)
{
	i2c_init(I2C_CLOCK_SELECT(SCL_CLOCK,F_CPU));
	initRTC(0,0);
	
	uart_config_default_stdio();
	uart_init( UART_BAUD_SELECT(UART_BAUD_RATE,F_CPU) );
	
	sei();
	
	Date date;
	Timestamp ts;
   date.year   = 1988;
   date.month  = 12;
   date.day    = 13;
   date.hours   = 6;
   date.minutes = 13;
   date.seconds = 57;
        
	printf("\n\nSetting clock to %d:%d:%d on %d/%d/%d\n",date.hours,date.minutes,date.seconds,date.month,date.day,date.year);
	rtc_set_date(&date);   
	rtc_get_date(&date);
	printf("The time is now %d:%d:%d on %d/%d/%d\n",date.hours,date.minutes,date.seconds,date.month,date.day,date.year);
	rtc_setCounting(1);
	
	printf("Kindly type a key to view the updated time.\n");
	while(1)
	{
		fgetc(stdin);
		rtc_get_date(&date);
		printf("The time is now %d:%d:%d on %d/%d/%d",date.hours,date.minutes,date.seconds,date.month,date.day,date.year);
		rtc_date_to_timestamp(&date,&ts);
		printf(" (%ld)\n",ts);
	}
	
	return 0;
}
示例#11
0
int main( void )
{
	BaseType_t	res = pdPASS;
	rtc_t	rtc;
	TickType_t xTimeNow;
	/* Seed the random number generator. */
	xTimeNow = 0;//xTaskGetTickCount();
	prvSRand( 0);

#if configUSE_TRACE_FACILITY == 1
	vTraceInitTraceData();
	vTraceSetISRProperties(TIID_EthRx, "i_EthRx", IPRI_EthRx);
	vTraceSetISRProperties(TIID_EthTx, "i_EthTx", IPRI_EthTx);
	vTraceSetISRProperties(TIID_EthSys, "i_EthSys", IPRI_EthSys);
	vTraceSetISRProperties(TIID_Tmr0, "i_Tmr0", IPRI_Tmr0);
	vTraceSetISRProperties(TIID_Tmr1, "i_Tmr1", IPRI_Tmr1);
	vTraceSetISRProperties(TIID_Tmr2, "i_Tmr2", IPRI_Tmr2);
	vTraceSetISRProperties(TIID_rtc, "i_rtc", IPRI_rtc);
	vTraceSetISRProperties(TIID_uart0, "i_uart0", IPRI_uart0);
	vTraceSetISRProperties(TIID_uart1, "i_uart1", IPRI_uart1);
	vTraceSetISRProperties(TIID_button0, "i_swb0", IPRI_button0);
	vTraceSetISRProperties(TIID_button1, "i_swb1", IPRI_button1);
	vTraceSetISRProperties(TIID_button2, "i_swb2", IPRI_button2);
	// uiTraceStart(); 
	// vTraceStop()
#endif
		
#if INCLUDE_CONSOLE == 1 || INCLUDE_MODEM == 1  		// Include serial port 0 or serial port 1
	initSerial();
#endif

#if INCLUDE_RTC	== 1		// Include Realtime Clock
	initRTC();
#endif

#if INCLUDE_BUTTONS == 1
	initButtons();
#endif

#if INCLUDE_NETWORK
	/* Initialise the RTOS's TCP/IP stack.  The tasks that use the network
    are created in the vApplicationIPNetworkEventHook() hook function
    below.  The hook function is called when the network connects. */
	res = FreeRTOS_IPInit( ucIPAddress, ucNetMask, ucGatewayAddress, ucDNSServerAddress, ucMACAddress );
    //vRegisterSampleCLICommands();
	vRegisterTCPCLICommands();
	vRegisterMonitorCLICommands();
	
	// Commandline interface (Telnet port 5010)
	vStartTCPCommandInterpreterTask( 2048, 5010, tskIDLE_PRIORITY + 1);
#endif 

#ifdef INCLUDE_MONITOR
	// Demo Sysinfo 
	// Connect putty 115200,8,1,n (ansi terminal) to get the status informations
	res = xTaskCreate( sysinfo, "SysInfo", configMINIMAL_STACK_SIZE*2, (void *)portMAX_DELAY, PRIO_SYSINFO, NULL);
#endif


#if INCLUDE_LED5x7	== 1
	initLED5x7();
	res = xTaskCreate( TaskLED, "TaskLED", configMINIMAL_STACK_SIZE, (void *)portMAX_DELAY, PRIO_LED, NULL);
#endif

#ifdef CPM22 
	memset(cpmmem,0,sizeof(cpmmem));
	res = xTaskCreate( prvTCPCpmIOTask, "CPMIO", configMINIMAL_STACK_SIZE*2, (void*)cpmmem, PRIO_CPMIO, NULL);
#endif

	vTaskStartScheduler();

    return res;
}
示例#12
0
int main(void) {
	int i;
	char buff1[3];
	char buff2[3];
	initDisplay();
	initSomGenerator();
	initTimer0();
	initRC5();
	resetTimer0();
	initRTC();
	initRIT();
	setPriorities();

	int lastAlarmToggle = 0;

	char alarmBit;

	//////////////////////////////////
	char* test = generateSom();
	char som[10];
	strcpy(som, test);
	free(test);

	//////////////////////////////////

//	char arr[3];
//	readRAM(arr, 0x08);
//	delay(500);
//	alarmBit = arr[2];
//	clear();



	int arr2[3];
 	//int arr[3] = {0x00, 0x24, 0x12};
	//setTime(arr);

	readTime(arr2, 0x00);
 	if(arr2[2] < 10){
 		sprintf(buff1, "0%d", arr2[2]);
 	} else {
 		sprintf(buff1, "%d", arr2[2]);
 	}

 	if(arr2[1] < 10){
 		sprintf(buff2, "0%d", arr2[1]);
 	} else {
 		sprintf(buff2, "%d", arr2[1]);
 	}

	//Set the last known values in RIT.c
	lastValues[0] = arr2[0];
	lastValues[1] = arr2[1];
	lastValues[2] = arr2[2];

	sprintf(output, "%s:%s", buff1, buff2);

//    printf("%d\n", arr2[0]);
//    printf("%d\n", arr2[1]);
//    printf("%d\n", arr2[2]);
	//Main loop
	while (1) {


		while (!isTimeForAlarm(alarmBit) && (getCommand(commandCount - 1) != 15 && getCommand(commandCount - 1) != 11)) {
			//This is the main loop, all we do here is print the current time to the display since the current time is updated through the RIT and the EINT takes care of the remote control
			//Prints the current time
			printToDisplay(output);
		}

		if (getCommand(commandCount - 1) == 15) {
			//Goes into the set alarm state
			addAlarmState();
		}

		if (getCommand(commandCount - 1) == 11 && commandCount != lastAlarmToggle) { // '11' needs to be replaced with an other number, because it's an temporary button
			//Toggle alar state
			alarmBit = !alarmBit;
			toggleAlarmState(alarmBit);
			lastAlarmToggle = commandCount;
			//Give the user some feedback(Tell them wether they set or unset the alarm)
			for(i=0; i<200; i++){
				asm("nop");
				if(alarmBit == 1){
					printToDisplay("  +  ");
				} else {
					printToDisplay("  -  ");
				}

			}
		}

		if (isTimeForAlarm(alarmBit)) {
			//Goes into the alarm state
			alarmState();
			resetAlarmTime();

		}
		printToDisplay(output);
	}
	return 0;
}
示例#13
0
int main(void)
{
    initRTC();
    initControls();
    initLCD();
    initValve();

    // timer0 is being used as a global 'heartbeat'
    // i.e. for blinking in the LCD
    // and for running a temperature check at regular intervals
    TCCR0A = (1<<CS02)|(1<<CS00);	// timer clock = system clock / 1024
    TIFR0 = (1<<TOV0);				// clear pending interrupts
    TIMSK0 = (1<<TOIE0);			// enable timer0 overflow Interrupt

    sei();							// Enable Global Interrupts

    // start a probe run to find the "fully open" and "fully closed" positions
    doProbe();

    // initialize the NTC sensor and start the 1st measurement
    // consequent measurements will be done every tick
    initTemp();

    runstate = NORMAL_STATE;

    while (1)
    {
        if( adcTemp < targetTemp && valvestate != VALVE_OPEN )
        {
            openValve();
        }
        else if( valvestate != VALVE_CLOSED )
        {
            closeValve();
        }

        if( menuButtonPressed() )
        {
            switch( runstate )
            {
            case NORMAL_STATE :
                runstate = MENU_STATE;
                break;

            default :
                runstate = NORMAL_STATE;
                break;
            }
        } // end if( menuButtonPressed )

        if( timeButtonPressed() )
        {
            switch( runstate )
            {
            case NORMAL_STATE :
                runstate = TIMESET_STATE;
                timesetphase = TIMESET_START;

                _delay_ms( 500 );

                // show time with hours blinking
                timesetphase = TIMESET_YEAR;
                break;

            default :
                runstate = NORMAL_STATE;
                break;
            }
        } // end if( timeButtonPressed )

        if( okButtonPressed() )
        {
            switch( runstate )
            {
            case MENU_STATE :
                switch( mainmenu )
                {
                case TEMP :
                    runstate = TEMPSET_STATE;
                    break;

                case TIME :
                    runstate = TIMESET_STATE;
                    timesetphase = TIMESET_START;

                    _delay_ms( 500 );

                    // show time with hours blinking
                    timesetphase = TIMESET_YEAR;
                    break;

                default:
                    break;
                }
                break;

            case TEMPSET_STATE :
                runstate = MENU_STATE;
                break;

            case TIMESET_STATE :
                switch( timesetphase )
                {
                case TIMESET_YEAR :
                    timesetphase = TIMESET_MONTH;
                    break;

                case TIMESET_MONTH :
                    timesetphase = TIMESET_DATE;
                    break;

                case TIMESET_DATE :
                    timesetphase = TIMESET_HOURS;
                    break;

                case TIMESET_HOURS :
                    timesetphase = TIMESET_MINUTES;
                    break;

                case TIMESET_MINUTES :
                    timesetphase = TIMESET_YEAR;
                    break;

                default :
                    break;
                }
                break;

            default :
                break;
            }
        } // end if( okButtonPressed )

        ROTARYBUTTON rotaryButton = readRotaryButton();

        if( rotaryButton == ROTARY_UP )
        {
            switch( runstate )
            {
            case NORMAL_STATE :
            case MENU_STATE :
                mainmenu++;
                if( mainmenu == LAST_ITEM )
                    mainmenu = 0;
                break;

            case TIMESET_STATE :
                increaseClock( timesetphase );
                break;

            case TEMPSET_STATE :
                if( targetTemp >= 500 )
                    targetTemp = 0;
                else
                    targetTemp += 5;
                break;

            default :
                break;
            }
        } // end if( BUTTON_UP_PRESSED )

        if( rotaryButton == ROTARY_DOWN )
        {
            switch( runstate )
            {
            case NORMAL_STATE :
            case MENU_STATE :
                if( mainmenu == 0 )
                    mainmenu = LAST_ITEM;
                mainmenu--;
                break;

            case TIMESET_STATE :
                decreaseClock( timesetphase );
                break;

            case TEMPSET_STATE :
                if( targetTemp == 0 )
                    targetTemp = MAXTEMP;
                else
                    targetTemp -= 5;
                break;

            default :
                break;
            }
        } // end if( BUTTON_DOWN_PRESSED )

        // go to sleep but wake up if any button is pressed
        set_sleep_mode( SLEEP_MODE_ADC );
        sleep_mode();

    } // end while forever

}
示例#14
0
 int main(void) {

  uint8_t payload[ADVLEN];

  //Disable JTAG to allow for Standby
  AONWUCJtagPowerOff();

  //Force AUX on
  powerEnableAuxForceOn();
  powerEnableRFC();

  powerEnableXtalInterface();
  

  // Divide INF clk to save Idle mode power (increases interrupt latency)
  powerDivideInfClkDS(PRCM_INFRCLKDIVDS_RATIO_DIV32);

  initRTC();

  powerEnablePeriph();
  powerEnableGPIOClockRunMode();
  /* Wait for domains to power on */
  while((PRCMPowerDomainStatus(PRCM_DOMAIN_PERIPH) != PRCM_DOMAIN_POWER_ON));

  sensorsInit();
  ledInit();

  //Config IOID4 for external interrupt on rising edge and wake up
  //IOCPortConfigureSet(BOARD_IOID_KEY_RIGHT, IOC_PORT_GPIO, IOC_IOMODE_NORMAL | IOC_FALLING_EDGE | IOC_INT_ENABLE | IOC_IOPULL_UP | IOC_INPUT_ENABLE | IOC_WAKE_ON_LOW);

  // Config reedSwitch as input
  IOCPortConfigureSet(BOARD_IOID_DP0, IOC_PORT_GPIO, IOC_IOMODE_NORMAL | IOC_RISING_EDGE | IOC_INT_ENABLE | IOC_IOPULL_DOWN | IOC_INPUT_ENABLE | IOC_WAKE_ON_HIGH);
  //Set device to wake MCU from standby on PIN 4 (BUTTON1)
  HWREG(AON_EVENT_BASE + AON_EVENT_O_MCUWUSEL) = AON_EVENT_MCUWUSEL_WU0_EV_PAD;  //Does not work with AON_EVENT_MCUWUSEL_WU0_EV_PAD4 --> WHY??

  IntEnable(INT_EDGE_DETECT);

  powerDisablePeriph();
  //Disable clock for GPIO in CPU run mode
  HWREGBITW(PRCM_BASE + PRCM_O_GPIOCLKGR, PRCM_GPIOCLKGR_CLK_EN_BITN) = 0;
  // Load clock settings
  HWREGBITW(PRCM_BASE + PRCM_O_CLKLOADCTL, PRCM_CLKLOADCTL_LOAD_BITN) = 1;

  initInterrupts();
  initRadio();




  // baek: before while
      powerEnablePeriph();
      powerEnableGPIOClockRunMode();

       /* Wait for domains to power on */
     while((PRCMPowerDomainStatus(PRCM_DOMAIN_PERIPH) != PRCM_DOMAIN_POWER_ON)); // CRASH !!!!!!!!!!!!!!

       sensorsInit();
       ledInit();
  // end baek:


  // Turn off FLASH in idle mode
  powerDisableFlashInIdle();

  // Cache retention must be enabled in Idle if flash domain is turned off (to avoid cache corruption)
  powerEnableCacheRetention();

  //AUX - request to power down (takes no effect since force on is set)
  powerEnableAUXPdReq();
  powerDisableAuxRamRet();

  //Clear payload buffer
  memset(payload, 0, ADVLEN);

  while(1) {

  //if((g_count& 0x04)== 1){

    rfBootDone  = 0;
    rfSetupDone = 0;
    rfAdvertisingDone = 0;

	select_bmp_280();     				// activates I2C for bmp-sensor
	enable_bmp_280(1);					// works

    //Wait until RF Core PD is ready before accessing radio
    waitUntilRFCReady();
    initRadioInts();
    runRadio();

    //Wait until AUX is ready before configuring oscillators
    waitUntilAUXReady();

    //Enable 24MHz XTAL
    OSCHF_TurnOnXosc();

    //IDLE until BOOT_DONE interrupt from RFCore is triggered
    while( ! rfBootDone) {
      powerDisableCPU();
      PRCMDeepSleep();
    }

    //This code runs after BOOT_DONE interrupt has woken up the CPU again
    // ->
    //Request radio to keep on system bus
    radioCmdBusRequest(true);

    //Patch CM0 - no RFE patch needed for TX only
    radioPatch();

    //Start radio timer
    radioCmdStartRAT();

    //Enable Flash access while doing radio setup
    powerEnableFlashInIdle();

    //Switch to XTAL
    while( !OSCHF_AttemptToSwitchToXosc())
    {}
  
/* baek: before while
    powerEnablePeriph();
    powerEnableGPIOClockRunMode();

     /* Wait for domains to power on */
 /*    while((PRCMPowerDomainStatus(PRCM_DOMAIN_PERIPH) != PRCM_DOMAIN_POWER_ON)); // CRASH !!!!!!!!!!!!!!

     sensorsInit();
     ledInit();
*/
/*****************************************************************************************/
// Read sensor values


     uint32_t pressure = 0;  			// only 3 Bytes used
	//uint32_t temp = 0;
	select_bmp_280();     				// activates I2C for bmp-sensor
	enable_bmp_280(1);					// works

	do{
		pressure = value_bmp_280(BMP_280_SENSOR_TYPE_PRESS);  //  read and converts in pascal (96'000 Pa)
		//temp = value_bmp_280(BMP_280_SENSOR_TYPE_TEMP);
	}while(pressure == 0x80000000);
		if(pressure == 0x80000000){
			CPUdelay(100);

			pressure = value_bmp_280(BMP_280_SENSOR_TYPE_PRESS);  //  read and converts in pascal (96'000 Pa)

		}


    //Start Temp measurement
    uint16_t temperature;
    enable_tmp_007(1);

   //Wait for, read and calc temperature
    {
    int count = 0;
    do{
    	temperature = value_tmp_007(TMP_007_SENSOR_TYPE_AMBIENT);
    	//g_count++;
    }while( ((temperature == 0x80000000) || (temperature == 0)) && (count <=5) );
    count++;
	count--;
    }
    enable_tmp_007(0);
    char char_temp[2];



   //start hum measurement
        configure_hdc_1000();
        start_hdc_1000();
//    //Wait for, read and calc humidity
    while(!read_data_hdc_1000());
   int humidity = value_hdc_1000(HDC_1000_SENSOR_TYPE_HUMIDITY);
//    char char_hum[5];



//END read sensor values
/*****************************************************************************************/

    powerDisablePeriph();
	// Disable clock for GPIO in CPU run mode
	HWREGBITW(PRCM_BASE + PRCM_O_GPIOCLKGR, PRCM_GPIOCLKGR_CLK_EN_BITN) = 0;
	// Load clock settings
	HWREGBITW(PRCM_BASE + PRCM_O_CLKLOADCTL, PRCM_CLKLOADCTL_LOAD_BITN) = 1;

/*****************************************************************************************/
// Set payload and transmit
	uint8_t p;
    p = 0;

    /*jedes 5.te mal senden*/


		payload[p++] = ADVLEN-1;        /* len */
		payload[p++] = 0x03;
		payload[p++] = 0xde;
		payload[p++] = 0xba;
		payload[p++] =(sequenceNumber >> 8);				// laufnummer
		payload[p++] = sequenceNumber;

		// Speed
		payload[p++] = g_diff >> 24;						// higher seconds
		payload[p++] = g_diff >> 16;						// lower  seconds
		payload[p++] = g_diff >> 8;							// higher subseconds
		payload[p++] = g_diff;								// lower  subseconds

		//pressure
		payload[p++] = 0;
		payload[p++] = 0; //(pressure >> 16);
		payload[p++] = 0; //(pressure >> 8);
		payload[p++] = 0; //pressure;

		//temperature
		payload[p++] = 0;
		payload[p++] = 0; // char_temp[2];
		payload[p++] = 0;//temperature >> 8; // char_temp[1];
		payload[p++] = 0; //temperature; //char_temp[0];

		// huminity
		payload[p++] = 0;
		payload[p++] = 0;//char_hum[0];
		payload[p++] = 0;//char_hum[1];
		payload[p++] = 0;//char_hum[2];

		payload[p++] = 0;
		payload[p++] = 0;



		//Start radio setup and linked advertisment
		radioUpdateAdvData(ADVLEN, payload);

		//Start radio setup and linked advertisment
		radioSetupAndTransmit();
	//}


//END: Transmit
/*****************************************************************************************/


    //Wait in IDLE for CMD_DONE interrupt after radio setup. ISR will disable radio interrupts
    while( ! rfSetupDone) {
      powerDisableCPU();
      PRCMDeepSleep();
    }

    //Disable flash in IDLE after CMD_RADIO_SETUP is done (radio setup reads FCFG trim values)
    powerDisableFlashInIdle();

    //Wait in IDLE for LAST_CMD_DONE after 3 adv packets
    while( ! rfAdvertisingDone) {
      powerDisableCPU();
      PRCMDeepSleep();
    }

    //Request radio to not force on system bus any more
    radioCmdBusRequest(false);

 // } // end if
 // g_count++;

    //
    // Standby procedure
    //

    powerDisableXtal();

    // Turn off radio
    powerDisableRFC();

    // Switch to RCOSC_HF
    OSCHfSourceSwitch();

    // Allow AUX to turn off again. No longer need oscillator interface
    powerDisableAuxForceOn();

    // Goto Standby. MCU will now request to be powered down on DeepSleep
    powerEnableMcuPdReq();

    // Disable cache and retention
    powerDisableCache();
    powerDisableCacheRetention();

    //Calculate next recharge
    SysCtrlSetRechargeBeforePowerDown(XOSC_IN_HIGH_POWER_MODE);

    // Synchronize transactions to AON domain to ensure AUX has turned off
    SysCtrlAonSync();

    //
    // Enter Standby
    //

    powerDisableCPU();
    PRCMDeepSleep();

    SysCtrlAonUpdate();

    SysCtrlAdjustRechargeAfterPowerDown();

    SysCtrlAonSync();

    //
	// Wakeup from RTC, code starts execution from here
	//
   
    powerEnableRFC();

    powerEnableAuxForceOn();

    //Re-enable cache and retention
    powerEnableCache();
    powerEnableCacheRetention();

    //MCU will not request to be powered down on DeepSleep -> System goes only to IDLE
    powerDisableMcuPdReq();
  }
}
示例#15
0
/*** SET DATE & TIME ***************************************************************/
void lcd_date(void)
{
	tag = 0;
	RTC_DateTypeDef newDate = Rdate;
	RTC_TimeTypeDef newTime = Rtime;
	
	ButtonStruct btnBack = TouchInit(5);
	ButtonStruct keys = TouchInit(0);
	
	/* write background into memory */
	store_date_defaults();
	
	/* display */
	draw_date_screen(&btnBack, &keys, &newDate, &newTime);
	
	while(1)
	{		
		tag = HOST_MEM_RD32(REG_TOUCH_TAG);
		
		/* Buttons */
		switch(tag)
		{
			case 5:
				if(!btnBack.pressed)
				{
					btnBack.pressed = 1;
					draw_date_screen(&btnBack, &keys, &newDate, &newTime);
				}
				break;
			
			case 10:
			case 11:
			case 20:
			case 21:
			case 30:
			case 31:
			case 40:
			case 41:
			case 50:
			case 51:
				if(!keys.pressed)
				{
					keys.pressed = 1;
					keys.tag = tag;
					draw_date_screen(&btnBack, &keys, &newDate, &newTime);
				}
			break;
			
			default:
				if( btnBack.pressed ||
				    keys.pressed )
				{
					if(buttonIsClicked(&btnBack, tag))
					{
						initRTC(1, &newDate, &newTime);
						RTC_GetTime(RTC_Format_BIN, &Rtime);
						RTC_GetDate(RTC_Format_BIN, &Rdate);
						return;
					}
					
					if(buttonIsClicked(&keys, tag))
					{
						if(keys.tag == 10 && newDate.RTC_Year  > 0)  { newDate.RTC_Year--; }
						if(keys.tag == 11 && newDate.RTC_Year  < 99) { newDate.RTC_Year++; }
						if(keys.tag == 20 && newDate.RTC_Month > 0)  { newDate.RTC_Month--; }
						if(keys.tag == 21 && newDate.RTC_Month < 12) { newDate.RTC_Month++; }
						if(keys.tag == 30 && newDate.RTC_Date > 0)   { newDate.RTC_Date--; }
						if(keys.tag == 31 && newDate.RTC_Date < 31)  { newDate.RTC_Date++; }
						
						if(keys.tag == 40 && newTime.RTC_Hours > 0)    { newTime.RTC_Hours--; }
						if(keys.tag == 41 && newTime.RTC_Hours < 23)   { newTime.RTC_Hours++; }
						if(keys.tag == 50 && newTime.RTC_Minutes > 0)  { newTime.RTC_Minutes--; }
						if(keys.tag == 51 && newTime.RTC_Minutes < 59) { newTime.RTC_Minutes++; }
						
						keys.tag = 0;
					}
					
					btnBack.pressed = 0;
					keys.pressed = 0;
					
					draw_date_screen(&btnBack, &keys, &newDate, &newTime);
				}
			break;
		}
		
	} /* while */
}
示例#16
0
void myfunc() {
	int num_rows,k, l;
    double orient,delta_orient,rot_speed,t_rot,t_trans;
    double x0,y0,x,y,dx,dy;
    float distance,distance1,lala;
    double PI=3.14159265;
    x0=0;
    y0=0;
    double orient0;
    orient0=0; // starting conditions still have to be properly intialized
    double D = 0.094; /*distance between wheels, has to be measured*/
    char ch;
    const float tol = 1.0e-7;  // 7 significant figures
    float xold, xnew;          // local variables
    int test;

	/*Read in coords, mat[d][0] contains x-coords, mat[d][1]	contains y-coords*/
    int i=0,j=0;
    double mat[100][2];
    double z;

//    UInt32* pathx;
//    UInt32* pathy;

    // Here we should store the path-coordinates

	//
	//    while((line=fgets(buffer,sizeof(buffer),fp))!=NULL)
	//    {
	//
	//        record = strtok(line,","); /*break up string, return first token */
	//        while(record != NULL)
	//        {
	//        printf("record : %s \n",record);  //here you can put the record into the array as per your requirement.
	//        mat[i][j++] = atof(record) ; /*Convert string to double, put in [i,j] then j+1*/
	//        record = strtok(NULL,",");
	//        }
	//     ++i ;
	//     j=0;
	//    }

	initRTC();
	camera_reset(160);
	init_uart1(57600);
	while(1){
		if(getsignal()){
			ch = getch();
			printf("Character on serial %c 1\r\n", ch );
			if(ch == 75)
				{return;}
			else{
				switch (ch) {

				case '1':
					/*Read in csv-file, mat[d][0] contains distance in m, mat[d][1]	contains delta_orientation in degrees */
				    mat[0][0]=0.61;
				    mat[0][1]=0;
				    mat[1][0]=0.58;
				    mat[1][1]=90;
				    mat[2][0]=1.00;
				    mat[2][1]=-45;
				    mat[3][0]=0.33;
				    mat[3][1]=-60;

					num_rows = 4; // to be determined depends on how weread in givens
                    k=0;
                   while(k<=num_rows-1) {
                        distance=mat[k][0];
                        delta_orient=mat[k][1];

                    if(delta_orient>0){
                        t_rot=1000*(0.010*delta_orient+0.003);
                    }
                    else{
                            if(delta_orient<0){
                                t_rot=1000*(-0.010*delta_orient+0.003);
                            }
                            else t_rot=0;

                    }

                    t_trans=1000*(4.8*distance+0.05);
                    printf("tekst 2 distance: %lf,delta_orient:%lf \n t_rot: %lf t_trans: %lf \n\n",distance*1000,delta_orient,t_rot,t_trans);

                    if (delta_orient>0){
                                sendReceive(203,22,202,20);//turn counterclockwise
                                delay(t_rot);
                                sendReceive(201,0,202,0);//stop
                            }
                    if(delta_orient<0){
                                sendReceive(201, 22, 204, 20);//turn clockwise
                                delay(t_rot);
                                sendReceive(201,0,202,0);//stop

                            }
                    sendReceive(201, 23, 202, 20);//drive forward
                    delay(t_trans);
                    sendReceive(201, 0, 202, 0);//stop

                    printf("k: %d",k);
                    k++;
                    }


				break;

				case '5': /* Drive forward */

					sendReceive(201, 23, 202, 20);
						/* 201: Right motor moves forward
						   202: Left motor moves forward
						   Forward= opposite the antenna
						   */
					break;

				case '6': /* Stop */

					sendReceive(201, 0, 202, 0);
					break;

				case '7':

					sendReceive(203, 22, 204, 20);
						/* 203: Right motor moves backward
							204: Left motor moves backward
							Backward= antenna - side
							*/
					break;

				case '8': /* Rotate left (counter clockwise) */

					sendReceive(203, 22, 202, 20);
						/* Rotate: left motor rotates backward; right one forward */
					break;


				case '9': /* Rotate right (clockwise) */

					sendReceive(201,22,204,20);
						/* Rotate: left motor rotates forward; right one backward */
					break;

				case 'a':
                  printf("Reading path");
                   l = readNumber();
                   printf("l = ",l);
				   followPath(l);
                   break;

				}

			}

		}
	} //end while
} //end  myfunc
示例#17
0
文件: init.c 项目: osstudy/glidix
void kmain2()
{
	kprintf("Initializing SDI... ");
	sdInit();
	kprintf("%$\x02" "Done%#\n");

	initMount();
	initSymtab();

	kprintf("Initializing ACPICA...\n");
	ACPI_STATUS status = AcpiInitializeSubsystem();
	if (ACPI_FAILURE(status))
	{
		panic("AcpiInitializeSubsystem failed");
	};
	
	status = AcpiInitializeTables(NULL, 16, FALSE);
	if (ACPI_FAILURE(status))
	{
		panic("AcpiInitializeTables failed");
	};
	
	status = AcpiLoadTables();
	if (ACPI_FAILURE(status))
	{
		panic("AcpiLoadTables failed");
	};
	
	status = AcpiEnableSubsystem(ACPI_FULL_INITIALIZATION);
	if (ACPI_FAILURE(status))
	{
		panic("AcpiEnableSubsystem failed");
	};
	
	status = AcpiInitializeObjects(ACPI_FULL_INITIALIZATION);
	if (ACPI_FAILURE(status))
	{
		panic("AcpiInitializeObjects failed");
	};
	
	if (AcpiInstallFixedEventHandler(ACPI_EVENT_POWER_BUTTON, onPowerButton, NULL) != AE_OK)
	{
		panic("failed to register power button event");
	};
	
	pciInitACPI();
	
	kprintf("Initializing the RTC... ");
	initRTC();
	kprintf("%$\x02" "Done%#\n");

	kprintf("Initializing the network interface... ");
	ipreasmInit();
	initNetIf();
	kprintf("%$\x02" "Done%#\n");
	
	kprintf("Starting the spawn process... ");
	MachineState state;
	void *spawnStack = kmalloc(0x1000);
	state.rip = (uint64_t) &spawnProc;
	state.rsp = (uint64_t) spawnStack + 0x1000 - 16;
	((uint64_t*)state.rsp)[0] = 0;
	((uint64_t*)state.rsp)[1] = 0;
	state.rdi = (uint64_t) spawnStack;
	state.rbp = 0;
	Regs regs;
	regs.cs = 8;
	regs.ds = 16;
	regs.rflags = getFlagsRegister() | (1 << 9);
	regs.ss = 0;
	threadClone(&regs, 0, &state);
	// "Done" is displayed by the spawnProc() and that's our job done pretty much.
	// Mark this thread as waiting so that it never wastes any CPU time.
	getCurrentThread()->flags = THREAD_WAITING;
};
示例#18
0
文件: main.c 项目: elmo2k3/McBetty
int main(void)
{
	sysInfo = 0;
	
	SCS |= 0x01;
	FIODIR0 |= ((1<<21) | (1<<4) | (1<<11) | (1<<6) | (1<<23) | (1<<19) | (1<<17));
	FIODIR0 |= (1<<12);
	FIOSET0 |= (1<<12);
	xx = 0x00;

	setSpeed(SPEED_30);

	lcd_init(0);
	serial_init();

	startTimerIRQ();
	startADC();

	initKeys();

	initSound();
	startSoundIRQ();

	initIR();
	startIrIRQ();

    RF_init();
    startcc1100IRQ();
	enableWOR();
	
	initRTC();
	startRtcIRQ();
	
	enableIRQ();

	testmenu_init();
	init_menu();
	
	initBacklight();

	oldkeys[0] = keys[0];
	oldkeys[1] = keys[0];

	key_state = KEY_IDLE;

	set_font(BOLDFONT);
	
	BFS_Mount();
	load_RC_setting();
	load_RF_setting();
	load_setting();
	
	{
		struct RAWset_ RAWset;
        unsigned char x;
        unsigned long RAWcmdbase;
        
        RAWcmdbase = FLASH1_BASE +(secaddr[0]<<1);
        x=memcmp((void*)RAWcmdbase,"RC01",4);
		
        if(!x) {
               
				memcpy(&RAWset,(void *)RAWcmdbase,sizeof(struct RAWset_));
				RAWset.name[7] = 0;
				BFS_SaveFile(BFS_ID_RAWslot0, sizeof(struct RAWset_), (unsigned char*) &RAWset);
				eraseSector(1,0);
        }
	}
	
	if (EncIsValid(irDevTab.device[irDevTab.active].encoder, irDevTab.device[irDevTab.active].set)) {
		setEncoder(irDevTab.device[irDevTab.active].encoder, irDevTab.device[irDevTab.active].set);
	}	
	
	drawMainscreen();
	ask_for_time(0);
	
						
/*
	playSound((unsigned char*)sound1_data, sound1_len);
	waitSound();
	playSound((unsigned char*)sound2_data, sound2_len);
*/

	while (1)
	{
		if(keys[0] != oldkeys[0] || keys[1] != oldkeys[1])
		{
			oldkeys[0] = keys[0];
			oldkeys[1] = keys[1];
			sysInfo |= 0x40;
		}

		switch(key_state)
		{
			case KEY_IDLE:
				if(sysInfo & 0x40)
				{
					sysInfo &= 0xBF;
					if(KEY_Betty)
					{
						setBacklight(BL_AUTO);
						menu_exec(&mainMenu);
						if (EncIsValid(irDevTab.device[irDevTab.active].encoder, irDevTab.device[irDevTab.active].set)) {
							setEncoder(irDevTab.device[irDevTab.active].encoder, irDevTab.device[irDevTab.active].set);
						}
						drawMainscreen();
					}
					else if(KEY_2)
					{
						//setSpeed(SPEED_30);
					}
					else if(KEY_3)
					{
						//setSpeed(SPEED_60);
					}
					else  if(KEY_A || KEY_B || KEY_C || KEY_D)
					{
						unsigned char x;
						//playSound((unsigned char*)sound3_data, sound3_len);
						x=0;
						if (KEY_B) x=1;
						if (KEY_C) x=2;
						if (KEY_D) x=3;
						
						if (EncIsValid(irDevTab.device[x].encoder, irDevTab.device[x].set)) {
							setBacklight(BL_AUTO);
							irDevTab.active = x;
							setEncoder(irDevTab.device[x].encoder, irDevTab.device[x].set);
							drawMainscreen();
						}	
					}
/*					else if(KEY_B)
					{
					
					}
					else if(KEY_C)
					{	
//						playSound((unsigned char*)sound1_data, sound1_len);
					}
					else if(KEY_D)
					{	
//						playSound((unsigned char*)sound2_data, sound2_len);
					}*/
					if((keys[0] != 0) || (keys[1] != 0))
						key_state = KEY_PRESS;
				}
				break;
			case KEY_PRESS:
				irSend(getCode());
				key_state = KEY_HOLD;
//				autorepeat = 0;
				break;
			case KEY_HOLD:
//				if(autorepeat >= AUTO_TIMEOUT)
					irRepeat();

				if(keys[0] == 0 && keys[1] == 0)
					key_state = KEY_RELEASE;

				break;
			case KEY_RELEASE:
				irStop();
				key_state = KEY_IDLE;
				break;
		}

		if(serial_tstc() > 0)
		{
			i = serial_getc();
			if(i=='.')
			{
				serial_puts("HELO");
			}
			else if(i=='0')
			{
				setBacklight(0x00);	// pwm value
			}
			else if(i=='1')
			{
				setBacklight(0x1F);	// pwm value
			}
			else if(i=='2')
			{
				setBacklight(0x3F);	// pwm value
			}
			else
				serial_putc(i);
		}
		
		if ((bl_val == 0) && (key_state == KEY_IDLE) && !((FIOPIN0 & (1<<30)) == 0) && (((RFstatus & (WORrxon | RXenabled)) == 0))) {
			EXTINT = 0x08;
			PCON = 0x02;
			PLLFEED = 0xAA;
			PLLFEED = 0x55;
		}
		
		if (timeInfo & timechanged) {
			printTime(86,152,(struct time_ *)&time);
			printDate(0,152,(struct date_ *)&date,0);
			
			timeInfo &= ~timechanged;
		}
		
	}
	return 0;
}