This is an efficienyefficiency question to the following code, writtewritten in MS Visual in C#. If any explanation is missing, please let me know and I will add. What this part of the programmprogram does is:
- Button is pushed
- Motor starts moving (by sending 9-byte array with command)
- Waiting for Sensor to register a change in value
- Motor stops
- Motorposition is saved (command to get position is send and 9-byte array response is send by the motor), to have accesaccess to it later on and return there
Calls like rotate(), stop()rotate() and stop() are commands that write data into a 9-byte-array and write bytearray to serial port.
Now, my main issue is Step 5. I read on stackoverflowStack Overflow that "if you have to use wait()wait() and there is no point of using the DataReceivedDataReceived implementation". So should iI really get rid of this or is there a nice way to handle this? If I do it without the wait()wait() it saves the answer that is send after the stop command (every command also sends an answer).
And would it be more efficient to use DataReceived onDataReceived in step 3? In the beginning I save a value as new 0, and compare the current sensor readout here to this 0 value. Now for the code:
private void button13_Click(object sender, EventArgs e)
{
//rotate right speed
string Test = textBox4.Text;
byte[] A = new byte[9];
rotate(A, Test);
//read sensor
serialPort2.WriteLine("SR,00,002\r\n");
string b = serialPort2.ReadLine();
decimal caliber = decimal.Parse(Regex.Split(b, "SR,00,002,")[1]);
decimal b1 = 0;
do
{
serialPort2.WriteLine("SR,00,002\r\n");
string z = serialPort2.ReadLine();
b1 = decimal.Parse(Regex.Split(z, "SR,00,002,")[1]);
}
while (b1 <= caliber);
// stop motor
byte[] B = new byte[9];
stop(B);
//save position
System.Threading.Thread.Sleep(5000);
byte[] C = new byte[9];
getPosi(C);
System.Threading.Thread.Sleep(5000);
M = buf;
//move to 0
byte[] D = new byte[9];
MoveTo0(D);
}
//global variables
byte[] buf = new byte[9];
byte[] M = new byte[9];
private void button1_Click(object sender, EventArgs e) //Ports öffnen
{
serialPort3 = new SerialPort();
serialPort3.PortName = "COM6";
serialPort3.Handshake = Handshake.RequestToSend;
serialPort3.ReceivedBytesThreshold = 8;
serialPort3.DataReceived += new SerialDataReceivedEventHandler(DataRecievedHandler);
serialPort3.Open();
}
private void DataRecievedHandler(object sender, SerialDataReceivedEventArgs e)
{
SerialPort sp = (SerialPort)sender;
int bytes = serialPort3.BytesToRead;
byte[] buffer = new byte[bytes];
sp.Read(buffer, 0, bytes);
string hex = BitConverter.ToString(buffer);
hex.Replace("-", "");
MessageBox.Show(hex);
buf = buffer;
}
Thanks in advance for helpful tipps. CodeThe code is working as iI want it to for several input tests. I just thought there might be a better way than the wait()wait().