/**
 *  QRCode
 *
 *  A quick example of generating a QR code.
 *
 *  This prints the QR code to the serial monitor as solid blocks. Each module
 *  is two characters wide, since the monospace font used in the serial monitor
 *  is approximately twice as tall as wide.
 *
 */

#include "qrcode.h"

#define TEXT_MAX 254
#define QR_VERSION 1

void setup() {
    int i;
    Serial.begin(115200);    
    while(!Serial){}
    delay(2000);
    Serial.println("Start");
}

void loop() {
  static char t[TEXT_MAX+2]="";
  static int ptr=0;
  int d;
  if(Serial.available()){
    d=Serial.read();
    if(d>31){
      t[ptr]=d;
      ptr++;
      if(ptr>TEXT_MAX){ptr=TEXT_MAX;} //clip
      t[ptr]=0;
    }else if(d==13){
        Serial.println(t);
        showCode(t);
        ptr=0;
        t[0]=0;
      }
    }else if(d==8){ //backspace
      if(ptr>0){
        ptr--;
        t[ptr]=0;
    }
  }
}

void showCode(const char* s){

    // Start time
    uint32_t dt = millis();
    int result;
  
    // Create the QR code
    QRCode qrcode;
    uint8_t qrcodeData[qrcode_getBufferSize(QR_VERSION)];
    result=qrcode_initText(&qrcode, qrcodeData, QR_VERSION, 0, s);
  
    // Delta time
    dt = millis() - dt;
    Serial.printf("Result:%d\r\n",result);
    Serial.printf("QR Code Generation Time: %dms\r\n",dt);

    // Top quiet zone
    Serial.print("\n\n\n\n");

    for (uint8_t y = 0; y < qrcode.size; y++) {

        // Left quiet zone
        Serial.print("        ");

        // Each horizontal module
        for (uint8_t x = 0; x < qrcode.size; x++) {

            // Print each module (UTF-8 \u2588 is a solid block)
            Serial.print(qrcode_getModule(&qrcode, x, y) ? "\u2588\u2588": "  ");

        }

        Serial.print("\n");
    }
    // Bottom quiet zone
    Serial.print("\n\n\n\n");
}
