示例#1
0
//Code blocks in the preamble are labelled with the names
//of the libraries in which the used functions are defined.
//Look in these to discover fundamental definitions.
void main(void) {

	EALLOW;//an assembly language thing required to allow access to system control registers
	SysCtrlRegs.WDCR = 0x68;//disable watchdog
	//clock
		SysClkInit(FIFTY);//set the system clock to 50MHz
	//gpio
		Uint8 out[3] = {31, 34};//0 is !shdn on wifi
		GpioOutputsInit(out, 2);	//34 is a pin that goes high/low each second
	//interrupts				//31 is ld2: lights when wifi is sending
		IsrInit(TINT0, &timerISR);
		IsrInit(ADCINT2, &adcISR);
	//adc
		AdcInit();
		AdcSetClock(FOURTH);
		AdcSetupSOC(SOC3, ADCB6, SOFTWARE);
		AdcEnableIsr(SOC3, ADCINT2);
	//clock
		TimerInit(1.0);//set the timer to 1kHz and start. Relies on SysClkInit, so call that first.
	EDIS;//disallow access to system control registers

	while(1) {
		loopcnt++;
	}
}
示例#2
0
//int seek_flag = 0;
////////////////////////////////////////////////////
// 功能:
// 输入:
// 输出:
// 返回:
// 说明:
////////////////////////////////////////////////////
int JzCtlInit(void)
{	
	// ADC & DAC设备初始化
	AdcInit();
	DacInit();
	return 0;
}
示例#3
0
void Board::init() // initialize the board specifics
{
	//
	// Enable lazy stacking for interrupt handlers.  This allows floating-point
	// instructions to be used within interrupt handlers, but at the expense of
	// extra stack usage.
	//
	FPUEnable();
	FPULazyStackingEnable();
	//
	// Set the clocking to run from the PLL at 50MHz
	//
	ROM_SysCtlClockSet(
	SYSCTL_SYSDIV_1 | SYSCTL_USE_PLL | SYSCTL_OSC_MAIN | SYSCTL_XTAL_16MHZ);
	IntMasterEnable(); // Enable interrupts to the processor.
	// Set up the period for the SysTick timer for 1 mS.
	SysTickPeriodSet(SysCtlClockGet() / 1000);
	SysTickIntEnable(); // Enable the SysTick Interrupt.
	SysTickEnable(); // Enable SysTick.
	/*	//
	 // Enable lazy stacking for interrupt handlers.  This allows floating-point
	 // instructions to be used within interrupt handlers, but at the expense of
	 // extra stack usage.
	 FPUEnable();
	 FPULazyStackingEnable();
	 SysCtlClockSet(
	 SYSCTL_SYSDIV_1 | SYSCTL_USE_OSC | SYSCTL_OSC_MAIN
	 | SYSCTL_XTAL_16MHZ); // Set the clocking to run directly from the crystal.
	 IntMasterEnable(); // Enable interrupts to the processor.*/

	SysCtlPeripheralEnable(SYSCTL_PERIPH_GPIOF); // Enable the GPIO port that is used for the on-board LED.
	GPIOPinTypeGPIOOutput(GPIO_PORTF_BASE, GPIO_PIN_2); // Enable the GPIO pins for the LED (PF2).
	GPIOPinTypeGPIOOutput(GPIO_PORTF_BASE, GPIO_PIN_1);
	GPIOPinTypeGPIOOutput(GPIO_PORTF_BASE, GPIO_PIN_3);

	/*	SysCtlPeripheralEnable(SYSCTL_PERIPH_UART0); // Enable the peripherals used by this example.
	 SysCtlPeripheralEnable(SYSCTL_PERIPH_GPIOA);
	 IntMasterEnable(); // Enable processor interrupts.
	 // Set up the period for the SysTick timer for 1 mS.
	 SysTickPeriodSet(SysCtlClockGet() / 1000);
	 SysTickIntEnable(); // Enable the SysTick Interrupt.
	 SysTickEnable(); // Enable SysTick.

	 GPIOPinConfigure(GPIO_PA0_U0RX); // Set GPIO A0 and A1 as UART pins.
	 GPIOPinConfigure(GPIO_PA1_U0TX);
	 GPIOPinTypeUART(GPIO_PORTA_BASE, GPIO_PIN_0 | GPIO_PIN_1);

	 UARTConfigSetExpClk(UART0_BASE, SysCtlClockGet(), 115200,
	 (UART_CONFIG_WLEN_8 | UART_CONFIG_STOP_ONE | UART_CONFIG_PAR_NONE)); // Configure the UART for 115,200, 8-N-1 operation.
	 IntEnable(INT_UART0);
	 UARTFIFODisable(UART0_BASE);
	 //	UARTFIFOLevelSet(UART0_BASE, UART_FIFO_TX1_8, UART_FIFO_RX1_8);
	 UARTFlowControlSet(UART0_BASE, UART_FLOWCONTROL_NONE);
	 UARTIntDisable(UART0_BASE, UART_INT_RT);
	 UARTIntEnable(UART0_BASE, UART_INT_RX | UART_INT_TX); // Enable the UART interrupt.*/
	Board::setLedOn(Board::LED_GREEN, false);
	Board::setLedOn(Board::LED_RED, false);
	Board::setLedOn(Board::LED_BLUE, false);
	AdcInit();
}
示例#4
0
void BoardInitMcu( void )
{
    if( McuInitialized == false )
    {
        // We use IRQ priority group 4 for the entire project
        // When setting the IRQ, only the preemption priority is used
        NVIC_PriorityGroupConfig( NVIC_PriorityGroup_4 );

        // Disable Systick
        SysTick->CTRL  &= ~SysTick_CTRL_TICKINT_Msk;    // Systick IRQ off 
        SCB->ICSR |= SCB_ICSR_PENDSTCLR_Msk;            // Clear SysTick Exception pending flag

        AdcInit( &Adc, POTI );

        SpiInit( &SX1272.Spi, RADIO_MOSI, RADIO_MISO, RADIO_SCLK, NC );
        SX1272IoInit( );

#if( LOW_POWER_MODE_ENABLE )
        TimerSetLowPowerEnable( true );
#else
        TimerSetLowPowerEnable( false );
#endif
        BoardUnusedIoInit( );

        if( TimerGetLowPowerEnable( ) == true )
        {
            RtcInit( );
        }
        else
        {
            TimerHwInit( );
        }
        McuInitialized = true;
    }
}
示例#5
0
void SensorProxyInit(void) {

	InternalAnalogSensorPowerCtrlInit();
	AdcInit();
	Sht11Init();
	Ms5540Init();
//	Bmp085Init();
}
示例#6
0
void BspInit(void)
{
	AdcInit();
//	BeepInit();
	KeyInit();
	LedInit();
//	MotorInit();
	UartInit();	
//	InitEEPROM();
}
示例#7
0
void BoardInitMcu( void )
{
    Gpio_t ioPin;

    if( McuInitialized == false )
    {
        HAL_Init( );

        // LEDs
        GpioInit( &Led1, LED_1, PIN_OUTPUT, PIN_PUSH_PULL, PIN_NO_PULL, 1 );
        GpioInit( &Led2, LED_2, PIN_OUTPUT, PIN_PUSH_PULL, PIN_NO_PULL, 1 );
        GpioInit( &Led3, LED_3, PIN_OUTPUT, PIN_PUSH_PULL, PIN_NO_PULL, Led3Status );

        SystemClockConfig( );

        GpioInit( &ioPin, UART_RX, PIN_INPUT, PIN_PUSH_PULL, PIN_NO_PULL, 0 );
        if( GpioRead( &ioPin ) == 1 )   // Debug Mode
        {
            UsbIsConnected = true;
            FifoInit( &Uart1.FifoTx, UartTxBuffer, UART_FIFO_TX_SIZE );
            FifoInit( &Uart1.FifoRx, UartRxBuffer, UART_FIFO_RX_SIZE );
            // Configure your terminal for 8 Bits data (7 data bit + 1 parity bit), no parity and no flow ctrl
            UartInit( &Uart1, UART_1, UART_TX, UART_RX );
            UartConfig( &Uart1, RX_TX, 115200, UART_8_BIT, UART_1_STOP_BIT, NO_PARITY, NO_FLOW_CTRL );
        }
        else
        {
            UsbIsConnected = false;
            UartDeInit( &Uart1 );
        }

        RtcInit( );

        BoardUnusedIoInit( );
    }
    else
    {
        SystemClockReConfig( );
    }

    I2cInit( &I2c, I2C_SCL, I2C_SDA );
    AdcInit( &Adc, BAT_LEVEL_PIN );

    SpiInit( &SX1272.Spi, RADIO_MOSI, RADIO_MISO, RADIO_SCLK, NC );
    SX1272IoInit( );

    if( McuInitialized == false )
    {
        McuInitialized = true;
        if( GetBoardPowerSource( ) == BATTERY_POWER )
        {
            CalibrateSystemWakeupTime( );
        }
    }
}
示例#8
0
void InitSystem() {
    // General init
    InitOsc();
    InitPort();

    // Peripheral init
    AdcInit();
    I2cInit();

    // Interrupt init
    InterruptInit();
}
示例#9
0
文件: main.c 项目: YuliaKON/amistom1
inline void Initialization_All(void)
{
	init_outpin();
	AdcInit();
	GlobalTimerInit();
	Button_Init();
	init_meandr__gpio();
	init_meandr_timer();
	Init_Uart3();
	//TIM3_IRQHandler();

	NVIC_InitTypeDef NVIC_InitStructure_usart3;
			NVIC_InitStructure_usart3.NVIC_IRQChannel                   = USART3_IRQn;
			NVIC_InitStructure_usart3.NVIC_IRQChannelSubPriority        = 1;
			NVIC_InitStructure_usart3.NVIC_IRQChannelPreemptionPriority = 1;
			NVIC_InitStructure_usart3.NVIC_IRQChannelCmd                = ENABLE;
			NVIC_Init (&NVIC_InitStructure_usart3);

			USART_ITConfig(USART3, USART_IT_RXNE, ENABLE);
			//state_err=2;
			//USART_ITConfig(USART3, USART_IT_ERR,  ENABLE);
			USART_ITConfig(USART3, USART_IT_TC,   DISABLE);
//	NVIC_conf();
		 display.a.port =	 	  GPIOH;
		 display.b.port =	 	  GPIOC;
		 display.c.port =	 	  GPIOE;
		 display.d.port = 		  GPIOE;
		 display.e.port = 		  GPIOE;
		 display.f.port =	 	  GPIOE;
		 display.g.port = 		  GPIOB;
		 display.common[0].port = GPIOC;
		 display.common[1].port = GPIOC;
		 display.common[2].port = GPIOH;
		 display.dot.port = 	  GPIOB;

		 display.a.pin = 		GPIO_Pin_0;
		 display.b.pin = 		GPIO_Pin_14;
		 display.c.pin = 		GPIO_Pin_6;
		 display.d.pin = 		GPIO_Pin_4;
		 display.e.pin = 		GPIO_Pin_2;
		 display.f.pin = 		GPIO_Pin_0;
		 display.g.pin = 		GPIO_Pin_8;

		 display.common[0].pin = 	GPIO_Pin_13;
		 display.common[1].pin = 	GPIO_Pin_15;
		 display.common[2].pin = 	GPIO_Pin_1;
		 display.dot.pin = 			GPIO_Pin_6;

		 DI_Init(&display);
}
示例#10
0
int main(void)
{
	UartInit();
	AdcInit();
	
    while(1)
    {
		for (int i=0; i < CHANNELS; ++i)
		{
			SendAdcResultViaUsart(i, AdcTakeMeasure(i));
			_delay_ms(100);
		}
    }
}
示例#11
0
void BoardInitMcu( void )
{
    if( McuInitialized == false )
    {
#if defined( USE_BOOTLOADER )
        // Set the Vector Table base location at 0x3000
        NVIC_SetVectorTable( NVIC_VectTab_FLASH, 0x3000 );
#endif
        // We use IRQ priority group 4 for the entire project
        // When setting the IRQ, only the preemption priority is used
        NVIC_PriorityGroupConfig( NVIC_PriorityGroup_4 );

        // Disable Systick
        SysTick->CTRL  &= ~SysTick_CTRL_TICKINT_Msk;    // Systick IRQ off 
        SCB->ICSR |= SCB_ICSR_PENDSTCLR_Msk;            // Clear SysTick Exception pending flag

        I2cInit( &I2c, I2C_SCL, I2C_SDA );
        AdcInit( &Adc, BAT_LEVEL );

        SpiInit( &SX1272.Spi, RADIO_MOSI, RADIO_MISO, RADIO_SCLK, NC );
        SX1272IoInit( );

#if defined( USE_DEBUG_PINS )
        GpioInit( &DbgPin1, CON_EXT_1, PIN_OUTPUT, PIN_PUSH_PULL, PIN_NO_PULL, 0 );
        GpioInit( &DbgPin2, CON_EXT_3, PIN_OUTPUT, PIN_PUSH_PULL, PIN_NO_PULL, 0 );
        GpioInit( &DbgPin3, CON_EXT_7, PIN_OUTPUT, PIN_PUSH_PULL, PIN_NO_PULL, 0 );
        GpioInit( &DbgPin4, CON_EXT_9, PIN_OUTPUT, PIN_PUSH_PULL, PIN_NO_PULL, 0 );
#endif

        BoardUnusedIoInit( );

#if defined( USE_USB_CDC )
        UsbMcuInit( );
        UartInit( &UartUsb, UART_USB_CDC, NC, NC );
        UartConfig( &UartUsb, RX_TX, 115200, UART_8_BIT, UART_1_STOP_BIT, NO_PARITY, NO_FLOW_CTRL );
#endif

#ifdef LOW_POWER_MODE_ENABLE
        RtcInit( );
#else
        TimerHwInit( );
#endif
        McuInitialized = true;
    }
}
示例#12
0
void BoardInitMcu( void )
{
    if( McuInitialized == false )
    {
#if defined( USE_BOOTLOADER )
        // Set the Vector Table base location at 0x3000
        SCB->VTOR = FLASH_BASE | 0x3000;
#endif
        HAL_Init( );

        SystemClockConfig( );

#if defined( USE_USB_CDC )
        UartInit( &UartUsb, UART_USB_CDC, NC, NC );
        UartConfig( &UartUsb, RX_TX, 115200, UART_8_BIT, UART_1_STOP_BIT, NO_PARITY, NO_FLOW_CTRL );

        DelayMs( 1000 ); // 1000 ms for Usb initialization
#endif

        RtcInit( );

        BoardUnusedIoInit( );

        I2cInit( &I2c, I2C_1, I2C_SCL, I2C_SDA );
    }
    else
    {
        SystemClockReConfig( );
    }

    AdcInit( &Adc, BAT_LEVEL_PIN );

    SpiInit( &SX1272.Spi, SPI_1, RADIO_MOSI, RADIO_MISO, RADIO_SCLK, NC );
    SX1272IoInit( );

    if( McuInitialized == false )
    {
        McuInitialized = true;
        if( GetBoardPowerSource( ) == BATTERY_POWER )
        {
            CalibrateSystemWakeupTime( );
        }
    }
}
示例#13
0
float Board::getTemp() {
	/*	float ulTempValueC;
	 unsigned long ulADC0Value[4], ulTempAvg;
	 //	ADCIntClear(ADC0_BASE, 1);
	 //	ADCIntEnable(ADC0_BASE, 1);
	 ADCProcessorTrigger(ADC0_BASE, 1);
	 while (!ADCIntStatus(ADC0_BASE, 1, false)) {
	 }
	 SysCtlDelay(100000);
	 ADCSequenceDataGet(ADC0_BASE, 1, ulADC0Value);
	 if (ulADC0Value[0] == 0)
	 ADCInit();
	 ulTempAvg = (ulADC0Value[0] + ulADC0Value[1] + ulADC0Value[2]
	 + ulADC0Value[3] + 2) / 4;
	 ulTempValueC = (1475.0 - ((2475.0 * ulTempAvg)) / 4096) / 10;*/
	if (ui32TempAvg == 0)
		AdcInit();
	fTempValueC = (1475.0 - ((2475.0 * ui32TempAvg)) / 4096) / 10; //TEMP = 147.5 – ((75 * (VREFP – VREFN) * ADCVALUE) / 4096) multiply by 10 to keep precision and then div by 10 at end
	return fTempValueC;
}
示例#14
0
int main(void)
{
	delay_init();
	Set_System();

	LcdInit();
	VBatInit();
	USB_Config();

	DacInit();
	AdcInit();

	MCPInit();
	QuadEncInit();

	LcdHello();

	ClearCorrector();
	while (1)
	{
		AdcQuant();
	}
}
示例#15
0
void main(void)
{

	int i=0;					// Loop Variable
	timeout_ctr	= 0	;

//############################ Initialisation ###############################//

						// _SOURCE_
	DeviceInit();		// DeviceInit.c
	InitGpio();			// GpioInit.c
	InitPieVectTable();	// PieVect.c
	InitPieCtrl();		// PieCtrl.c

	InitSci();			// Serial.c
	init_lcd_menu();	// LcdMenu.c
	lcd_init();			// LcdDriver.c

	SineRefInit();		// SineRefInit.c
	AdcInit();			// AdcInit.c
	PwmInit();			// PwmInit.c

	State.all				= 0;
	State.bit.Start			= 1;
	PeripheralEn.bit.Buttons= 1;	// Allow button checks

	EnableInterrupts();				// PieCtrl.c
	DisableInverter();				// Ensure inverter is disabled on start-up

	lcd_position(0x5,0x0);
	lcd_puts("Kingfisher");				// Print introductory message on top line
	lcd_position(0x0,0x1);				// Start Cursor From First Line
	lcd_puts("  Hydro Controller    ");	// Print introductory message on bottom line

	asm(" CLRC INTM, DBGM");			// Enable global interrupts and real-time debug

	CpuTimer0Regs.PRD.all =  COUNTER0_PRD;	// Initialise CPU timer0
	CpuTimer1Regs.PRD.all =  COUNTER1_PRD;	// Initialise CPU timer0



//############################# Polling Loop ################################//

	while(1)
	{

	//#######################################################################//
	//									STATES 								 //
	//#######################################################################//
	//
	//############################ START STATE ##############################//
		if(State.bit.Start)
		{
			asm("NOP");
		}

	//######################### EXCITATION STATE ############################//
		if (State.bit.Excitation)
		{
			data_out.bit.led_ctrl_green	= 1;
			data_out.bit.led_ctrl_red	= 0;

			if ( (AdcSignal.V_HVDC < 50) && (AdcSignal.Shaft_Velocity > 2000) && !(State.bit.Fault) )
			{
//				PeripheralEn.bit.Buttons= 0;

				timeout_ctr++;
				if (timeout_ctr > 3)
				{
					State.all		= 0;
					State.bit.Fault	= 1;
					timeout_ctr		= 0;
				}
				else
				{
					data_out.bit.startup = 1;
					shift_data_out();
					if (CpuTimer0Regs.TCR.bit.TIF == 1)
					{
						for (i=1;i<=2;i++)						// wait 2 seconds
						{
							CpuTimer0Regs.TCR.bit.TIF	= 1;	// Clear flag
							while(!CpuTimer0Regs.TCR.bit.TIF);
						}
					}
					data_out.bit.startup = 0;
					shift_data_out();
					if (CpuTimer0Regs.TCR.bit.TIF == 1)
					{
						for(i=1;i<=3;i++)						// wait 3 seconds
						{
							CpuTimer0Regs.TCR.bit.TIF	= 1;	// Clear flag
							while(!CpuTimer0Regs.TCR.bit.TIF);
						}
					}
				}
			}
			else if ( (AdcSignal.V_HVDC >= 50) && (AdcSignal.V_HVDC < 250) )
			{
				timeout_ctr			= 0;
				State.all			= 0;
				State.bit.Excited	= 1;
				// Perhaps change LCD Screen to message saying "Slowly increase turbine speed to increase voltage."
			}
			else if ( (AdcSignal.V_HVDC > 250) )
			{
				timeout_ctr					= 0;		// Resets the timeout counter for excitation
				State.all					= 0;
				State.bit.StartupSequence	= 1;
			}
		}

	//############################ EXCITED STATE ############################//
		if (State.bit.Excited)
		{
			if (AdcSignal.V_HVDC > 250)
			{
				timeout_ctr					= 0;		// Resets the timeout counter for excitation
				State.all					= 0;
				State.bit.StartupSequence	= 1;
			}
			else
			{
				// !!!!! ADD SOME CODE FOR THIS CONDITION !!!!!
			}
		}

	//############################# FAULT STATE #############################//
		if (State.bit.Fault)
		{
			if (PeripheralEn.bit.Inverter)
			{
				DisableInverter();
				data_out.bit.led_dump1		= 0;
				data_out.bit.led_dump2		= 0;
				data_out.bit.led_inverter	= 0;
				data_out.bit.led_update		= 0;
			}
			data_out.bit.protect_trig	= 1;

			data_out.bit.led_ctrl_green	= 0;
			data_out.bit.led_ctrl_red	= 1;
			if ( !(LED_Fault_Ctr++ % 16384) )
			{
				data_out.bit.led_dump1		= ~(data_out.bit.led_dump1);
				data_out.bit.led_dump2		= ~(data_out.bit.led_dump2);
				data_out.bit.led_inverter	= ~(data_out.bit.led_inverter);
				data_out.bit.led_update		= ~(data_out.bit.led_update);
			}
		}

	//########################### DC STABLE STATE ###########################//
		if (State.bit.DcStable)
		{
			if ( !(PeripheralEn.bit.Inverter) )	EnableInverter();
			data_out.bit.led_ctrl_green	= 1;
			data_out.bit.led_ctrl_red	= 0;
		}

	//############################## TEST STATE #############################//
		if (State.bit.Test)
		{

		}

	//########################### TURNED OFF STATE ##########################//
		if (State.bit.TurnOff)
		{
			data_out.bit.led_ctrl_green	= 0;
			data_out.bit.led_ctrl_red	= 0;
			data_out.bit.led_dump1		= 0;
			data_out.bit.led_dump2		= 0;
			data_out.bit.led_inverter	= 0;
			data_out.bit.led_update		= 0;
		}

	//#######################################################################//
	//								FLAGS 									 //
	//#######################################################################//
	//
	//######################## SCREEN UPDATE FLAG #######################//
		if (flag_bc)
		{
			menu_update_lcd();
			flag_bc = 0;
		}
		asm(" nop");

	//########################### READ IN DATA FLAG #########################//
		if (flag.bit.DataIN)
		{
			shift_data_in();
			check_buttons();
			flag.bit.DataIN = 0;
		}

	//########################## SEND OUT DATA FLAG #########################//
		if (flag.bit.DataOUT)
		{
			shift_data_out();
			flag.bit.DataOUT = 0;
		}

	//######################## HVDC VOLTAGE REGULATION ######################//
		if (flag.bit.V_HVDC)
		{
			if ( !(State.bit.TurnOff) && !(State.bit.Fault) )
			{
				V_DcError	= V_DC_REF - AdcSignal.V_HVDC;			// Calculate the DC error from the reference
				DutyError	= 0.75*K_DC*V_DcError + 0.25*DutyError;	// Modify the dump load duty cycle with respect to the DC error

				if (V_DcError > 0)		// If the DC voltage is less than the reference, dump no power
				{
					EPwm3Regs.CMPA.half.CMPA= 0;
					EPwm3Regs.CMPB			= 0;
				}
				else if (DutyError > DUMP1_DUTY_MAX)
				{
					DutyFeedback			= 1.0*(DUMP1_DUTY_MAX)*DUMP_PRD;
					EPwm3Regs.CMPA.half.CMPA= DutyFeedback;
					DutyFeedback			= 1.0*(DutyError - DUMP1_DUTY_MAX)*DUMP_PRD;
					EPwm3Regs.CMPB			= DutyFeedback;
				}
				else
				{
					DutyFeedback			= 1.0*(DutyError)*DUMP_PRD;
					EPwm3Regs.CMPA.half.CMPA= DutyFeedback;
					EPwm3Regs.CMPB			= 0;
				}
			}else		// If there is a fault or the system is off, dump all power
			{
				EPwm3Regs.CMPA.half.CMPA	= (DUMP1_DUTY_MAX)*DUMP_PRD;	// Dump all power!
				EPwm3Regs.CMPB				= DUMP_PRD;	// Dump all power!
			}

			flag.bit.V_HVDC	= 0;		// Reset the flag
		}


	//###################### SHAFT VELOCITY MEASUREMENT #####################//
		if (ShaftVelocCtr >= 1000)										// Updates the measured velocity every 1000*(1/EPWM8) = 0.5s
		{
			AdcSignal.Shaft_Velocity	= shaftspeedtest; //0.8*(ShaftPulseCtr/0.5)*60 + 0.2*AdcSignal.Shaft_Velocity;	// Where 1 pulse = 1 rotation
			ShaftPulseCtr				= 0;	// { Reset counters
			ShaftVelocCtr				= 0;	// {
		}

	//################### OUTPUT AC VOLTAGE FREQUENCY MEASURE ################//
		if (V_AcOutPrdCtr >= 10)
		{
			AdcSignal.V_AcOut_Freq	= (SYSCLK/ADC_SAMP_PRD+1)*(V_AcOutPrdCtr/FreqOutDivCtr);	// Approximate frequency over at least 10 periods
			AcOutFreqError			= AC_OUT_FREQ - AdcSignal.V_AcOut_Freq;	// Find frequency error
			V_AcOutReqFreq			= V_AcOutReqFreq + 0.05*AcOutFreqError;	// Frequency feedback loop
			sinGen.freq				= V_AcOutReqFreq*(BIT31)*(2*BIT32*INVERTER_PWM_PRD)*(1/(sinGen.step_max*SYSCLK));	// Alter reference sine wave frequency
			V_AcOutPrdCtr			= 0	;	// }
			FreqOutDivCtr			= 0	;	// } Reset counters
		}

	//####################### INVERTER CONTROL #######################//
		if (flag.bit.Inverter)
		{
/* BROKEN	InverterMaxDuty	= V_AC_OUT_REF*(1.0/(AdcSignal.V_HVDC));	// Find the maximum duty cycle necessary to create Vacoutpeak=325V
			DutyScaleMax	= (BIT16*InverterMaxDuty-BIT15)*30.51850948e-6;	// 30.51850948e-6 = 1/(BIT15-1)

			if ( !(State.bit.InvSoftStart) )
			{
				DutyScaleError	= DutyScaleMax - DutyScale;
				DutyScale	= DutyScale + 0.01*DutyScaleError;
				if (DutyScale < 0.2)
				{
				DutyScale	= 0.2;
				ADD SOME CODE IN CASE IT IS DANGEROUS TO GO BELOW 0.2
				}
			}
*/

			// ----- Toggle the onboard LED to show inverter control is active
			if (GPIO34_count >= 4000)						// toggle_time = GPIO34_count_limit/fpwm
			{
				GpioDataRegs.GPBTOGGLE.bit.GPIO34	= 1;	// Toggle the pin
				GPIO34_count	= 0;						// Reset the count
			}

			flag.bit.Inverter	= 0;
		}

	//################### INPUT AC VOLTAGE FREQUENCY MEASURE ################//
		if (V_AcInPrdCtr >= 10)
		{
			AdcSignal.V_AcIn_Freq	= 0.8*((SYSCLK/ADC_SAMP_PRD+1)*(V_AcInPrdCtr/FreqInDivCtr)) + 0.2*(AdcSignal.V_AcIn_Freq);	// Approximate frequency over at least 10 periods
			genSlip					= 100*((AdcSignal.V_AcIn_Freq*60) - (AdcSignal.Shaft_Velocity))/(AdcSignal.V_AcIn_Freq*60);	// Calculates slip: s= 100%*((ns-nr)/ns)
			V_AcInPrdCtr			= 0	;	// }
			FreqInDivCtr			= 0	;	// } Reset counters
		}


/*		if(SendADCResult)
		{
			SendADCResult = 0;

			SerialSendStr("Voltage: ");
			SerialSendInt((int)V_DC_measured);
			SerialSendStr("   PWM1: ");
			SerialSendInt((int)(EPwm3Regs.CMPA.half.CMPA*100.0/(DUMP_PRD*1.0)));
			SerialSendCR();
			SerialSendStr("   PWM2: ");
			SerialSendInt((int)((EPwm3Regs.CMPB*100.0)/(DUMP_PRD*1.0)));
			SerialSendCR();
		}*/

	}

}
示例#16
0
文件: main.c 项目: PolyakovV/Unit213
int32_t main()
{

/***************************************************************************
*       ClkInit()
****************************************************************************/
	ClkInit();

/***************************************************************************
*       GPIOInit();
****************************************************************************/
//	DrvGPIO_InitFunction(E_FUNC_GPIO);
	outpw(&SYS->P0_MFP, 0);
	outpw(&SYS->P1_MFP, 0);
	outpw(&SYS->P2_MFP, 0);
	outpw(&SYS->P3_MFP, 0);
	outpw(&SYS->P4_MFP, 0);

	_GPIO_SET_PIN_MODE(MODEM_ON_PORT, MODEM_ON_PIN, GPIO_PMD_OUTPUT);
	ModuleOn(TRUE);

	_GPIO_SET_PIN_MODE(MODEM_POWER_PORT, MODEM_POWER_PIN, GPIO_PMD_OUTPUT);
	ModulePowerOn(FALSE);

	_GPIO_SET_PIN_MODE(LOCK_POWER_PORT, LOCK_POWER_PIN, GPIO_PMD_OUTPUT);
	LockPower(FALSE);

	_GPIO_SET_PIN_MODE(KEY_HELP_PORT, KEY_HELP_PIN, GPIO_PMD_QUASI);
	_GPIO_SET_PIN_MODE(KEY_BAT_PORT, KEY_BAT_PIN, GPIO_PMD_QUASI);

	_GPIO_SET_PIN_MODE(SLEEP_PORT, SLEEP_PIN, GPIO_PMD_OUTPUT);
	ModemSleep(FALSE);

	_GPIO_SET_PIN_MODE(LED_PORT, LED_PIN, GPIO_PMD_OUTPUT);
	
	LedDark();
	
	_GPIO_SET_PIN_MODE(INT_PORT, INT_PIN, GPIO_PMD_INPUT);

/***************************************************************************
*       TimerInit();
****************************************************************************/
	SysTick_Config(SYS_TICK);
//	SYS_LockReg();

/***************************************************************************
*       UartInit();
****************************************************************************/
	UartInit();
//	debug(VERSION);
//	DrvSYS_GetPLLClockFreq();

/***************************************************************************
*       WatchdogInit();
****************************************************************************/	
	WatchdogInit();

//	udpTest();
	NvInit();



 	WhatToDo();
	AdcInit();
	
	
	
	WaitLockPower();

  LockPower(!custermParam.param.lockState);


	InitMsgDebug();	
	
	if( Communication(10) == FALSE )
		SoftReset();

	if( isCheckingBattery )
	{
		delay_50ms(40);
		MeasurePower(4);
	}
	else
	{
		MeasurePower(2);
	}
					
	Flag_ModuleOn = TRUE;
	//Flag_ModuleOn = TRUE;
	ModemVolumeInit();

	///--------------------24.11.2015----------------------------------------------
	////////////////////////////////////////////////////////////////////////////////////////
while(PressHelp()&&(tmp_my<200)&&(PressBatter())){
	tmp_my++;
		
	delay_50ms(1);
if (tmp_my>=150) {
	  LedLight(144);
	    if (custermParam.param.lockState) {
														LockPower(TRUE);
														custermParam.param.lockState = FALSE;
												    WriteToNv( &custermParam ); //- save to eeprom
  													PlayVoice("\"unitUnlock.wav\",2\r");
														delay_ms(2000);
			                      LockPower(FALSE);
			
			} else {
	                          //  debug("ins");
															while(PressBatter()){};
														 tmp_my=0;
												while (tmp_my<25){               
																											tmp_my++;
																											delay_ms(150);
																											if (PressBatter()){counterPress++;
																																				while(!PressBatter()){};
																																					}
																										  if (counterPress>2){ 
																																					PlayVoice("\"unitLock.wav\",2\r");
																																					delay_ms(2000);
																																					custermParam.param.lockState = TRUE;
																																					WriteToNv( &custermParam ); //- save to eeprom
																																		      tmp_my=0;
																																					delay_ms(2000);
																																					LockPower(DISABLE);

																																				}
																											}
													LedBlink();
										} 
					///////				
			tmp_my=0;
			}

}

while(custermParam.param.lockState){}
 
///////////////////////////////////////////////////////////////////////////////////////////////													
#ifdef DELAY_TEST
	DelayTest();
#endif
	PowerOn();
	
	

	
	if(state==STATE_POWERING_DOWN || Flag_Power_Down)
	{
		Flag_Power_Down = FALSE;
		EnterPowerDown();
		while( TimerWait )
			FeedWatchdog();
		PowerDown();
		//不会返回
	}
	
	InitVariables();
	  
	if(state == STATE_NULL)
	{
		state = STATE_1ST_CALL;
		TimerWait = 100;	// 5 s
	}
	
	TimerTestMode = 6000;
	//debug("ent main loop");
	while(1)
	{  
			
		///--------------------
				if (!TimerTestMode && state==STATE_TEST)
										{ 
										PlayMusic(MUSIC_PD);
										EnterPowerDown();
										}
		
		///--------------------
		
		if( Flag_Incomming )
		{
	#if 1
			TimerWait = 200;
			Flag_Incomming = FALSE;
			TimerStandby = custermParam.param.delay;
			//if(state != STATE_ACTIVE)
			{
				ModemSleep(FALSE);
				state = STATE_INCOMMING;
			}
	#else
			Flag_Incomming = FALSE;
			if(state != STATE_INCOMMING)
			{
				state = STATE_INCOMMING;
				ModemSleep(FALSE);
				EnterAnswer();
			}
	#endif
		}
		
		if(TimerWait == 0)
		{
			switch(state)
			{
									
			case STATE_POWERING_DOWN:
				PowerDown();
				break;

			case STATE_1ST_CALL:
				RegisterWait();
				break;

			case STATE_REGISTER_OK:	
				GetCpsiInfo();
				if( Flag_ObtainCpsi==TRUE)
				{
					state = STATE_GSM_STEADY;
					if( Flag_SimExist )
					{
						//delay_50ms(200);
						SockOpen();
						TimerWait = 400;
					}
					else
					{
						TimerWait = 60;
					}
				}
				else
				{
					TimerWait = 70;
				}
				break;

			case STATE_GSM_STEADY:	
				if( gPhoneNumOk==PHONE_NUM_READY || Flag_SimExist==FALSE)
					EnterCall();
				else
					TimerWait = 40;
				break;
				
			case STATE_CALL_PROMPT:
				Call();
				break;

			case STATE_ALERT:
				EnterCallFail();
				break;
			
			case STATE_NEXT_CALL:
				Redial();
				break;				

			case STATE_BATT_DISPLAY:
				EnterPowerDown();
				break;

			case STATE_INCOMMING:
				TimerStandby = custermParam.param.delay;
				EnterStandby();
				break;
			}
		}

		if( TimerSock==0 && Flag_SimExist
			&& ( (state>=STATE_GSM_STEADY && state<STATE_STANDBY) || progress>=TEST_GPS ) )
		{
			switch(sockState)
			{
			//case SOCKSTATE_NULL:
			case SOCKSTATE_CONFIG:				
			case SOCKSTATE_OPENNING:
				SockOpen();	// 打开失败,从新打开
				break;

			case SOCKSTATE_OPENED:
				SendAtWaitRsq(50, 1, FALSE, "AT+CIPOPEN=0,\"UDP\",,,%s\r\n", custermParam.param.local_port);
				TimerSock = 80;
				break;
	#if 0
			case SOCKSTATE_CONNECTING:
				SockConnect();	// 连接失败,从新连接
				break;
	#endif
			case SOCKSTATE_CONNECT_OK:		
				if( witchApn == 1)
					ClientInit();
				break;

			default:
				break;
			}
		}

		KeyHandle();

		SecondHandle();
		//SignalCheck();
		BatterCheck();
		PowerDownHandle();
		MsgHandle();
											
		if( Flag_SimExist )
		{
			UdpHandle();
			SmsHandle();
			PowerDownHandle();
		}
		
		FeedWatchdog();
	}
}	
示例#17
0
void main()
{
#if 0
	extern void DebugAdc();
	DebugAdc();
#endif

	//////////////////////////////////////////////////////////////////////////
	//                       局部变量或结构体                               //
	//////////////////////////////////////////////////////////////////////////
	SpeedForline = FreecaleConfig.Config.Motor.Speed.LineSpeed;
	//////////////////////////////////////////////////////////////////////////
	//                       位置提示                                       //
	//////////////////////////////////////////////////////////////////////////
	/************************************************************************/
	/* 开中断                                                               */
	/************************************************************************/

	set_vector_handler(UART0_VECTORn, UartHandler);   // 设置中断服务函数到中断向量表里
	uart_rx_irq_en(UART0);//串口中断
	FLKeyIrqEnable();
	//wdog_init (1000);//初始化看门狗
	//wdog_enable ();
	//////////////////////////////////////////////////////////////////////////
	//                       用户操作                                       //
	//////////////////////////////////////////////////////////////////////////
#if UseEndLine
	switch (FreecaleConfig.Config.CarState)
	{
	case CarStandby:
#endif//UseEndLine
		printf("start");
#if UseAdcNormalizingInit
		AdcNormalizingInit();//初始化归一化变量
#else//UseAdcNormalizingInit
		LCDPrint(0, 0, "Car Ready!");


		AdcInit();
		if (FreecaleConfig.Config.Mode.NrfStartCar == On)
		{
			if (FreecaleConfig.Config.CarThis == MyCar1)
			{
				uint8 exitfunc = false;
				LCDPrint(0, LcdLine2, "Press the");
				LCDPrint(LcdLocal2, LcdLine3, "start!");
				LCDPrint(LcdLocal1, LcdLine4, "Nrf Mode");

				while (!exitfunc)
				{
					switch (KeyScanWithoutIrq())//按键检测
					{
					case FLKeyAdcNorExit:
						LcdCls();
						LCDPrint(LcdLocal1, LcdLine1, "Findind Car2!");
						while (NrfSendStr("$", 1) != Nrf_AllGreen)
						{
							led(LED1, LED_ON);
							DELAY_MS(1);
						};
						led(LED1, LED_OFF);
						exitfunc = TRUE;//退出
						break;

					default:
						break;
					}
				}
			}
			else
			{
				LCDPrint(0, LcdLine2, "Wait Command!");
				uint8 strTemp[10];
				while (true)
				{
					if (NrfRecStrCheck(strTemp, 5) != 0)
					{
						if (strTemp)
						{
							break;
						}
					}

					led(LED1, LED_ON);
					DELAY_MS(1);
				} led(LED1, LED_OFF);
			}
#endif//UseAdcNormalizingInit
		}
		else
		{
			uint8 exitfunc = false;
			LCDPrint(0, LcdLine2, "Press the");
			LCDPrint(LcdLocal2, LcdLine3, "start!");
			LCDPrint(LcdLocal1, LcdLine4, "Manual Mode");

			while (!exitfunc)
			{
				switch (KeyScanWithoutIrq())//按键检测
				{
				case FLKeyAdcNorExit:
					exitfunc = TRUE;//退出
					break;

				default:
					break;
				}
			}
		}
#if UsePowerOnDelay
		DELAY_MS(2000);
#else
		if (FreecaleConfig.Config.CarDelay > 0)
		{
			LcdCls();
			LCDPrint(0, 0, "wait TimeOut!");
			DELAY_MS(FreecaleConfig.Config.CarDelay * 10);
		}
		LcdCls();
#endif//UsePowerOnDelay

		//////////////////////////////////////////////////////////////////////////
		//终点线
#if UseEndLine
		break;

	case CarRunning:
		break;

	case CarFinish:
		LCDPrint(0, 0, "Finish!");
		break;

	default:
		break;
	}
#endif//UseEndLine




	//uint16 spwm = SteerCenterDuty;
	Speed.Expect = SpeedForline;
	enable_irq(PIT_IRQn);								  //使能PIT0中断
	//程序循环
	while (1)
	{
		//////////////////////////////////////////////////////////////////////////
		//舵机控制
		SteerCtrl();

#if 1

#else
		///lcd show

		NumShow16(Speed.Expect, LcdLocal1, LcdLine1);
		NumShow16(Speed.Acturally, LcdLocal1, LcdLine2);

		NumShow3(MotorPid.P, LcdLocal1, LcdLine3);
		NumShow3(MotorPid.I, LcdLocal2, LcdLine3);
		NumShow3(MotorPid.D, LcdLocal3, LcdLine3);

#endif
		if (FreecaleConfig.Config.Mode.Ultrasonic == On)
		{
			NumShow4(CarDistance, LcdLocal1, LcdLine2);
		}
		

		SpeedCtrl();


		//////////////////////////////////////////////////////////////////////////
		//nrf
		if (FreecaleConfig.Config.Mode.NrfSendDistance)
		{
		//NrfErrorType_e nrfErr;
			if (FreecaleConfig.Config.CarThis)
			{
				if (NrfRecStrCheck(NrfBuff, 3))
				{
					if (FreecaleConfig.Config.Mode.NrfSendDistance)
					{
						if (NrfBuff[0] == '$')//超声波识别符
						{
							uint8 i = 0;
							while (NrfBuff[i + 1] != '#')//求字符串长度
							{
								if (NrfBuff[i + 1] == '\0')//error
								{
									goto exitthismainloop;//没辙了,我真不想这么写,实在不能再循环了,变量太多了
									//break;
								}
								i++;
							}

							uint32 dis = 0;
							for (uint8 j = 0; j < i; j++)//求数值
							{
								dis += POW((uint32)(NrfBuff[j + 1] - '0'), i - j);
							}
						}
					}
				}
			}
			else
			{
				if (FreecaleConfig.Config.Mode.NrfSendDistance)
				{
					sprintf(NrfBuff, "$%d#", CarDistance);
					NrfSendStrCheck(NrfBuff, sizeof(NrfBuff) / sizeof(uint8), 3);
				}
			}
		}

		//////////////////////////////////////////////////////////////////////////
	exitthismainloop:
		//延迟,控制周期
		DELAY_MS(20);
	}
	//////////////////////////////////////////////////////////////////////////
	//////////////////////////////////////////////////////////////////////////
	//Don't leave main////////////////////////////////////////////////////////
	//////////////////////////////////////////////////////////////////////////
}
示例#18
0
// *****************************************************************************
// InitialiseHW
// Setup the processor
// *****************************************************************************
void InitialiseHW ( void )
{
	// If running on Rev A2 silicon, turn the LDO voltage up to 2.75V.  This is
	// a workaround to allow the PLL to operate reliably.
	//
	if(REVISION_IS_A2)
	{
		SysCtlLDOSet(SYSCTL_LDO_2_75V);
	}

	// 50 MHz
	SysCtlClockSet(SYSCTL_SYSDIV_4 | SYSCTL_USE_PLL | SYSCTL_OSC_MAIN | SYSCTL_XTAL_8MHZ);

	// Enable Peripherals
	SysCtlPeripheralEnable(SYSCTL_PERIPH_ETH);
	SysCtlPeripheralEnable(SYSCTL_PERIPH_GPIOA);
	SysCtlPeripheralEnable(SYSCTL_PERIPH_GPIOB);
	SysCtlPeripheralEnable(SYSCTL_PERIPH_GPIOC);
	SysCtlPeripheralEnable(SYSCTL_PERIPH_GPIOD);
	SysCtlPeripheralEnable(SYSCTL_PERIPH_GPIOE);
	SysCtlPeripheralEnable(SYSCTL_PERIPH_GPIOF);
	SysCtlPeripheralEnable(SYSCTL_PERIPH_GPIOG);
	SysCtlPeripheralEnable(SYSCTL_PERIPH_GPIOH);
	SysCtlPeripheralEnable(SYSCTL_PERIPH_UART0);
	SysCtlPeripheralEnable(SYSCTL_PERIPH_UART1);

	// Set interrupt priority levels
	IntPrioritySet(INT_ETH, 0x20);
	IntPrioritySet(FAULT_SYSTICK, 0x40);

	//
	// Enable the peripherals that should continue to run when the processor
	// is sleeping.
	//
	SysCtlPeripheralSleepEnable(SYSCTL_PERIPH_GPIOA);
	SysCtlPeripheralSleepEnable(SYSCTL_PERIPH_GPIOB);
	SysCtlPeripheralSleepEnable(SYSCTL_PERIPH_GPIOC);
	SysCtlPeripheralSleepEnable(SYSCTL_PERIPH_GPIOD);
	SysCtlPeripheralSleepEnable(SYSCTL_PERIPH_GPIOE);
	SysCtlPeripheralSleepEnable(SYSCTL_PERIPH_GPIOF);
	SysCtlPeripheralSleepEnable(SYSCTL_PERIPH_GPIOG);
	SysCtlPeripheralSleepEnable(SYSCTL_PERIPH_GPIOH);
	SysCtlPeripheralSleepEnable(SYSCTL_PERIPH_UART0);
	SysCtlPeripheralSleepEnable(SYSCTL_PERIPH_UART1);
	SysCtlPeripheralSleepEnable(SYSCTL_PERIPH_ETH);

	SysCtlPeripheralSleepEnable(SYSCTL_PERIPH_TIMER0);
	SysCtlPeripheralSleepEnable(SYSCTL_PERIPH_TIMER1);
	SysCtlPeripheralSleepEnable(SYSCTL_PERIPH_TIMER2);

    //
    // Enable peripheral clock gating.  Note that this is required in order to
    // measure the the processor usage.
    //
    SysCtlPeripheralClockGating(true);

	// Grab the Config from Flash
	SysConfigInit();

	AdcInit();
	pwmInit();
	RelayInit();

	//usrand(0x23482937);

	// Note (From the DriverLib) :
	// It takes five clock cycles after the write to enable a peripheral
	// before the the peripheral is actually enabled.  During this time, attempts
	// to access the peripheral result in a bus fault.  Care should be taken
	// to ensure that the peripheral is not accessed during this brief time
	// period.

	#ifdef SERIAL_ENABLED
		Serial_Init();
	#endif

	#ifdef UPNP_ENABLED
		UPnPInit();
	#endif

	Ethernet_Init();

	#ifdef LOGIC_ENABLED
		LogicStartStop(true);
	#endif

	#ifdef SOLDERBRIDGES_ENABLED
		SB_Init();
		ExtGpio_Init();

		SolderBridge_StartScan();
		ExtGpio_Scan();
	#endif

	#ifdef SPLASHPIXEL_ENABLED
		SP_Init();
	#endif

	// Set up the GPIO as specified by the user
	UserGpioInit();

	// Most, if not all M3's have a SysTick which you can use for scheduling your code
	SysTickPeriodSet(SysCtlClockGet() / SYSTICKHZ);
	SysTickEnable();
	SysTickIntEnable();
}
示例#19
0
/******************************************************************************
 * HostCtrlInitiateReset()
 *
 * Triggers a reset according to the reason and modifies the reset behaviour
 * based on any rstFlags/overrides
 *****************************************************************************/
void HostCtrlInitiateReset( WORD reason, WORD rstFlags )
{
    if( ResetInProgress ) {
        return;
    }
    if( (rstFlags & RESET_HOST_WARM) == 0 ) {
        ResetInProgress = TRUE;

        HostCtrlPrepResetProc();

        if( AppCallsAllowed ) {
            AppExitpoint();
        }

        I2cUninit();

        HostCtrlGpioReset( rstFlags );
    }

    // if we are doing a soft reset we need to capture the log here
    if( (rstFlags & RESET_PMU430_CORE) == 0 ) {
        // trigger the pre-reset log to be captured to our buffer
        // so when the host boots up again we can read it.
        EventLogInit();
        // make sure we update the correct reset value which will be read
        // by the host when it boots again
        UpdateResetStat( reason );
    }

    InitiateResetReason = reason;
    InitiateResetFlags = rstFlags;

    // don't sequence the supplies if its a warm reset, just
    // turn off the ones that should be off, and reset their default voltages
    if( rstFlags & RESET_HOST_WARM ) {
#if defined( PROCESSOR_MQ31 )
    	const BYTE mask[] = { PLATFORM_WARM_RESET_MASK_LIST };
    	const BYTE size = sizeof(mask) / sizeof(mask[0]);
    	BYTE reg;
    	BYTE index;
#endif
        // stop any pending adc and re-init it
        if( AppCallsAllowed ) {
            AdcUninit();
            AdcInit();
        }

        HostCtrlPmicRegisterReset( rstFlags );

#if defined( PROCESSOR_PMU430 )
        PmicClear( PMIC_EN_CMD0, ~CMD0_WARM_RESET_MASK );
        PmicClear( PMIC_EN_CMD1, ~CMD1_WARM_RESET_MASK );
        PmicClear( PMIC_EN_CMD2, ~CMD2_WARM_RESET_MASK );
#else
#if defined( PROCESSOR_MQ31 )
        // disable only supply voltages which are not on the mask list
        for( reg=PMIC_VOUTCONFIG1B1 ; reg<=PMIC_L23_CNFG1 ; reg++ ) {
        	if( (reg <= PMIC_VOUTCONFIG1B5) || (reg >= PMIC_L01_CNFG1) ) {
        		// search if supply voltage is on the mask list
            	for( index=0; index<size; index++ ) {
            		if( reg == mask[index] ) {
            			break;
            		}
            	}
            	if( index == size) {
            		// supply voltage is not on the mask list
            		if( reg == PMIC_LDO_RSVD ) {
            			// reserve supply voltage
            		} else if( reg <= PMIC_VOUTCONFIG1B5 ) {
            			// SM supply voltage
            			PmicClear( reg, BUCK_PWR_MD_NORMAL );
            		} else {
            			// LDO supply voltage
            		    if( PMIC_L23_CNFG1 == reg )
                            PmicClear( reg, (1 << 5) );
                        else
                			PmicClear( reg, LDO_PWR_MD_NORMAL );
            		}
            	}
        	}
        }
#endif // PROCESSOR_MQ31
#endif // PROCESSOR_PMU430
        ResetInProgress = FALSE;
    } else {
#if defined( PROCESSOR_MQ31 )
        // Disable active discharge on LDO4
        PmicClear( PMIC_L04_CNFG2, (1<<1) );
#endif
        SupplySequenceRun( SUPSEQ_POS_UNCHANGED, SUPSEQ_DIR_PWRDN );
    }

    return;
}
示例#20
0
/*
 * This function initializes the ADC for the POT_ANALOG_PIN to be available for use. Also
 * initializes the last value used for detecting events within PotCheckEvents().
 */
void PotInit(void)
{
    AdcInit(POT_ANALOG_PIN);
}
示例#21
0
int main()
{
    // Configure the device for maximum performance but do not change the PBDIV
    // Given the options, this function will change the flash wait states, RAM
    // wait state and enable prefetch cache but will not change the PBDIV.
    // The PBDIV value is already set via the pragma FPBDIV option above..
    SYSTEMConfig(F_SYS, SYS_CFG_WAIT_STATES | SYS_CFG_PCACHE);

    // Auto-configure the PIC32 for optimum performance at the specified operating frequency.
    SYSTEMConfigPerformance(F_SYS);

    // osc source, PLL multipler value, PLL postscaler , RC divisor
    OSCConfig(OSC_POSC_PLL, OSC_PLL_MULT_20, OSC_PLL_POST_1, OSC_FRC_POST_1);

    // Configure the PB bus to run at 1/4th the CPU frequency, so 20MHz.
    OSCSetPBDIV(OSC_PB_DIV_4);

    // Enable multi-vector interrupts
    INTEnableSystemMultiVectoredInt();
    INTEnableInterrupts();

    // Configure Timer 2 using PBCLK as input. We configure it using a 1:16 prescalar, so each timer
    // tick is actually at F_PB / 16 Hz, so setting PR2 to F_PB / 16 / 100 yields a .01s timer.
    OpenTimer2(T2_ON | T2_SOURCE_INT | T2_PS_1_16, F_PB / 16 / 100);

    // Set up the timer interrupt with a medium priority of 4.
    INTClearFlag(INT_T2);
    INTSetVectorPriority(INT_TIMER_2_VECTOR, INT_PRIORITY_LEVEL_4);
    INTSetVectorSubPriority(INT_TIMER_2_VECTOR, INT_SUB_PRIORITY_LEVEL_0);
    INTEnable(INT_T2, INT_ENABLED);

/******************************** Your custom code goes below here ********************************/
    int check;
    OledInit();
    AdcInit();
    LEDS_INIT();
    check = GameInit();

    if(check == STANDARD_ERROR) {
        FATAL_ERROR();
    }
    float currPage;
    float binSize;
    float titleSize;
    float descSize;
    float numPages;
    uint8_t roomExit;
    uint16_t adcValue = 0;

    while(1) {
        roomExit = GameGetCurrentRoomExits();
        LEDS_SET(roomExit);
        while(buttonEvents == 0) {
            descSize = GameGetCurrentRoomDescription(roomData.description);
            titleSize = GameGetCurrentRoomTitle(roomData.title);

            numPages = ((titleSize + descSize) / MAX_OLED_PIXELS);
            binSize = (ADC_MAX_VALUE / numPages);

            if(AdcChanged()) {
                adcValue = AdcRead();
            }

            currPage = (adcValue / binSize);
            if(currPage < 1) {
                char titleArray[TITLE_OLED_SPACE] = {0};
                char descriptionBuffer[FIRST_PG_DESCRIPTION_OLED_SPACE] = {0};

                strncpy(descriptionBuffer, roomData.description, DESCRIPTION_COPY);
                sprintf(titleArray, "%s\n%s", roomData.title, descriptionBuffer);

                OledClear(OLED_COLOR_BLACK);
                OledDrawString(titleArray);
            } else {
                char buffer[MAX_OLED_PIXELS] = {0};
                int buffIndex;
                buffIndex = (int)currPage * MAX_OLED_PIXELS;
                strncpy(buffer, (roomData.description + buffIndex - OFFSET), MAX_OLED_PIXELS);

                OledClear(OLED_COLOR_BLACK);
                OledDrawString(buffer);
            }
            OledUpdate();
        }

        if((buttonEvents & BUTTON_EVENT_4UP) && (roomExit & GAME_ROOM_EXIT_NORTH_EXISTS)) {
            GameGoNorth();
        } else if((buttonEvents & BUTTON_EVENT_3UP) && (roomExit & GAME_ROOM_EXIT_EAST_EXISTS)) {
            GameGoEast();
        } else if((buttonEvents & BUTTON_EVENT_2UP) && (roomExit & GAME_ROOM_EXIT_SOUTH_EXISTS)) {
            GameGoSouth();
        } else if((buttonEvents & BUTTON_EVENT_1UP) && (roomExit & GAME_ROOM_EXIT_WEST_EXISTS)) {
            GameGoWest();
        }
        buttonEvents = BUTTON_EVENT_NONE;
    }



/**************************************************************************************************/
    while (1);
}
示例#22
0
文件: main.c 项目: zzy-driver/usb
/********************************************************************
函数功能:主函数。
入口参数:无。
返    回:无。
备    注:无。
********************************************************************/
void main(void)
{
#ifdef DEBUG0
 int i;
#endif

 int InterruptSource;
 
 SystemClockInit(); //系统时钟初始化
 LedInit();         //LED对应的管脚初始化
 LcdInit();         //LCD初始化
 AdcInit();         //ADC初始化
 Timer1Init();      //定时器1初始化,用来产生10ms的定时扫描信号
 KeyInit();         //键盘初始化
 Uart0Init();       //串口0初始化

#ifdef DEBUG0
 for(i=0;i<16;i++)   //显示头信息
 {
  Prints(HeadTable[i]);
 }
#endif

 UsbChipInit();  //初始化USB部分
 
 while(1)
 {
  InterruptSource=(*AT91C_UDP_ISR)&(0x0F|(1<<8)|(1<<12)); //取出需要的中断
  if(InterruptSource) //如果监视的中断发生
  {
   if(InterruptSource&(1<<8))
   {
    *AT91C_UDP_ICR=1<<8; //清除中断
    UsbBusSuspend(); //总线挂起中断处理
   }
   if(InterruptSource&(1<<12))
   {
    *AT91C_UDP_ICR=1<<12; //清除中断
    UsbBusReset();   //总线复位中断处理
   }
   if(InterruptSource&(1<<0))
   {
    if(AT91C_UDP_CSR[0]&((1<<1)|(1<<2)|(1<<6)))  //如果是SETUP包、缓冲未空等
    {
     UsbEp0Out();     //端点0输出中断处理
    }
    if(AT91C_UDP_CSR[0]&(1<<0)) //如果是端点0输入完成
    {
     UsbEp0In();     //端点0输入中断处理
    }
   }
   if(InterruptSource&(1<<1))
   {
    UsbEp1In();      //端点1输入中断处理
   }
   if(InterruptSource&(1<<2))
   {
    UsbEp2Out();     //端点2输出中断处理
   }
   if(InterruptSource&(1<<3))
   {
    UsbEp3In();     //端点3输入中断处理
   }
  }
  if(KeyUp||KeyDown)  //如果用户操作了按键
  {
   DispKey(); //在LCD上显示按键情况
   if(ConfigValue!=0) //如果已经设置为非0的配置,则可以返回报告数据
   {
    if(!Ep1InIsBusy)  //如果端点1输入没有处于忙状态,则可以发送数据
    {
     KeyCanChange=0;  //禁止按键扫描
     if(KeyUp||KeyDown) //如果有按键事件发生
     {
      SendReport();  //则返回报告
     }
     KeyCanChange=1;  //允许按键扫描
    }
   }
   //清除KeyUp和KeyDown
   KeyUp=0;
   KeyDown=0;
   LcdRefresh();  //刷新LCD显示
  }
 }
}
示例#23
0
/******************主程序********************************/
void main(void)
{
   Pin_Init();
   T0_Init();
   Uart_Init();
   Uart2_Init();
   Uart_AppInit();
   Uart2_AppInit();
   MdTcbInit();
   MdTcbInit2();
   AdcInit();
   PWMInit();
   FCInitOne();
   while (1)
   {
      TimeDeal(&FC1);
      MdPoll();
      MdMasterPoll();
      FCKeyScan(&FC1);
      ResetDeal(&FC1);
      FCURun(&FC1);
      FCRelayOutput(&FC1);
      if (FC1.Buff.Flag.solo._2msFlag)
      {
//        FC2IOScan(&FC1);
          swih ^= 1;
          PORTB_PORTB4 = swih;
         TestSpeed();
         UartTimeOut(&UartAppData1);
         UartTimeOut(&UartAppData2);
      }
      if (FC1.Buff.Flag.solo._4msFlag)
      {
         InputDeal();
      }
      if (FC1.Buff.Flag.solo._10msFlag)
      {
         FCWorkTime(&FC1);
      }
      if (FC1.Buff.Flag.solo._20msFlag)
      {
         AdcGetAll(&FC1);
         FCAnalogOutSet(&FC1);
         EePromDeal(&FC1.Run, sizeof(FC_RUNING_Def) - CRC_LEN, &EeSave1);
      }
      if (FC1.Buff.Flag.solo._10000msFlag)
      {
         uint16 tmpCrc = FC1.Run.RunCrc;
         uint16 tmpCrcNew = GetCRC16((uint08 *)&FC1.Run, sizeof(FC_RUNING_Def) - CRC_LEN);
         if (tmpCrc != tmpCrcNew)
         {
            EeWriteTrg(&EeSave1);
         }
      }
      if (FC1.Buff.Flag.solo._nmsFlag)
      {
          speedPerMin = speedCnt * 60 / 4 / (nTimeSpeed / 100);
          speedCnt = 0;
      }

      FC1.Buff.Flag.All = 0;
   }
}
示例#24
0
int main(void) {
  MainInit();
  I2C1init();
  RtcInit();
  LcdInit();
  DataLogInit();
  StringInit();
  Mct485Init();
  FieldInit();
  Ads1115Init();
  Ads1244Init();
  USBInit();
  RtuInit();
  AdcInit();
  TC74Init();

  // enable multi-vector interrupts
  INTEnableSystemMultiVectoredInt();

  MainDelay(50);
  DataLogDateTime(DLOG_SFC_POWERUP);

  // init param after interrupts are enabled 
  ParamInit();
  // wait to init desiccant until after ParamInit
  DesiccantInit();

  string[0].mct[0].chan[4] = 0x7FFF;



	// 
	// Begin Main Loop
	//
  for (;;) {
    if (test == 1) {
      test = 0;
      FieldNewState((FIELD_STATE_m)t1);
    }
    
    USBUpdate(); // called as often as possible
    
    //sysTickEvent every ms
    if (sysTickEvent) {
      sysTickEvent = 0;
      sysTicks++;

      UsbTimeoutUpdate();

      LcdUpdate();
      
      // fill time before dropping LCD_E
      if (sysTicks >= 1000) {
        sysSec++;
        sysTicks = 0;
        
        mPORTDToggleBits(PD_LED_HEARTBEAT);
        
        // These Updates are 
        // called once a second
        //TODO if any of these are long, we could split them on separate milliseconds.
        DesiccantUpdate();
        AdcUpdate();
        TC74Update();
        
      }// end 1 Hz
      
      else if (sysTicks == 250) {
        mPORTDToggleBits(PD_LED_HEARTBEAT);
      }
      else if (sysTicks == 500) {
        mPORTDToggleBits(PD_LED_HEARTBEAT);
      }
      else if (sysTicks == 750) {
        mPORTDToggleBits(PD_LED_HEARTBEAT);
      }
      // Complete LcdUpdate() by dropping LCD_E)
      PORTClearBits(IOPORT_G, PG_LCD_E);

      // These Updates called once each millisecond
      RtcUpdate();
      I2C1update();
      StringUpdate();
      Mct485Update();
      FieldUpdate();
      RtuUpdate();
      DessicantFanPWMupdate();
      
    } // if (sysTickEvent)
  } // for (;;)
} // main()
示例#25
0
// Attached to USB
void RunAttached(void)
{
	// Do this first to give the card time to start up
	SD_ENABLE(); 		// Turn on SD card

    // Enable peripherals
	RtcInterruptOn(0);  // Keeps time upto date

	LED_SET(LED_WHITE);
    CLOCK_PLL();		// PLL clock

    // Initialize sensors
    // Check if we have an accelerometer
    AccelVerifyDeviceId();
    // Check if we have a gyro
	#ifdef USE_GYRO 
    GyroVerifyDeviceId();
	#endif
	#ifdef HAS_PROX
	// Check for prox
	ProxVerifyDeviceId();
	ProxStartup();
	#endif

    // Initialize sensors
    AccelStartup(ACCEL_RANGE_4G|ACCEL_RATE_100);
	#ifdef USE_GYRO 
	GyroStartup();
	#endif
	AdcInit();

	#ifndef NO_DISPLAY
	DisplayClear();
	Display_print_xy(" <= USB =>",0,2,2);
	#endif
	
	status.diskMounted = (status.lockCode == 0x0000) ? 1 : 0;
	status.stream = 0;

//   MDD_MediaInitialize();  // KL FIX: The SD card is re-inited in the usb framework which causes a lockup in some cases

	// Power up module if off
	PMD4bits.USB1MD = 0;

    USBInitializeSystem(); 	// Initializes buffer, USB module SFRs and firmware
    #ifdef USB_INTERRUPT
    USBDeviceAttach();
    #endif

    while(USB_BUS_SENSE && restart != 1)
    {
        // Check bus status and service USB interrupts.
        #ifndef USB_INTERRUPT
        USBDeviceTasks(); 	// Interrupt or polling method.  If using polling, must call
        #endif
        USBProcessIO();

        if ((USBGetDeviceState() >= CONFIGURED_STATE) && (USBIsDeviceSuspended() == FALSE))
        {
            const char *line = _user_gets();
            status.attached = 1;
            if (line != NULL)
            {
                status.stream = 0;  // Disable streaming
                SettingsCommand(line, SETTINGS_USB);
            }
        }
        else
        {
            status.attached = -1;
        }
	
        TimedTasks();	


        // Stream accelerometer data
        if (status.stream)
		{
			#define STREAM_RATE 10
			#define STREAM_INTERVAL (0x10000UL / STREAM_RATE)
			static unsigned long lastSampleTicks = 0;
            unsigned long now = RtcTicks();
            if (lastSampleTicks == 0) { lastSampleTicks = now; }
            if (now - lastSampleTicks > STREAM_INTERVAL)
            {
                accel_t accelSample;
				#ifdef USE_GYRO 
				gyro_t gyroSample;
				#endif

				extern unsigned char scratchBuffer[];
				char * ptr = (char *)scratchBuffer;
				unsigned short len;

                lastSampleTicks += STREAM_INTERVAL;
                if (now - lastSampleTicks > 2 * STREAM_INTERVAL) { lastSampleTicks = now; } // not keeping up with sample rate
                
#ifdef HAS_PROX
				// Sample sensors
				if(ProxSampleReady())
				{
					ProxReadSample();
					ProxStartSample();
				}
#endif
                AccelSingleSample(&accelSample);
				#ifdef USE_GYRO
				GyroSingleSample(&gyroSample);
				#endif
			
				// Write ascii to scratch buffer
				ptr = (char *)scratchBuffer;
				ptr += sprintf(ptr, "\f$ACCEL=%d,%d,%d\r\n", accelSample.x, accelSample.y, accelSample.z);
				#ifdef USE_GYRO 
				ptr += sprintf(ptr, "$GYRO=%d,%d,%d\r\n", gyroSample.x, gyroSample.y, gyroSample.z);
				#endif
				#ifdef HAS_PROX
				ptr += sprintf(ptr, "$PROX=%d\r\n", prox.proximity);
				ptr += sprintf(ptr, "$LIGHT=%d\r\n", prox.light);
				#endif
				len = (unsigned short)((void*)ptr - (void*)scratchBuffer);

				// Stream over USB
				if ((status.stream) && status.attached == 1) { usb_write(scratchBuffer, len); }
            }
        }
    }
	#if defined(USB_INTERRUPT)
    USBDeviceDetach();
	#endif
    status.attached = -1;

    return;
}