Exemplo n.º 1
0
uint32_t millis( void )
{
	double t = ((double)SysTickPeriodGet()-(double)SysTickValueGet())/(double)SysTickPeriodGet();
	t *= 10;

	return get_SystickCount() * 10 + (uint32_t)t;
}
Exemplo n.º 2
0
// This function is used for debouncing the buttons
void debounce_button(void){
	int current_time = SysTickValueGet();
	int diff = 0;
	if (current_time <= last_debounce){
		diff = last_debounce - current_time;
	}
	else {
		diff = (last_debounce + MAX_24BIT_VAL) - current_time;
	}
	if(diff > DEBOUNCE_TIME){
		raw_up = (GPIOPinRead (GPIO_PORTG_BASE, GPIO_PIN_3) == GPIO_PIN_3);
		raw_down = (GPIOPinRead (GPIO_PORTG_BASE, GPIO_PIN_4) == GPIO_PIN_4);
		raw_left = (GPIOPinRead (GPIO_PORTG_BASE, GPIO_PIN_5) == GPIO_PIN_5);
		raw_cw = (GPIOPinRead (GPIO_PORTG_BASE, GPIO_PIN_6) == GPIO_PIN_6);
		raw_select = (GPIOPinRead (GPIO_PORTG_BASE, GPIO_PIN_7) == GPIO_PIN_7);

		DebUpBut = button_choker(raw_up, raw_up_p, DebUpBut);			// 'Official' debounced value for the down button
		DebDownBut = button_choker(raw_down, raw_down_p, DebDownBut);		// Debounced value for up button
		DebLeftBut = button_choker(raw_left, raw_left_p, DebLeftBut);
		DebCwBut = button_choker(raw_cw, raw_cw_p, DebCwBut);
		DebSelectBut = button_choker(raw_select, raw_select_p, DebSelectBut);

		raw_up_p = raw_up;
 		raw_down_p = raw_down;
		raw_left_p = raw_left;
		raw_cw_p = raw_cw;
		raw_select_p = raw_select;

		last_debounce = current_time;
	}
}
Exemplo n.º 3
0
/* Delay Function */
void delay(unsigned long ulSeconds)
{
    /* Loop while there are more seconds to wait. */
	while(ulSeconds--)
    {
        /* Wait until the SysTick value is less than 1000. */
        while(SysTickValueGet() > 1000)
        {
        }

        /* Wait until the SysTick value is greater than 1000. */
        while(SysTickValueGet() < 1000)
        {
        }
    }
}
Exemplo n.º 4
0
uint32_t micros( void )
{
	double t = ((double)SysTickPeriodGet()-(double)SysTickValueGet())/(double)SysTickPeriodGet();
	t *= 10;
	t *= 1000;

	return (get_SystickCount() * 1000 * 10 + (uint32_t)t);
}
Exemplo n.º 5
0
//*****************************************************************************
// Executes commands within a adress range
//*****************************************************************************
void ExecuteFromStack(void) {
	uart_cmd_t *cmd = GetCmdPointer();
	stack_info_t *stack = GetStackPointer();
	timing_info_t *timing = GetTimerPointer();
	bool loop = stack->contExecution;
	int j = stack->stopIdx;

	// 
	// assign code entry point in stack
	// NB!: entry point is always valid
	// handled by cmdqueue commands
	//
	stack->currIdx = stack->startIdx;
		//
		// Execute code from stack, if user cancels execution
		// finish executing current function, before returning
		// cancel is handled from uart interrupt service routine
		//
		while (stack->currIdx != j && stack->execFromStack) {
			// calculate usage if running a script
			CalculateUsage(timing);
			timing->cmdStart = SysTickValueGet();
			// check if current stack i properly populated, skip overwise
			if (uartCmdStack[stack->currIdx].commandFound) {
				// copy command from stack to cmd
				GetFromStack(stack->currIdx);		
				ExecuteCommand(cmd);	
				stack->currIdx++;
			}
			else {
				// increment stack counter if command is not valid
				stack->currIdx++;
			}
			// loop forever if requested
			if (loop && stack->currIdx >= j) {
					stack->currIdx = stack->startIdx;
			}
			// Get stop value for timing
			timing->cmdStop = SysTickValueGet();
		}
	// reset stack control strucutre after
	// execution has been completed or 
	// canceled
	StackResetCtrlStructure(stack);
}
Exemplo n.º 6
0
//*****************************************************************************
//
//! Get the elapsed time since the application started.
//!
//! \param None
//!
//! This function returns the number of milliseconds since the application
//! started running. The granularity of the timing is MILLISECONDS_PER_TICK,
//! (currently set to 100).
//!
//! \return The number of milliseconds that the application has been running.
//*****************************************************************************
unsigned long
UTUtilsGetSysTime(void)
{
    unsigned long ulTickVal1;
    unsigned long ulTickVal2;
    unsigned long ulExtraTicks;
    unsigned long ulCycleTicks;
    unsigned long ulCycleMs;
    unsigned long ulSysTime;

    
    //
    // Read the system tick value and take a snapshot of the wrap count. We
    // read the tick value twice to determine if there is a chance that we
    // wrapped during the process.
    //
    do
    {
        ulTickVal1 = SysTickValueGet();
        ulCycleMs = g_ulSysTime;
        ulExtraTicks = g_ulSysTimeError;
        ulTickVal2 = SysTickValueGet();
    }
    while (ulTickVal2 > ulTickVal1);

    //
    // Determine how many ticks the systick has ticked since it last timed
    // out. This value must be less than the reload period so is safe to
    // pass to TICKS_TO_MILLISECONDS.
    //
    ulCycleTicks = SYSTICK_RELOAD_VALUE - ulTickVal2;

    //
    // The time to return is the total time for completed cycles (ulCycleMs)
    // plus the time since the last timeout (ulCycleTicks) plus the
    // outstanding accumulated error (ulExtraTicks).
    //
    ulSysTime = ulCycleMs + TICKS_TO_MILLISECONDS(ulCycleTicks) +
                TICKS_TO_MILLISECONDS(ulExtraTicks);

    //
    // Return the calculated time.
    //
    return(ulSysTime);
}
Exemplo n.º 7
0
Arquivo: main.c Projeto: gluker/sonar
void GPIODIntHandler(void){

	static unsigned long cnt = 0;
	static int state = 0;

	if (state){

		//dist = (f_cpu/(SysTickValueGet()-cnt))*58;
		dist = SysTickValueGet();
		dist = cnt - dist;
		GPIOIntTypeSet(SONAR_PORT, ECHO_PIN, GPIO_RISING_EDGE);
		state = 0;

	}else{
		cnt = SysTickValueGet();
		GPIOIntTypeSet(SONAR_PORT, ECHO_PIN, GPIO_FALLING_EDGE);
		state = 1;
	}
}
Exemplo n.º 8
0
/*
 * @brief Systick backed delay in milisecond increment (imprecise)
 * @param delay Delay time (ms)
 * @return void
 */
void systemDelay(uint32 delay) {
	unsigned long start, end;
	uint32 i;
	boolean done;

	// Systick counts down, max interval = 0xfffff (16777216)
	// CPU runs at 50 MHz
	// 1 ms = 50,000 ticks
	for (i = 0; i < delay; i++) {
		start = SysTickValueGet();
		done = FALSE;
		while (!done) {
			end = SysTickValueGet();
			if (start - end > 50000 ) {
				done = TRUE;
			}
		}
	}
}
Exemplo n.º 9
0
/*
 * @brief Systick backed delay in 10 microseconds increment (imprecise)
 * @param delay Delay time (10 us)
 * @return void
 */
void systemDelayTenMicroSecond(uint32 delay) {
	unsigned long start, end;
	uint32 i;
	boolean done;

	// Systick counts down, max interval = 0xfffff (16777216)
	// CPU runs at 50 MHz
	// 1 us = 50 ticks
	// Because 50 is too short of a delta to sample, 1 microsecond delay is very inaccurate
	for (i = 0; i < delay; i++) {
		start = SysTickValueGet();
		done = FALSE;
		while (!done) {
			end = SysTickValueGet();
			if (start - end > 500) {
				done = TRUE;
			}
		}
	}
}
Exemplo n.º 10
0
//*****************************************************************************
// This is the main routine of the command line processor, this routine should
// ideally run in the while loop in the main(), but it also can be run in 
// a task/thread on a RTOS
//
// This function checks if enter key has been detected by the interrupt
// service routine and if it's true, the processing of the buffer and
// execution of the command will take place
//
//*****************************************************************************
void CMDLineScheduler (void) {

	uart_info_t *packet = GetUartPointer();
	uart_cmd_t *cmd = GetCmdPointer();
	timing_info_t *timing = GetTimerPointer();
	stack_info_t *stack = GetStackPointer();

	if(packet->enterFlag) {
		CalculateUsage(timing);
		timing->cmdStart = SysTickValueGet();
		cmd->currentCmd = UARTEncodeCommand(packet); 
		UARTGetArguments(packet, cmd);
		if (!FindCommand(cmd)) {
			if (packet->rxCount >= MIN_CMD_LENGTH) {
				UARTprintf(CMD_NOT_FOUND);
			}
		}
		else {
			ExecuteCommand(cmd);
			SaveToStack(cmd);
			if (stack->execFromStack) {
				ExecuteFromStack();
			}			
		}	
		CMDResetCtrlStructure(cmd);	
		UARTResetCtrlStructure(packet);
		timing->cmdStop = SysTickValueGet();
		// display different input prompts based on mode
		// during scripting, show current stack position
		if (stack->saveCommands) {
			UARTprintf(STACK_PROMPT, stack->stackIdx);
		} else {
			UARTprintf(INPUT_PROMPT);
		}
	}	
}
Exemplo n.º 11
0
void send_info(int fake_speed){// in knots
	long current_time = SysTickValueGet();
	long diff = 0;
	char buf[90];
	fake_speed = (int)fake_speed;

	if (current_time <= time_last_2){
		diff = time_last_2 - current_time;
	}
	else {
		diff = (time_last_2 + MAX_24BIT_VAL) - current_time;
	}
	if (diff > 2000000) {
		sprintf(buf, "$GPRMC,194509.000,A,4042.6142,N,07400.4168,W,%d,221.11,160412,,,A*77\n", fake_speed);
		UARTSend((unsigned char *)buf, 85, 1);
		time_last_2 = current_time;
	}
}
Exemplo n.º 12
0
float calculate_distance(void){
	int current_time = SysTickValueGet();
	int delta_time = 0;
	if (current_time <= last_time){
		delta_time = last_time - current_time;
	}
	else {
		delta_time = (last_time + MAX_24BIT_VAL) - current_time;
	}

	float distance = (buffed_speed/3.6)*(delta_time/10000000);

	last_time = current_time;

	if (distance > 1){
		return distance;
	}
	return 0;
}
Exemplo n.º 13
0
//*****************************************************************************
//
// Generate an IV (initialization vector) for AES use.
//
// \param ucIV is where the generated initialization vector is stored.
// \param bNewTime determines if the SysTick timer is read or if the previous
// time value is used.
//
// This will generate a new unique IV for AES use. It may be set to
// inject the Systick (timer) time value each time or only once.
//
// \note  There are 4 easy methods to handle the Initialization Vector (IV)
// to be shared by two or more devices:
// 1. You build up one from one side and send to the other side using
//    no encryption or ECB encryption. The other side may validate
//    the IV (e.g. matches a CRC code or something). Then, the new
//    IV is sent in each encrypted message or in certain messages (such
//    as requests).
// 2. You send part of the IV to the other side and pre-agree to the
//    rest as an application unique value. Again, the follow on IVs are
//    normally sent in following messages.
// 3. Using time. After an initial message, a time base is agreed.
//    Then, each following IV represents the time since that base.
//    Either the next IV is sent in messages (and so validated by
//    being within a short time range) or the time is rounded up to
//    units such as seconds, so that the reciever can guess the IV
//    (current seconds count or previous seconds count).
// 4. A message counter is used so that each side knows what the
//    next IV will be (and replay attacks will fail). This only
//    works with reliable communications.
//
// \return None.
//
//*****************************************************************************
void
AESGenerateIV(unsigned char ucIV[16], int bNewTime)
{
    //
    // To make an IV, we need to build up a unique 16 byte value
    // we use 3 components using the method 1 or 2 above:
    // - Current value of SysTick: you need to have it running for this to
    //   work. It is best if this is called after some communications
    //   with something else, so a "random" amount of time has passed
    // - Some application unique string of values.
    // - A counter
    //

    //
    // Determine if the SysTick timer should be read.
    // Note that the SysTick value is 24 bits.
    //
    if(bNewTime)
    {
        g_uTime = SysTickValueGet();
    }

    //
    // Change the value of the counter.  Use a prime number so it does not
    // wrap evenly.
    //
    g_uWalkCounter += 617;

    //
    // Build the initialization vector from the counter, the time, and
    // the unique application ID.
    // Note that if the application ID is known by both sides in the
    // transaction, then only the first half of the initialization vector
    // needs to be transmited from one side to the other.
    //
    ((unsigned*)ucIV)[0] = g_uWalkCounter;
    ((unsigned*)ucIV)[1] = g_uTime;
    ((unsigned*)ucIV)[2] = ((unsigned*)g_ucApplicationUnique)[0];
    ((unsigned*)ucIV)[3] = ((unsigned*)g_ucApplicationUnique)[1];
}
Exemplo n.º 14
0
int step(float time_step){
	int current_time = SysTickValueGet();
	int diff = 0;
	int direction = 0; //0 = clockwise, 1 = anti clockwise

	if (time_step < 0){
		direction = 1;
		time_step = -1*time_step;
	}
	//if time less then 0, change direction

	if (current_time <= time_last){
		diff = time_last - current_time;
	}
	else {
		diff = (time_last + MAX_24BIT_VAL) - current_time;
	}
	if (diff > (time_step*FACTOR) && time_step != 0) {

		stepper_motor(direction);
		time_last = current_time;
	}
	return current_time;
}
Exemplo n.º 15
0
Arquivo: main.c Projeto: arduic/GitHub
//Converts all the gyro acc data into usable data for roll pitch yaw... eventually
void getInclination(float *RwAcc, float *RwEst, float *RwGyro, float *Gyro_ds, float *Awz){
	//Long convaluted equation that someone found and i'm borrowing. Returns a unit vector need to convet to degrees
	int w = 0;
	//int x = 0;
	float tmpf = 0.0;
	long currentTime, signRzGyro;
	float R;
	//currentTime = ((SysCtlClockGet() / (1000 * 3))*timeBetweenCalculations)-(SysTickValueGet()*(1000*3));	//So I BELIEVE this will tell me how many ms
	currentTime = (SysTickPeriodGet()-SysTickValueGet())/80000;	//I think this actually converts to ms between calculations
	interval = (currentTime - lastTime);	//
	interval = (interval < 0) ? interval + SysTickValueGet()/80000 : interval;
	lastTime = currentTime;
	//We need to fill in an inital RwEst for the math to work. We'll assume that the object is stable on the first start thus accelerometer angles are the angles
	//However, if we needed to restart mid flight this would fix itself fairly quickly in theory
	if (firstSample) { // the NaN check is used to wait for good data from the Stellaris
		for(w=0;w<=2;w++) {
			RwEst[w] = RwAcc[w];    //initialize with accelerometer readings
		}
	}else{
		/*float bob = 0.7;			//This was here to debug float compares. The below RwEst statment is bugged!
		if(bob < 0.1){
			UARTSend(0xD4);
		}*/
		//Rz is too small and because it is used as reference for computing Axz, Ayz it's error fluctuations will amplify leading to bad results
		//in this case skip the gyro data and just use previous estimate
		//My comment on this, The RzEST is very small which means if me divide by a small number we will get close to infinity which is bad
		if((fabs(RwEst[2])) < ((float)0.1)) {
			for(w=0;w<=2;w++) {
				RwGyro[w] = RwEst[w];
			}
		}else{
			//get angles between projection of R on ZX/ZY plane and Z axis, based on last RwEst
			//This calculates the Axz Ayz part. It seems right
			for(w=0;w<=1;w++){
				tmpf = Gyro_ds[w];                        //get current gyro rate in deg/s
				tmpf *= interval / ((float)1000.0);                     //get angle change in deg
				Awz[w] = atan2f(RwEst[w],RwEst[2]) * 180 / PI;   //get angle and convert to degrees
				Awz[w] += tmpf;             //get updated angle according to gyro movement		//These are in degrees
			}
			//Awz[0] = 30;
			//Awz[1] = 45;
			//estimate sign of RzGyro by looking in what qudrant the angle Axz is,
			//RzGyro is pozitive if  Axz in range -90 ..90 => cos(Awz) >= 0
			signRzGyro = ( cosf(Awz[0] * PI / 180) >=0 ) ? 1 : -1;
			//reverse calculation of RwGyro from Awz angles, for formulas deductions see  http://starlino.com/imu_guide.html
				//Effectively RwGyro is unitless. Completly unitless
			RwGyro[0] = sinf(Awz[0] * PI / 180);
			RwGyro[0] /= floatingSquare( 1 + (cosf(Awz[0] * PI / 180)*cosf(Awz[0] * PI / 180)) * (tanf(Awz[1] * PI / 180)*tanf(Awz[1] * PI / 180)));
			RwGyro[1] = sinf(Awz[1] * PI / 180);
			RwGyro[1] /= floatingSquare( 1 + (cosf(Awz[1] * PI / 180)*cosf(Awz[1] * PI / 180)) * (tanf(Awz[0] * PI / 180)*tanf(Awz[0] * PI / 180)));

			RwGyro[2] = signRzGyro * floatingSquare((float)1.0 - (RwGyro[0]*RwGyro[0]) - (RwGyro[1]*RwGyro[1]));	//THIS THIS IS THE DEVIL!		//Note this does not ever try to eval sqrt(<0)
			/*RwGyro[0] = 0.2;
			RwGyro[1] = 0.3;
			RwGyro[2] = 0.4;*/
		}
		//combine Accelerometer and gyro readings
		//THIS FOR LOOP CAUSES THE SYSTEM :P
		//w = 0;	failed attempt
		for(w=0;w<=2;w++){
			//I believe the units are in g's
			//RwEst[w] = (RwAcc[w] + (float)10.0 * RwGyro[w]) / (1 + 10);	failed attempt
			//RwEst[w] = (RwAcc[w] + wGyro * RwGyro[w]) / (1 + wGyro);		failed attempt
			/*RwEst[w] = (RwAcc[w] + wGyro * RwGyro[w]);
			RwEst[w] /= (1+wGyro);		failed attempt */
			//RwEst[w] = nextafter(fmaf(wGyro,RwGyro[w],RwAcc[w]),100000000);		//So when I add RwAcc[2] + RwGyro[2] it crashes invebitably. WTF!!!!!
			RwEst[w] = floatingAdd(RwGyro[w],wGyro*RwAcc[w])/(1+wGyro);			//DO NOT REMOVE FLOATING ADD it for some reason allows this addition to happen which otherwise fails misserably.
		}
		/*for(x=0;x<=2;x++){		failed attempt
			RwEst[x] = (RwAcc[x] + wGyro * RwGyro[x]) / (1 + wGyro);
		}*/

		R = floatingSquare(RwEst[0]*RwEst[0]+RwEst[1]*RwEst[1]+RwEst[2]*RwEst[2]);

		RwEst[0]/=R;
		RwEst[1]/=R;	//This is unitless.
		RwEst[2]/=R;
	}

	firstSample = 0;
}
Exemplo n.º 16
0
//*****************************************************************************
//
// This function is called to handle the GPIO edge interrupt from the
// quadrature encoder.
//
//*****************************************************************************
void
QEI1IntHandler(void)
{
    unsigned long ulNow;

    //
    // Save the time.
    //
    ulNow = SysTickValueGet();

    //
    // Clear the encoder interrupt.
    //
    GPIOPinIntClear(QEI_ROLL_PHA_PORT, QEI_ROLL_PHA_PIN);

	ulstatus1 = QEIIntStatus(QEI1_BASE,false); 
	if (  (ulstatus1 & QEI_INTDIR) == QEI_INTDIR) 
	{ 
	  // 
	  // clear	Interrupt Bit	 
	   QEIIntClear(QEI1_BASE, QEI_INTDIR); 
	  // 
	  //code for Direction change 
	  //.............. 
	} 
	if (  (ulstatus1 & QEI_INTINDEX) == QEI_INTINDEX) 
	{ 
	  // 
	  // clear	Interrupt Bit	 
	   QEIIntClear(QEI1_BASE, QEI_INTINDEX); 
	  // 
	  //code for Index change 
	  //.............. 
	}		
	if (  (ulstatus1 & QEI_INTERROR) == QEI_INTERROR) 
	{ 
	  //	 
	  // clear	Interrupt Bit	 
		QEIIntClear(QEI1_BASE, QEI_INTERROR); 
	  // 
	  //code for Phase ERROR 
	  //.............. 
	} 

    //
    // Determine the number of system clocks between the previous edge and this
    // edge.
    //
    if(g_ulEncoder1Previous > ulNow)
    {
        g_ulEncoder1Clocks = g_ulEncoder1Previous - ulNow;
    }
    else
    {
        g_ulEncoder1Clocks = (SYSCLK_50MHZ - ulNow) + g_ulEncoder1Previous;		
		
    }

    //
    // Save the time of the current edge as the time of the previous edge.
    //
    g_ulEncoder1Previous = ulNow;

    //
    // Indicate that an edge has been seen.
    //
    HWREGBITH(&g_usEncoder1Flags, ENCODER_FLAG_EDGE) = 1;

    //
    // If the previous edge time was valid, then indicate that the time between
    // edges is also now valid.
    //
    if(HWREGBITH(&g_usEncoder1Flags, ENCODER_FLAG_PREVIOUS) == 1)
    {
        HWREGBITH(&g_usEncoder1Flags, ENCODER_FLAG_VALID) = 1;
    }

    //
    // Indicate that the previous edge time is valid.
    //
    HWREGBITH(&g_usEncoder1Flags, ENCODER_FLAG_PREVIOUS) = 1;
}
Exemplo n.º 17
0
//*****************************************************************************
//
//! Initializes the user interface.
//!
//! This function initializes the user interface modules (on-board and serial),
//! preparing them to operate and control the motor drive.
//!
//! \return None.
//
//*****************************************************************************
void
UIInit(void)
{
    unsigned long ulSysTickVal;

    //
    // Enable the GPIO peripherals needed for the button and LEDs
    //
    SysCtlPeripheralEnable(USER_BUTTON_GPIO_PERIPH);
    SysCtlPeripheralEnable(LED_GPIO_PERIPH);

    //
    // Set up button GPIO as input, and LEDs as outputs, and turn them off
    //
    GPIODirModeSet(USER_BUTTON_PORT, USER_BUTTON_PIN, GPIO_DIR_MODE_IN);
    GPIODirModeSet(STATUS_LED_PORT, STATUS_LED_PIN, GPIO_DIR_MODE_OUT);
    GPIODirModeSet(MODE_LED_PORT, MODE_LED_PIN, GPIO_DIR_MODE_OUT);
    GPIOPinWrite(STATUS_LED_PORT, STATUS_LED_PIN, 0);
    GPIOPinWrite(MODE_LED_PORT, MODE_LED_PIN, 0);

    //
    // Set up the LED blinking function
    //
    BlinkInit(STATUS_LED, STATUS_LED_PORT, STATUS_LED_PIN);
    BlinkInit(MODE_LED, MODE_LED_PORT, MODE_LED_PIN);
    BlinkStart(MODE_LED, UI_INT_RATE / 2, UI_INT_RATE / 2, eUIMode + 1);

    //
    // Enable the ADC peripheral, needed for potentiometer
    //
    SysCtlPeripheralEnable(SYSCTL_PERIPH_ADC0);
    SysCtlPeripheralSleepEnable(SYSCTL_PERIPH_ADC0);

    //
    // Set the ADC to run at the maximum rate of 500 ksamples.
    //
    HWREG(SYSCTL_RCGC0) |= 0x00000200;
    HWREG(SYSCTL_SCGC0) |= 0x00000200;

    //
    // Program sequencer for collecting ADC sample for potentiometer
    // position, bus voltage, and temperature sensor.
    //
    ADCSequenceConfigure(ADC0_BASE, UI_ADC_SEQUENCER, ADC_TRIGGER_PROCESSOR,
                         UI_ADC_PRIORITY);
    ADCSequenceStepConfigure(ADC0_BASE, UI_ADC_SEQUENCER, 0, POT_ADC_CHAN);
    ADCSequenceStepConfigure(ADC0_BASE, UI_ADC_SEQUENCER, 1, BUSV_ADC_CHAN);
    ADCSequenceStepConfigure(ADC0_BASE, UI_ADC_SEQUENCER, 2,
                             ADC_CTL_TS | ADC_CTL_END);
    ADCSequenceEnable(ADC0_BASE, UI_ADC_SEQUENCER);
    ADCProcessorTrigger(ADC0_BASE, UI_ADC_SEQUENCER);   // take initial sample

    //
    // initialize the lower level,
    // positioner, which handles computing all the motion control
    //
    StepperInit();

    //
    // Get a pointer to the stepper status.
    //
    pStepperStatus = StepperGetMotorStatus();

    //
    // Force an update of all the parameters (sets defaults).
    //
    UISetPWMFreq();
    UISetChopperBlanking();
    UISetMotorParms();
    UISetControlMode();
    UISetDecayMode();
    UISetStepMode();
    UISetFixedOnTime();

    //
    // Initialize the flash parameter block driver.
    //
    FlashPBInit(FLASH_PB_START, FLASH_PB_END, FLASH_PB_SIZE);

    //
    // Initialize the serial user interface.
    //
    UISerialInit();
    IntPrioritySet(INT_UART0, UI_SER_INT_PRI);

    //
    // Make sure that the UART doesnt get put to sleep
    //
    SysCtlPeripheralSleepEnable(SYSCTL_PERIPH_UART0);

    //
    // Initialize the on-board user interface.
    //
    UIOnboardInit(GPIOPinRead(USER_BUTTON_PORT, USER_BUTTON_PIN), 0);

    //
    // Initialize the processor usage routine.
    //
    CPUUsageInit(SysCtlClockGet(), UI_INT_RATE, 2);

    //
    // Configure SysTick to provide a periodic user interface interrupt.
    //
    SysTickPeriodSet(SysCtlClockGet() / UI_INT_RATE);
    SysTickIntEnable();
    SysTickEnable();
    IntPrioritySet(FAULT_SYSTICK, SYSTICK_INT_PRI);

    //
    // A delay is needed to let the current sense line discharge after
    // reset, before the current fault parameter is configured.  The
    // two loops below let the systick roll around once before proceeding.
    //
    ulSysTickVal = SysTickValueGet();

    //
    // Wait for systick to reach 0 and roll over to top.
    //
    while(SysTickValueGet() <= ulSysTickVal)
    {
    }

    //
    // Wait for systick to get back to the starting value.
    //
    while(SysTickValueGet() > ulSysTickVal)
    {
    }

    //
    // Now set the current fault parameter (after the delay above).
    //
    UISetFaultParms();

    //
    // Load stored parameters from flash, if any are available.
    //
    UIParamLoad();
}
Exemplo n.º 18
0
STATIC mp_obj_t time_ticks_cpu(void) {
    // We want to "cast" the 32 bit unsigned into a 30-bit small-int
    return MP_OBJ_NEW_SMALL_INT((SysTickPeriodGet() - SysTickValueGet()) & MP_SMALL_INT_POSITIVE_MASK);
}
Exemplo n.º 19
0
// ******** OS_MsTime ************
// reads the current time in msec (from Lab 1)
// Inputs:  none
// Outputs: time in ms units
// You are free to select the time resolution for this function
unsigned long OS_MsTime(void){
return SysTickValueGet();  //returns value in SystickCounter
}
int BsdTcpServer(unsigned short usPort)
{
  
    UART_PRINT("BsdTcpServer\r\n"); 
    while( wlanConnectStatus == 0);
  
  
  
    SlSockAddrIn_t  sAddr;
    SlSockAddrIn_t  sLocalAddr;
    int             iCounter;
    int             iAddrSize;
    int             iSockID;
    int             iStatus;
    int             iNewSockID;
    unsigned long            lLoopCount = 0;
    long            lBytesSent = 0;
    long            lNonBlocking = 0;                   //0 :non-blocking,
    int             iTestBufLen;

    // filling the buffer
    for (iCounter=0 ; iCounter<BUF_SIZE ; iCounter++)
    {
        g_cBsdBuf[iCounter] = (char)(iCounter % 10) + '0';
    }

    iTestBufLen  = BUF_SIZE;

    //filling the TCP server socket address
    sLocalAddr.sin_family = SL_AF_INET;
   sLocalAddr.sin_port = sl_Htons((unsigned short)usPort);
   sLocalAddr.sin_addr.s_addr = 0;
   
//	sLocalAddr.sin_port = usPort;
//	sLocalAddr.sin_addr.s_addr = SL_IPV4_VAL(192,168,1,101);
    

   

   
    // creating a TCP socket
    iSockID = sl_Socket(SL_AF_INET,SL_SOCK_STREAM, 0);
    if( iSockID < 0 )
    {
      
      // UART_PRINT("error at creating a TCP socket ! \n\r"); 
       
        // error
        return -1;
    }
    
 //   UART_PRINT("iSockID :"); 
 //   Z_NumDispaly(iSockID, 2);
        

    iAddrSize = sizeof(SlSockAddrIn_t);

    // binding the TCP socket to the TCP server address
    iStatus = sl_Bind(iSockID, (SlSockAddr_t *)&sLocalAddr, iAddrSize);
    if( iStatus < 0 )
    {
    
 //   UART_PRINT("error at binding the TCP socket to the TCP server address ! \n\r"); 
     
      // error
    	return -1;
    }
    
    
//	UART_PRINT("binding the TCP socket to the TCP server address ok! \n\r"); 
        
        

    // putting the socket for listening to the incoming TCP connection
    iStatus = sl_Listen(iSockID, 0);
    if( iStatus < 0 )
    {
      
 //     UART_PRINT("error at putting the socket for listening to the incoming TCP connection ! \n\r"); 
    	return -1;
    }

//	UART_PRINT("listen end! \n\r"); 

    // setting socket option to make the socket as non blocking
    iStatus = sl_SetSockOpt(iSockID, SL_SOL_SOCKET, SL_SO_NONBLOCKING, &lNonBlocking, sizeof(lNonBlocking));
    iNewSockID = SL_EAGAIN;

    char uttMessage[50]={0};
       snprintf(uttMessage,sizeof(uttMessage),"IntTimes:%d, TickValue:%d,\n\r",IntTimes, SysTickValueGet());
       UART_PRINT(uttMessage); 
 
 serverCreatOK = 1;
 
UART_PRINT(" waiting for an incoming TCP connection! \n\r"); 



    // waiting for an incoming TCP connection
    while( iNewSockID < 0 )
    {
    	// accepts a connection form a TCP client, if there is any
    	// otherwise returns SL_EAGAIN
       iNewSockID = sl_Accept(iSockID, ( struct SlSockAddr_t *)&sAddr, (SlSocklen_t*)&iAddrSize);
       if( iNewSockID == SL_EAGAIN )
       {
         UtilsDelay(10000);
         
             char uttMessage[50]={0};
       snprintf(uttMessage,sizeof(uttMessage),"IntTimes:%d, TickValue:%d,\n\r",IntTimes, SysTickValueGet());
       UART_PRINT(uttMessage); 
       
 //      vTaskResume((xTaskHandle)&clientTaskHandle);
       vTaskSuspend((xTaskHandle)&ServerTaskHandle);
       
//	  UART_PRINT(" iNewSockID == SL_EAGAIN! \n\r"); 
       }
       /*
       else if( iNewSockID < 0 )
       {
    	  // error
    	   UART_PRINT(" iNewSockID < 0! \n\r"); 
    	   return -1;
       }*/
    }
    
                 char utttMessage[50]={0};
       snprintf(utttMessage,sizeof(utttMessage),"IntTimes:%d, TickValue:%d,\n\r",IntTimes, SysTickValueGet());
       UART_PRINT(utttMessage); 


	    UART_PRINT("connect succeed the new iSockID :"); 
    		Z_NumDispaly(iSockID, 5);

	unsigned long the_client_ip = sl_BIGtoLITTLE_l( (unsigned long)sAddr.sin_addr.s_addr );


	UART_PRINT("the client ip is :"); 
	Z_IPDispaly(&the_client_ip);


	unsigned short the_client_port = sl_BIGtoLITTLE_S( (unsigned short)sAddr.sin_port );
        


	UART_PRINT("the client port is :"); 
	Z_NumDispaly( (unsigned long)the_client_port,5);
	


/*
UART_PRINT(" waits for 1000 packets from the connected TCP client! \n\r"); 

    // waits for 1000 packets from the connected TCP client
    while (lLoopCount < 1000)
    {
        iStatus = sl_Recv(iNewSockID, g_cBsdBuf, iTestBufLen, 0);
        if( iStatus <= 0 )
		{
			// error
        	return -1;
		}

		lLoopCount++;
		lBytesSent += iStatus;
    }
  */

/*

    // sending 3 packets to the TCP server
    while (lLoopCount < 3)
    {
    	// sending packet
 //       iStatus = sl_Send(iNewSockID, g_cBsdBuf, iTestBufLen, 0 );

	char *send_buffer = "hellow i am cc3200 , welcome to wifi world !\n\r";

	 iStatus = sl_Send(iNewSockID, send_buffer, strlen(send_buffer), 0 );
        if( iStatus <= 0 )
        {
        	UART_PRINT("error at sending packet\n\r"); 
		 Z_NumDispaly(lLoopCount,5);
            // error
        	return -1;
        }

        lLoopCount++;
        lBytesSent += iStatus;




    }

/*
//#define SL_POLICY_CONNECTION    (0x10)
//#define SL_POLICY_SCAN          (0x20)
//#define SL_POLICY_PM            (0x30)    
    
    
//    while(1){
//   Z_DelayS(1);
//    char OutMessage[50]={0};
//    snprintf(OutMessage,sizeof(OutMessage),"IntTimes:%d, TickValue:%d,\n\r",IntTimes, SysTickValueGet());
//    sl_Send(iNewSockID, OutMessage, strlen(OutMessage), 0 );        
//    }   
    
    
 
    
    char *setbuffer= "\n set policy \n\r";
sl_Send(iNewSockID, setbuffer, strlen(setbuffer), 0 );

char recBuffer[2] = {0};
char numBuffer[15]={0};

while(1){
  
char sl_policy = '0';
char set_prar = '0';
char OutMessage[50] = {0};
char num = 0;
                
                
                
                while(1){
                  
                  char temp_num = sl_Recv(iNewSockID, recBuffer, sizeof(recBuffer), 0);                 
                 
                  if(temp_num>0)
                    num += temp_num;
                  
                  if(num == 1)
                      sl_policy = recBuffer[0]-'0';
                      
                  
                  if(num == 3)
                    set_prar = recBuffer[0]-'0';
                  
                  if(num>3 && (recBuffer[0]=='\r' || recBuffer[0]=='\n'))
                    break;
                    
                  
                  if(num>3){
                    num = 0;
                  
                  char *send_buffer= "\nplease input again!!!\n\r";
                    sl_Send(iNewSockID, send_buffer, strlen(send_buffer), 0 );}
                  
                  
                  snprintf(numBuffer,sizeof(numBuffer),"num:%d\n\r",num);
                  UART_PRINT(numBuffer);
                   
                }
                
                char *send_buffer= "\nfinished input!\n\r";
                sl_Send(iNewSockID, send_buffer, strlen(send_buffer), 0 );
                
                



                switch(sl_policy*16){
                    case SL_POLICY_CONNECTION://1 x 
                          snprintf(OutMessage,sizeof(OutMessage),"CONN= first:%d, second:%d,\n\r",sl_policy, set_prar);
                          UART_PRINT(OutMessage);
                          break;
                          
                    case SL_POLICY_SCAN://2 x 
                          snprintf(OutMessage,sizeof(OutMessage),"SCAN= first:%d, second:%d,\n\r",sl_policy, set_prar);
                          if(set_prar == 0)
                                  sl_WlanPolicySet(SL_POLICY_SCAN,0,0,0);
                          else
                                  sl_WlanPolicySet(SL_POLICY_SCAN,1,(unsigned char *)&set_prar,sizeof(set_prar));
                          
                          UART_PRINT(OutMessage);
                          break;
                          
                case SL_POLICY_PM://3 x : x=0(normal),x=1(latency),x=2(low),x=3(always on),
                          snprintf(OutMessage,sizeof(OutMessage),"PM= first:%d, second:%d,\n\r",sl_policy, set_prar);
                          UART_PRINT(OutMessage);
                          sl_WlanPolicySet(SL_POLICY_PM , set_prar, NULL,0);
                          break;
                                                   
                case 0x00://0 x :finished set 
                          break;
                          
                case 0x40:{//4xx: hibernate
                                  char *send_buffer= "\nsl_hibernate!\n\r";
                sl_Send(iNewSockID, send_buffer, strlen(send_buffer), 0 );
                   sl_Stop(0);
                   break;}
                   
                case 0x50:{//4xx: hibernate
                                  char *send_buffer= "\ndevice_hibernate!\n\r";
                sl_Send(iNewSockID, send_buffer, strlen(send_buffer), 0 );
                   PRCMHibernateEnter();
                   break;}
                          
                    default:
                          snprintf(OutMessage,sizeof(OutMessage),"Error= first:%d, second:%d,\n\r",sl_policy, set_prar);
                          UART_PRINT(OutMessage);
                          break;
                            
                }
                
                
                if(sl_policy == 0)
                  break;

}





  
  
Sl_WlanNetworkEntry_t netEntries[20];
 char message[80];




/****no scan*********/
 /* 
#define SL_SCAN_DISABLE  0
sl_WlanPolicySet(SL_POLICY_SCAN,SL_SCAN_DISABLE,0,0);

while(1);
return 0;







    
 UINT8  intervalInSeconds=1;  
    

 while(1){
        Z_DelayS(1); 
        sl_WlanPolicySet(SL_POLICY_SCAN,SL_SCAN_POLICY_EN(1), (unsigned char *)&intervalInSeconds,sizeof(intervalInSeconds));
 }
    
    
     
*/ 
 
 /*
char *noticebuffer= "\n set send message time \n\r";
sl_Send(iNewSockID, noticebuffer, strlen(noticebuffer), 0 );

 
while(1){
                  
                  char temp_num = sl_Recv(iNewSockID, recBuffer, sizeof(recBuffer), 0);                 
                 
                  if(temp_num>0)
                    break;                  
                   
}
                
    

 while(1){  
    
   

    //Get Scan Result
   UINT8 Index = sl_WlanGetNetworkList(0,20,&netEntries[0]);

  
    for(UINT8 i=0; i< Index; i++)
    {
         snprintf(message, 60, "%d) SSID %s  RSSI %d \n\r",i,netEntries[i].ssid,netEntries[i].rssi);
	//UART_PRINT(message); 
        sl_Send(iNewSockID, message, strlen(message), 0 );
        
        
        
        
    }  
    
  Z_DelayS(recBuffer[0]-'0');  

  }    
    









    // close the connected socket after receiving from connected TCP client
    sl_Close(iNewSockID);

    // close the listening socket
    sl_Close(iSockID);

    return 0;
    
    */
}