Reply To: Engine control – move 45°, wait, move 45°, wait

HomeForumsMonoBrick EV3 FirmwareEngine control – move 45°, wait, move 45°, waitReply To: Engine control – move 45°, wait, move 45°, wait

#5013
Author Image
Jacek S
Participant

Hi,

Few days ago I was trying to fix it on my own.

This is my version of pooling mechanism:


	    private bool started = false;
		private void PollFunction (Object source, ElapsedEventArgs e)
		{
			if (!Monitor.TryEnter (this)) {
				//cancel has the lock
				return;
			}
			//Do the polling
			if (IsRunning ()) {
			    start.Set ();
			    started = true;
			} 
			else 
			{
			    if (started)
			    {
			        stop.Set ();
			        started = false;
			    }
			}
			Monitor.Exit(this);
		}

	    protected void StartPooling()
	    {
                waitHandle.Reset();
                start.Set();
		stop.Set();
		started = false;
                stop.Reset();
                start.Reset();
	        timer.Start();
	    }

		protected WaitHandle WaitForMotorsToStartAndStop()
		{
			//Optimize the poll function to save this exstra thread
			(new Thread(() => {
				start.WaitOne();
				stop.WaitOne();
				timer.Stop();
				start.Reset();
				stop.Reset();
				waitHandle.Set();
		    })).Start();
			return waitHandle;
		}

And start pooling call in the speedprofile method:


		public WaitHandle SpeedProfile(sbyte speed, UInt32 rampUpSteps, UInt32 constantSpeedSteps, UInt32 rampDownSteps, bool brake)
		{
			output.SetPower (0);
                        StartPooling();
			output.SetStepSpeed (speed, rampUpSteps, constantSpeedSteps, rampDownSteps, brake);
			return WaitForMotorsToStartAndStop();
		}

I also noticed that LcdConsole.WriteLine method is not thread safe. There should be lock block:


		static public void WriteLine(string format, params Object[] arg)
		{
			if (cw == null)
				cw = new ConsoleWriter();
		    lock (cw)
		    {
		        cw.WriteLine(string.Format(format, arg));
		    }
		}

Jacek

Posted in

Make a donation