ricmoo / QRCode

QR code generation library in C, optimized for low-power devices, such as Arduino.
Other
638 stars 202 forks source link

Precomputing the QR codes #30

Open ardakdemir opened 2 years ago

ardakdemir commented 2 years ago

Hi!

First of all thanks for this amazing library. It helped a lot to display QR codes on an OLED using Arduino.

I have a question that might be too simple. I want to precompute the QR codes in order to save time. Is it possible to precompute and store them inside an array-like structure and draw them immediately.

The code works fine when I compute the QR code, i.e. call the qrcode_initText, and draw the image inside the same function call. But I failed to draw the QR codes properly with precomputing. For precomputing, I tried computing them inside the setup() function and then print them after a button press inside the loop().

Below are the code snippets.

setup():

...
QRCode qrcode;

void setup() {
  Serial.begin(BAUD_RATE);

  if (!display.begin(SSD1306_SWITCHCAPVCC, 0x3C)) { // Address 0x3D for 128x64
    Serial.println(F("SSD1306 allocation failed"));
    for (;;); // Don't proceed, loop forever
  }
  display.display();
  delay(2000);
  display.clearDisplay();
  display.setTextSize(3);             // Normal 1:1 pixel scale
  display.setTextColor(WHITE);        // Draw white text
  display.display();

  uint8_t qrcodeBytes[qrcode_getBufferSize(QR_VERSION)];
  qrcode_initText(&qrcode, qrcodeBytes, QR_VERSION, 0, "hello");

}

loop():

void loop() {

  if (Serial.available() > 0) {

    const uint8_t y0 = 10;
    const uint8_t x0 = 10;
    char data = Serial.read();
    if (data == 'Q') {
      display.clearDisplay();
      for (uint8_t y = 0; y < qrcode.size; y++)
      {
        for (uint8_t x = 0; x < qrcode.size; x++)
        {
          uint8_t pixel = 0;
          if (qrcode_getModule(&qrcode, x, y) )
          {
            /*Put black pixel*/
            pixel = 1;
          }
          else
          {
            /*White pixel*/
            pixel = 0;
          }

          display.drawPixel(x0 + 2 * x, y0 + y, pixel);
          display.drawPixel(x0 + 2 * x + 1, y0 + y, pixel);
        }
      }
      for (uint8_t y = 0; y < qrcode.size; y++) {
        for (uint8_t x = 0; x < qrcode.size; x++) {
          if (qrcode_getModule(&qrcode, x, y)) {
            Serial.print("**");
          } else {
            Serial.print("  ");
          }
        }
        Serial.print("\n");
      }

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

  display.display();
  delay(1000);
}

However, I get a broken QR (image below) when I do this. I suspect the values inside the qrCodeBytes get changed between setup and loop.

IMG_0035