예제 #1
0
파일: platform.c 프로젝트: zhanjun/elua
int platform_init()
{
    // Set the clocking to run from PLL
#if defined( FORLM3S9B92 ) || defined( FORLM3S9D92 )
    MAP_SysCtlClockSet(SYSCTL_SYSDIV_4 | SYSCTL_USE_PLL | SYSCTL_OSC_MAIN | SYSCTL_XTAL_16MHZ);
#else
    MAP_SysCtlClockSet(SYSCTL_SYSDIV_4 | SYSCTL_USE_PLL | SYSCTL_OSC_MAIN | SYSCTL_XTAL_8MHZ);
#endif

    // Setup PIO
    pios_init();

    // Setup SSIs
    spis_init();

    // Setup UARTs
    uarts_init();

    // Setup timers
    timers_init();

    // Setup PWMs
    pwms_init();

#ifdef BUILD_ADC
    // Setup ADCs
    adcs_init();
#endif

#ifdef BUILD_CAN
    // Setup CANs
    cans_init();
#endif

    // Setup system timer
    cmn_systimer_set_base_freq( MAP_SysCtlClockGet() );
    cmn_systimer_set_interrupt_freq( SYSTICKHZ );

    // Setup ethernet (TCP/IP)
    eth_init();

    // Common platform initialization code
    cmn_platform_init();

    // Virtual timers
    // If the ethernet controller is used the timer is already initialized, so skip this sequence
#if VTMR_NUM_TIMERS > 0 && !defined( BUILD_UIP )
    // Configure SysTick for a periodic interrupt.
    MAP_SysTickPeriodSet( MAP_SysCtlClockGet() / SYSTICKHZ );
    MAP_SysTickEnable();
    MAP_SysTickIntEnable();
    MAP_IntMasterEnable();
#endif

    // All done
    return PLATFORM_OK;
}
예제 #2
0
파일: tn_user.c 프로젝트: serikovigor/surd
void tn_reset_int_handler()
{

    hw_watchdog_init();

    tn_cpu_int_disable(); // switched back in tn_start_system();

#ifdef BOOT_LOADER
    hw_delay(BOOT_DELAY);
#endif // BOOT_LOADER

#ifdef DEBUG
    hw_delay(1000000); // DEBUG delay 1000 mS
#endif // DEBUG

#ifndef BOOT_LOADER
        // Set system clock to 80 MHz
        MAP_SysCtlClockSet(SYSCTL_USE_PLL | SYSCTL_OSC_MAIN | SYSCTL_XTAL_16MHZ | SYSCTL_SYSDIV_2_5 | SYSCTL_INT_OSC_DIS | SYSCTL_INT_PIOSC_DIS);

        // Set system clock to 50 MHz
        //MAP_SysCtlClockSet(SYSCTL_USE_PLL | SYSCTL_OSC_MAIN | SYSCTL_XTAL_16MHZ | SYSCTL_SYSDIV_4 | SYSCTL_INT_OSC_DIS | SYSCTL_INT_PIOSC_DIS);
#endif // BOOT_LOADER


    __iar_program_start();
}
예제 #3
0
파일: wiring.c 프로젝트: Aginorty/Energia
void timerInit()
{
#ifdef TARGET_IS_BLIZZARD_RB1
    //
    //  Run at system clock at 80MHz
    //
    MAP_SysCtlClockSet(SYSCTL_SYSDIV_2_5|SYSCTL_USE_PLL|SYSCTL_XTAL_16MHZ|
                       SYSCTL_OSC_MAIN);
#else
    //
    //  Run at system clock at 120MHz
    //
    MAP_SysCtlClockFreqSet((SYSCTL_XTAL_25MHZ|SYSCTL_OSC_MAIN|SYSCTL_USE_PLL|SYSCTL_CFG_VCO_480), F_CPU);
#endif

    //
    //  SysTick is used for delay() and delayMicroseconds()
    //

    MAP_SysTickPeriodSet(F_CPU / SYSTICKHZ);
    MAP_SysTickEnable();
    MAP_IntPrioritySet(FAULT_SYSTICK, SYSTICK_INT_PRIORITY);
    MAP_SysTickIntEnable();
    MAP_IntMasterEnable();

    // PIOSC is used during Deep Sleep mode for wakeup
    MAP_SysCtlPIOSCCalibrate(SYSCTL_PIOSC_CAL_FACT);  // Factory-supplied calibration used
}
예제 #4
0
파일: main.c 프로젝트: MrAureliusR/rtcdebug
int main(void) {
	
	MAP_SysCtlClockSet(SYSCTL_SYSDIV_4 | SYSCTL_USE_PLL | SYSCTL_XTAL_16MHZ | SYSCTL_OSC_MAIN);
	sysClock = SysCtlClockGet();

	MAP_SysCtlPeripheralEnable(SYSCTL_PERIPH_I2C3);
	MAP_SysCtlPeripheralEnable(SYSCTL_PERIPH_GPIOD);

	MAP_GPIOPinConfigure(GPIO_PD1_I2C3SDA);
	MAP_GPIOPinTypeI2C(GPIO_PORTD_BASE, GPIO_PIN_1);
	MAP_GPIOPinConfigure(GPIO_PD0_I2C3SCL);
	MAP_GPIOPinTypeI2CSCL(GPIO_PORTD_BASE, GPIO_PIN_0);

	MAP_I2CMasterInitExpClk(I2C3_BASE, sysClock, 0);

	pRTC->address = RTC_addr;
	SysCtlDelay(20000);
	setupRTC(pRTC);
	SysCtlDelay(20000);
	setTime(pRTC);
	SysCtlDelay(20000);
	getTime(pRTC);

	return 0;
}
int main(void)
{
  // TivaC application specific code
  MAP_FPUEnable();
  MAP_FPULazyStackingEnable();
  // TivaC system clock configuration. Set to 80MHz.
  MAP_SysCtlClockSet(SYSCTL_SYSDIV_2_5 | SYSCTL_USE_PLL | SYSCTL_XTAL_16MHZ | SYSCTL_OSC_MAIN);

  uint8_t button_debounced_delta;
  uint8_t button_raw_state;
  ButtonsInit();

  // ROS nodehandle initialization and topic registration
  nh.initNode();
  nh.advertise(button_publisher);

  while (1)
  {
    uint8_t button_debounced_state = ButtonsPoll(&button_debounced_delta, &button_raw_state);
    // Publish message to be transmitted.
    button_msg.sw1.data = button_debounced_state & LEFT_BUTTON;
    button_msg.sw2.data = button_debounced_state & RIGHT_BUTTON;
    button_publisher.publish(&button_msg);

    // Handle all communications and callbacks.
    nh.spinOnce();

    // Delay for a bit.
    nh.getHardware()->delay(100);
  }
}
예제 #6
0
//*****************************************************************************
//
//! init clk
//!
//!  \param  None
//!
//!  \return none
//!
//!  \Init the device with 16 MHz clock.
//
//*****************************************************************************
void initClk(void)
{
	 
	// 16 MHz Crystal on Board. SSI Freq - configure M4 Clock to be ~50 MHz
	//
	MAP_SysCtlClockSet(SYSCTL_SYSDIV_4 | SYSCTL_USE_PLL | SYSCTL_OSC_MAIN |SYSCTL_XTAL_16MHZ);	


}
예제 #7
0
static void
cpu_init(void) {
  // A safety loop in order to interrupt the MCU before setting the clock (wrongly)
  int i;
  for(i=0; i<1000000; i++);

  // Setup for 16MHZ external crystal, use 200MHz PLL and divide by 4 = 50MHz
  MAP_SysCtlClockSet(SYSCTL_SYSDIV_16 | SYSCTL_USE_PLL | SYSCTL_OSC_MAIN |
      SYSCTL_XTAL_16MHZ);
}
예제 #8
0
파일: GTBEA_basic.c 프로젝트: IMEMS/Public
/********
 * Main *
 ********/
int main(void) {

	// Control Parameters
	float amp_set_v = 0.2;
	float pi_k = -1;

	float Q1H_V = -1;
	float Q1L_V = 2;
	float Q2H_V = -3;
	float Q2L_V = 4;
	int32_t P_gain2 = 10; // 2 * ALC Proportional Gain
	int32_t I_gain2 = -62; // 2 * ALC Integral Gain
	//int32_t P_gain2 = 2 * PGA_GAIN_MUTE; // Mute
	//int32_t I_gain2 = 2 * PGA_GAIN_MUTE; // Mute

	/* System initialization */
	uint32_t SysClkFreq;
	#ifdef PART_TM4C123GH6PM
		// Set system clock to 80 MHz (400MHz main PLL (divided by 5 - uses DIV400 bit)  [16MHz external xtal drives PLL]
		SysClkFreq = MAP_SysCtlClockSet(SYSCTL_SYSDIV_2_5 | SYSCTL_USE_PLL | SYSCTL_OSC_MAIN | SYSCTL_XTAL_16MHZ);
	#endif
	#ifdef PART_TM4C1294NCPDT
		// Set system clock to 120 MHz
		SysClkFreq = SysCtlClockFreqSet((SYSCTL_XTAL_25MHZ | SYSCTL_OSC_MAIN | SYSCTL_USE_PLL | SYSCTL_CFG_VCO_480), 120000000);
	#endif

	/* Error LED Initialization */
	GTBEA_initErrLED();

	/* PGA Initialization */
	//pga_init(SysClkFreq, false, true); // unmuted, zero crossing mode enabled

	/* UART Comm. Initialization */
	//twe_initVCOM(SysClkFreq, UART_BAUD);

	/* DAC Initialization */
	DACd_initDAC(DAC_RANGE_PM5V | DAC_RANGE_PM5V_EH, DAC_PWR_PU_AMP_SET | DAC_PWR_PU_PI_K | DAC_PWR_PUALL_EH, SysClkFreq);

	DACd_updateDataVolt(DAC_ADDR_NONE_AD | DAC_ADDR_Q1H, DAC_RANGE_PM5V | DAC_RANGE_PM5V_EH, OFFSET_BINARY, OFFSET_BINARY, 0, Q1H_V);
	MAP_SysCtlDelay(4000);
	DACd_updateDataVolt(DAC_ADDR_NONE_AD | DAC_ADDR_Q1L, DAC_RANGE_PM5V | DAC_RANGE_PM5V_EH, OFFSET_BINARY, OFFSET_BINARY, 0, Q1L_V);
	MAP_SysCtlDelay(4000);
	DACd_updateDataVolt(DAC_ADDR_AMP_SET | DAC_ADDR_Q2H, DAC_RANGE_PM5V | DAC_RANGE_PM5V_EH, OFFSET_BINARY, OFFSET_BINARY, amp_set_v - DAC_AMP_SET_OFFSET, Q2H_V);
	MAP_SysCtlDelay(4000);
	DACd_updateDataVolt(DAC_ADDR_PI_K | DAC_ADDR_Q2L, DAC_RANGE_PM5V | DAC_RANGE_PM5V_EH, OFFSET_BINARY, OFFSET_BINARY, pi_k - DAC_PI_K_OFFSET, Q2L_V);
	MAP_SysCtlDelay(4000);
	DACd_loadDACs_AH();
	//DACd_loadDACsPin_EH();
	//pga_setGainInt(P_gain2, I_gain2);
	//pga_setGainInt(2 * PGA_GAIN_MUTE, 2 * PGA_GAIN_MUTE);  // Mute while testing other circuits...

	while(1) {
		// wait...
	}
}
예제 #9
0
파일: tn_user.c 프로젝트: serikovigor/surd
void init_hardware()
{
    // Set SysTick timer period (TN_SYS_TICK_FQ_HZ)
    MAP_SysCtlClockSet(SYSCTL_SYSDIV_4 | SYSCTL_USE_PLL | SYSCTL_OSC_MAIN |
                       SYSCTL_XTAL_16MHZ);
    ///////////
    MAP_SysTickDisable();
    MAP_SysTickPeriodSet(MAP_SysCtlClockGet() / TN_SYS_TICK_FQ_HZ);
    MAP_SysTickIntEnable();
    MAP_SysTickEnable();
}
예제 #10
0
void SetupClock(int clk)
{
    switch (clk) {
        case CLK80:
            MAP_SysCtlClockSet(SYSCTL_SYSDIV_2_5 | SYSCTL_USE_PLL |
                       SYSCTL_OSC_MAIN | SYSCTL_XTAL_16MHZ);
            break;
        case CLK50:
            MAP_SysCtlClockSet(SYSCTL_SYSDIV_4 | SYSCTL_USE_PLL |
                       SYSCTL_XTAL_16MHZ | SYSCTL_OSC_MAIN);
            break;
        case CLK16:
            MAP_SysCtlClockSet(SYSCTL_SYSDIV_1 | SYSCTL_USE_OSC |
                       SYSCTL_OSC_MAIN | SYSCTL_XTAL_16MHZ);
            break;
        default:
            MAP_SysCtlClockSet(SYSCTL_SYSDIV_1 | SYSCTL_USE_OSC |
                       SYSCTL_OSC_MAIN | SYSCTL_XTAL_16MHZ);
            break;
    }
}
예제 #11
0
    StellarisIO()
        : magic(gMagic)
    {
        MAP_FPULazyStackingEnable();

        /* Set clock to PLL at 50MHz */
        MAP_SysCtlClockSet(SYSCTL_SYSDIV_4 | SYSCTL_USE_PLL | SYSCTL_OSC_MAIN | SYSCTL_XTAL_16MHZ);

        MAP_SysTickPeriodSet(MAP_SysCtlClockGet() / (1000*10)); // 1us
        MAP_SysTickIntEnable();
        MAP_SysTickEnable();
    }
예제 #12
0
// Couldn't manage to build UTF version without warnings. Trying
// --fwide-exec-charset=UTF-16 build flag doesn't help.
int main(void)
{
    FATFS fs;
    FIL f;
    FRESULT returned;
    UINT scratch;
    int i;

	/// Set clock to 66,67 MHz (200 MHz / 3)
    MAP_SysCtlClockSet(SYSCTL_SYSDIV_3 | SYSCTL_USE_PLL | SYSCTL_OSC_MAIN |
                       SYSCTL_XTAL_16MHZ);

    /// LED initialization
    RgbLedInit();

    /// Initialize UART0 (used for stdout)
    UartInit(0, 115200);
    printf("Test start!\r\n");

    /// Color cycle the LED. Ends with red color.
    for (i = 7; i > 0; i--)
    {
    	MAP_SysCtlDelay(2500000);
    	RgbLedSet(i<<1);
    }

    // TODO: check mount options
    if ((returned = f_mount(&fs, _T("/"), 0)))
    {
        printf("ERROR: couldn't mount volume.\r\n");
        return 1;
    }

    if ((returned = f_open(&f, _T("test.txt"), FA_CREATE_ALWAYS | FA_WRITE)))
    {
        printf("ERROR: couldn't open file.\r\n");
        return 2;
    }

    if ((returned = f_write(&f, HELLO_STR, HELLO_STR_LEN, &scratch)))
    {
        printf("ERROR: couldn't write to file.\r\n");
        return 3;
    }
    printf("%d bytes written.\r\n", scratch);

    // TODO: unmount volume or at least sync filesystem
    f_sync(&f);
   return 0;
}
예제 #13
0
static void cpu_init(void) {
	g_ulSysTickCount = 0;
		// 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.
	ROM_FPULazyStackingEnable();

  // A safety loop in order to interrupt the MCU before setting the clock (wrongly)
  int i;
  for(i=0; i<1000000; i++);

  // Setup for 16MHZ external crystal, use 200MHz PLL and divide by 4 = 50MHz
  MAP_SysCtlClockSet(SYSCTL_SYSDIV_16 | SYSCTL_USE_PLL | SYSCTL_OSC_MAIN |
      SYSCTL_XTAL_16MHZ);
}
예제 #14
0
int main(){

	// System clock set to run at 50 MHz from PLL with crystal ref.
	// With EK-TM4C123GXL Launchpad, no need to change SYSCTL_XTAL_16MHZ to anything else
	MAP_SysCtlClockSet(SYSCTL_SYSDIV_4|SYSCTL_USE_PLL|SYSCTL_XTAL_16MHZ|SYSCTL_OSC_MAIN);
	MAP_SysCtlPeripheralEnable(SYSCTL_PERIPH_GPIOF);
	MAP_GPIOPinTypeGPIOOutput(GPIO_PORTF_BASE, LED_RED|LED_BLUE|LED_GREEN);

	while(1){
		MAP_GPIOPinWrite(GPIO_PORTF_BASE, LED_RED|LED_GREEN|LED_BLUE, LED_GREEN|LED_RED|LED_BLUE);
		// SysCtlDelay and ROM_SysCtlDelay behave differently, see http://e2e.ti.com/support/microcontrollers/tiva_arm/f/908/t/256106.aspx
		MAP_SysCtlDelay(2333333);	// Number of loop iterations to perform @ 3 cycles/loop using ROM. Not Accurate. Input = (DesiredTime*ClockFrequency)/3
		MAP_GPIOPinWrite(GPIO_PORTF_BASE, LED_RED|LED_GREEN|LED_BLUE, 0);
		MAP_SysCtlDelay(16333333);
	}
}
예제 #15
0
파일: platform.c 프로젝트: arnew/matelight
void platform_init(void) {
	/* 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. */
	MAP_FPULazyStackingEnable();

	/* Set clock to PLL at 50MHz */
	MAP_SysCtlClockSet(SYSCTL_SYSDIV_4 | SYSCTL_USE_PLL | SYSCTL_OSC_MAIN |
					   SYSCTL_XTAL_16MHZ);

	/* Enable the GPIO pins for the LED (PF2 & PF3). */
	MAP_SysCtlPeripheralEnable(SYSCTL_PERIPH_GPIOF);
	MAP_GPIOPinTypeGPIOOutput(GPIO_PORTF_BASE, GPIO_PIN_3|GPIO_PIN_2);
	/* Enable the system tick. FIXME do we need this? */
	MAP_SysTickPeriodSet(MAP_SysCtlClockGet() / SYSTICKS_PER_SECOND);
	MAP_SysTickIntEnable();
	MAP_SysTickEnable();
}
예제 #16
0
//*****************************************************************************
//
// Set up the system clock using the mapped ROM function.
//
//*****************************************************************************
int
main(void)
{
    //
    // Set the clocking to run directly from the PLL at 20 MHz.
    // The MAP_ prefix means that this will be coded as a ROM call if the
    // part supports this function in ROM.  Otherwise it will be coded by
    // the compiler as a library call.
    //
    MAP_SysCtlClockSet(SYSCTL_SYSDIV_10 | SYSCTL_USE_PLL | SYSCTL_OSC_MAIN |
                       SYSCTL_XTAL_16MHZ);

    //
    // Return with no errors.
    //
    return(0);
}
예제 #17
0
int main(void)
{
	//MAP_SysCtlClockSet(SYSCTL_SYSDIV_2_5 | SYSCTL_USE_PLL | SYSCTL_OSC_MAIN |
    //                   SYSCTL_XTAL_16MHZ);	// for LM3S9B92
	MAP_SysCtlClockSet(SYSCTL_SYSDIV_3 | SYSCTL_USE_PLL | SYSCTL_OSC_MAIN |
                       SYSCTL_XTAL_8MHZ);	// for LM3S6965

	SampTask = LutosTaskCreate(
		LowSpeedSampling,
		"LowSamp",
		NULL,
		PRIORITY_HARD_REALTIME);
	LutosTickEventCreate(
		10, //PERIOD_10_MS,
		0,
		SampTask);
	LutosTaskStartScheduler();
}
예제 #18
0
/*
 * @brief Initialize the minimal amount of hardware for the bootloader to function
 * @returns void
 */
void systemInit(void) {
	uint32 i, j;

	MAP_IntMasterDisable();

	// increase LDO voltage so that PLL operates properly
	MAP_SysCtlLDOSet(SYSCTL_LDO_2_75V);
	#ifdef PART_LM3S8962
	MAP_SysCtlClockSet(SYSCTL_SYSDIV_4 | SYSCTL_USE_PLL | SYSCTL_OSC_MAIN | SYSCTL_XTAL_8MHZ);
	#endif

	systemIDInit();
	blinkyLedInit();
	buttonsInit();
	srand(roneID);
	serialInit();
	#if defined(RONE_V9) || defined(RONE_V12)
	SPIInit();
	radioInit();
	#endif // defined(RONE_V9) || defined(RONE_V12)

	// Triple blink blinky, startup signal
	for (i = 0; i < 3; i++) {
		blinkyLedSet(1);
		for (j = 0; j < 150000;) {
			j++;
		}
		blinkyLedSet(0);
		for (j = 0; j < 250000;) {
			j++;
		}
	}

	// Initialize 24-bit Systick
	SysTickPeriodSet(0xffffff);
	SysTickEnable();
}
예제 #19
0
int main()
{
	//
	// 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.
	//
	MAP_FPUEnable();
	MAP_FPULazyStackingEnable();

	//
	// Set the clocking to run from the PLL at 50MHZ, change to SYSCTL_SYSDIV_2_5 for 80MHz if neeeded
	//
	MAP_SysCtlClockSet(SYSCTL_SYSDIV_4 | SYSCTL_USE_PLL | SYSCTL_OSC_MAIN | SYSCTL_XTAL_16MHZ);
	MAP_IntMasterDisable();

	//
	// Initialize the SW2 button
	//
	MAP_SysCtlPeripheralEnable(SYSCTL_PERIPH_GPIOF);
	//
	// Unlock PF0 so we can change it to a GPIO input
	// Once we have enabled (unlocked) the commit register then re-lock it
	// to prevent further changes.  PF0 is muxed with NMI thus a special case.
	//
	HWREG(GPIO_PORTF_BASE + GPIO_O_LOCK) = GPIO_LOCK_KEY;
	HWREG(GPIO_PORTF_BASE + GPIO_O_CR) |= 0x01;
	HWREG(GPIO_PORTF_BASE + GPIO_O_LOCK) = 0;
	MAP_GPIOPinTypeGPIOInput(GPIO_PORTF_BASE, GPIO_PIN_0);
	MAP_GPIOPadConfigSet(GPIO_PORTF_BASE, GPIO_PIN_0, GPIO_STRENGTH_2MA , GPIO_PIN_TYPE_STD_WPU);

	//
	// Initialize the communication layer with a default UART setting
	//
	AbstractComm * comm = NULL;
	AbstractComm * uart_comm = new UARTComm();
	purpinsComm communication(uart_comm);

	//
	// Initialize the robot object
	//
	purpinsRobot purpins;

	//
	// Initialize the EEPROM
	//
	purpinsSettings settings;

	//
	// Initialize the MPU6050-based IMU
	//
	mpudata_t mpu;
	//unsigned long sample_rate = 10 ;
	//mpu9150_init(0, sample_rate, 0);
	memset(&mpu, 0, sizeof(mpudata_t));

	//
	// Get the current processor clock frequency.
	//
	ulClockMS = MAP_SysCtlClockGet() / (3 * 1000);
	//unsigned long loop_delay = (1000 / sample_rate) - 2;

	//
	// Configure SysTick to occur 1000 times per second
	//
	MAP_SysTickPeriodSet(MAP_SysCtlClockGet() / SYSTICKS_PER_SECOND);
	MAP_SysTickIntEnable();
	MAP_SysTickEnable();

	MAP_IntMasterEnable();

	//
	// Load the settings from EEPROM
	//
	// Load the robot's ID
	settings.get(PP_SETTING_ID, &id, sizeof(uint32_t));
	// Load the motors' PID gains
	settings.get(PP_SETTING_LEFT_PID, purpins.leftPIDGains(), sizeof(PIDGains));
	settings.get(PP_SETTING_RIGHT_PID, purpins.rightPIDGains(), sizeof(PIDGains));
	// Load the communication type
	uint32_t comm_type;
	settings.get(PP_SETTING_COMM_TYPE, &comm_type, sizeof(uint32_t));
	// Holding SW2 at startup forces USB Comm
	if(comm_type != PP_COMM_TYPE_USB && MAP_GPIOPinRead(GPIO_PORTF_BASE, GPIO_PIN_0) == 1)
	{
		if(comm_type == PP_COMM_TYPE_CC3000)
		{
			comm = new WiFiComm();
			// Load network and server settings
			settings.get(PP_SETTING_NETWORK_DATA, (static_cast<WiFiComm*>(comm))->network(), sizeof(Network));
			settings.get(PP_SETTING_SERVER_DATA, (static_cast<WiFiComm*>(comm))->server(), sizeof(Server));
			// Set WiFiComm as the underlying communication layer
			communication.setCommLayer(comm);
		}
		else if(comm_type == PP_COMM_TYPE_ESP8266)
		{
			// TODO
		}
		else if(comm_type == PP_COMM_TYPE_XBEE)
		{
			// TODO
		}
	}

	//
	// Communication variables and stuff
	//
	uint8_t sensors_pack[SENSORS_PACK_SIZE];
	bool send_pack = false;
	unsigned long sensor_streaming_millis = 0;
	unsigned long last_millis = millis();

	uint8_t data[SERIAL_BUFFER_SIZE];
	size_t data_size;
	uint8_t action;

	//
	// Main loop, just managing communications
	//
	while(1)
	{
		//
		// Check for a new action
		//
		action = communication.getMsg(data, data_size);

		// If we got an action...
		if(action > 0)
		{
			// Process it!!!
			if(action == PP_ACTION_GET_VERSION)
			{
				uint8_t version = VERSION;
				communication.sendMsg(PP_ACTION_GET_VERSION, (void*)(&version), 1);
			}
			else if(action == PP_ACTION_DRIVE)
			{
				RobotSpeed speed;
				memcpy(&speed, data, sizeof(speed));
				purpins.setSpeed(&speed);
				communication.sendAck(PP_ACTION_DRIVE);
			}
			else if(action == PP_ACTION_DRIVE_MOTORS)
			{
				MotorSpeeds motor_speeds;
				memcpy(&motor_speeds, data, sizeof(motor_speeds));
				purpins.setMotorSpeeds(&motor_speeds);
				communication.sendAck(PP_ACTION_DRIVE_MOTORS);
			}
			else if(action == PP_ACTION_DRIVE_PWM)
			{
				MotorPWMs motor_pwms;
				memcpy(&motor_pwms, data, sizeof(motor_pwms));
				purpins.setPWM(&motor_pwms);
				communication.sendAck(PP_ACTION_DRIVE_PWM);
			}
			else if(action == PP_ACTION_GET_ODOMETRY)
			{
				Pose odometry;
				purpins.getOdometry(&odometry);
				communication.sendMsg(PP_ACTION_GET_ODOMETRY, (void*)(&odometry), sizeof(odometry));
			}
			else if(action == PP_ACTION_GET_MOTOR_SPEEDS)
			{
				MotorSpeeds speed;
				purpins.getMotorSpeeds(&speed);
				communication.sendMsg(PP_ACTION_GET_MOTOR_SPEEDS, (void*)(&speed), sizeof(speed));
			}
			else if(action == PP_ACTION_GET_ENCODER_PULSES)
			{
				EncoderPulses encoder_pulses;
				purpins.getEncoderTicks(&encoder_pulses);
				communication.sendMsg(PP_ACTION_GET_ENCODER_PULSES, (void*)(&encoder_pulses), sizeof(encoder_pulses));
			}
			else if(action == PP_ACTION_GET_IMU)
			{
				IMU imu_data;
				imu_data.orientation_x = mpu.fusedQuat[0];
				imu_data.orientation_y = mpu.fusedQuat[1];
				imu_data.orientation_z = mpu.fusedQuat[2];
				imu_data.orientation_w = mpu.fusedQuat[4];
				imu_data.linear_acceleration_x = mpu.calibratedAccel[0];
				imu_data.linear_acceleration_y = mpu.calibratedAccel[1];
				imu_data.linear_acceleration_z = mpu.calibratedAccel[2];
				imu_data.angular_velocity_x = mpu.calibratedMag[0];
				imu_data.angular_velocity_y = mpu.calibratedMag[1];
				imu_data.angular_velocity_z = mpu.calibratedMag[2];
				communication.sendMsg(PP_ACTION_GET_IMU, (void*)(&imu_data), sizeof(imu_data));
			}
			else if(action == PP_ACTION_GET_IR_SENSORS)
			{
				// TODO: Add the IR sensors
			}
			else if(action == PP_ACTION_GET_GAS_SENSOR)
			{
				// TODO: Add the gas sensor
			}
			else if(action == PP_ACTION_SET_SENSORS_PACK)
			{
				bool ok = true;
				memset(sensors_pack, 0, SENSORS_PACK_SIZE);
				if(data_size > SENSORS_PACK_SIZE)
				{
					communication.error(PP_ERROR_BUFFER_SIZE);
					ok = false;
					break;
				}
				for(unsigned int i=0 ; i<data_size ; i++)
				{
					if(data[i] < PP_ACTION_GET_ODOMETRY || data[i] > PP_ACTION_GET_GAS_SENSOR)
					{
						communication.error(PP_ERROR_SENSOR_UNKNOWN);
						ok = false;
						break;
					}
				}
				if(ok)
				{
					memcpy(sensors_pack, data, data_size);
					communication.sendAck(PP_ACTION_SET_SENSORS_PACK);
				}
			}
			else if(action == PP_ACTION_GET_SENSORS_PACK)
			{
				send_pack = true;
			}
			else if(action == PP_ACTION_SET_SENSOR_STREAMING)
			{
				float sensor_streaming_frequency;
				memcpy(&sensor_streaming_frequency, data, sizeof(sensor_streaming_frequency));
				sensor_streaming_millis = 1/sensor_streaming_frequency * 1000;
				communication.sendAck(PP_ACTION_SET_SENSOR_STREAMING);
			}
			else if(action == PP_ACTION_SET_GLOBAL_POSE)
			{
				Pose pose;
				memcpy(&pose, data, sizeof(pose));
				purpins.setGlobalPose(&pose);
				communication.sendAck(PP_ACTION_SET_GLOBAL_POSE);
			}
			else if(action == PP_ACTION_SET_NEIGHBORS_POSES)
			{
				// TODO: Finish this
			}
			else if(action == PP_ACTION_SET_ID)
			{
				memcpy(&id, data, sizeof(id));
				settings.save(PP_SETTING_ID, data, sizeof(uint32_t));
				communication.sendAck(PP_ACTION_SET_ID);
			}
			else if(action == PP_ACTION_GET_ID)
			{
				communication.sendMsg(PP_ACTION_GET_ID, (void*)(&id), sizeof(id));
			}
			else if(action == PP_ACTION_SET_PID_GAINS)
			{
				memcpy(purpins.leftPIDGains(), data, sizeof(PIDGains));
				memcpy(purpins.rightPIDGains(), data+sizeof(PIDGains), sizeof(PIDGains));
				settings.save(PP_SETTING_LEFT_PID, data, sizeof(PIDGains));
				settings.save(PP_SETTING_RIGHT_PID, data+sizeof(PIDGains), sizeof(PIDGains));
				communication.sendAck(PP_ACTION_SET_PID_GAINS);
			}
			else if(action == PP_ACTION_GET_PID_GAINS)
			{
				memcpy(data, purpins.leftPIDGains(), sizeof(PIDGains));
				memcpy(data+sizeof(PIDGains), purpins.rightPIDGains(), sizeof(PIDGains));
				communication.sendMsg(PP_ACTION_GET_ID, (void*)(data), 2*sizeof(PIDGains));
			}
			else if(action == PP_ACTION_SET_SERVER_DATA)
			{
				settings.save(PP_SETTING_SERVER_DATA, data, sizeof(Server));
				communication.sendAck(PP_ACTION_SET_SERVER_DATA);
			}
			else if(action == PP_ACTION_GET_SERVER_DATA)
			{
				settings.get(PP_SETTING_SERVER_DATA, data, sizeof(Server));
				communication.sendMsg(PP_ACTION_GET_SERVER_DATA, (void*)(data), sizeof(Server));
			}
			else if(action == PP_ACTION_SET_NETWORK_DATA)
			{
				settings.save(PP_SETTING_NETWORK_DATA, data, sizeof(Network));
				communication.sendAck(PP_ACTION_SET_NETWORK_DATA);
			}
			else if(action == PP_ACTION_GET_NETWORK_DATA)
			{
				settings.get(PP_SETTING_NETWORK_DATA, data, sizeof(Network));
				communication.sendMsg(PP_ACTION_GET_NETWORK_DATA, (void*)(data), sizeof(Network));
			}
			else if(action == PP_ACTION_SET_COMM_TYPE)
			{
				memcpy(&comm_type, data, sizeof(comm_type));
				if(comm_type != communication.type())
				{
					if(comm_type == PP_COMM_TYPE_USB)
					{
						communication.setCommLayer(uart_comm);
						if(comm != NULL) delete comm;
					}
					if(comm_type == PP_COMM_TYPE_CC3000)
					{
						if(comm != NULL) delete comm;
						comm = new WiFiComm();
						// Load network and server settings
						settings.get(PP_SETTING_NETWORK_DATA, (static_cast<WiFiComm*>(comm))->network(), sizeof(Network));
						settings.get(PP_SETTING_SERVER_DATA, (static_cast<WiFiComm*>(comm))->server(), sizeof(Server));
						// Set WiFiComm as the underlying communication layer
						communication.setCommLayer(comm);
					}
					else if(comm_type == PP_COMM_TYPE_ESP8266)
					{
						// TODO
					}
					else if(comm_type == PP_COMM_TYPE_XBEE)
					{
						// TODO
					}
					else
					{
						communication.error(PP_ERROR_COMM_UNKNOWN);
					}
					communication.sendAck(PP_ACTION_SET_COMM_TYPE);
				}
			}

		} // if(action > 0)

		//
		// Manage sensor streaming
		//
		unsigned long current_millis = millis();
		if(send_pack || (sensor_streaming_millis > 0 && (current_millis - last_millis) >= sensor_streaming_millis))
		{
			size_t size = 0;
			for(int i=0 ; i<SENSORS_PACK_SIZE ; i++)
			{
				if(sensors_pack[i] == 0) break;

				if(sensors_pack[i] == PP_ACTION_GET_ODOMETRY)
				{
					Pose odometry;
					purpins.getOdometry(&odometry);
					memcpy(data+size, &odometry, sizeof(odometry));
					size += sizeof(odometry);
				}
				else if(sensors_pack[i] == PP_ACTION_GET_MOTOR_SPEEDS)
				{
					MotorSpeeds speed;
					purpins.getMotorSpeeds(&speed);
					memcpy(data+size, &speed, sizeof(speed));
					size += sizeof(speed);
				}
				else if(sensors_pack[i] == PP_ACTION_GET_ENCODER_PULSES)
				{
					EncoderPulses encoder_pulses;
					purpins.getEncoderTicks(&encoder_pulses);
					memcpy(data+size, &encoder_pulses, sizeof(encoder_pulses));
					size += sizeof(encoder_pulses);
				}
				else if(sensors_pack[i] == PP_ACTION_GET_IMU)
				{
					IMU imu_data;
					imu_data.orientation_x = mpu.fusedQuat[0];
					imu_data.orientation_y = mpu.fusedQuat[1];
					imu_data.orientation_z = mpu.fusedQuat[2];
					imu_data.orientation_w = mpu.fusedQuat[4];
					imu_data.linear_acceleration_x = mpu.calibratedAccel[0];
					imu_data.linear_acceleration_y = mpu.calibratedAccel[1];
					imu_data.linear_acceleration_z = mpu.calibratedAccel[2];
					imu_data.angular_velocity_x = mpu.calibratedMag[0];
					imu_data.angular_velocity_y = mpu.calibratedMag[1];
					imu_data.angular_velocity_z = mpu.calibratedMag[2];
					memcpy(data+size, &imu_data, sizeof(imu_data));
					size += sizeof(imu_data);
				}
				else if(sensors_pack[i] == PP_ACTION_GET_IR_SENSORS)
				{
					// TODO: Add the IR sensors
				}
				else if(sensors_pack[i] == PP_ACTION_GET_GAS_SENSOR)
				{
					// TODO: Add the gas sensor
				}
			}

			communication.sendMsg(PP_ACTION_GET_SENSORS_PACK, (void*)(data), size);
			last_millis = current_millis;
			send_pack = false;

		} // if(send_pack ...

	} // while(1)

	return 0;
}
//*****************************************************************************
//
// The main function sets up the peripherals for the example, then enters
// a wait loop until the DMA transfers are complete.  At the end some
// information is printed for the user.
//
//*****************************************************************************
int
main(void)
{
    unsigned long ulIdx;

    //
    // Set the clocking to run directly from the PLL at 50 MHz.
    //
    MAP_SysCtlClockSet(SYSCTL_SYSDIV_4 | SYSCTL_USE_PLL | SYSCTL_OSC_MAIN |
                       SYSCTL_XTAL_16MHZ);

    //
    // Initialize the console UART and write a message to the terminal.
    //
    MAP_SysCtlPeripheralEnable(SYSCTL_PERIPH_GPIOA);
    MAP_GPIOPinConfigure(GPIO_PA0_U0RX);
    MAP_GPIOPinConfigure(GPIO_PA1_U0TX);
    MAP_GPIOPinTypeUART(GPIO_PORTA_BASE, GPIO_PIN_0 | GPIO_PIN_1);
    UARTStdioInit(0);
    UARTprintf("\033[2JMemory/UART scatter-gather uDMA example\n\n");

    //
    // Configure UART1 to be used for the loopback peripheral
    //
    MAP_SysCtlPeripheralEnable(SYSCTL_PERIPH_UART1);

    //
    // Configure the UART communication parameters.
    //
    MAP_UARTConfigSetExpClk(UART1_BASE, MAP_SysCtlClockGet(), 115200,
                            UART_CONFIG_WLEN_8 | UART_CONFIG_STOP_ONE |
                            UART_CONFIG_PAR_NONE);

    //
    // Set both the TX and RX trigger thresholds to one-half (8 bytes).  This
    // will be used by the uDMA controller to signal when more data should be
    // transferred.  The uDMA TX and RX channels will be configured so that it
    // can transfer 8 bytes in a burst when the UART is ready to transfer more
    // data.
    //
    MAP_UARTFIFOLevelSet(UART1_BASE, UART_FIFO_TX4_8, UART_FIFO_RX4_8);

    //
    // Enable the UART for operation, and enable the uDMA interface for both TX
    // and RX channels.
    //
    MAP_UARTEnable(UART1_BASE);
    MAP_UARTDMAEnable(UART1_BASE, UART_DMA_RX | UART_DMA_TX);

    //
    // This register write will set the UART to operate in loopback mode.  Any
    // data sent on the TX output will be received on the RX input.
    //
    HWREG(UART1_BASE + UART_O_CTL) |= UART_CTL_LBE;

    //
    // Enable the UART peripheral interrupts.  Note that no UART interrupts
    // were enabled, but the uDMA controller will cause an interrupt on the
    // UART interrupt signal when a uDMA transfer is complete.
    //
    MAP_IntEnable(INT_UART1);

    //
    // Enable the uDMA peripheral clocking.
    //
    MAP_SysCtlPeripheralEnable(SYSCTL_PERIPH_UDMA);

    //
    // Enable the uDMA controller.
    //
    MAP_uDMAEnable();

    //
    // Point at the control table to use for channel control structures.
    //
    MAP_uDMAControlBaseSet(sControlTable);

    //
    // Configure the UART TX channel for scatter-gather
    // Peripheral scatter-gather is used because transfers are gated by
    // requests from the peripheral
    //
    UARTprintf("Configuring UART TX uDMA channel for scatter-gather\n");
#ifndef USE_SGSET_API
    //
    // Use the original method for configuring the scatter-gather transfer
    //
    uDMAChannelControlSet(UDMA_CHANNEL_UART1TX, UDMA_SIZE_32 |
                          UDMA_SRC_INC_32 | UDMA_DST_INC_32 | UDMA_ARB_4);
    uDMAChannelTransferSet(UDMA_CHANNEL_UART1TX, UDMA_MODE_PER_SCATTER_GATHER,
                           g_TaskTableSrc,
                           &sControlTable[UDMA_CHANNEL_UART1TX], 6 * 4);
#else
    //
    // Use the simplified API for configuring the scatter-gather transfer
    //
    uDMAChannelScatterGatherSet(UDMA_CHANNEL_UART1TX, 6, g_TaskTableSrc, 1);
#endif

    //
    // Configure the UART RX channel for scatter-gather task list.
    // This is set to peripheral s-g because it starts by receiving data
    // from the UART
    //
    UARTprintf("Configuring UART RX uDMA channel for scatter-gather\n");
#ifndef USE_SGSET_API
    //
    // Use the original method for configuring the scatter-gather transfer
    //
    uDMAChannelControlSet(UDMA_CHANNEL_UART1RX, UDMA_SIZE_32 |
                          UDMA_SRC_INC_32 | UDMA_DST_INC_32 | UDMA_ARB_4);
    uDMAChannelTransferSet(UDMA_CHANNEL_UART1RX, UDMA_MODE_PER_SCATTER_GATHER,
                           g_TaskTableDst,
                           &sControlTable[UDMA_CHANNEL_UART1RX], 7 * 4);
#else
    //
    // Use the simplified API for configuring the scatter-gather transfer
    //
    uDMAChannelScatterGatherSet(UDMA_CHANNEL_UART1RX, 7, g_TaskTableDst, 1);
#endif

    //
    // Fill the source buffer with a pattern
    //
    for(ulIdx = 0; ulIdx < 1024; ulIdx++)
    {
        g_ucSrcBuf[ulIdx] = ulIdx + (ulIdx / 256);
    }

    //
    // Enable the uDMA controller error interrupt.  This interrupt will occur
    // if there is a bus error during a transfer.
    //
    IntEnable(INT_UDMAERR);

    //
    // Enable the UART RX DMA channel.  It will wait for data to be available
    // from the UART.
    //
    UARTprintf("Enabling uDMA channel for UART RX\n");
    MAP_uDMAChannelEnable(UDMA_CHANNEL_UART1RX);

    //
    // Enable the UART TX DMA channel.  Since the UART TX will be asserting
    // a DMA request (since the TX FIFO is empty), this will cause this
    // DMA channel to start running.
    //
    UARTprintf("Enabling uDMA channel for UART TX\n");
    MAP_uDMAChannelEnable(UDMA_CHANNEL_UART1TX);

    //
    // Wait for the TX task list to be finished
    //
    UARTprintf("Waiting for TX task list to finish ... ");
    while(!g_bTXdone)
    {
    }
    UARTprintf("done\n");

    //
    // Wait for the RX task list to be finished
    //
    UARTprintf("Waiting for RX task list to finish ... ");
    while(!g_bRXdone)
    {
    }
    UARTprintf("done\n");

    //
    // Verify that all the counters are in the expected state
    //
    UARTprintf("Verifying counters\n");
    if(g_ulDMAIntCount != 2)
    {
        UARTprintf("ERROR in interrupt count, found %d, expected 2\n",
                  g_ulDMAIntCount);
    }
    if(g_uluDMAErrCount != 0)
    {
        UARTprintf("ERROR in error counter, found %d, expected 0\n",
                  g_uluDMAErrCount);
    }

    //
    // Now verify the contents of the final destination buffer.  Compare it
    // to the original source buffer.
    //
    UARTprintf("Verifying buffer contents ... ");
    for(ulIdx = 0; ulIdx < 1024; ulIdx++)
    {
        if(g_ucDstBuf[ulIdx] != g_ucSrcBuf[ulIdx])
        {
            UARTprintf("ERROR\n    @ index %d: expected 0x%02X, found 0x%02X\n",
                       ulIdx, g_ucSrcBuf[ulIdx], g_ucDstBuf[ulIdx]);
            UARTprintf("Checking stopped.  There may be additional errors\n");
            break;
        }
    }
    if(ulIdx == 1024)
    {
        UARTprintf("OK\n");
    }

    //
    // End of program, loop forever
    //
    for(;;)
    {
    }
}
//*****************************************************************************
//
// Main application entry function.
//
//*****************************************************************************
int
main(void)
{
    tBoolean bRetcode;
    smplStatus_t eRetcode;

    //
    // Set the system clock to run at 50MHz from the PLL
    //
    MAP_SysCtlClockSet(SYSCTL_SYSDIV_4 | SYSCTL_USE_PLL | SYSCTL_OSC_MAIN |
                       SYSCTL_XTAL_16MHZ);

    //
    // NB: We don't call PinoutSet() in this testcase since the EM header
    // expansion board doesn't currently have an I2C ID EEPROM.  If we did
    // call PinoutSet() this would configure all the EPI pins for SDRAM and
    // we don't want to do this.
    //
    g_eDaughterType = DAUGHTER_NONE;

    //
    // Enable peripherals required to drive the LCD.
    //
    ROM_SysCtlPeripheralEnable(SYSCTL_PERIPH_GPIOB);
    ROM_SysCtlPeripheralEnable(SYSCTL_PERIPH_GPIOD);
    ROM_SysCtlPeripheralEnable(SYSCTL_PERIPH_GPIOE);
    ROM_SysCtlPeripheralEnable(SYSCTL_PERIPH_GPIOH);

    //
    // Configure SysTick for a 10Hz interrupt.
    //
    ROM_SysTickPeriodSet(ROM_SysCtlClockGet() / TICKS_PER_SECOND);
    ROM_SysTickEnable();
    ROM_SysTickIntEnable();

    //
    // Initialize the display driver.
    //
    Kitronix320x240x16_SSD2119Init();

    //
    // Initialize the touch screen driver.
    //
    TouchScreenInit();

    //
    // Set the touch screen event handler.
    //
    TouchScreenCallbackSet(WidgetPointerMessage);

    //
    // Add the compile-time defined widgets to the widget tree.
    //
    WidgetAdd(WIDGET_ROOT, (tWidget *)&g_sHeading);

    //
    // Initialize the status string.
    //
    UpdateStatus("Initializing...");

    //
    // Paint the widget tree to make sure they all appear on the display.
    //
    WidgetPaint(WIDGET_ROOT);

    //
    // Initialize the SimpliciTI BSP.
    //
    BSP_Init();

    //
    // Set the SimpliciTI device address using the current Ethernet MAC address
    // to ensure something like uniqueness.
    //
    bRetcode = SetSimpliciTIAddress();

    //
    // Did we have a problem with the address?
    //
    if(!bRetcode)
    {
        //
        // Yes - make sure the display is updated then hang the app.
        //
        WidgetMessageQueueProcess();
        while(1)
        {
            //
            // MAC address is not set so hang the app.
            //
        }
    }

    //
    // Turn on both our LEDs
    //
    SetLED(1, true);
    SetLED(2, true);

    UpdateStatus("Waiting...");

    //
    // Initialize the SimpliciTI stack but don't set any receive callback.
    //
    while(1)
    {
        eRetcode = SMPL_Init((uint8_t (*)(linkID_t))0);

        if(eRetcode == SMPL_SUCCESS)
        {
            break;
        }

        ToggleLED(1);
        ToggleLED(2);
        SPIN_ABOUT_A_SECOND;
    }

    //
    // Tell the user what's up.
    //
    UpdateStatus("Range Extender active.");

    //
    // Do nothing after this - the SimpliciTI stack code handles all the
    // access point function required.
    //
    while(1)
    {
        //
        // Process the widget message queue.
        //
        WidgetMessageQueueProcess();
    }
}
예제 #22
0
//*****************************************************************************
//
// This example demonstrates how to send a string of data to the UART.
//
//*****************************************************************************
int
main(void)
{
	uint32_t ui32_Period, ui32_PWM=0, ui32_PWM_step = 40, ui32_PWM_min=2000, ui32_PWM_max=4000;
	uint32_t ui32_sw1;
    uint32_t ui32_sw2;
    //
    // 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.
    //
    //MAP_FPUEnable();
    //MAP_FPULazyStackingEnable();

    //
    // Set the clocking to run directly from the crystal.
    //
    MAP_SysCtlClockSet(SYSCTL_SYSDIV_1 | SYSCTL_USE_OSC | SYSCTL_OSC_MAIN |
                       SYSCTL_XTAL_16MHZ);

    //
    // Enable the GPIO port that is used for the on-board LED.
    //
    MAP_SysCtlPeripheralEnable(SYSCTL_PERIPH_GPIOF);

    //
    // Enable the GPIO pins for the LED (PF2).
    //
    MAP_GPIOPinTypeGPIOOutput(GPIO_PORTF_BASE, GPIO_PIN_2);
    
    // Configure UART
    InitConsole();

    
    // -----------------------------------------------------------------
    // Configure PWM for servo control
    // -----------------------------------------------------------------
    // follow page 1240 of the datasheet:
    ui32_Period = (MAP_SysCtlClockGet()/8) / 50; //PWM frequency 50HZ, T=20ms
    // GOTO middle of servo in the beginning
    ui32_PWM = ui32_PWM_min + (ui32_PWM_max - ui32_PWM_min) / 2;
    ui32_PWM_max = ui32_Period*.1;
    ui32_PWM_min = ui32_Period*.05;
    
    //Configure PWM Clock to match system
	MAP_SysCtlPWMClockSet(SYSCTL_PWMDIV_8);
    
    // Enable system clock for PWM0 module
    MAP_SysCtlPeripheralEnable(SYSCTL_PERIPH_PWM0);
  
    // Enable the GPIO port that is used for the PWM outputs
    MAP_SysCtlPeripheralEnable(SYSCTL_PERIPH_GPIOB);
    
    //Configure PB5,PB5 Pins as PWM
    MAP_GPIOPinConfigure(GPIO_PB4_M0PWM2);
    MAP_GPIOPinConfigure(GPIO_PB5_M0PWM3);
    MAP_GPIOPinTypePWM(GPIO_PORTB_BASE, GPIO_PIN_4);
    MAP_GPIOPinTypePWM(GPIO_PORTB_BASE, GPIO_PIN_5);
    
    //Configure PWM Options
    MAP_PWMGenConfigure(PWM0_BASE, PWM_GEN_1 , PWM_GEN_MODE_UP_DOWN | PWM_GEN_MODE_NO_SYNC);
    
    //
    // Set the PWM period to 50Hz.  To calculate the appropriate parameter
    // use the following equation: N = (1 / f) * SysClk.  Where N is the
    // function parameter, f is the desired frequency, and SysClk is the
    // system clock frequency.
    // In this case you get: (1 / 50Hz) * 16MHz/8div = 40000 cycles.  Note that
    // the maximum period you can set is 2^16 - 1.
    // TODO: modify this calculation to use the clock frequency that you are
    // using.
    //
    PWMGenPeriodSet(PWM0_BASE, PWM_GEN_1, ui32_Period);
    
    //Set PWM duty - 25% and 75%
    PWMPulseWidthSet(PWM0_BASE, PWM_OUT_2, ui32_PWM);
    PWMPulseWidthSet(PWM0_BASE, PWM_OUT_3, ui32_PWM);
    
    // Enable the PWM generator
    MAP_PWMGenEnable(PWM0_BASE, PWM_GEN_1);

    // Turn on the Output pins
    MAP_PWMOutputState(PWM0_BASE, PWM_OUT_2_BIT | PWM_OUT_3_BIT, true);
    
    
    // -----------------------------------------------------------------
    // Enable PORTF and Configure SW1 and SW2 as input
    // -----------------------------------------------------------------
    MAP_SysCtlPeripheralEnable(SYSCTL_PERIPH_GPIOF);
    GPIO_PORTF_LOCK_R = 0x4C4F434B;   // unlock GPIO Port F
    GPIO_PORTF_CR_R = 0x1F;           // allow changes to PF4-0
    MAP_GPIOPadConfigSet(GPIO_PORTF_BASE, (GPIO_PIN_4 | GPIO_PIN_0), GPIO_STRENGTH_2MA, GPIO_PIN_TYPE_STD_WPU);
    MAP_GPIODirModeSet(GPIO_PORTF_BASE, (GPIO_PIN_4 | GPIO_PIN_0), GPIO_DIR_MODE_IN);

    //
    // Loop forever echoing data through the UART.
    //
    while(1)
    {
		// Get buttons:
		ui32_sw1 = MAP_GPIOPinRead(GPIO_PORTF_BASE, GPIO_PIN_4);
		ui32_sw2 = MAP_GPIOPinRead(GPIO_PORTF_BASE, GPIO_PIN_0);
		// if pressing SW1 on LaunchPad TM4C123G
		if( ui32_sw1 == 0 )
		{
			if(ui32_PWM >= ui32_PWM_min+ui32_PWM_step) {
				ui32_PWM -= ui32_PWM_step;
			}
		}
		if( ui32_sw2 == 0 )
		{
			if(ui32_PWM <= ui32_PWM_max-ui32_PWM_step) {
				ui32_PWM += ui32_PWM_step;
			}
		}
		
		UARTprintf("Period: %d, PWM: %d\n", ui32_Period, ui32_PWM);
		MAP_SysCtlDelay(2000000);
		
		MAP_PWMPulseWidthSet(PWM0_BASE, PWM_OUT_2 , ui32_Period - ui32_PWM);
		MAP_PWMPulseWidthSet(PWM0_BASE, PWM_OUT_3 , ui32_PWM);
    }
}
예제 #23
0
//*****************************************************************************
//
// Configue UART in internal loopback mode and tranmsit and receive data
// internally.
//
//*****************************************************************************
int
main(void)
{

#if defined(TARGET_IS_TM4C129_RA0) ||                                         \
    defined(TARGET_IS_TM4C129_RA1) ||                                         \
    defined(TARGET_IS_TM4C129_RA2)
    uint32_t ui32SysClock;
#endif
    uint8_t ui8DataTx[NUM_UART_DATA];
    uint8_t ui8DataRx[NUM_UART_DATA];
    uint32_t ui32index;

    //
    // Set the clocking to run directly from the crystal.
    //
#if defined(TARGET_IS_TM4C129_RA0) ||                                         \
    defined(TARGET_IS_TM4C129_RA1) ||                                         \
    defined(TARGET_IS_TM4C129_RA2)
    ui32SysClock = SysCtlClockFreqSet((SYSCTL_XTAL_25MHZ | SYSCTL_OSC_MAIN |
                                       SYSCTL_USE_OSC), 25000000);
#else
    MAP_SysCtlClockSet(SYSCTL_SYSDIV_1 | SYSCTL_USE_OSC | SYSCTL_OSC_MAIN |
                       SYSCTL_XTAL_16MHZ);
#endif

    //
    // Enable the peripherals used by this example.
    // UART0 :  To dump information to the console about the example.
    // UART7 :  Enabled in loopback mode. Anything transmitted to Tx will be
    //          received at the Rx.
    //
    MAP_SysCtlPeripheralEnable(SYSCTL_PERIPH_UART0);
    MAP_SysCtlPeripheralEnable(SYSCTL_PERIPH_UART7);
    MAP_SysCtlPeripheralEnable(SYSCTL_PERIPH_GPIOA);

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

    //
    // Internal loopback programming.  Configure the UART in loopback mode.
    //
    UARTLoopbackEnable(UART7_BASE);

    //
    // Configure the UART for 115,200, 8-N-1 operation.
    //
#if defined(TARGET_IS_TM4C129_RA0) ||                                         \
    defined(TARGET_IS_TM4C129_RA1) ||                                         \
    defined(TARGET_IS_TM4C129_RA2)
    MAP_UARTConfigSetExpClk(UART0_BASE, ui32SysClock, 115200,
                            (UART_CONFIG_WLEN_8 | UART_CONFIG_STOP_ONE |
                             UART_CONFIG_PAR_NONE));
    MAP_UARTConfigSetExpClk(UART7_BASE, ui32SysClock, 115200,
                            (UART_CONFIG_WLEN_8 | UART_CONFIG_STOP_ONE |
                             UART_CONFIG_PAR_NONE));
#else
    MAP_UARTConfigSetExpClk(UART0_BASE, MAP_SysCtlClockGet(), 115200,
                            (UART_CONFIG_WLEN_8 | UART_CONFIG_STOP_ONE |
                             UART_CONFIG_PAR_NONE));
    MAP_UARTConfigSetExpClk(UART7_BASE, MAP_SysCtlClockGet(), 115200,
                            (UART_CONFIG_WLEN_8 | UART_CONFIG_STOP_ONE |
                             UART_CONFIG_PAR_NONE));
#endif

    //
    // Print banner after clearing the terminal.
    //
    UARTSend(UART0_BASE, (uint8_t *)"\033[2J\033[1;1H", 10);
    UARTSend(UART0_BASE, (uint8_t *)"\nUART Loopback Example ->",
             strlen("\nUART Loopback Example ->"));

    //
    // Prepare data to send over the UART configured for internal loopback.
    //
    ui8DataTx[0] = 'u';
    ui8DataTx[1] = 'a';
    ui8DataTx[2] = 'r';
    ui8DataTx[3] = 't';

    //
    // Inform user that data is being sent over for internal loopback.
    //
    UARTSend(UART0_BASE, (uint8_t *)"\n\n\rSending : ",
             strlen("\n\n\rSending : "));
    UARTSend(UART0_BASE, (uint8_t*)ui8DataTx, NUM_UART_DATA);

    //
    // Send the data, which was prepared above, over the UART configured for
    // internal loopback operation.
    //
    for(ui32index = 0 ; ui32index < NUM_UART_DATA ; ui32index++)
    {
        UARTCharPut(UART7_BASE, ui8DataTx[ui32index]);
    }

    //
    // Wait for the UART module to complete transmitting.
    //
    while(MAP_UARTBusy(UART7_BASE))
    {
    }

    //
    // Inform user that data the loopback data is being received.
    //
    UARTSend(UART0_BASE, (uint8_t *)"\n\rReceiving : ",
             strlen("\n\rReceiving : "));

    //
    // Read data from the UART's receive FIFO and store it.
    //
    for(ui32index = 0 ; ui32index < NUM_UART_DATA ; ui32index++)
    {
        //
        // Get the data received by the UART at its receive FIFO
        //
        ui8DataRx[ui32index] = UARTCharGet(UART7_BASE);
    }

    //
    // Display the data received, after loopback, over UART's receive FIFO.
    //
    UARTSend(UART0_BASE, (uint8_t*)ui8DataRx, NUM_UART_DATA);

    //
    // Return no errors
    //
    return(0);
}
예제 #24
0
/*
 * initialize tm4c
 */
void init_satellite()
{
	FPUEnable();
	FPULazyStackingEnable();

	/*
	 * init clock
	 */
	MAP_SysCtlClockSet(SYSCTL_SYSDIV_3 | SYSCTL_USE_PLL | SYSCTL_XTAL_16MHZ | SYSCTL_OSC_MAIN);	//66.6..MHz

	MAP_IntMasterEnable();

	/*
	 * Enable peripherals
	 */
	MAP_SysCtlPeripheralEnable(SYSCTL_PERIPH_GPIOF);	//for LED indication

	MAP_SysCtlPeripheralEnable(SYSCTL_PERIPH_GPIOA);	//for UART
	MAP_SysCtlPeripheralEnable(SYSCTL_PERIPH_UART0);

	MAP_SysCtlPeripheralEnable(SYSCTL_PERIPH_GPIOB);	//for IRQ and SW_EN
	MAP_SysCtlPeripheralEnable(SYSCTL_PERIPH_GPIOE);	//for SPI


	/*
	 * configure
	 */
	MAP_GPIOPinTypeGPIOOutput(GPIO_PORTF_BASE, GPIO_PIN_1|GPIO_PIN_2|GPIO_PIN_3);
	MAP_GPIOPinWrite(GPIO_PORTF_BASE, GPIO_PIN_1|GPIO_PIN_2|GPIO_PIN_3, SIGNAL_LOW);	//off

	MAP_GPIOPinConfigure(GPIO_PA0_U0RX);
	MAP_GPIOPinConfigure(GPIO_PA1_U0TX);
	MAP_GPIOPinTypeUART(GPIO_PORTA_BASE, GPIO_PIN_0 | GPIO_PIN_1);
	UARTStdioConfig(UART_PORT, UART_BAUDRATE, SysCtlClockGet());


	MAP_GPIOIntDisable(GPIO_PORTB_BASE, SIGNAL_HIGH);	//interrupt disable

	MAP_GPIOPinTypeGPIOInput(GPIO_PORTB_BASE, GPIO_PIN_2);	//IRQ as input
	MAP_GPIOPadConfigSet(GPIO_PORTB_BASE, GPIO_PIN_2, GPIO_STRENGTH_2MA, GPIO_PIN_TYPE_STD_WPU);
	MAP_GPIOIntTypeSet(GPIO_PORTB_BASE, GPIO_PIN_2, GPIO_FALLING_EDGE);		//enable interrupt

	MAP_GPIOPinTypeGPIOOutput(GPIO_PORTB_BASE, GPIO_PIN_5);	//sw enable
	MAP_GPIODirModeSet(GPIO_PORTB_BASE, GPIO_PIN_5, GPIO_DIR_MODE_OUT);
	MAP_GPIOPadConfigSet(GPIO_PORTB_BASE, GPIO_PIN_5, GPIO_STRENGTH_2MA, GPIO_PIN_TYPE_STD_WPD);

	MAP_GPIOPinWrite(GPIO_PORTB_BASE, GPIO_PIN_5, SIGNAL_LOW);

	MAP_SysCtlPeripheralEnable(SYSCTL_PERIPH_GPIOE);
	MAP_GPIOPinTypeGPIOOutput(GPIO_PORTE_BASE, GPIO_PIN_0);

	MAP_GPIOPadConfigSet(GPIO_PORTE_BASE, GPIO_PIN_0, GPIO_STRENGTH_2MA, GPIO_PIN_TYPE_STD_WPU);
	MAP_GPIOPinWrite(GPIO_PORTE_BASE, GPIO_PIN_0, SIGNAL_HIGH);	//chip select

	MAP_GPIOIntEnable(GPIO_PORTB_BASE, GPIO_PIN_2);	//enable interrupt for WLAN_IRQ pin

	SpiCleanGPIOISR();	//clear interrupt status

	MAP_IntEnable(INT_GPIOB);	//spi


	init_worker();

	setState(READY);
}
int main(void)
{
	MAP_SysCtlClockSet(SYSCTL_SYSDIV_4 | SYSCTL_USE_PLL | SYSCTL_OSC_MAIN |SYSCTL_XTAL_12MHZ); //50MHZ

	//
	// Enable peripherals to operate when CPU is in sleep.
	//
	MAP_SysCtlPeripheralClockGating(true);

	//
	// Configure SysTick to occur 1000 times per second, to use as a time
	// reference.  Enable SysTick to generate interrupts.
	//
	MAP_SysTickPeriodSet(MAP_SysCtlClockGet() / SYSTICKS_PER_SECOND);
	MAP_SysTickIntEnable();
	MAP_SysTickEnable();

	//
	// Get the current processor clock frequency.
	//
	ulClockMS = MAP_SysCtlClockGet() / (3 * 1000);

	// init Serial Comm
	initSerialComm(230400);

	// init SSI0 in slave mode
	initSPIComm();

#ifdef DEBUG
	UARTprintf("Setting up PID\n");
#endif
	initCarPID();
#ifdef DEBUG
	UARTprintf("done\n");
#endif

#ifdef DEBUG
	UARTprintf("Setting up PWM ... \n");
#endif
	configurePWM();
	configureGPIO();
#ifdef DEBUG
	UARTprintf("done\n");
#endif

#ifdef DEBUG
	UARTprintf("Setting up Servo ... \n");
#endif
	servo_init();
	servo_setPosition(90);
#ifdef DEBUG
	UARTprintf("done\n");
#endif

#ifdef DEBUG
	UARTprintf("Starting QEI...");
#endif
	encoder_init();
#ifdef DEBUG
	UARTprintf("done\n");
#endif

#ifdef USE_I2C
#ifdef DEBUG
	UARTprintf("Setting up I2C\n");
#endif
	//I2C
	MAP_SysCtlPeripheralEnable(SYSCTL_PERIPH_I2C0);
	MAP_SysCtlPeripheralEnable(SYSCTL_PERIPH_GPIOB);
	MAP_GPIOPinTypeI2C(GPIO_PORTB_AHB_BASE,GPIO_PIN_2 | GPIO_PIN_3);
	MAP_I2CMasterInitExpClk(I2C0_MASTER_BASE,SysCtlClockGet(),true);  //false = 100khz , true = 400khz
	I2CMasterTimeoutSet(I2C0_MASTER_BASE, 1000);
#ifdef DEBUG
	UARTprintf("done\n");
#endif
#endif

#ifdef USE_I2C
#ifdef USE_INA226
#ifdef DEBUG
	UARTprintf("Setting up INA226\n");
#endif
	initINA226();
#ifdef DEBUG
	UARTprintf("done\n");
#endif
#endif
#endif


	while (1)
	{

	}
}
예제 #26
0
int main(void) {
	
	int  delay;
	float fTemperature, fPressure, fAltitude, fK_Altitude, fAltitude_sum,fK_Altitude_sum;
	int count,i;
//	static float f_meas[VAR_COUNT], fAlt_Mean, fAlt_Var;
	unsigned short sw1_count, sw2_count;
	unsigned char sw1_was_cleared = 0, sw2_was_cleared = 0;


	// Set the clocking to run directly from the external crystal/oscillator.
	MAP_SysCtlClockSet(SYSCTL_SYSDIV_1 | SYSCTL_USE_OSC | SYSCTL_OSC_MAIN |
			WRFL_XTAL);


	//init ports and peripherals
	PlatformInit();
	Nokia5110_Init();
	Nokia5110_Clear();


    Nokia5110_DrawFullImage(gears_logo);
    for(delay=0; delay<1000000; delay=delay+1);

    Nokia5110_Clear();
    Nokia5110_SetCursor(3, 1);
    Nokia5110_OutString("WRFL");
    Nokia5110_SetCursor(1, 2);
    Nokia5110_OutString("Prototype");
    Nokia5110_SetCursor(2, 4);
    Nokia5110_OutString("VER 0.1");
    Nokia5110_SetCursor(0, 5);
    Nokia5110_OutString("NightMecanic");
    for(delay=0; delay<1000000; delay=delay+1);
    Nokia5110_Clear();
    //
   // Enable interrupts to the processor.
   //
   MAP_IntMasterEnable();

   //
   // Initialize I2C1 peripheral.
   //
   I2CMInit(&g_sI2CInst, BMP180_I2C_BASE, BMP180_I2C_INT, 0xff, 0xff,
			MAP_SysCtlClockGet());

   //
   // Initialize the BMP180
   //
   BMP180Init(&g_sBMP180Inst, &g_sI2CInst, BMP180_I2C_ADDRESS,
			  BMP180AppCallback, &g_sBMP180Inst);


   //
   // Wait for initialization callback to indicate reset request is complete.
   //
   while(g_vui8DataFlag == 0)
   {
	   //
	   // Wait for I2C Transactions to complete.
	   //
   }

   //
   // Reset the data ready flag
   //
   g_vui8DataFlag = 0;

   //set oversampling to 8x
   g_sBMP180Inst.ui8Mode = 0xC0;

   //Initialize the Kalman filter
   Kalman_Init(&Alt_KState, 0.0f, 1.0f, ALT_KALMAN_R, ALT_KALMAN_Q);

   //
   // Enable the system ticks at 10 hz.
   //
   MAP_SysTickPeriodSet(MAP_SysCtlClockGet() / (40 * 3));
   MAP_SysTickIntEnable();
   MAP_SysTickEnable();


   Nokia5110_SetCursor(0, 0);
   Nokia5110_OutString("SW1:");

   Nokia5110_SetCursor(0, 2);
   Nokia5110_OutString("SW2:");

  //config done
   count = 0;
   //
   // Begin the data collection and printing.  Loop Forever.
   //
   while(1)
   {

	   // SW1
	   if (sw_state & SW1){
		   if (sw1_was_cleared){
			   sw1_was_cleared = 0;
			   sw1_count++;
		   	   Nokia5110_SetCursor(5, 0);
		   	   Nokia5110_OutUDec(sw1_count);
		   }
	   }else
		   sw1_was_cleared = 1;

	   //SW2
	   if (sw_state & SW2){
	   		   if (sw2_was_cleared){
	   			   sw2_was_cleared = 0;
	   			   sw2_count++;
	   		   	   Nokia5110_SetCursor(5, 2);
	   		   	   Nokia5110_OutUDec(sw2_count);
	   		   }
	   	   }else
	   		   sw2_was_cleared = 1;

	   // handle BMP180 data (display average every 50 samples)
	   if (g_vui8DataFlag ){
		   //
		   // Reset the data ready flag.
		   //
		   g_vui8DataFlag = 0;

		   //
		   // Get a local copy of the latest temperature data in float format.
		   //
		   BMP180DataTemperatureGetFloat(&g_sBMP180Inst, &fTemperature);

		   //
		   // Print temperature with three digits of decimal precision.
		   //

		   //Nokia5110_SetCursor(0, 0);
		   //Nokia5110_OutString("Temp:");
		   //Nokia5110_OutFloatp3(fTemperature);

		   //
		   // Get a local copy of the latest air pressure data in float format.
		   //
		   BMP180DataPressureGetFloat(&g_sBMP180Inst, &fPressure);

	   	   //
	   	   // Print Pressure with three digits of decimal precision.
	   	   //

	   	   //Nokia5110_SetCursor(0, 1);
	   	   // Nokia5110_OutString("Pres:");
	   	   //Nokia5110_SetCursor(0, 2);

	   	   //display in hPa
	   	   //Nokia5110_OutFloatp3((fPressure / 100.0f));

	   	   //
	   	   // Calculate the altitude.
	   	   //
	   	   //fAltitude = 44330.0f * (1.0f - powf(fPressure / 101325.0f,
	   	   //									   1.0f / 5.255f));
	   	   //corrected:
	   	   fAltitude = 44330.0f * (1.0f - powf(fPressure / LOC_ALT_P0,
	   										   1.0f / 5.255f));
	   	   // Kalman filtered altitude

	  	   Kalman_Update (&Alt_KState, fAltitude);
	  	   fK_Altitude = Alt_KState.X;


	  	   fAltitude_sum += fAltitude;
	  	   fK_Altitude_sum += fK_Altitude;
	  	   count++;

	  	   if (count>=50){
	  		 Nokia5110_SetCursor(0, 3);
	  		 Nokia5110_OutString("Alt:");
	  		 Nokia5110_OutFloatp3(fAltitude_sum/50.0);

	  		 Nokia5110_SetCursor(0, 5);
	  		 Nokia5110_OutString("KAlt:");
	  		 Nokia5110_OutFloatp3(fK_Altitude_sum/50.0);

	  		fAltitude_sum = 0;
	  		fK_Altitude_sum = 0;
	  		count = 0;
	  	   }


/*
	  	 //calculate variance
	  	 f_meas[count]=fK_Altitude;
	  	 count++;

	  	 if (count>=VAR_COUNT){
	  		 fAlt_Mean = 0.0f;
	  		 fAlt_Var = 0.0f;
	  		 // calculate mean
	  		 for(i=0; i<VAR_COUNT; i++){
	  			 fAlt_Mean = fAlt_Mean +f_meas[i];
	  		 }
	  		 fAlt_Mean = fAlt_Mean/((float) VAR_COUNT);

	  		 // Calculate Var
	  		 for(i=0; i<VAR_COUNT; i++){
	  			 fAlt_Var = fAlt_Var + powf((f_meas[i] - fAlt_Mean),2.0f);
	  		 }
	  		 fAlt_Var = fAlt_Var/((float) VAR_COUNT);



	  		 //
	  		 // Print altitude with three digits of decimal precision.
	  		 //

	  		 Nokia5110_SetCursor(0, 4);
	  		 Nokia5110_OutString("Var:");

	  		 Nokia5110_OutFloatp3(fAlt_Var);

	  		 count = 0;

	  	 }
*/
	   //
	   // Delay to keep printing speed reasonable. About 100msec.
	   //
	   //MAP_SysCtlDelay(MAP_SysCtlClockGet() / (10 * 3));

	   }
   }//while end
}
예제 #27
0
int main(){

	unsigned long ulClockMS=0;

	//
	// 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.
	//
	MAP_FPUEnable();
	MAP_FPULazyStackingEnable();

	//
	// Set the clocking to run directly from the crystal.
	//
	MAP_SysCtlClockSet(SYSCTL_SYSDIV_4 | SYSCTL_USE_PLL | SYSCTL_OSC_MAIN |
			SYSCTL_XTAL_16MHZ);

	MAP_IntMasterDisable();

	configureQEI();
	configurePWM();

	/*leftmotor_pid.setMaxOutput(255);
	leftmotor_pid.setMinOutput(-255);
	leftmotor_pid.setGains(12.0,5.0,0.0);
	leftmotor_pid.setSampleTime(1.0/QEILOOPFREQUENCY);*/

	leftmotor_pid.setInputLimits(-100,100);
	leftmotor_pid.setOutputLimits(-255,255);
    leftmotor_pid.setBias(0.0);
    leftmotor_pid.setMode(AUTO_MODE);


	configureUART();

	MAP_IntMasterEnable();


	// Get the current processor clock frequency.
	ulClockMS = MAP_SysCtlClockGet() / (3 * 1000);
	int char_counter=0;
	char inputbuffer[10];

	while(1){

		inputbuffer[char_counter]=UARTgetc();
		char_counter++;

		if (char_counter==3){
			inputbuffer[3]=0;
			goal_vel=atoi(inputbuffer);
			char_counter=0;
		}


		//uint32_t pos = MAP_QEIPositionGet(QEI1_BASE);
		/*uint32_t vel = MAP_QEIVelocityGet(QEI1_BASE);
		//UARTprintf("pos : %u \n",pos);QEIDirectionGet(QEI1_BASE)*/

		/*UARTprintf("vel : %d pwm %d\n",vel,pwm_value);
		MAP_SysCtlDelay(ulClockMS*50);*/

	}
	return 0;
}
예제 #28
0
//*****************************************************************************
//
// Initialize and operate the data logger.
//
//*****************************************************************************
int
main(void)
{
    tContext sDisplayContext, sBufferContext;
    uint32_t ui32HibIntStatus, ui32SysClock, ui32LastTickCount;
    bool bSkipSplash;
    uint8_t ui8ButtonState, ui8ButtonChanged;
    uint_fast8_t ui8X, ui8Y;


    //
    // 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.
    //
    MAP_FPULazyStackingEnable();

    //
    // Set the clocking to run at 50 MHz.
    //
    MAP_SysCtlClockSet(SYSCTL_SYSDIV_4 | SYSCTL_USE_PLL | SYSCTL_XTAL_16MHZ |
                       SYSCTL_OSC_MAIN);
    ui32SysClock = MAP_SysCtlClockGet();

    //
    // Initialize locals.
    //
    bSkipSplash = false;
    ui32LastTickCount = 0;

    //
    // Initialize the data acquisition module.  This initializes the ADC
    // hardware.
    //
    AcquireInit();

    //
    // Enable access to  the hibernate peripheral.  If the hibernate peripheral
    // was already running then this will have no effect.
    //
    MAP_SysCtlPeripheralEnable(SYSCTL_PERIPH_HIBERNATE);

    //
    // Check to see if the hiberate module is already active and if so then
    // read the saved configuration state.  If both are okay, then proceed
    // to check and see if we are logging data using sleep mode.
    //
    if(HibernateIsActive() && !GetSavedState(&g_sConfigState))
    {
        //
        // Read the status of the hibernate module.
        //
        ui32HibIntStatus = HibernateIntStatus(1);

        //
        // If this is a pin wake, that means the user pressed the select
        // button and we should terminate the sleep logging.  In this case
        // we will fall out of this conditional section, and go through the
        // normal startup below, but skipping the splash screen so the user
        // gets immediate response.
        //
        if(ui32HibIntStatus & HIBERNATE_INT_PIN_WAKE)
        {
            //
            // Clear the interrupt flag so it is not seen again until another
            // wake.
            //
            HibernateIntClear(HIBERNATE_INT_PIN_WAKE);
            bSkipSplash = true;
        }

        //
        // Otherwise if we are waking from hibernate and it was not a pin
        // wake, then it must be from RTC match.  Check to see if we are
        // sleep logging and if so then go through an abbreviated startup
        // in order to collect the data and go back to sleep.
        //
        else if(g_sConfigState.ui32SleepLogging &&
                (ui32HibIntStatus & HIBERNATE_INT_RTC_MATCH_0))
        {
            //
            // Start logger and pass the configuration.  The logger should
            // configure itself to take one sample.
            //
            AcquireStart(&g_sConfigState);
            g_iLoggerState = eSTATE_LOGGING;

            //
            // Enter a forever loop to run the acquisition.  This will run
            // until a new sample has been taken and stored.
            //
            while(!AcquireRun())
            {
            }

            //
            // Getting here means that a data acquisition was performed and we
            // can now go back to sleep.  Save the configuration and then
            // activate the hibernate.
            //
            SetSavedState(&g_sConfigState);

            //
            // Set wake condition on pin-wake or RTC match.  Then put the
            // processor in hibernation.
            //
            HibernateWakeSet(HIBERNATE_WAKE_PIN | HIBERNATE_WAKE_RTC);
            HibernateRequest();

            //
            // Hibernating takes a finite amount of time to occur, so wait
            // here forever until hibernate activates and the processor
            // power is removed.
            //
            for(;;)
            {
            }
        }

        //
        // Otherwise, this was not a pin wake, and we were not sleep logging,
        // so just fall out of this conditional and go through the normal
        // startup below.
        //
    }
    else
    {
        //
        // In this case, either the hibernate module was not already active, or
        // the saved configuration was not valid.  Initialize the configuration
        // to the default state and then go through the normal startup below.
        //
        GetDefaultState(&g_sConfigState);
    }

    //
    // Enable the Hibernate module to run.
    //
    HibernateEnableExpClk(SysCtlClockGet());

    //
    // The hibernate peripheral trim register must be set per silicon
    // erratum 2.1
    //
    HibernateRTCTrimSet(0x7FFF);

    //
    // Start the RTC running.  If it was already running then this will have
    // no effect.
    //
    HibernateRTCEnable();

    //
    // In case we were sleep logging and are now finished (due to user
    // pressing select button), then disable sleep logging so it doesnt
    // try to start up again.
    //
    g_sConfigState.ui32SleepLogging = 0;
    SetSavedState(&g_sConfigState);

    //
    // Initialize the display driver.
    //
    CFAL96x64x16Init();

    //
    // Initialize the buttons driver.
    //
    ButtonsInit();

    //
    // Pass the restored state to the menu system.
    //
    MenuSetState(&g_sConfigState);

    //
    // Enable the USB peripheral
    //
    MAP_SysCtlPeripheralEnable(SYSCTL_PERIPH_USB0);

    //
    // Configure the required pins for USB operation.
    //
    MAP_SysCtlPeripheralEnable(SYSCTL_PERIPH_GPIOB);
    MAP_SysCtlPeripheralEnable(SYSCTL_PERIPH_GPIOG);
    MAP_GPIOPinConfigure(GPIO_PG4_USB0EPEN);
    MAP_GPIOPinTypeUSBDigital(GPIO_PORTG_BASE, GPIO_PIN_4);
    MAP_SysCtlPeripheralEnable(SYSCTL_PERIPH_GPIOL);
    MAP_GPIOPinTypeUSBAnalog(GPIO_PORTL_BASE, GPIO_PIN_6 | GPIO_PIN_7);
    MAP_GPIOPinTypeUSBAnalog(GPIO_PORTB_BASE, GPIO_PIN_0 | GPIO_PIN_1);

    //
    // Erratum workaround for silicon revision A1.  VBUS must have pull-down.
    //
    if(CLASS_IS_BLIZZARD && REVISION_IS_A1)
    {
        HWREG(GPIO_PORTB_BASE + GPIO_O_PDR) |= GPIO_PIN_1;
    }

    //
    // Initialize the USB stack mode and pass in a mode callback.
    //
    USBStackModeSet(0, eUSBModeOTG, ModeCallback);

    //
    // Initialize the stack to be used with USB stick.
    //
    USBStickInit();

    //
    // Initialize the stack to be used as a serial device.
    //
    USBSerialInit();

    //
    // Initialize the USB controller for dual mode operation with a 2ms polling
    // rate.
    //
    USBOTGModeInit(0, 2000, g_pui8HCDPool, HCD_MEMORY_SIZE);

    //
    // Initialize the menus module.  This module will control the user
    // interface menuing system.
    //
    MenuInit(WidgetActivated);

    //
    // Configure SysTick to periodically interrupt.
    //
    g_ui32TickCount = 0;
    MAP_SysTickPeriodSet(ui32SysClock / CLOCK_RATE);
    MAP_SysTickIntEnable();
    MAP_SysTickEnable();

    //
    // Initialize the display context and another context that is used
    // as an offscreen drawing buffer for display animation effect
    //
    GrContextInit(&sDisplayContext, &g_sCFAL96x64x16);
    GrContextInit(&sBufferContext, &g_sOffscreenDisplayA);

    //
    // Show the splash screen if we are not skipping it.  The only reason to
    // skip it is if the application was in sleep-logging mode and the user
    // just waked it up with the select button.
    //
    if(!bSkipSplash)
    {
        const uint8_t *pui8SplashLogo = g_pui8Image_TI_Black;

        //
        // Draw the TI logo on the display.  Use an animation effect where the
        // logo will "slide" onto the screen.  Allow select button to break
        // out of animation.
        //
        for(ui8X = 0; ui8X < 96; ui8X++)
        {
            if(ButtonsPoll(0, 0) & SELECT_BUTTON)
            {
                break;
            }
            GrImageDraw(&sDisplayContext, pui8SplashLogo, 95 - ui8X, 0);
        }

        //
        // Leave the logo on the screen for a long duration.  Monitor the
        // buttons so that if the user presses the select button, the logo
        // display is terminated and the application starts immediately.
        //
        while(g_ui32TickCount < 400)
        {
            if(ButtonsPoll(0, 0) & SELECT_BUTTON)
            {
                break;
            }
        }

        //
        // Extended splash sequence
        //
        if(ButtonsPoll(0, 0) & UP_BUTTON)
        {
            for(ui8X = 0; ui8X < 96; ui8X += 4)
            {
                GrImageDraw(&sDisplayContext,
                            g_ppui8Image_Splash[(ui8X / 4) & 3],
                            (int32_t)ui8X - 96L, 0);
                GrImageDraw(&sDisplayContext, pui8SplashLogo, ui8X, 0);
                MAP_SysCtlDelay(ui32SysClock / 12);
            }
            MAP_SysCtlDelay(ui32SysClock / 3);
            pui8SplashLogo = g_ppui8Image_Splash[4];
            GrImageDraw(&sDisplayContext, pui8SplashLogo, 0, 0);
            MAP_SysCtlDelay(ui32SysClock / 12);
        }

        //
        // Draw the initial menu into the offscreen buffer.
        //
        SlideMenuDraw(&g_sMenuWidget, &sBufferContext, 0);

        //
        // Now, draw both the TI logo splash screen (from above) and the initial
        // menu on the screen at the same time, moving the coordinates so that
        // the logo "slides" off the display and the menu "slides" onto the
        // display.
        //
        for(ui8Y = 0; ui8Y < 64; ui8Y++)
        {
            GrImageDraw(&sDisplayContext, pui8SplashLogo, 0, -ui8Y);
            GrImageDraw(&sDisplayContext, g_pui8OffscreenBufA, 0, 63 - ui8Y);
        }
    }

    //
    // Add the menu widget to the widget tree and send an initial paint
    // request.
    //
    WidgetAdd(WIDGET_ROOT, (tWidget *)&g_sMenuWidget);
    WidgetPaint(WIDGET_ROOT);

    //
    // Set the focus handle to the menu widget.  Any button events will be
    // sent to this widget
    //
    g_ui32KeyFocusWidgetHandle = (uint32_t)&g_sMenuWidget;

    //
    // Forever loop to run the application
    //
    while(1)
    {

        //
        // Each time the timer tick occurs, process any button events.
        //
        if(g_ui32TickCount != ui32LastTickCount)
        {
            //
            // Remember last tick count
            //
            ui32LastTickCount = g_ui32TickCount;

            //
            // Read the debounced state of the buttons.
            //
            ui8ButtonState = ButtonsPoll(&ui8ButtonChanged, 0);

            //
            // Pass any button presses through to the widget message
            // processing mechanism.  The widget that has the button event
            // focus (probably the menu widget) will catch these button events.
            //
            if(BUTTON_PRESSED(SELECT_BUTTON, ui8ButtonState, ui8ButtonChanged))
            {
                SendWidgetKeyMessage(WIDGET_MSG_KEY_SELECT);
            }
            if(BUTTON_PRESSED(UP_BUTTON, ui8ButtonState, ui8ButtonChanged))
            {
                SendWidgetKeyMessage(WIDGET_MSG_KEY_UP);
            }
            if(BUTTON_PRESSED(DOWN_BUTTON, ui8ButtonState, ui8ButtonChanged))
            {
                SendWidgetKeyMessage(WIDGET_MSG_KEY_DOWN);
            }
            if(BUTTON_PRESSED(LEFT_BUTTON, ui8ButtonState, ui8ButtonChanged))
            {
                SendWidgetKeyMessage(WIDGET_MSG_KEY_LEFT);
            }
            if(BUTTON_PRESSED(RIGHT_BUTTON, ui8ButtonState, ui8ButtonChanged))
            {
                SendWidgetKeyMessage(WIDGET_MSG_KEY_RIGHT);
            }
        }

        //
        // Tell the OTG library code how much time has passed in milliseconds
        // since the last call.
        //
        USBOTGMain(GetTickms());

        //
        // Call functions as needed to keep the host or device mode running.
        //
        if(g_iCurrentUSBMode == eUSBModeDevice)
        {
            USBSerialRun();
        }
        else if(g_iCurrentUSBMode == eUSBModeHost)
        {
            USBStickRun();
        }

        //
        // If in the logging state, then call the logger run function.  This
        // keeps the data acquisition running.
        //
        if((g_iLoggerState == eSTATE_LOGGING) ||
           (g_iLoggerState == eSTATE_VIEWING))
        {
            if(AcquireRun() && g_sConfigState.ui32SleepLogging)
            {
                //
                // If sleep logging is enabled, then at this point we have
                // stored the first data item, now save the state and start
                // hibernation.  Wait for the power to be cut.
                //
                SetSavedState(&g_sConfigState);
                HibernateWakeSet(HIBERNATE_WAKE_PIN | HIBERNATE_WAKE_RTC);
                HibernateRequest();
                for(;;)
                {
                }
            }

            //
            // If viewing instead of logging then request a repaint to keep
            // the viewing window updated.
            //
            if(g_iLoggerState == eSTATE_VIEWING)
            {
                WidgetPaint(WIDGET_ROOT);
            }
        }

        //
        // If in the saving state, then save data from flash storage to
        // USB stick.
        //
        if(g_iLoggerState == eSTATE_SAVING)
        {
            //
            // Save data from flash to USB
            //
            FlashStoreSave();

            //
            // Return to idle state
            //
            g_iLoggerState = eSTATE_IDLE;
        }

        //
        // If in the erasing state, then erase the data stored in flash.
        //
        if(g_iLoggerState == eSTATE_ERASING)
        {
            //
            // Save data from flash to USB
            //
            FlashStoreErase();

            //
            // Return to idle state
            //
            g_iLoggerState = eSTATE_IDLE;
        }

        //
        // If in the flash reporting state, then show the report of the amount
        // of used and free flash memory.
        //
        if(g_iLoggerState == eSTATE_FREEFLASH)
        {
            //
            // Report free flash space
            //
            FlashStoreReport();

            //
            // Return to idle state
            //
            g_iLoggerState = eSTATE_IDLE;
        }

        //
        // If we are exiting the clock setting widget, that means that control
        // needs to be given back to the menu system.
        //
        if(g_iLoggerState == eSTATE_CLOCKEXIT)
        {
            //
            // Give the button event focus back to the menu system
            //
            g_ui32KeyFocusWidgetHandle = (uint32_t)&g_sMenuWidget;

            //
            // Send a button event to the menu widget that means the left
            // key was pressed.  This signals the menu widget to deactivate
            // the current child widget (which was the clock setting wigdet).
            // This will cause the menu widget to slide the clock set widget
            // off the screen and resume control of the display.
            //
            SendWidgetKeyMessage(WIDGET_MSG_KEY_LEFT);
            g_iLoggerState = eSTATE_IDLE;
        }

        //
        // Process any new messages that are in the widget queue.  This keeps
        // the user interface running.
        //
        WidgetMessageQueueProcess();
    }
}
//*****************************************************************************
//
// Main application entry function.
//
//*****************************************************************************
int
main(void)
{
    tBoolean bSuccess, bRetcode, bInitialized;

    //
    // Set the system clock to run at 50MHz from the PLL
    //
    MAP_SysCtlClockSet(SYSCTL_SYSDIV_4 | SYSCTL_USE_PLL | SYSCTL_OSC_MAIN |
                       SYSCTL_XTAL_16MHZ);

    //
    // NB: We don't call PinoutSet() in this testcase since the EM header
    // expansion board doesn't currently have an I2C ID EEPROM.  If we did
    // call PinoutSet() this would configure all the EPI pins for SDRAM and
    // we don't want to do this.
    //
    g_eDaughterType = DAUGHTER_NONE;

    //
    // Enable peripherals required to drive the LCD.
    //
    ROM_SysCtlPeripheralEnable(SYSCTL_PERIPH_GPIOB);
    ROM_SysCtlPeripheralEnable(SYSCTL_PERIPH_GPIOD);
    ROM_SysCtlPeripheralEnable(SYSCTL_PERIPH_GPIOE);
    ROM_SysCtlPeripheralEnable(SYSCTL_PERIPH_GPIOH);

    //
    // Configure SysTick for a 10Hz interrupt.
    //
    ROM_SysTickPeriodSet(ROM_SysCtlClockGet() / TICKS_PER_SECOND);
    ROM_SysTickEnable();
    ROM_SysTickIntEnable();

    //
    // Initialize the display driver.
    //
    Kitronix320x240x16_SSD2119Init();

    //
    // Initialize the touch screen driver.
    //
    TouchScreenInit();

    //
    // Set the touch screen event handler.
    //
    TouchScreenCallbackSet(WidgetPointerMessage);

    //
    // Add the compile-time defined widgets to the widget tree.
    //
    WidgetAdd(WIDGET_ROOT, (tWidget *)&g_sHeading);

    //
    // Paint the widget tree to make sure they all appear on the display.
    //
    WidgetPaint(WIDGET_ROOT);

    //
    // Initialize the SimpliciTI BSP.
    //
    BSP_Init();

    //
    // Set the SimpliciTI device address using the current Ethernet MAC address
    // to ensure something like uniqueness.
    //
    bRetcode = SetSimpliciTIAddress();
    if(!bRetcode)
    {
        //
        // The Ethernet MAC address can't have been set so hang here since we
        // don't have an address to use for SimpliciTI.
        //
        WidgetMessageQueueProcess();
        while(1)
        {
            //
            // MAC address is not set so hang the app.
            //
        }
    }

    //
    // First time through, we need to initialize the SimpliciTI stack.
    //
    bInitialized = false;

    //
    // The main loop starts here now that we have joined the network.
    //
    while(1)
    {
        //
        // Tell the user what to do.
        //
        UpdateStatus(true, "Please choose the operating mode.");

        //
        // Now wait until the user selects whether we should run as the sender
        // or the receiver.
        //
        while(g_ulMode == MODE_UNDEFINED)
        {
            //
            // Just spin, processing UI messages and waiting for someone to
            // press one of the mode buttons.
            //
            WidgetMessageQueueProcess();
        }

        //
        // At this point, the mode is set so remove the buttons from the
        // display and replace them with the LEDs.
        //
        WidgetRemove((tWidget *)&g_sBtnContainer);
        WidgetAdd((tWidget *)&g_sBackground,
                  (tWidget *)&g_sLEDContainer);
        WidgetPaint((tWidget *)&g_sBackground);

        //
        // Tell the user what we're doing now.
        //
        UpdateStatus(false, "Joining network...");

        if(!bInitialized)
        {
            //
            // Initialize the SimpliciTI stack  We keep trying to initialize until
            // we get a success return code.  This indicates that we have also
            // successfully joined the network.
            //
            while(SMPL_SUCCESS != SMPL_Init((uint8_t (*)(linkID_t))0))
            {
                ToggleLED(1);
                ToggleLED(2);
                SPIN_ABOUT_A_SECOND;
            }

            //
            // Now that we are initialized, remember not to call this again.
            //
            bInitialized = true;
        }

        //
        // Once we have joined, turn both LEDs on and tell the user what we want
        // them to do.
        //
        SetLED(1, true);
        SetLED(2, true);

        //
        // Now call the function that initiates communication in
        // the desired mode.  Note that these functions will not return
        // until communication is established or an error occurs.
        //
        if(g_ulMode == MODE_SENDER)
        {
            bSuccess = LinkTo();
        }
        else
        {
            bSuccess = LinkFrom();
        }

        //
        // If we were unsuccessfull, go back to the mode selection
        // display.
        //
        if(!bSuccess)
        {
            //
            // Remove the LEDs and show the buttons again.
            //
            WidgetRemove((tWidget *)&g_sLEDContainer);
            WidgetAdd((tWidget *)&g_sBackground, (tWidget *)&g_sBtnContainer);
            WidgetPaint((tWidget *)&g_sBackground);

            //
            // Tell the user what happened.
            //
            UpdateStatus(false, "Error establishing communication!");

            //
            // Remember that we don't have an operating mode chosen.
            //
            g_ulMode = MODE_UNDEFINED;
        }
    }
}