Advertisement
INOUETAICHI

Untitled

Dec 17th, 2019
344
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.19 KB | None | 0 0
  1. #define DEBUG_SEND 0
  2.  
  3. void rs485_send(){};
  4.  
  5. void rs485_send(){};
  6.  
  7.  
  8.  
  9.  
  10.  
  11. void rs485_send(byte _id, byte cmd, long top, long btm) {
  12.   digitalWrite(DE, HIGH);             // Driver Enable
  13.   delayMicroseconds(tZH);             // Driver Enable to Output High (us)
  14.  
  15.   byte b[12];
  16.   b[0] = 0x7E;                        // start byte
  17.   b[1] = _id;                         // id / id() とかぶるので _id とした
  18.   b[2] = cmd;                         // cmd
  19.   b[3] = (byte)(top >> 24);           // top HH
  20.   b[4] = (byte)(top >> 16);           // top HL
  21.   b[5] = (byte)(top >> 8);            // top LH
  22.   b[6] = (byte)top;                   // top LL
  23.   b[7] = (byte)(btm >> 24);           // btm HH
  24.   b[8] = (byte)(btm >> 16);           // btm HL
  25.   b[9] = (byte)(btm >> 8);            // btm LH
  26.   b[10] = (byte)btm;                  // btm LL
  27.   b[11] = 0;                          // チェックサムが入る箇所を初期化
  28.   for (int i = 0; i < 11; i++)        // チェックサム算出 b[1-10] を足し合わせる
  29.     b[11] += b[i];
  30.  
  31.   rs485.write(b[0]);                  // start byte
  32.   if (DEBUG_SEND) {
  33.     Serial.println();
  34.     Serial.print(b[0], HEX);
  35.     Serial.print(" ");
  36.   }
  37.   for (int i = 1; i < 12; i++)        // b[1-11]
  38.     rs485_write_esc(b[i]);            // スタートバイト以外はエスケープ処理を通す
  39.  
  40.   //rs485.flush();                      // rs485送信終了を待ってからDEをおろさないと送信が途中で切れる
  41.  
  42.   delayMicroseconds(tPLH);            // Driver Input to Output (us)
  43.   digitalWrite(DE, LOW);
  44. }
  45.  
  46. void rs485_write_esc(byte b) {
  47.   if (b == 0x7E) {                    // スタートバイト 0x7E が来た場合は
  48.     rs485.write(0x7D);                // 0x7D を送ってから
  49.     rs485.write(b ^ 0x20);            // 送信したいバイトと 0x20 の AND を送る
  50.     if (DEBUG_SEND) {
  51.       Serial.print(0x7D, HEX);
  52.       Serial.print(" ");
  53.       Serial.print(b ^ 0x20, HEX);
  54.       Serial.print(" ");
  55.     }
  56.   }
  57.   else {
  58.     rs485.write(b);                   // 0x7E 以外の場合はそのまま送信
  59.     if (DEBUG_SEND) {
  60.       Serial.print(b, HEX);
  61.       Serial.print(" ");
  62.     }
  63.   }
  64. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement