I need to read a message coming from a CAN
network every 20ms
. For this purpose I made a function which works defined below. It's kind of work around, but does the job.
public void Read_CAN_RC_Message()
{
bool a = true;
while (a)
{
Stopwatch t = Stopwatch.StartNew();
// My actual Function Starts Here
int rMulti = CANbus.CAN_Receive_multiple_nonblock(recieveMsg, 5);
if (0 < rMulti)
{
count++;
for (int k = 0; k < rMulti; k++)
{
if (recieveMsg[k].id == 0x400)
{
currentX = 0;
currentY = 0;
currentX = currentX | recieveMsg[k].data[3];
currentX = (currentX << 8) | recieveMsg[k].data[2];
currentX = (currentX << 8) | recieveMsg[k].data[1];
currentX = (currentX << 8) | recieveMsg[k].data[0];
currentY = currentY | recieveMsg[k].data[7];
currentY = (currentY << 8) | recieveMsg[k].data[6];
currentY = (currentY << 8) | recieveMsg[k].data[5];
currentY = (currentY << 8) | recieveMsg[k].data[4];
}
// Function Ends here
int timestep = t.Elapsed.Milliseconds; // To measure Time Needded to complete the Operation
timeCheck.Rows.Add(timestep,str);
}
while (t.Elapsed < timer20ms)
{
// Nothing
}
}
}
I soon realized that the operation takes 2ms
to complete and for remaining 18ms
my processor is stuck in an infinite loop. So this operation requires its own separate thread which always works (using the Processor). Is there a neater a more professional way to do this. Please suggest. I need to run this application in a separate thread as it has to run always as soon as the application starts till it shuts down.