 //
-//  serial_sseg.ino
-//
-//  see also... 
-//    https://www.switch-science.com/catalog/742/
-//    http://morecatlab.akiba.coocan.jp/lab/index.php/aruino/7segduino/
+//  serial_sseg.ino - serial display control sketch for 7segduino
+//
+// github:
+//     https://gist.github.com/yoggy/80e47ff0932f3900c77f
+//
+// license:
+//     Copyright (c) 2015 yoggy <yoggy0@gmail.com>
+//     Released under the MIT license
+//     http://opensource.org/licenses/mit-license.php
+//
+// reference: 
+//     http://morecatlab.akiba.coocan.jp/lab/index.php/aruino/7segduino/
+//     https://github.com/kuwatay/7segduino
+//     https://www.switch-science.com/catalog/742/
+//     https://gist.github.com/yoggy/0365b24d193f9999c83e
 //
 
 // download & install SSeg library

  mySseg.begin();

  Serial.begin(9600);
  Serial.println("hello7seg");

  // hello
  buf[0] = 1;
  buf[1] = 2;
  buf[2] = 3;
  buf[3] = 4;
  buf_idx = 0;
  update7seg();
  for (int j = 0; j < 10; ++j) {
    for (int i = 0; i < 9999; ++i) {
      mySseg.update();
    }
  }

  // clear display (set blank)
  buf[0] = 10;
  buf[1] = 10;
  buf[2] = 10;
  buf[3] = 10;
  buf_idx = 0;
  update7seg();
}

void update7seg() {
  mySseg.writeRawData(patterns[buf[0]], patterns[buf[1]], patterns[buf[2]], patterns[buf[3]]);
  buf_idx = 0;
}

void loop()

    // protocol
    //   segd1234[CR][LF]
    if (mode == MODE_WAITING_S) {
      if (c == 's') change_mode(MODE_WAITING_E);
      else change_mode(MODE_WAITING_S);
    }
    else if (mode == MODE_WAITING_E) {
      if (c == 'e') change_mode(MODE_WAITING_G);
      else change_mode(MODE_WAITING_S);
    }
    else if (mode == MODE_WAITING_G) {
      if (c == 'g') change_mode(MODE_WAITING_D);
      else change_mode(MODE_WAITING_S);
    }
    else if (mode == MODE_WAITING_D) {
      if (c == 'd') change_mode(MODE_RECV_DIGIT);
      else change_mode(MODE_WAITING_S);
    }
    else {
      if (c == 0x0d) { // CR
        // nothing to do...
      }
      else if (c == 0x0a) { // LF
        update7seg();
        change_mode(MODE_WAITING_S);
      }
      else if (0x00 <= c && c <= 0x1f) {
        // invalid charactor data...
        change_mode(MODE_WAITING_S);
      }
      else if (c == '.' || c == ',') {
        int idx = buf_idx - 1;
        idx = idx < 0 ? 0 : idx;
        dot[idx] = 1;
      }
      else {
        buf[buf_idx] = c;
        if (buf_idx < 4) buf_idx ++;
      }
    }
  }
  mySseg.update();
}

