2015年10月5日月曜日

Wait signals and proceed

双方向で通信してる時にはこういうのって必要になることありますよね。
シリアル通信における待ちプログラムについて,MATLABとArduinoの両方で書いてみます。
Sometimes you needs to wait until certain signals come in serial communication. Here I'll describe it in Arduino and MATLAB codes.

一番簡単なのは,こうです。
The simplest one would be

@Arduino

Serial.begin(115200);
while (Serial.available() == 0) {
      delay(1);
}

// CODE //

@MATLAB

s = serial('COM1');
set(s,'BaudRate',115200);
fopen(s);
while (s.BytesAvailable==0)
      WaitSecs(0.001);
end

%% CODE %%

fclose(s);

2つのコードはほぼ同じであることが分かると思います。あとは,特定の文字が入力された時のみ次のステップに進むとかもありますね,書き方はたくさんありますが,例えばこうしてみます。
You can see the two codes are essentially the same. In another case, you have to proceed a program only after a particular character is input. You can write like this for example.

@Arduino

byte WaitingFlag = 1;
while (WaitingFlag == 1) {
    while (Serial.available() == 0) {
      delay(1);
    }
    int str = Serial.read();
    if (str == 'R') {
      WaitingFlag = 0;
    }
}

@MATLAB

WaitingFlag = 1;
while (WaitingFlag)
   while (s.BytesAvailable==0)
        WaitSecs(0.001);
   end
   if strmatch(fgets(s),'R')
        WaitingFlag = 0;
   end
end

どちらも,WaitingFlagが1の間はwhile文を繰り返します。ただし,その中にもう一つwhile文がありますので,何か信号が入ってくるまではここから出れません。出たと思ったら,if文によってそれが目的の文字かどうかが照合され,マッチしていたらWaitingFlagを変更して,while文を抜ける,というロジックになってます。
In both programs, the while sentence is repeated as long as Waitingflag = 1. However, before that, an additional while sentence loops until some signals come to the port. After signals come and processing exits from the while loop, the if sentence judges whether the character is expected one or not. If it is not, you cannot exit from the loop. lol