Home > database >  Scheduling communication with a slow device
Scheduling communication with a slow device

Time:03-12

Example C code algorithm

while(1)
{
   fun1();
   switch(fun2())
   case 1:  fun3();
   case 2 : fun4();
}

fun1()
{
  command;
  delay 1 sec;
  response;
  if failure, retry;
}

Here, fun1, fun2, etc are functions which are similar to each other. So, the issue is I need to wait 1 sec for response. How can I eliminate the waiting delay?

CodePudding user response:

You implement multi-threading.

Be it include a full blown RTOS, like FreeRTOS or Contiki or MbedOS or other.

Or use a thin layer of scheduling, like protothread or coroutines.

Or reorganize your code and implement in a form of a state-machine in an event-driven system, with scheduling in the form event/timer -> callback. Either using hardware interrupts, or with a custom library to handle the wait-for-event loop, like TimerEvent from MBed or libevent work.

CodePudding user response:

Implement fun1() as a state machine that performs a portion of its duties over many invocations. This example is rough but something like this.

typedef enum Status {
   CompletedSuccessfully = 0,
   RetryingDueToError = 1,
   Busy = 2
} Status;

typedef enum State {
   SendCommand = 0,
   Wait = 1,
   CheckResponse = 2,
   Done = 3
} State;


while(1)
{
   Status fun1_status = fun1();
   Status fun2_status = fun2();
   if (fun2_status == CompletedSuccessfully)
   {
      switch(fun2_status)
      case 1:  fun3();
      case 2 : fun4();
   }
}


Status fun1() {
   // state is static so that it retains its value on subsequent invocations.
   static State state = SendCommand;
   Status status = Busy;
  
   switch (state) {
      case SendCommand:
         command;
         state = Wait;
         status = Busy;
         break;

      case Wait:
         if (is time to check response?) {
            state = CheckResponse;
         }
         status = Busy;
         break;

      case CheckResponse:
         response;
         if (failure) {
            status = RetryingDueToError;
            state = SendCommand;
         }
         else {
            status = CompletedSuccessfully;
            state = Done;
         }
         break;

      case Done:
         status = CompletedSuccessfully;
         break;
   }

   return status;
}
  • Related