Beispiel #1
0
template <class T> bool
karbtest (Connector<T>* rc) {

	GradientParams gp;

	std::string in_file;// = std::string (base + "/" + std::string(rc->GetElement("/config/data-in")->Attribute("fname")));
	std::string out_file;// = std::string (base + "/" + rc->GetElement("/config/data-out")->Attribute("fname"));

	bool   simann  = false;
	size_t hpoints = 1;
	rc->Attribute ("simann",   &simann);
	rc->Attribute ("hpoints",  &hpoints);

	if (simann) {

		double coolrate, startt, finalt;
		size_t coolit;
		bool   verbose, exchange;
		
		rc->Attribute ("coolrate", &coolrate);
		rc->Attribute ("startt",   &startt);
		rc->Attribute ("finalt",   &finalt);
		rc->Attribute ("coolit",   &coolit);
		rc->Attribute ("verbose",  &verbose);
		rc->Attribute ("exchange", &exchange);
		
		SimulatedAnnealing sa (gp.k, coolit, startt, finalt, coolrate, verbose, exchange);
		sa.Cool();
		gp.k = sa.GetSolution();
		
	}
	
	rc->Attribute ("maxgrad", &(gp.mgr));
	rc->Attribute ("maxslew", &(gp.msr));
	rc->Attribute ("dt",      &(gp.dt));
	
	rc->Attribute ("gunits",  &(gp.gunits));
	rc->Attribute ("lunits",  &(gp.lunits));
	
	Matrix<double> x  = linspace<double> (0.0,1.0,size(gp.k,0));
	Matrix<double> xi = linspace<double> (0.0,1.0,size(gp.k,0)*hpoints);

	gp.k = interp1 (x, gp.k, xi, INTERP::AKIMA);

	printf ("\nComputing trajectory for ... \n");
	printf ("    [maxgrad: %.2f, maxslew: %.2f, dt: %.2e]\n\n", gp.mgr, gp.msr, gp.dt);
	
    SimpleTimer st ("VD spiral design");
	Solution s = ComputeGradient (gp);
    st.Stop();
	
    IOContext f = fopen (out_file.c_str(), WRITE);
    s.dump (f);
    fclose (f);
	

	return true;

}
Beispiel #2
0
int main( int , char** ) {
	SimpleTimer timer;

	timer.tic();
	DoubleVector a(5);
	a[0] = 1;
	a[1] = 3;
	a[2] = 5;
	a[3] = 7;
	a[4] = 9;
	DoubleVector b = a;
	a.steady(1);
	DoubleVector c = a+b+a*a+a;
	a += b+a*a+a;
	qDebug() << "------------" << timer.tic();
	qDebug() << a[0] << a[1] << a[2] << a[3] << a[4] ;
	qDebug() << c[0] << c[1] << c[2] << c[3] << c[4] ;

	qDebug() << "------------";
	int row = 2;
	int col = 3;
	DoubleMatrix m1( row, col );
	for( int i=0; i<row; i++ ) {
		for( int j=0; j<col; j++ ) {
			m1[i][j] = i+j;
		}
	}
	for( int i=0; i<row; i++ ) {
		for( int j=0; j<col; j++ ) {
			cout << m1[i][j] << " ";
		}
		cout << endl;
	}
	timer.tic();
	DoubleMatrix m2 = m1 + m1;
	m1.steady( row-1, col-1 );
	m1 %= m2;
	qDebug() << "------------" << timer.tic();

	for( int i=0; i<row; i++ ) {
		for( int j=0; j<col; j++ ) {
			cout << m2[i][j] << " ";
		}
		cout << endl;
	}
	qDebug() << "------------";
	for( int i=0; i<row; i++ ) {
		for( int j=0; j<col; j++ ) {
			cout << m1[i][j] << " ";
		}
		cout << endl;
	}

	return 0;
}
Beispiel #3
0
UndoCommandPtr Selection::AddItems(const OS_ObjectDumbPtr &items, const SelectionChangingSignature::Delegate& emitterChanging, const SelectionChangedSignature::Delegate& emitterChanged)
{
	if ( items.Empty() )
	{
		return NULL;
	}

	EDITOR_SCENE_SCOPE_TIMER( ("") );

	SimpleTimer timer;

	std::vector<Reflect::Object*> added;
	OS_ObjectDumbPtr temp = m_Items;
	OS_ObjectDumbPtr::Iterator itr = items.Begin();
	OS_ObjectDumbPtr::Iterator end = items.End();
	for ( ; itr != end; ++itr )
	{
		if ( temp.Append(*itr) )
		{
			added.push_back(*itr);
		}
	}

	UndoCommandPtr command;

	if ( !temp.Empty() )
	{
		SelectionChangingArgs args ( temp );
		m_SelectionChanging.RaiseWithEmitter( args, emitterChanging );
		if ( !args.m_Veto )
		{
			command = new SelectionChangeCommand( this );

			std::vector<Reflect::Object*>::iterator itr = added.begin();
			std::vector<Reflect::Object*>::iterator end = added.end();
			for ( ; itr != end; ++itr )
			{
				SceneNode *pSceneNode = Reflect::SafeCast<SceneNode>(*itr);
				if (pSceneNode)
				{
					pSceneNode->SetSelected(true);
				}
			}

			m_Items = temp;

			m_SelectionChanged.RaiseWithEmitter(m_Items, emitterChanged);
		}
	}

	Log::Profile( TXT( "Selection AddItems took %fms\n" ), timer.Elapsed());

	return command;
}
void FNiagaraSimulation::Tick(float DeltaSeconds)
{
	SCOPE_CYCLE_COUNTER(STAT_NiagaraTick);
	SimpleTimer TickTime;

	UNiagaraEmitterProperties* PinnedProps = Props.Get();
	if (!PinnedProps || !bIsEnabled || TickState == NTS_Suspended || TickState == NTS_Dead)
	{
		return;
	}

	Age += DeltaSeconds;

	check(Data.GetNumVariables() > 0);
	check(PinnedProps->SpawnScriptProps.Script);
	check(PinnedProps->UpdateScriptProps.Script);
	
	TickEvents(DeltaSeconds);

	// Figure out how many we will spawn.
	int32 OrigNumParticles = Data.GetNumInstances();
	int32 NumToSpawn = CalcNumToSpawn(DeltaSeconds);
	int32 MaxNewParticles = OrigNumParticles + NumToSpawn;
	Data.Allocate(MaxNewParticles);

	ExternalConstants.SetOrAdd(BUILTIN_CONST_EMITTERAGE, FVector4(Age, Age, Age, Age));
	ExternalConstants.SetOrAdd(BUILTIN_CONST_DELTATIME, FVector4(DeltaSeconds, DeltaSeconds, DeltaSeconds, DeltaSeconds));

	// Simulate particles forward by DeltaSeconds.
	if (TickState==NTS_Running || TickState==NTS_Dieing)
	{
		SCOPE_CYCLE_COUNTER(STAT_NiagaraSimulate);
		RunVMScript(PinnedProps->UpdateScriptProps, EUnusedAttributeBehaviour::PassThrough);
	}

	//Init new particles with the spawn script.
	if (TickState==NTS_Running)
	{
		SCOPE_CYCLE_COUNTER(STAT_NiagaraSpawn);
		Data.SetNumInstances(MaxNewParticles);
		//For now, zero any unused attributes here. But as this is really uninitialized data we should maybe make this a more serious error.
		RunVMScript(PinnedProps->SpawnScriptProps, EUnusedAttributeBehaviour::Zero, OrigNumParticles, NumToSpawn);

		if (bGenerateSpawnEvents)
		{
			SpawnEventGenerator.OnSpawned(OrigNumParticles, NumToSpawn);
		}
	}


	CPUTimeMS = TickTime.GetElapsedMilliseconds();

	INC_DWORD_STAT_BY(STAT_NiagaraNumParticles, Data.GetNumInstances());
}
Beispiel #5
0
int main()
{
    SimpleTimer timer;

    cout << "Begin timer!" << endl;
    timer.Start();

    sleep( 2 );

    cout << "Elapsed time: " << timer.GetElapsed() << endl;

    return 0;
}
Beispiel #6
0
void Selection::Refresh()
{
	EDITOR_SCENE_SCOPE_TIMER( ("") );

	SimpleTimer timer;

	m_SelectionChanging.Raise(m_Items);

	// do nothing

	m_SelectionChanged.Raise(m_Items);

	Log::Profile( TXT( "Selection Refresh took %fms\n" ), timer.Elapsed());
}
/** Update render data buffer from attributes */
FNiagaraDynamicDataBase *NiagaraEffectRendererSprites::GenerateVertexData(const FNiagaraEmitterParticleData &Data)
{
	SCOPE_CYCLE_COUNTER(STAT_NiagaraGenSpriteVertexData);

	SimpleTimer VertexDataTimer;

	FNiagaraDynamicDataSprites *DynamicData = new FNiagaraDynamicDataSprites;
	TArray<FParticleSpriteVertex>& RenderData = DynamicData->VertexData;

	RenderData.Reset(Data.GetNumParticles());
	//CachedBounds.Init();

	const FVector4 *PosPtr = Data.GetAttributeData("Position");
	const FVector4 *ColPtr = Data.GetAttributeData("Color");
	const FVector4 *AgePtr = Data.GetAttributeData("Age");
	const FVector4 *RotPtr = Data.GetAttributeData("Rotation");
	uint32 NumSubImages = 1;
	if (Properties)
	{
		NumSubImages = Properties->SubImageInfo.X*Properties->SubImageInfo.Y;
	}
	float ParticleId = 0.0f, IdInc = 1.0f / Data.GetNumParticles();
	RenderData.AddUninitialized(Data.GetNumParticles());
	for (uint32 ParticleIndex = 0; ParticleIndex < Data.GetNumParticles(); ParticleIndex++)
	{
		FParticleSpriteVertex& NewVertex = RenderData[ParticleIndex];
		NewVertex.Position = PosPtr[ParticleIndex];
		NewVertex.OldPosition = NewVertex.Position;
		NewVertex.Color = FLinearColor(ColPtr[ParticleIndex]);
		NewVertex.ParticleId = ParticleId;
		ParticleId += IdInc;
		NewVertex.RelativeTime = AgePtr[ParticleIndex].X;
		NewVertex.Size = FVector2D(RotPtr[ParticleIndex].Y, RotPtr[ParticleIndex].Z);
		NewVertex.Rotation = RotPtr[ParticleIndex].X;
		NewVertex.SubImageIndex = RotPtr[ParticleIndex].W * NumSubImages;

		FPlatformMisc::Prefetch(PosPtr + ParticleIndex+1);
		FPlatformMisc::Prefetch(RotPtr + ParticleIndex + 1);
		FPlatformMisc::Prefetch(ColPtr + ParticleIndex + 1);		
		FPlatformMisc::Prefetch(AgePtr + ParticleIndex + 1);

		//CachedBounds += NewVertex.Position;
	}
	//CachedBounds.ExpandBy(MaxSize);

	CPUTimeMS = VertexDataTimer.GetElapsedMilliseconds();


	return DynamicData;
}
void ECCalibrateScreen::highCalibration()
{
	myUTFT.clrScr();
	myUTFT.setColor(255, 0, 0);
	myUTFT.fillRect(0, 0, 220, 13);
	myUTFT.setColor(255, 255, 255);
	myUTFT.setBackColor(255, 0, 0);
	myUTFT.drawLine(0, 14, 320, 14);
	myUTFT.print("EC Calibration", CENTER, 1);
	myUTFT.setBackColor(0, 0, 0);

	myUTFT.print("Calibrate now with the high side liquid", LEFT, 30);
	myUTFT.print("Place the sensor in the 3,000Us ", LEFT, 42);
	myUTFT.print("calibration liquid. This process", LEFT, 54);
	myUTFT.print("will take 5 minutes to complete", LEFT, 66);
	myUTFT.print("Wait for process to finish before ", LEFT, 78);
	myUTFT.print("removing the sensor from the liquid", LEFT, 90);
	myUTFT.print("", LEFT, 102);
	myUTFT.print("************************************", LEFT, 114);
	myUTFT.print("Touch screen to continue", CENTER, 162);

	waitForTouch();
	myUTFT.clrScr();

	inputstring = "C\r";  //set in continious mode

	myUTFT.clrScr();
	String thisSt = String(iSeconds);
	myUTFT.print("Calibration in Progress", CENTER, 30);
	myUTFT.print("Seconds left until ready " + thisSt, CENTER, 42);
	simpleTimer.setTimer(3000, updateWaitScreen, /*100*/ 4); //Update screen every 3 seconds for 5 minues.

}
void rcb_rec2D(vector<T> *p_coord,
               vector<int> *p_map,
               vector<int> *p_part,
               int start,
               int end,
               int dims, 
               int cur_depth,
               int ttl_depth){

	// end of partitioning
	if(cur_depth == 0) return;

	//cout << "-------------------------------------------------------------" << endl;
	//cout << "    start=" << start << " end=" << end << " cur_depth=" << cur_depth << endl;

tmr_span.start();
	// calculate max distance on each axis
	double x_span = calc_span(p_coord, start, end, dims, 0);
	double y_span = calc_span(p_coord, start, end, dims, 1);
tmr_span.stop_and_add_to_total();;

	// choose axis
	int axis = -1;
	if(x_span >= y_span)
		axis = 0;
	else
		axis = 1;

	//cout << "    x_span=" << x_span << " y_span=" << y_span << " axis=" << axis << endl;

	// find mid-point
tmr_pivot1.start();
	T pivot = find_pivot(p_coord, start, end, dims, axis);
tmr_pivot1.stop_and_add_to_total();;
	//cout << "    pivot=" << pivot <<endl;

	// partition into two
	int level= cur_depth-1;
	int part_index = partition(p_coord, p_map, p_part, start, end, dims, axis, pivot, level);

	//cout << "    part_index=" << part_index << endl;

	// next partitioning
	rcb_rec2D(p_coord, p_map, p_part, start, start+part_index, dims, cur_depth-1, ttl_depth);
	rcb_rec2D(p_coord, p_map, p_part, start+part_index, end, dims, cur_depth-1, ttl_depth);

}
Beispiel #10
0
boolean MyTone::writeVal( HardwareTypeIdentifier type, HardwareCommandResult* result ) {
	if(type == HWType_tone && result != NULL && result->getUint16ListNum() > 0) {
		uint16_t length = result->getUint16List()[0];

		uint8_t tone = this->myTone;
		if(result->getUint16ListNum() > 1)
		tone = result->getUint16List()[1];

		write(tone);
		int num = timer.setTimeout(length, (timer_callback) &MyTone::stopOutputHook);
		timer.setCallbackContext(num, (void*) this);

		return true;
	}

	return false;
}
Beispiel #11
0
void CreateTool::CreateMultipleObjects( bool stamp )
{
	HELIUM_EDITOR_SCENE_SCOPE_TIMER( "Place Multiple Instances At Location" );

	if ( m_InstanceRadius <= 0.0f )
	{
		return;
	}

	if ( m_InstanceOffsets.empty() || m_InstanceUpdateOffsets )
	{
		m_InstanceOffsets.clear();
		SetupInstanceOffsets( m_InstanceRadius, m_InstanceOffsets );
		m_InstanceUpdateOffsets = false;
	}

	float32_t maxTime = 100.0f;
	SimpleTimer instanceTimer;
	Vector3 instanceNormalOffset = m_InstanceNormal.Normalize() * 2.0f * s_PaintRadius;

	while ( m_InstanceOffsets.size() && ( stamp || ( instanceTimer.Elapsed() < maxTime ) ) )
	{
		V_Vector3::iterator itr = m_InstanceOffsets.begin();

		Matrix4 instanceTransform;
		instanceTransform.t = Vector4( *itr );
		instanceTransform *= Matrix4( AngleAxis::Rotation( Editor::SideVector, m_InstanceNormal ) );
		instanceTransform.t += Vector4( m_InstanceTranslation );

		Vector3 point = Vector3( instanceTransform.t.x, instanceTransform.t.y, instanceTransform.t.z );
		LinePickVisitor pick( m_Scene->GetViewport()->GetCamera(), Line( point + instanceNormalOffset, point - instanceNormalOffset ) );

		Vector3 instanceTranslation;
		Vector3 instanceNormal;
		if ( DetermineTranslationAndNormal( pick, instanceTranslation, instanceNormal ) )
		{
			point = Vector3( instanceTranslation.x - m_InstanceTranslation.x, instanceTranslation.y - m_InstanceTranslation.y, instanceTranslation.z - m_InstanceTranslation.z );
			if ( point.Length() <= s_PaintRadius )
			{
				CreateSingleObject( instanceTranslation, instanceNormal, true );
			}
		}

		m_InstanceOffsets.erase( itr );
	}
}
Beispiel #12
0
void doTest(const int numThreads, std::thread* threads, const bool stest, const bool locking)
{
	iterations = 1;
	do
	{
		SimpleTimer timer;
		timer.Start();
		//initialize testing threads, then wait for all threads to finish
		if(stest)
		{
			for(int i = 0; i < numThreads; ++i)
			{
				threads[i] = std::thread(StackSThread);
			}
		}
		else 
		{
			for(int i = 0; i < numThreads; ++i)
			{
				threads[i] = std::thread(StackTThread);
			}
		}
		for(int i = 0; i < numThreads; ++i)
		{
			threads[i].join();
		}
		timer.Stop();
		while(!stack->IsEmpty())
		{
			delete (stack->Pop());
		}
		std::cout << (locking ? "Locking " : "LockFree ") << (stest ? "STest " : "TTest ") <<
		    iterations << " inner iterations with " <<
			numThreads << " threads: " << timer.ElapsedMilliseconds() << std::endl;

		std::ofstream outfile;
		outfile.open(OUTPUT_FILE, std::ios_base::app);
		outfile << (locking ? "L," : "F,") << (stest ? "S," : "T,") << iterations << "," << numThreads << "," << timer.ElapsedMilliseconds() << std::endl;
		outfile.close();

		iterations = iterations << 1;
	}
	while(iterations < MAX_INNER_ITERATIONS);
}
Beispiel #13
0
// this function expects that simulation params be updated beforehand
int launchExpt(){

	SimpleTimer clockExpt; clockExpt.reset();
	clockExpt.start();

	cout << "\n> Launch Experiment: " << exptDesc << "_runSet(" << iEns << ")\n";
	cout << "   > Simulate " << genMax << " generations, plot after every " << plotStep << " steps.\n   > "; 
	cout.flush();

	// start run
//	int k=0, g=0;
	while(1){	// infinite loop needed to poll anim_on signal.
		if (graphicsQual > 0) glutMainLoopEvent();		

		// animate particles
		if (b_anim_on) {
			animateParticles(); 
			++stepNum;
			if (b_displayEveryStep && stepNum % (-dispInterval) == 0) displayDevArrays();	// update display if every step update is on
		}

		// if indefinite number of steps desired, skip gen-advance check
		if (moveStepsPerGen < 0) continue;	

		// check if generation is to be advanced.
		if (stepNum >= moveStepsPerGen){
			stepNum = 0;
			advanceGen();	// Note: CudaMemCpy at start and end of advanceGen() ensure that all movement kernel calls are done
			++genNum;			
			if (genNum % plotStep == 0) { cout << "."; cout.flush(); }
		}

		// when genMax genenrations are done, end run
		if (genNum >= genMax) break;
	}

	// end run, reset counters
	cout << " > DONE. "; // << "Return to main().\n\n";
	printTime_hhmm(clockExpt.getTime());
	stepNum = genNum = 0;
	++iExpt;
	return 0;
}
// SETUP
void setup()
{
    // For algorithm speed checking
    loopPeriod = 0;
    lastLoop = micros();

    // Lap timer
    lapTimer.setInterval(100, IncrementTime);
    lapTimer.disable(0);

    // Initialize LCD
    lcd.begin(16, 2);   
    lcd.setCursor(0,0);
    
    // Turn signals
    pinMode(LEFT_TURN_LED, OUTPUT);
    pinMode(RIGHT_TURN_LED, OUTPUT);
    digitalWrite(LEFT_TURN_LED, 0);
    digitalWrite(RIGHT_TURN_LED, 0);
    turnSignalTimer.setInterval(50, TurnSignal);

    // Force motors off by default
    MotorSpeed(LEFT_MOTOR, 0);
    MotorSpeed(RIGHT_MOTOR, 0);

    // Parameters need to be loaded from EEPROM
    LoadFromEEPROM();

    // Intro text
    Clear();
    Cursor(TOP, 0);
    Print("FAST ORANGE");
    Cursor(BOTTOM, 0);
    #ifdef DEBUG_MODE
    Print("Debug Mode");
    #else
    Print("Race Mode");
    #endif
    delay(1000);

    currentState = menu;
}
Beispiel #15
0
UndoCommandPtr Selection::Clear(const SelectionChangingSignature::Delegate& emitterChanging, const SelectionChangedSignature::Delegate& emitterChanged)
{
	if (m_Items.Empty())
	{
		return NULL;
	}

	EDITOR_SCENE_SCOPE_TIMER( ("") );

	SimpleTimer timer;

	UndoCommandPtr command;

	OS_ObjectDumbPtr empty;
	SelectionChangingArgs args ( empty );
	m_SelectionChanging.RaiseWithEmitter( args, emitterChanging );
	if ( !args.m_Veto )
	{
		command = new SelectionChangeCommand( this );

		OS_ObjectDumbPtr::Iterator itr = m_Items.Begin();
		OS_ObjectDumbPtr::Iterator end = m_Items.End();
		for ( ; itr != end; ++itr )
		{
			SceneNode *pSceneNode = Reflect::SafeCast<SceneNode>(*itr);
			if (pSceneNode)
			{
				pSceneNode->SetSelected(false);
			}
		}

		m_Items.Clear();

		m_SelectionChanged.RaiseWithEmitter(m_Items, emitterChanged);
	}

	Log::Profile( TXT( "Selection Clear took %fms\n" ), timer.Elapsed());

	return command;
}
Beispiel #16
0
void setup()
{
	Serial.begin(9600);

	pinMode (11,OUTPUT);
	pinMode (12,OUTPUT);

	pinMode(8, INPUT);    // Set the switch pin as input
	pinMode(9, INPUT);    // Set the switch pin as input
	pinMode(10, INPUT);    // Set the switch pin as input


    // Pin 13 has an LED connected on most Arduino boards
    pinMode(13, OUTPUT);


    timer.setInterval(10,&debDown);
    timer.setInterval(10,&debUp);
    timer.setInterval(10,&debStop);
    timer.setInterval(10000,&clockTimer);
    mgr.moveUp();
}
// LOOP
void loop()
{
    switch(currentState)
    {
        case menu:
        MotorSpeed(LEFT_MOTOR, 0);
        MotorSpeed(RIGHT_MOTOR, 0);
        ShowMenu();
        break;

        case moveStraight:
        Update();
        ProcessMovementAnalog();
        break;

        case turnLeft:
        case turnRight:
        Turn();
        break;
    }
    turnSignalTimer.run();
    lapTimer.run();
}
void part_rcb(int numoflevel, int dims,
              int nnode, int nedge, int nbedge, int ncell,
              point *partnode, point *partedge, point *partbedge, point *partcell,
              int *cell, int *ecell, int *becell, int *edge,
              float *x){

	// calc coordinate of center of gravity in each cell
	vector<float> coord_cell(ncell*dims);
	calc_cellcentre(ncell, dims, cell, x, &coord_cell);

	// initialize map and partition data
	vector<int> map, part;
	for(int i=0; i<ncell; i++){
		map.push_back(i);
		part.push_back(0);
	}

 	// call recursive coordinate bisection algorithm
	rcb_rec2D(&coord_cell, &map, &part, 0, ncell, dims, numoflevel, numoflevel);

	// Debug Print
	//part_rcb_DebugPrint(ncell, dims, &coord_cell, &map, &part);
	
 	// output partition data
tmr_out.start();
/*
	if(check_partdata(ncell, &map, &part, numoflevel)){
		generate_partdata(nnode, nedge, nbedge, ncell,
                          &map, &part, 
                          partnode, partedge, partbedge, partcell, 
                          cell, ecell, becell);
	}else{
		cout << "partition data is invalid" << endl;
		exit(-1);
	}
*/
tmr_out.stop_and_add_to_total();

printf("span  =%lf\n", tmr_span.total_time());
printf("pivot =%lf\n", tmr_pivot1.total_time());
printf("part1 =%lf\n", tmr_part1.total_time());
printf("part2 =%lf\n", tmr_part2.total_time());
printf("part3 =%lf\n", tmr_part3.total_time());
printf("out   =%lf\n", tmr_out.total_time());

}
Beispiel #19
0
void setup()
{
	Blynk.begin(AUTH, SSID, PASSWORD);

	pinMode(heatPin, OUTPUT);
	pinMode(tempPin, INPUT);

	Serial.begin(9600);
	Serial.println("\n\n\nTime, target, temp");

	done = false;
	RUNNING = false;
	setHeater(LOW);

	timerId = timer.setInterval(TIMESTEP * 1000L, setTemperature);
}
void ECCalibrateScreen::lowCalibration()
{
	myUTFT.clrScr();
	myUTFT.setColor(255, 0, 0);
	myUTFT.fillRect(0, 0, 220, 13);
	myUTFT.setColor(255, 255, 255);
	myUTFT.setBackColor(255, 0, 0);
	myUTFT.drawLine(0, 14, 320, 14);
	myUTFT.print("EC Calibration", CENTER, 1);
	myUTFT.setBackColor(0, 0, 0);

	myUTFT.print("Calibrate now with the low side liquid", LEFT, 30);
	myUTFT.print("Place the sensor in the 220Us", LEFT, 42);
	myUTFT.print("calibration liquid.  This process", LEFT, 54);
	myUTFT.print("will take 5 mins to complete", LEFT, 66);
	myUTFT.print("Wait for process to finish before ", LEFT, 78);
	myUTFT.print("removing the sensor from the liquid", LEFT, 90);
	myUTFT.print("", LEFT, 102);
	myUTFT.print("************************************", LEFT, 114);
	myUTFT.print("Touch screen to continue", CENTER, 162);

	SwaitForTouch();
	myUTFT.clrScr();

	inputstring = "C\r";  //set in continious mode

	String thisSt = String(12);
	myUTFT.print("Calibration in Progress", CENTER, 30);
	myUTFT.print("Seconds left until ready " + thisSt, CENTER, 42);
	simpleTimer.setTimer(3000, updateLowWaitScreen, /*100*/ 4); //Update screen every 3 seconds for 5 minues.


	//delay(2000);  //Wait 2 seconds -- make 5mins
	//Serial3.print(inputstring); //send command to sensor.
	//inputstring = "Z2\r";  //set the sensor at this value.
	//Serial3.print(inputstring); //need to send twice??


}
// Updates the sensors and machine state
void Update()
{
    if ((lcdRefreshCount == 0) && (currentState != menu) && (ReadButton() == SELECT))
    {
        delay(750);
        if(ReadButton() == SELECT) // debounce MENU button
        {
            // Stop motors before entering menu
            MotorSpeed(LEFT_MOTOR, 0);
            MotorSpeed(RIGHT_MOTOR, 0);

            Clear();
            Cursor(TOP, 0);
            Print("Entering menu");
            currentState = menu;
            delay(1000);
            lapTimer.disable(0);
            return;
        }
    }

    // Read raw sensor values
    left = analogRead(LEFT_SENSOR);
    right = analogRead(RIGHT_SENSOR);
    leftDetected = left > thresholdLeft.Value;
    rightDetected = right > thresholdRight.Value;
    if (leftDetected || rightDetected)
    {
        CenterSmartUpdate();
    }

    // Display values on LCD
    lcdRefreshCount = (lcdRefreshCount <= 0) ? lcdRefreshPeriod : (lcdRefreshCount - 1);
    batteryCount = (batteryCount <= 0) ? batteryPeriod : (batteryCount - 1);
    DisplaySensorValues();   
}
Beispiel #22
0
bool MediaParserGst::probingConditionsMet(const SimpleTimer& timer)
{
    return foundAllStreams() || (timer.expired() && getBytesLoaded() >= MIN_PROBE_SIZE);
}
int  main()
   {
    SelSorter dateObjectI1;
    MrgSorter dateObjectM1;
    QkSorter dateObjectQ1;
    DateType dateValue;
    SimpleTimer timer;
    char tempString[ SMALL_STR_LEN ], insTime[ SMALL_STR_LEN ];
    char qkTime[ SMALL_STR_LEN ], mrgTime[ SMALL_STR_LEN ]; 
    bool qSortGood = false, mSortGood = false, iSortGood = false;

    // load dates ////////////////////////////////////////////////////////////
    cout << endl << "Enter list of dates: " << endl;

    while( getALine( cin, tempString ) )
       {
        dateObjectI1.add( tempString );
       }

    // assign dates to other objects /////////////////////////////////////////
    dateObjectM1 = dateObjectI1;

    dateObjectQ1 = dateObjectM1;

    // display lists, unsorted ///////////////////////////////////////////////
    displayList( dateObjectI1, 'S', UNSORTED );

    displayList( dateObjectM1, 'M', UNSORTED );

    displayList( dateObjectQ1, 'Q', UNSORTED );

    // Selection sort operation //////////////////////////////////////////////
    timer.start();

    if( dateObjectI1.sort() )
       {
        timer.stop();
        timer.getElapsedTime( insTime );
        displayList( dateObjectI1, 'S', SORTED );
        iSortGood = true;
       }

    // stop timer in case of failure
    timer.stop();

    // Merge sort operation //////////////////////////////////////////////////
    timer.start();

    if( dateObjectM1.sort() )
       {
        timer.stop();
        timer.getElapsedTime( mrgTime );
        displayList( dateObjectM1, 'M', SORTED );
        mSortGood = true;
       }

    // stop timer in case of failure
    timer.stop();

    // Quick sort operation //////////////////////////////////////////////////
    timer.start();

    if( dateObjectQ1.sort() )
       {
        timer.stop();
        timer.getElapsedTime( qkTime );
        displayList( dateObjectQ1, 'Q', SORTED );
        qSortGood = true;
       }

    // stop timer in case of failure
    timer.stop();

    // Results displayed /////////////////////////////////////////////////////
    if( iSortGood )
       {
        cout << "Elapsed Time for Selection Sort: " 
             << insTime << " seconds." << endl;
       }
    else
       {
        cout << "ERROR: Failure of Selection sort due to bad input" 
             << endl << endl;
       }

    if( mSortGood )
       {
        cout << endl << "Elapsed Time for Merge Sort: " 
             << mrgTime << " seconds." << endl;
       }
    else
       {
        cout << "ERROR: Failure of merge sort due to bad input" 
             << endl << endl;
       }


    if( qSortGood )
       {
        cout << endl << "Elapsed Time for Quick Sort: " 
             << qkTime << " seconds." << endl << endl;
       }
    else
       {
        cout << "ERROR: Failure of quick sort due to bad input" 
             << endl << endl;
       }

    return 0;
   }
int doParallelSuperPMI(CommandLine::Options& o)
{
    HRESULT hr = E_FAIL;
    SimpleTimer st;
    st.Start();

#ifndef FEATURE_PAL // TODO-Porting: handle Ctrl-C signals gracefully on Unix
    //Register a ConsoleCtrlHandler
    if (!SetConsoleCtrlHandler(CtrlHandler, TRUE))
    {
        LogError("Failed to set control handler.");
        return 1;
    }
#endif // !FEATURE_PAL

    char tempPath[MAX_PATH];
    if (!GetTempPath(MAX_PATH, tempPath))
    {
        LogError("Failed to get path to temp folder.");
        return 1;
    }

    if (o.workerCount <= 0)
    {
        //Use the default value which is the number of processors on the machine.
        SYSTEM_INFO sysinfo;
        GetSystemInfo(&sysinfo);

        o.workerCount = sysinfo.dwNumberOfProcessors;

        //If we ever execute on a machine which has more than MAXIMUM_WAIT_OBJECTS(64) CPU cores
        //we still can't spawn more than the max supported by WaitForMultipleObjects()
        if (o.workerCount > MAXIMUM_WAIT_OBJECTS)
            o.workerCount = MAXIMUM_WAIT_OBJECTS;
    }

    // Obtain the folder path of the current executable, which we will use to spawn ourself.
    char* spmiFilename = new char[MAX_PATH];
    if (!GetModuleFileName(NULL, spmiFilename, MAX_PATH))
    {
        LogError("Failed to get current exe path.");
        return 1;
    }

    char* spmiArgs = ConstructChildProcessArgs(o);

    // TODO: merge all this output to a single call to LogVerbose to avoid all the newlines.
    LogVerbose("Using child (%s) with args (%s)", spmiFilename, spmiArgs);
    if (o.mclFilename != nullptr)
        LogVerbose(" failingMCList=%s", o.mclFilename);
    if (o.diffMCLFilename != nullptr)
        LogVerbose(" diffMCLFilename=%s", o.diffMCLFilename);
    LogVerbose(" workerCount=%d, skipCleanup=%d.", o.workerCount, o.skipCleanup);

    HANDLE *hProcesses = new HANDLE[o.workerCount];
    HANDLE *hStdOutput = new HANDLE[o.workerCount];
    HANDLE *hStdError  = new HANDLE[o.workerCount];

    char** arrFailingMCListPath = new char*[o.workerCount];
    char** arrDiffMCListPath    = new char*[o.workerCount];
    char** arrStdOutputPath     = new char*[o.workerCount];
    char** arrStdErrorPath      = new char*[o.workerCount];

    // Add a random number to the temporary file names to allow multiple parallel SuperPMI to happen at once.
    unsigned int randNumber = 0;
#ifdef FEATURE_PAL
    PAL_Random(/* bStrong */ FALSE, &randNumber, sizeof(randNumber));
#else // !FEATURE_PAL
    rand_s(&randNumber);
#endif // !FEATURE_PAL

    for (int i = 0; i < o.workerCount; i++)
    {
        if (o.mclFilename != nullptr)
        {
            arrFailingMCListPath[i] = new char[MAX_PATH];
            sprintf_s(arrFailingMCListPath[i], MAX_PATH, "%sParallelSuperPMI-%u-%d.mcl", tempPath, randNumber, i);
        }
        else
        {
            arrFailingMCListPath[i] = nullptr;
        }

        if (o.diffMCLFilename != nullptr)
        {
            arrDiffMCListPath[i] = new char[MAX_PATH];
            sprintf_s(arrDiffMCListPath[i], MAX_PATH, "%sParallelSuperPMI-Diff-%u-%d.mcl", tempPath, randNumber, i);
        }
        else
        {
            arrDiffMCListPath[i] = nullptr;
        }

        arrStdOutputPath[i] = new char[MAX_PATH];
        arrStdErrorPath[i]  = new char[MAX_PATH];

        sprintf_s(arrStdOutputPath[i], MAX_PATH, "%sParallelSuperPMI-stdout-%u-%d.txt", tempPath, randNumber, i);
        sprintf_s(arrStdErrorPath[i],  MAX_PATH, "%sParallelSuperPMI-stderr-%u-%d.txt", tempPath, randNumber, i);
    }

    char cmdLine[MAX_CMDLINE_SIZE];
    cmdLine[0] = '\0';
    int bytesWritten;

    for (int i = 0; i < o.workerCount; i++)
    {
        bytesWritten = sprintf_s(cmdLine, MAX_CMDLINE_SIZE, "%s -stride %d %d", spmiFilename, i + 1, o.workerCount);

        if (o.mclFilename != nullptr)
        {
            bytesWritten += sprintf_s(cmdLine + bytesWritten, MAX_CMDLINE_SIZE - bytesWritten, " -failingMCList %s", arrFailingMCListPath[i]);
        }

        if (o.diffMCLFilename != nullptr)
        {
            bytesWritten += sprintf_s(cmdLine + bytesWritten, MAX_CMDLINE_SIZE - bytesWritten, " -diffMCList %s", arrDiffMCListPath[i]);
        }

        bytesWritten += sprintf_s(cmdLine + bytesWritten, MAX_CMDLINE_SIZE - bytesWritten, " -v ewmin %s", spmiArgs);

        SECURITY_ATTRIBUTES sa;
        sa.nLength = sizeof(sa);
        sa.lpSecurityDescriptor = NULL;
        sa.bInheritHandle = TRUE;       // Let newly created stdout/stderr handles be inherited.

        LogDebug("stdout %i=%s", i, arrStdOutputPath[i]);
        hStdOutput[i] = CreateFileA(arrStdOutputPath[i], GENERIC_WRITE, FILE_SHARE_READ, &sa, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
        if (hStdOutput[i] == INVALID_HANDLE_VALUE)
        {
            LogError("Unable to open '%s'. GetLastError()=%u", arrStdOutputPath[i], GetLastError());
            return -1;
        }

        LogDebug("stderr %i=%s", i, arrStdErrorPath[i]);
        hStdError[i] = CreateFileA(arrStdErrorPath[i], GENERIC_WRITE, FILE_SHARE_READ, &sa, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
        if (hStdError[i] == INVALID_HANDLE_VALUE)
        {
            LogError("Unable to open '%s'. GetLastError()=%u", arrStdErrorPath[i], GetLastError());
            return -1;
        }

        //Create a SuperPMI worker process and redirect its output to file
        if (!StartProcess(cmdLine, hStdOutput[i], hStdError[i], &hProcesses[i]))
        {
            return -1;
        }
    }

    WaitForMultipleObjects(o.workerCount, hProcesses, true, INFINITE);

    // Close stdout/stderr
    for (int i = 0; i < o.workerCount; i++)
    {
        CloseHandle(hStdOutput[i]);
        CloseHandle(hStdError[i]);
    }

    DWORD exitCode = 0; // 0 == assume success

    if (!closeRequested)
    {
        // Figure out the error code to use. We use the largest magnitude error code of the children.
        // Mainly, if any child returns non-zero, we want to return non-zero, to indicate failure.
        for (int i = 0; i < o.workerCount; i++)
        {
            DWORD exitCodeTmp;
            BOOL ok = GetExitCodeProcess(hProcesses[i], &exitCodeTmp);
            if (ok && (exitCodeTmp > exitCode))
            {
                exitCode = exitCodeTmp;
            }
        }

        bool usageError = false; //variable to flag if we hit a usage error in SuperPMI

        int loaded = 0, jitted = 0, failed = 0, diffs = 0;

        //Read the stderr files and log them as errors
        //Read the stdout files and parse them for counts and log any MISSING or ISSUE errors
        for (int i = 0; i < o.workerCount; i++)
        {
            ProcessChildStdErr(arrStdErrorPath[i]);
            ProcessChildStdOut(o, arrStdOutputPath[i], &loaded, &jitted, &failed, &diffs, &usageError);
            if (usageError)
                break;
        }

        if (o.mclFilename != nullptr && !usageError)
        {
            //Concat the resulting .mcl files
            MergeWorkerMCLs(o.mclFilename, arrFailingMCListPath, o.workerCount);
        }

        if (o.diffMCLFilename != nullptr && !usageError)
        {
            //Concat the resulting diff .mcl files
            MergeWorkerMCLs(o.diffMCLFilename, arrDiffMCListPath, o.workerCount);
        }

        if (!usageError)
        {
            if (o.applyDiff)
            {
                LogInfo(g_AsmDiffsSummaryFormatString, loaded, jitted, failed, diffs);
            }
            else
            {
                LogInfo(g_SummaryFormatString, loaded, jitted, failed);
            }
        }

        st.Stop();
        LogVerbose("Total time: %fms", st.GetMilliseconds());
    }

    if (!o.skipCleanup)
    {
        // Delete all temporary files generated
        for (int i = 0; i < o.workerCount; i++)
        {
            if (arrFailingMCListPath[i] != nullptr)
            {
                DeleteFile(arrFailingMCListPath[i]);
            }
            if (arrDiffMCListPath[i] != nullptr)
            {
                DeleteFile(arrDiffMCListPath[i]);
            }
            DeleteFile(arrStdOutputPath[i]);
            DeleteFile(arrStdErrorPath[i]);
        }
    }

    return (int)exitCode;
}
Beispiel #25
0
// Lower drill, outputs 2sec pulse to lowering pin
void LowerDrill(){
  DrillDown.on();
  timer.setTimeout(2000, StopDrillMove);
}
Beispiel #26
0
// Lift drill, outputs 2sec pulse to lifting pin.
void LiftDrill(){
  DrillUp.on();
  timer.setTimeout(2000, StopDrillMove);
}
Beispiel #27
0
void loop() {
  
  //Start timer, this is used to lift and lower the drill.
  timer.run();
  
  // send data only when you receive data:
	if (Serial.available() > 0) {
		// read the incoming byte:
		incomingString = Serial.read();
                
				// If incoming is "q"
                if (incomingString == 101){
                  dirA = 'F';
                  dirB = 'F';
                }
				// If incoming is "e"
                else if (incomingString == 113){
                  dirA = 'F';
                  dirB = 'R';
                }
				// If incoming is "w"
                else if (incomingString == 119){
                  dirA = 'F';
                  dirB = 'N';
                }
				// If incoming is "z"
                else if (incomingString == 99){
                  dirA = 'R';
                  dirB = 'F';
                }
				// If incoming is "c"
                else if (incomingString == 122){
                  dirA = 'R';
                  dirB = 'R';
                }
				// If incoming is "x"
                else if (incomingString == 120){
                  dirA = 'R';
                  dirB = 'N';
                }
				// If incoming is "a"
                else if (incomingString == 100){
                  dirA = 'N';
                  dirB = 'F';
                }
				// If incoming is "d"
                else if (incomingString == 97){
                  dirA = 'N';
                  dirB = 'R';
                }
				// If incoming is "s"
                else if (incomingString == 115){
                  dirA = 'N';
                  dirB = 'N';
                }
				// If incoming is "r"
                else if (incomingString == 114){
                  ResetCoords();
                  dirA = 'N';
                  dirB = 'N';
                }
				// If incoming is "f"
                else if (incomingString == 102){
                  LiftDrill();
                  Serial.print("Drill is up");
                  Serial.print("\n");
                  dirA = 'N';
                  dirB = 'N';
                }
				// If incoming is "v"
                else if (incomingString == 118){
                  LowerDrill();
                  Serial.print("Drill is down");
                  Serial.print("\n");
                  dirA = 'N';
                  dirB = 'N';
                }

				//Calculate steps according to selected direction and last step
                Step(dirA, dirB);
				//Write data to ShiftRegister
                WriteData(Output);
                
				//Write coordinates to LCD
                outgoingString = "";
                outgoingString = outgoingString + "X: ";
                outgoingString = outgoingString + CoordX;
                outgoingString = outgoingString + "   Y: ";
                outgoingString = outgoingString + CoordY;
                //Write coordintes to Serial port
                Serial.print("Position");
                Serial.print(outgoingString);
                Serial.print("\n");
                Serial.print("\n");
	}

  // LCD Part of code
  // set the cursor to column 0, line 1
  // (note: line 1 is the second row, since counting begins with 0):
  lcd.setCursor(0, 1);
  // print the number of seconds since reset:
  lcd.print("X: ");
  lcd.setCursor(3, 1);
  lcd.print(CoordX);
  lcd.setCursor(8, 1);
  lcd.print("Y: ");
  lcd.setCursor(11, 1);
  lcd.print(CoordY);
}
Beispiel #28
0
/*
 * SpeeDroid image processing is done here.
 *
 * PARAMS:
 * JNIEnv*			-	JNI function access pointer (not used)
 * jobject			-	Java "this" (not used)
 * jlong addrRgba	-	Memory address of frame to process (OpenCV Mat)
 * jint				-	ROI width as percentage of image
 * jint				-	ROI height as percentage of
 */
JNIEXPORT void JNICALL Java_mvs_speedroid_SpeeDroidActivity_ProcessImage(JNIEnv*, jobject, jlong addrRgba, jint roiWidth, jint roiHeight)
{
    //Get the image data from Java side pointer
	Mat& rgb = *(Mat*)addrRgba;

	//Buffer images
    Mat thresh;
    Mat mainRoiImg;
    Mat cropped;

    //log the function execution time
    clock_t startTime = clock();
    clock_t endTime;

    //We do the processing for to regions of interest.
    //We create a ROI on both sides of the image to scan both sides of the road.
    //Both ROIs have same dimensions.
    unsigned int roiW = (unsigned int)(rgb.cols/2 * (roiWidth / 100.0));
    unsigned int roiH = (unsigned int)(rgb.rows * (roiHeight / 100.0));

    if(roiW == 0){
    	LOGD("ROI width set to 0!");
    	return;
    }

    if(roiH == 0){
    	LOGD("ROI height set to 0!");
    	return;
    }

    //Timer for cooldown after successful detection
    static SimpleTimer resultCooldown = SimpleTimer();

    //Circle to store RANSAC result
    CircleType c = {Point(0,0), 0};

    if(rgb.cols < 2*roiW || rgb.rows < roiH){
    	LOGD("Too small frame!");
    	return;
    }

    //Copy the rois from input image
    mainRoiImg = Mat::zeros(Size(2*roiW,roiH), CV_8UC4);
	rgb(Rect(0,0,roiW,roiH)).copyTo(mainRoiImg(Rect(0,0,roiW,roiH)));
	rgb(Rect(rgb.cols-roiW, 0, roiW, roiH)).copyTo(mainRoiImg(Rect(roiW,0,roiW,roiH)));

	//median blur on the rois to remove noise but preserve edges
    //this is quite expensive operation!!
    //medianBlur(mainRoiImg, mainRoiImg, 3);

    //Find red pixels in the image
    findRed(mainRoiImg, thresh);

    //Identify red circles as traffic sign candidates
    if (CircleRANSAC(thresh, c)){

    	//correct the coordinate if the circle center is in roi 2
		if(c.center.x >= roiW){
			c.center.x = (c.center.x - roiW) + (rgb.cols - roiW);
		}

		Point displace(c.radius, c.radius);
		Rect roiSign(c.center-displace, c.center+displace);

		safeCrop(rgb, cropped, roiSign);

		//update results if the sign candidate is accepted and
		//2 seconds has elapsed since last detection
		if(!detectFalsePositives(cropped) && resultCooldown.isElapsed()){

			//findFeatures(cropped);
			updateDetectedSigns(cropped);
			resultCooldown.startTimer(2.0);
		}

		//Draw RANSAC result on output Mat
		circle(rgb, c.center, c.radius, Scalar(0,255,255), 4);
    }

    //Draw the ROI on the output Mat
	rectangle(rgb, Rect(0,0,roiW,roiH), Scalar(0,0,255), 2);
	rectangle(rgb, Rect(rgb.cols-roiW,0,roiW,roiH), Scalar(0,0,255), 2);

	//Draw detection results to output Mat
	drawDetectedSigns(rgb);

    thresh.release();
    mainRoiImg.release();
    cropped.release();

    endTime = clock();
    LOGD("JNI exec time: %lf", (double(endTime - startTime) / CLOCKS_PER_SEC));

}
int partition(vector<T> *p_in, 
              vector<int> *p_map,
              vector<int> *p_part,
              int start, 
              int end, 
              int dims, 
              int axis, 
              T pivot,
              int level){

/*
tmr_part1.start();
	// Buffer
	vector<T> out1, out2;
	vector<int> map1, map2;
	int cnt1=0, cnt2=0;
	for(int i=start; i < end; i++){
		if(p_in->at(i*dims+axis)> pivot){
			for(int d_index=0; d_index<dims; d_index++)
				out1.push_back(p_in->at(i*dims+d_index));
			map1.push_back(p_map->at(i));
			cnt1+=1;
		}else{
			for(int d_index=0; d_index<dims; d_index++)
				out2.push_back(p_in->at(i*dims+d_index));
			map2.push_back(p_map->at(i));
			cnt2+=1;
		}
	}

tmr_part1.stop_and_add_to_total();
*/


tmr_part1.start();

	// Buffer
	vector<T> out1, out2;
	vector<int> map1, map2;
	int cnt1=0, cnt2=0;
	int halfcnt = (end-start)/2;
	map1.reserve(halfcnt);
	map2.reserve(halfcnt);
	out1.reserve(halfcnt*dims);
	out2.reserve(halfcnt*dims);
	T tmpcoord;
	for(int i=start; i < end; i++){
	
		tmpcoord = p_in->at(i*dims+axis);

		// - balance load when multiple node has same coordinate value
		if(tmpcoord == pivot){
			// if cnt1 is less than half size, data belong to map1
			if(halfcnt>cnt1){
				for(int d_index=0; d_index<dims; d_index++)
					out1.push_back(p_in->at(i*dims+d_index));
				map1.push_back(p_map->at(i));
				cnt1+=1;
			// if cnt1 is more than half size, data belong to map2
			}else{
				for(int d_index=0; d_index<dims; d_index++)
					out2.push_back(p_in->at(i*dims+d_index));
				map2.push_back(p_map->at(i));
				cnt2+=1;
			}
		}else if(tmpcoord > pivot){
			for(int d_index=0; d_index<dims; d_index++)
				out1.push_back(p_in->at(i*dims+d_index));
			map1.push_back(p_map->at(i));
			cnt1+=1;
		}else{
			for(int d_index=0; d_index<dims; d_index++)
				out2.push_back(p_in->at(i*dims+d_index));
			map2.push_back(p_map->at(i));
			cnt2+=1;
		}
	}
tmr_part1.stop_and_add_to_total();;

	//cout << "    out1.size =" << out1.size()/dims << " out2.size =" << out2.size()/dims << endl;
	//cout << "    level =" << level  << endl;

	// Replace to original coord data <--- can be replaced with this loop to memcpy but may not safe..

tmr_part2.start();

	for(int i=0; i < (int)out1.size(); i++){
		p_in->at(start*dims+i) = out1.at(i);
	}

	for(int i=0; i < (int)out2.size(); i++){
		p_in->at(start*dims+out1.size()+i) = out2.at(i);
	}
tmr_part2.stop_and_add_to_total();;


tmr_part3.start();
	for(int i=0; i<cnt2; i++){
		p_part->at(start+cnt1+i) |= (1 << level);
	}

	// Replace to original map/part data
	for(int i=0; i < (int)map1.size(); i++)
		p_map->at(start+i) = map1.at(i);

	for(int i=0; i < (int)map2.size(); i++)
		p_map->at(start+map1.size()+i) = map2.at(i);
tmr_part3.stop_and_add_to_total();;

	return cnt1;
}
inline void CenterSmartUpdate()
{
    center = analogRead(CENTER_SENSOR);

    if (centerTimeoutCount)
        centerTimeoutCount += 1;

    if (!centerOldHigh && (center > centerSchmittHigh.Value)) // On switch-to-high
    {
        centerOldHigh = true; // Switch current center state to high

        if((intersectionSignalRecent + 1) == INTERSECTION_COUNT_ORIGIN) // If the start/stop signal is encountered, toggle clock.
        // This is done on when it switches high (instead of waiting for timeout) to save a bit of clock-time.
        {
            lapTimer.toggle(0);
            if (!lapTimer.isEnabled(0))
            {
               // Stop motors before entering menu
                MotorSpeed(LEFT_MOTOR, 0);
                MotorSpeed(RIGHT_MOTOR, 0);

                Clear();
                Cursor(TOP, 0);
                Print("Finish!");
                currentState = menu;
                delay(800);
                return;
            }

        }

        switch(intersectionTurnFlag)
        {
            case INTERSECTION_COUNT_LEFT: // First intersection after left signal
            currentState = turnLeft;
            break;
            case INTERSECTION_COUNT_RIGHT: // First intersection after right signal
            currentState = turnRight;
            break;
            default: // Else
            currentState = moveStraight;
            intersectionSignalRecent += 1;
            break;
        }

        centerTimeoutCount = 0; // Stop timeout counter
        intersectionTurnFlag = 0; // Reset flag
    }
    else if (centerOldHigh && (center < centerSchmittLow.Value)) // On switch-to-low
    {
        centerOldHigh = false; // Swtich current center state to low
        centerTimeoutCount = 1; // Start timeout counter
    }

    if (centerTimeoutCount >= (centerTimeoutLimit.Value * 2)) // Timeout
    {
        if (intersectionTurnFlag < intersectionSignalRecent) // Do not let false signals effect the flag
            intersectionTurnFlag = intersectionSignalRecent; // Set flag

        intersectionSignalRecent = 0; // Reset signal counter
        centerTimeoutCount = 0; // Stop timeout counter
    }
}