title: 2 Fingerprint scanner using 1 arduino

text:
# Question
Title: 2 Fingerprint scanner using 1 arduino
I have problem in using 2 fingerprint scanner in arduino mega, every time I need to register I need to go and register my fingerprint on each fingerprint module,

> what i am planning to do is when I registered on 1 fingerprint scanner then the other fingerprint module automatically registered the fingerprint and vise versa.

Can anyone help me with my project thanks. btw my project was already working but I have problems in registration of bio-metrics.

here is my code in verifying the registered fingerprint

```
#include <Adafruit_Fingerprint.h>
int door1 = 8;
int door2 = 11;
Adafruit_Fingerprint finger1 = Adafruit_Fingerprint(&Serial2);
//fplabas
Adafruit_Fingerprint finger2 = Adafruit_Fingerprint(&Serial3);
void setup() {
Serial.begin(9600);

pinMode(door2, OUTPUT);
  pinMode(door1, OUTPUT);
//  pinMode(Buzzer, OUTPUT);
//
  digitalWrite(door2, HIGH);
  digitalWrite(door1, HIGH);

 finger1.begin(57600);
  finger2.begin(57600);
    if (finger1.verifyPassword() || finger2.verifyPassword()) {
    Serial.println("Found fingerprint sensors!");
  } else {
    Serial.println("Did not find any fingerprint sensors :(");
    while (1) { delay(1); }
  }

  finger1.getTemplateCount();
  finger2.getTemplateCount();

  Serial.print("Fingerprint Sensor1 contains "); Serial.print(finger1.templateCount); Serial.println(" templates");
  Serial.print("Fingerprint Sensor2 contains "); Serial.print(finger2.templateCount); Serial.println(" templates");
  Serial.println("Waiting for valid finger...");
}

void loop () {
  getFingerprintdoor2();
  delay(50);
  //Fingerprint Sensor Labas
  getFingerprintdoor1();
  delay(50);
}

uint8_t getFingerprintdoor2() {
  uint8_t p = finger1.getImage();
  switch (p) {
    case FINGERPRINT_OK:
      //Serial.println("Image taken");
      break;
    case FINGERPRINT_NOFINGER:
     // Serial.println("No finger detected");
      return p;
    case FINGERPRINT_PACKETRECIEVEERR:
    //  Serial.println("Communication error");
      return p;
    case FINGERPRINT_IMAGEFAIL:
      //Serial.println("Imaging error");
      return p;
    default:
      //Serial.println("Unknown error");
      return p;
  }
  // OK success!

  p = finger1.image2Tz();
  switch (p) {
    case FINGERPRINT_OK:
      //Serial.println("Image converted");
      break;
    case FINGERPRINT_IMAGEMESS:
      //Serial.println("Image too messy");
      return p;
    case FINGERPRINT_PACKETRECIEVEERR:
     // Serial.println("Communication error");
      return p;
    case FINGERPRINT_FEATUREFAIL:
     // Serial.println("Could not find fingerprint features");
      return p;
    case FINGERPRINT_INVALIDIMAGE:
     // Serial.println("Could not find fingerprint features");
      return p;
    default:
      //Serial.println("Unknown error");
      return p;
  }

  // OK converted!
  p = finger1.fingerFastSearch();
  if (p == FINGERPRINT_OK) {
    Serial.println("Found a print match!");
    digitalWrite(door2, LOW);
//    sendsms(textForSMS + " Noah", f1001);
//    Serial.println(textForSMS);
//    Serial.println("message sent.");
    delay(3000);
    digitalWrite(door2, HIGH);
    delay(1000);
   // Serial.print(finger1.fingerID);
  } else if (p == FINGERPRINT_PACKETRECIEVEERR) {
    //Serial.println("Communication error");
    return p;
  } else if (p == FINGERPRINT_NOTFOUND) {
//    Serial.println("Did not find a match");
//    digitalWrite(Buzzer,LOW);
//    delay(1000);
//    digitalWrite(Buzzer,HIGH);
    return p;
  } else {
    //Serial.println("Unknown error");
    return p;
  }

  return finger1.fingerID;
}

uint8_t getFingerprintdoor1() {
  uint8_t p = finger2.getImage();
  switch (p) {
    case FINGERPRINT_OK:
      //Serial.println("Image taken");
      break;
    case FINGERPRINT_NOFINGER:
     // Serial.println("No finger detected");
      return p;
    case FINGERPRINT_PACKETRECIEVEERR:
    //  Serial.println("Communication error");
      return p;
    case FINGERPRINT_IMAGEFAIL:
      //Serial.println("Imaging error");
      return p;
    default:
      //Serial.println("Unknown error");
      return p;
  }

  // OK success!

  p = finger2.image2Tz();
  switch (p) {
    case FINGERPRINT_OK:
      //Serial.println("Image converted");
      break;
    case FINGERPRINT_IMAGEMESS:
      //Serial.println("Image too messy");
      return p;
    case FINGERPRINT_PACKETRECIEVEERR:
     // Serial.println("Communication error");
      return p;
    case FINGERPRINT_FEATUREFAIL:
     // Serial.println("Could not find fingerprint features");
      return p;
    case FINGERPRINT_INVALIDIMAGE:
     // Serial.println("Could not find fingerprint features");
      return p;
    default:
      //Serial.println("Unknown error");
      return p;
  }

  // OK converted!
  p = finger2.fingerFastSearch();
  if (p == FINGERPRINT_OK) {
    Serial.println("Found a print match!");

    digitalWrite(door1, LOW);

   delay(5000);
    digitalWrite(door1, HIGH);

  } else if (p == FINGERPRINT_PACKETRECIEVEERR) {
    //Serial.println("Communication error");
    return p;
  } else if (p == FINGERPRINT_NOTFOUND) {

    return p;
  } else {
    //Serial.println("Unknown error");
    return p;
  }

  // found a match!
  return finger2.fingerID;
}

```

And here is the problem code where I need to register on both Fingerprint scanner:

```
#include <Adafruit_Fingerprint.h>
Adafruit_Fingerprint finger = Adafruit_Fingerprint(&Serial2);

Adafruit_Fingerprint finger2 = Adafruit_Fingerprint(&Serial3);

uint8_t id;

void setup()
{
  Serial.begin(9600);
  while (!Serial);  // For Yun/Leo/Micro/Zero/...
  delay(100);
  Serial.println("\n\nAdafruit Fingerprint sensor enrollment");

  // set the data rate for the sensor serial port
  finger.begin(57600);

  if (finger.verifyPassword()) {
    Serial.println("Found fingerprint sensor!");
  } else {
    Serial.println("Did not find fingerprint sensor :(");
    while (1) { delay(1); }
  }
}

uint8_t readnumber(void) {
  uint8_t num = 0;

  while (num == 0) {
    while (! Serial.available());
    num = Serial.parseInt();
  }
  return num;
}

void loop()
{
  Serial.println("Ready to enroll a fingerprint!");
  Serial.println("Please type in the ID # (from 1 to 127) you want to save this finger as...");

 if (Serial.available()>0)
   switch(Serial.read())
  {
    case 'A':

        id = readnumber();
        if (id == 0) {
           return;
        }
        Serial.print("Enrolling ID #");
        Serial.println(id);

        while (!  getFingerprintEnroll1() );

      break;

       case 'B':

        id = readnumber();
        if (id == 0) {
           return;
        }
        Serial.print("Enrolling ID #");
        Serial.println(id);

        while (!  getFingerprintEnroll2() );

      break;

}

}

uint8_t getFingerprintEnroll1() {

  int p = -1;
  Serial.print("Waiting for valid finger to enroll as #"); Serial.println(id);
  while (p != FINGERPRINT_OK) {
    p = finger.getImage();
    switch (p) {
    case FINGERPRINT_OK:
      Serial.println("Image taken");
      break;
    case FINGERPRINT_NOFINGER:
      Serial.println(".");
      break;
    case FINGERPRINT_PACKETRECIEVEERR:
      Serial.println("Communication error");
      break;
    case FINGERPRINT_IMAGEFAIL:
      Serial.println("Imaging error");
      break;
    default:
      Serial.println("Unknown error");
      break;
    }
  }

  // OK success!

  p = finger.image2Tz(1);
  switch (p) {
    case FINGERPRINT_OK:
      Serial.println("Image converted");
      break;
    case FINGERPRINT_IMAGEMESS:
      Serial.println("Image too messy");
      return p;
    case FINGERPRINT_PACKETRECIEVEERR:
      Serial.println("Communication error");
      return p;
    case FINGERPRINT_FEATUREFAIL:
      Serial.println("Could not find fingerprint features");
      return p;
    case FINGERPRINT_INVALIDIMAGE:
      Serial.println("Could not find fingerprint features");
      return p;
    default:
      Serial.println("Unknown error");
      return p;
  }

  Serial.println("Remove finger");
  delay(2000);
  p = 0;
  while (p != FINGERPRINT_NOFINGER) {
    p = finger.getImage();
  }
  Serial.print("ID "); Serial.println(id);
  p = -1;
  Serial.println("Place same finger again");
  while (p != FINGERPRINT_OK) {
    p = finger.getImage();
    switch (p) {
    case FINGERPRINT_OK:
      Serial.println("Image taken");
      break;
    case FINGERPRINT_NOFINGER:
      Serial.print(".");
      break;
    case FINGERPRINT_PACKETRECIEVEERR:
      Serial.println("Communication error");
      break;
    case FINGERPRINT_IMAGEFAIL:
      Serial.println("Imaging error");
      break;
    default:
      Serial.println("Unknown error");
      break;
    }
  }

  // OK success!

  p = finger.image2Tz(2);
  switch (p) {
    case FINGERPRINT_OK:
      Serial.println("Image converted");
      break;
    case FINGERPRINT_IMAGEMESS:
      Serial.println("Image too messy");
      return p;
    case FINGERPRINT_PACKETRECIEVEERR:
      Serial.println("Communication error");
      return p;
    case FINGERPRINT_FEATUREFAIL:
      Serial.println("Could not find fingerprint features");
      return p;
    case FINGERPRINT_INVALIDIMAGE:
      Serial.println("Could not find fingerprint features");
      return p;
    default:
      Serial.println("Unknown error");
      return p;
  }

  // OK converted!
  Serial.print("Creating model for #");  Serial.println(id);

  p = finger.createModel();
  if (p == FINGERPRINT_OK) {
    Serial.println("Prints matched!");
  } else if (p == FINGERPRINT_PACKETRECIEVEERR) {
    Serial.println("Communication error");
    return p;
  } else if (p == FINGERPRINT_ENROLLMISMATCH) {
    Serial.println("Fingerprints did not match");
    return p;
  } else {
    Serial.println("Unknown error");
    return p;
  }

  Serial.print("ID "); Serial.println(id);
  p = finger.storeModel(id);
  if (p == FINGERPRINT_OK) {
    Serial.println("Stored!");
  } else if (p == FINGERPRINT_PACKETRECIEVEERR) {
    Serial.println("Communication error");
    return p;
  } else if (p == FINGERPRINT_BADLOCATION) {
    Serial.println("Could not store in that location");
    return p;
  } else if (p == FINGERPRINT_FLASHERR) {
    Serial.println("Error writing to flash");
    return p;
  } else {
    Serial.println("Unknown error");
    return p;
  }
}

uint8_t getFingerprintEnroll2() {

  int p = -1;
  Serial.print("Waiting for valid finger to enroll as #"); Serial.println(id);
  while (p != FINGERPRINT_OK) {
    p = finger2.getImage();
    switch (p) {
    case FINGERPRINT_OK:
      Serial.println("Image taken");
      break;
    case FINGERPRINT_NOFINGER:
      Serial.println(".");
      break;
    case FINGERPRINT_PACKETRECIEVEERR:
      Serial.println("Communication error");
      break;
    case FINGERPRINT_IMAGEFAIL:
      Serial.println("Imaging error");
      break;
    default:
      Serial.println("Unknown error");
      break;
    }
  }

  // OK success!

  p = finger2.image2Tz(1);
  switch (p) {
    case FINGERPRINT_OK:
      Serial.println("Image converted");
      break;
    case FINGERPRINT_IMAGEMESS:
      Serial.println("Image too messy");
      return p;
    case FINGERPRINT_PACKETRECIEVEERR:
      Serial.println("Communication error");
      return p;
    case FINGERPRINT_FEATUREFAIL:
      Serial.println("Could not find fingerprint features");
      return p;
    case FINGERPRINT_INVALIDIMAGE:
      Serial.println("Could not find fingerprint features");
      return p;
    default:
      Serial.println("Unknown error");
      return p;
  }

  Serial.println("Remove finger");
  delay(2000);
  p = 0;
  while (p != FINGERPRINT_NOFINGER) {
    p = finger2.getImage();
  }
  Serial.print("ID "); Serial.println(id);
  p = -1;
  Serial.println("Place same finger again");
  while (p != FINGERPRINT_OK) {
    p = finger2.getImage();
    switch (p) {
    case FINGERPRINT_OK:
      Serial.println("Image taken");
      break;
    case FINGERPRINT_NOFINGER:
      Serial.print(".");
      break;
    case FINGERPRINT_PACKETRECIEVEERR:
      Serial.println("Communication error");
      break;
    case FINGERPRINT_IMAGEFAIL:
      Serial.println("Imaging error");
      break;
    default:
      Serial.println("Unknown error");
      break;
    }
  }

  // OK success!

  p = finger2.image2Tz(2);
  switch (p) {
    case FINGERPRINT_OK:
      Serial.println("Image converted");
      break;
    case FINGERPRINT_IMAGEMESS:
      Serial.println("Image too messy");
      return p;
    case FINGERPRINT_PACKETRECIEVEERR:
      Serial.println("Communication error");
      return p;
    case FINGERPRINT_FEATUREFAIL:
      Serial.println("Could not find fingerprint features");
      return p;
    case FINGERPRINT_INVALIDIMAGE:
      Serial.println("Could not find fingerprint features");
      return p;
    default:
      Serial.println("Unknown error");
      return p;
  }

  // OK converted!
  Serial.print("Creating model for #");  Serial.println(id);

  p = finger2.createModel();
  if (p == FINGERPRINT_OK) {
    Serial.println("Prints matched!");
  } else if (p == FINGERPRINT_PACKETRECIEVEERR) {
    Serial.println("Communication error");
    return p;
  } else if (p == FINGERPRINT_ENROLLMISMATCH) {
    Serial.println("Fingerprints did not match");
    return p;
  } else {
    Serial.println("Unknown error");
    return p;
  }

  Serial.print("ID "); Serial.println(id);
  p = finger2.storeModel(id);
  if (p == FINGERPRINT_OK) {
    Serial.println("Stored!");
  } else if (p == FINGERPRINT_PACKETRECIEVEERR) {
    Serial.println("Communication error");
    return p;
  } else if (p == FINGERPRINT_BADLOCATION) {
    Serial.println("Could not store in that location");
    return p;
  } else if (p == FINGERPRINT_FLASHERR) {
    Serial.println("Error writing to flash");
    return p;
  } else {
    Serial.println("Unknown error");
    return p;
  }
}

```

Please help I am stuck in this situation..

# Answer
The library, that you are using, doesn't seem to support exporting or importing fingerprints. Though if you look into the user manual of the fingerprint sensor at the Adafruit site, there are two commands mentioned, that seem to do what you need:

> 6.2.2 Upload image: UpImage
>
> Description: to upload the image in Img\_Buffer to upper computer. Refer to 1.1.1 for more about image buffer.
>
> 6.2.3 Download the image: DownImage
>
> Description: to download image from upper computer to Img\_Buffer. Refer to 1.1.1 for more about the image buffer.

These commands can be used to read or write the image buffer, where an image is stored, when it was taken by the sensor (this is only about the image data, not about the recognition or enrolling; that has to be done after loading the image to the buffer). I could not find corresponding functions in the library, so I guess it doesn't support this. So, to get what you need, you need to stop using the library and handle the things yourself (or - maybe better - extend the library to incorporate that feature).

The manual has no good documentation about these functions and the datasheet, that Adafruit has, is in Chinese, so I couldn't read it. You will need to try it out and see, what you get, when issuing the mentioned commands (unless you can read Chinese and there is more useful information in that datasheet).

I guess after requesting the upload of the current image, the module will send data packets in the configured package size, until it has transferred the whole image (Note, that it will only send 4 bits for every pixel over UART, meaning 16-greyscale image). After than you could request the download on the other module. After the acknowledgement packet, I guess you need to send the image data in the same format, as you received it from the first module, in packets with the configured packet size.

When configured to the same packet size, you could request upload and download at the same time for each module and simply let the packets pass through. After transferring the image, you can start the recognition on both modules.
> 1 votes

---
Tags: arduino-mega
---


# Question
Title: Home made drum kit - How can I speed up the response time after my sensor gets triggered?
I am trying to make a psudo drum kit with my Arduino Due and a couple Force Sensitive Resistors (activated with my fingers, no drum sticks). So far in my testing I'm only using one FSR. I've attached an SD Card reader and put a WAV File on there (44100 Hz, 16-bit, stereo). In my 'Loop', I read in the resistance of the FSR to know if it's been triggered, then I play the WAV file accordingly. It works but its not that fast. If this project is going to work, the response time needs to be much faster.

Here's my code:

```
#include "SD.h" //Lib to read SD card
#include "SPI.h" //SPI lib for SD card
#include <Audio.h>

#define SD_ChipSelectPin 2

const int FSR_PIN = A0; // Pin connected to FSR/resistor divider

const float VCC = 4.875;
const float R_DIV = 10000.0;

void setup()
{
  Serial.println("Starting Drum Kit!");
  Serial.begin(9600);
  while (!Serial) {}

  pinMode(FSR_PIN, INPUT);
  pinMode(LED_PIN, OUTPUT);

  Serial.print("Initializing SD Card...");
  if (!SD.begin(SD_ChipSelectPin)) {
    Serial.println("FAILED!");
    while(true);
  }
  Serial.println("done");

  // 44100kHz stereo => 88200 sample rate
  // 100 mSec of prebuffering.
  Audio.begin(88200, 100);

  void loop()
{
  File snare_file;
  short snare_buffer[1024];
  int fsrADC = analogRead(FSR_PIN);
  if (fsrADC > 20) // If the analog reading is non-zero
  {
    Serial.println(String(fsrADC));

    snare_file = SD.open("606snare.wav");
    while (snare_file.available()) {
      snare_file.read(snare_buffer, 1024);
      Audio.prepare(snare_buffer, 1024, 1024);
      Audio.write(snare_buffer, 1024);
    }
    snare_file.close();
  }
}

```

If I hold down the sensor (constant triggering), the fastest that the file plays is about every half second. Here's the Serial output:

```
15:12:28.453 -> Initializing SD Card...done
15:12:28.487 -> 1023
15:12:28.930 -> 1023
15:12:29.510 -> 1023
15:12:30.050 -> 1023
15:12:30.628 -> 1023
15:12:31.136 -> 1023
15:12:31.744 -> 1023
15:12:32.328 -> 1023
15:12:32.834 -> 1023
15:12:33.411 -> 1023
15:12:33.955 -> 1023

```

I've tried playing around with loading the file and buffer in the `setup` section but I can't get it to work properly. There's not a whole lot of documentation on the `Audio` library either.

If you know of a better way to speed this up, or if I should be using a different library, please let me know.

# Answer
> 1 votes
This is not really a 'solution', but it might help you in finding out where the real problem is.

Check out which of the statements in the `loop` function uses up the most time, probably;

1. int fsrADC = analogRead(FSR\_PIN);
2. Serial.println(String(fsrADC));
3. snare\_file = SD.open("606snare.wav");
4. while (snare\_file.available()) {
5. snare\_file.read(snare\_buffer, 1024);
6. Audio.prepare(snare\_buffer, 1024, 1024);
7. Audio.write(snare\_buffer, 1024);
8. snare\_file.close()

Try improving the most time consuming item if possible.

Some possibilities you can try in the steps above:

1. Do not use AnalogRead but direct port commands
2. Remove this completely or at least remove the String instance.
3. Not much you can do here, except not using a file system but raw SD read (you might have problems getting the files on your SD) without a dedicated program on your PC
4. Not sure about improving this one
5. Read less bytes, although it might even worsen things. Or read the bytes BEFORE waiting on the trigger (if you know which sample will be played).
6. Execute the prepare as before the trigger as 5 if possible.
7. Not sure about this... High likely you cannot keep too many files open at the same time.

Afaik in my synthesizer (Korg Kronos), it reads from all samples the initial part, meaning it can startup the data from RAM, while the rest is read through SSD (in your case SD). However, you might not have enough memory in an Arduino for that.

---
Tags: arduino-due, audio
---


title: problem with decrement in a loop

text:
# Question
Title: problem with decrement in a loop
I am trying to write a sketch wherein the led brightness increases in increments of 15 until it reaches 255. At that point I want to make decrements of 15 until it reaches 0. The increment part of the program works well but the decrement part goes haywire. It gets stuck between 255 & 240. I am not sure how can I fix it. Could you please tell how can I make it work?

Here is my sketch:

```
int led = 9; //led pin
int fade = 0; // pwm value

void setup() {
  // put your setup code here, to run once:

  Serial.begin(9600);
  pinMode(led, OUTPUT);
}

void loop() {
  // put your main code here, to run repeatedly:

   analogWrite(led,fade);
   fade += 15;
   Serial.println(fade);
   delay(250);

  if (fade >= 240){
    fade = fade - 15;
    analogWrite(led, fade);
    Serial.println(fade);
    delay(250);
  }

}

```

# Answer
The problem is that you add 15, and than if it's \>= 240, you decrease 15, so it will not change (I wouldn't consider it haywire though).

You can better use a direction sign. Below is only the relevant code (not the GPIO functionality). What it does in the loop is, in case up is true, it adds fifteen, otherwise it subtracts 15. When 255 is reached, it starts counting down (`up` is false), when reaching 0, it starts counting up (`up` is true). This only works if 255 / the amount to add/subtracts reaches exactly 255, otherwise you have to check for \<= 0 and \>= 255.

```
bool up = true;
int fade = 0;

void loop()
{
    fade += up ? 15 : -15;
    if (fade == 0)
    {
      up = true;
    }
    else if (fade == 255)
    {
      up = false;
    }
}

```

**Not considered good coding practices:**

The last `if` statement can be substituted for the following line, which means: if going up and 255 is reached, go down, else if going down and 0 is reached, go up, otherwise don't change `direction`. But it is much less readable, so I prefer the longer `if` statement.

```
up = (up && (fade == 255)) ? false : ((!up && (fade == 0)) ? true : up);

```

Another version: if `fade` is 0 or 255 (only two possibilities), go up if 0 is reached, else (can only be 255) go down, else don't change.

```
up = (fade % 255 == 0) ? (fade == 0) : up;

```
> 4 votes

# Answer
The `if` condition is causing the issue. When the global variable `fade` reaches `240`, upon entering the `loop()`, you are incrementing it by `15`, making `fade = 255`. So, the `if` condition becomes `true` and `15` is subtracted from `255` making `fade` to be equal to `240` again. This keeps repeating and hence the value `fade` variable is stuck between the values `240` and `255`.
> 1 votes

---
Tags: arduino-ide, pwm, loop
---


# Question
Title: How to dim background LEDs on TFT display with ILI9341
I have bought a 2.5" TFT shield online, which is equipped with the ILI9341 controller. I need to dim the intensity of the background LEDs to match ambient light.

This particular shield does not provide a pin to control the intensity of the LEDs with PWM via a separate input, so I need to dim the background LEDs of this display via software.

The zip file with the libraries can be downloaded here.

Does one of you know how can issue a command to the TFT display to dim the background LEDs?

Thanks in advance!

# UPDATE 1:

I wrote a new function to set the display's brightness by controlling the background LEDs, but something is missing as I can seem to be writing correctly to the display. So I'm trying to get the display to answer to a known command first, like 0x28 (Display Off).

The new function is defined in Adafruit\_TFTLCD.cpp:

```
// Set display brightness (background LED's)
void Adafruit_TFTLCD::setDisplayBrightness(uint8_t x) {
  // Try with 0x28 (Display Off) to see if display reacts
  writeRegister8(0x28, 0);
  return;
}

```

The function prototype is defined in Adafruit\_TFTLCD.h

```
// New functions
void setDisplayBrightness(uint8_t x);

```

Then I call the function in my main loop. To make sure, I first write some rectangles on screen, wait 5 seconds, then fill the screen with blue, call the new function and enter an endless loop so no other commands can interfere:

```
  tft.fillScreen(BLUE);
  tft.setDisplayBrightness(10); // Which really is command 0x28 to test

```

Any clues what I might be missing?

Thanks!

UPDATE 2:

I got so far as to have the ILI9341 react to some commands, but not all the time, and not to all commands. I suspect there is something in the way you issue the commands that I'm missing( timing?, sequence?, other?)

Here is what I have found out so far:

I can get the display to react to the Display Off command (0x28), but only when I issue it in the begin(..) function. So, the original code in Adafruit\_TFTLCD.cpp is like this:

```
void Adafruit_TFTLCD::begin(uint16_t id) {
...
writeRegister8(ILI9341_DISPLAYON, 0);
delay(500);

```

If I change it to the following the display reacts by remaining white:

```
void Adafruit_TFTLCD::begin(uint16_t id) {
...
writeRegister8(ILI9341_DISPLAYON, 0);
writeRegister8(ILI9341_DISPLAYOFF, 0); // Display off is declared as 0x28
delay(500);

```

So, I have a reaction to command 28h.

Then I tried function 0x51 like this in the begin(...) function:

```
void Adafruit_TFTLCD::begin(uint16_t id) {
...
writeRegister8(ILI9341_DISPLAYON, 0);
delay(500);
writeRegister8(0x51, 0x80); // Test command 0x51 - background intensity
delay(500);

```

To no effect :-(

I even added command 0xBE (background PWM frequency) to see if it had any effect, but nothing :-(

```
void Adafruit_TFTLCD::begin(uint16_t id) {
  ...
  writeRegister8(ILI9341_DISPLAYON, 0);
  writeRegister8(0xbe, 0x80);
  delay(500);
  writeRegister8(0x51, 0x0);
  delay(500);

```

Also if I issue the 0x28 command:

```
writeRegister8(ILI9341_DISPLAYOFF, 0)

```

elsewhere in Adafruit\_TFTLCD (e.g. in FillScreen, Fill Rect etc, it doesn't work either).

Any ideas? They would be highly appreciated!

# Answer
> 3 votes
I got in contact with the manufacturer of the shield, they informed that the background LEDs are hardwired and not controllable via the ILI9341. So, it is not possible to dim the background light in this shield

:-(

I will look for another TFT shield and make sure it's dimmable before buying.

# Answer
> 1 votes
Most of thees cheap Chinese LCD modules have the LED backlight hardwired to Vcc and GND and cannot be controlled.

However, after inspecting the module I have and some similar ones online I found that most have the Back-light LEDs pins available through the LCD panel flex cable. If yours is similar to the one in the picture then you will notice that the main flex cable is for the LCD itself, and there are usually two other flex cables connected to it. The one on the left is for touch panel (if equipped), and the one of the right is for the back light LEDs (sometimes it is connected on the backside of the flex).

In this panel and on mine (a little different from this) they are labeled as K1, K2, K3 and K4 which are mostly the Cathode side of the LED (negative side) and they are exposed as separate pins in the main flex cable, while the Anode is soldered to the main flex cable Vcc plane and cannot be easily accessed without desoldering the LED flex cable.

So in ordered to control the backlight you have to cut the trace on the PCB (not the flex cable) and connect it to a transistor which you control through the Arduino.

* Double check the polarity in your LCD panel, it could be different from mine.

# Answer
> 0 votes
It looks like it should be controllable with command 0x51.

I would modify the library and add a new method to the `Adafruit_ILI9341_8bit_AS` class - something like:

```
void Adafruit_ILI9341_8bit_AS::setBacklight(uint8_t brightness) {
    writeRegister8(0x51, brightness);
}

```

Then you can change the brightness by calling that method on your TFT object in your sketch. (Don't forget to add the prototype to the class definition in the header file of course).

# Answer
> 0 votes
After looking at the schematic (mine is different) but on pin 16 is labeled as BL. If that is indeed the power for the LED backlights then a voltage applied to it should vary the brightness. Caution:You need to know how much current the LEDs are pulling. If over the limit for a PWM pin you will have to run it through a transistor to boost the current.

# Answer
> 0 votes
I have successfully dimmed the backlight on a ili9341 by simply modulating the pin the LED pin is connected to.

Note, I am using a teensy 3.2 your mileage may vary.

```
ledPin=32;

void loop() {
analogWrite(ledPin, 60);

```

---
Tags: tft
---


# Question
Title: Reading Buffer from Software-Serial & Writing to Serial
My progress so far:

```
#include <SoftwareSerial.h>

SoftwareSerial ttySerial(10, 11); // RX, TX
byte buffer;

void setup()
{
  // Open serial communications and wait for port to open:
  Serial.begin(115200);
  while (!Serial) {
    ; // wait for serial port to connect. Needed for Native USB only
  }

  Serial.println("Serial Initialized");

  //Set the data rate for the SoftwareSerial port
  ttySerial.begin(115200);
  ttySerial.println("tty Initialized");
}

void loop()
{
  ttySerial.listen();
  while (ttySerial.available())
    //byte buffer = ttySerial.read();
    //Serial.write(buffer);
    Serial.write(ttySerial.read());

//    if (Serial.available())
//      ttySerial.write(Serial.read());
}

```

I am really confused because if I write the data as the as the buffer I have defined, the serial monitor goes crazy. If I upload the code as shown, I don't get anything weird in the monitor but the behavior is not what I expect.

I am writing to the software-serial on RX10 & TX11 (from javascript) the following data:
Buffer.from(`[0, 0, 4, 0, 0, 0, 0, 0]`) (keystroke "a")

The `Buffer.from` method comes from `node` using the `serialport` `npm` module. (This is basically irrelevant since sending the data from `Buffer.from('test')` works and is output to the monitor.

As you can see, the buffer is 1 byte (the array forming the 8 bits). Why is the buffer not read as "a" in the monitor? Is it because the Micro has an abstract HID report descriptor (see below)?

Additionally, what does `Serial.write(...)` represent? I.e. when I close the Arduino IDE serial monitor, will my Arduino Micro automatically assume its HID function and write the data as an HID device? S

I know there are already `keyboard` and `mouse` HID libraries but I already have code that generates the raw HID data that I would prefer to utilize. Note that the buffer described above comes from the HID report descriptor for a generic keyboard i.e. the "4" is not merely the ASCII code for "a". Explained Here Maybe I can use https://www.arduino.cc/en/Reference/HID ?

Thanks in advance!

EDIT 1: This is the output I see from the code as shown (without the monitor "going crazy")

```
19:51:03.017 -> Serial Initialized
19:51:13.932 -> //Where I was hoping to see "a"

```

EDIT 2: I found the report descriptor in `Keyboard.cpp`:

```
  //  Keyboard
    0x05, 0x01,                    // USAGE_PAGE (Generic Desktop)  // 47
    0x09, 0x06,                    // USAGE (Keyboard)
    0xa1, 0x01,                    // COLLECTION (Application)
    0x85, 0x02,                    //   REPORT_ID (2)
    0x05, 0x07,                    //   USAGE_PAGE (Keyboard)

  0x19, 0xe0,                    //   USAGE_MINIMUM (Keyboard LeftControl)
    0x29, 0xe7,                    //   USAGE_MAXIMUM (Keyboard Right GUI)
    0x15, 0x00,                    //   LOGICAL_MINIMUM (0)
    0x25, 0x01,                    //   LOGICAL_MAXIMUM (1)
    0x75, 0x01,                    //   REPORT_SIZE (1)

  0x95, 0x08,                    //   REPORT_COUNT (8)
    0x81, 0x02,                    //   INPUT (Data,Var,Abs)
    0x95, 0x01,                    //   REPORT_COUNT (1)
    0x75, 0x08,                    //   REPORT_SIZE (8)
    0x81, 0x03,                    //   INPUT (Cnst,Var,Abs)

  0x95, 0x06,                    //   REPORT_COUNT (6)
    0x75, 0x08,                    //   REPORT_SIZE (8)
    0x15, 0x00,                    //   LOGICAL_MINIMUM (0)
    0x25, 0x73,                    //   LOGICAL_MAXIMUM (115)
    0x05, 0x07,                    //   USAGE_PAGE (Keyboard)

  0x19, 0x00,                    //   USAGE_MINIMUM (Reserved (no event indicated))
    0x29, 0x73,                    //   USAGE_MAXIMUM (Keyboard Application)
    0x81, 0x00,                    //   INPUT (Data,Ary,Abs)
    0xc0,                          // END_COLLECTION

```

I will need to compare this to the data I would be sending to `Keyboard.write()`

# Answer
Don't use listen() this way. It clears the receive buffer. You loose the data received before listen() call.

You have only one SoftwareSerial instance so you don't need to call listen(). The listen() function clears the receive buffer because there is only one buffer for all SoftwareSerial instances.
> 0 votes

---
Tags: serial, softwareserial, arduino-micro, bytes, hid
---


# Question
Title: How to get Transmission package Timestamp from ESP8266
I am trying to make an Indoor positioning system using ESP8266 as a beacon, how do I get the transmission package timestamp from router to ESP8266 and vice-versa?

Thank you in advance for any advice

# Answer
You can use timestamp from NTP client and attach it

Install NTPclient library from Arduino library manager This library uses WiFiUdp library to connect to the NTP server, so download that too

Then you can just update the time every time your sending/receiving something and log it as and how you see fit!
> -1 votes

---
Tags: esp8266, wifi
---


# Question
Title: Using ALL the analog pins on Mega for Servo
I wish to use ALL the Analog pins on a Mega2560 R3 to control Servo's, all is well up to and including A9, but from there on nothing. {sound familiar} this is apparently not a new problem. I have tried Servo.h and MegaServo.h but still no luck, does anyone have info on a library that will do this or a method to get around it........all the pins on the end buss are used for other purposes and are not available. I can post the code, but first just asking the general questions. Thanks Doug

# Answer
OK..Solved...tried a library I had previously discarded for another project but it works with this situation..SoftwareServo ....(had also tried versions of Servo and MegaServo with no luck) I have attached a proven sketch that shows the method using arrays (as i have 16 servos to control) hope this is of use to others.

```
    /*This sketch will enable you to use ALL of the Analog pins on a Mega2560 to control a Servo
 * it uses the Arrays and the Softwareservo.h as the other Servo libraries do not support
 * Mega Analog above A9
 * this is the only method i have found that works
 * hope this is of use to others.
 */
#include <SoftwareServo.h>

SoftwareServo servos[16];  // create servo object to control a servo

int pos=0;
int servoPins[] = {A0,A1,A2,A3,A4,A5,A6,A7,A8,A9,A10,A11,A12,A13,A14,A15};                    //servo pin numbers
int servoPosMin[] = {80,80,80,80,80,80,80,80,80,89,80,81,80,70,80,45};                        //servo lower setting to suit individual servo
int servoPosMax[] = {100,100,100,100,100,100,100,100,100,100,100,100,100,110,100,160};        //servo upper setting to suit individual servo
boolean refresh = false;  // toggle refresh on/off
int m = 0;
int p = 0;
void setup()
{
  Serial.begin(115200);
  for (m=0;m < 16;m++) {
      // attaches the servo on pin to the servo object
    servos[m].attach(servoPins[m]);
      // init angle of servo inbetween two limitations
    servos[m].write(((servoPosMax[m]+servoPosMin[m])/2));
    Serial.println(m);
    delay(10);
      SoftwareServo::refresh();
  }
}
void loop()
{
  for (p=0;p < 16;p++) {

    for (pos = servoPosMin[p]; pos <= servoPosMax[p]; pos += 1) { // goes from 0 degrees to 180 degrees
      servos[p].write(pos);                                       // tell servo to go to position in variable 'pos'
      delay(15);                                                  // waits 15ms for the servo to reach the position
      Refresh();
  }
    for (pos = servoPosMax[p]; pos >= servoPosMin[p]; pos -= 1) { // goes from 180 degrees to 0 degrees
      servos[p].write(pos);                                       // tell servo to go to position in variable 'pos'
      delay(15);                                                  // waits 15ms for the servo to reach the position
      Refresh();
    }
  }
}
void Refresh() {
  refresh = refresh ? false : true;                             // set refresh one time / 2
  if (refresh) SoftwareServo::refresh();
  Serial.print("Servo Number = ");
  Serial.println(p);
  Serial.print("  Angle =  ");
  Serial.println(pos);
}

```
> 1 votes

# Answer
There is a relatively easy fix, you need to change one symbol in the library code, in `Servo.h`:

Change

```
typedef struct  {
   uint8_t nbr        :6 ;
   uint8_t isActive   :1 ;
 } ServoPin_t   ;

```

To

```
typedef struct  {
   uint8_t nbr        :7 ;
   uint8_t isActive   :1 ;
 } ServoPin_t   ;

```

Pull request here: https://github.com/arduino-libraries/Servo/pull/11
> 0 votes

---
Tags: arduino-mega, servo, analogwrite
---


title: Use Low Power Arduino with Solar Panel

text:
# Question
Title: Use Low Power Arduino with Solar Panel
I am trying to create an arduino system with radio-transmitters and radio-receivers. The system runs from a rechargable battery that is charged with a solar panel. I am using a **1.1W 6V solar panel**.

My problem is that I don't know how to make such a connection and I don't know what batteries to choose to power the arduino, assuming that I need it to run for **5-7 days** without solar power and that the solar panel is good enough to recharge the batteries while they power the arduino. We are also assuming that the solar panel has **8 hours of sunlight**.

To the arduino are connected the following sensors:

* **Flame Sensor**
* **Light Resistor x2**
* **Smoke Sensor**
* **Radio Transmitter**
* **Radio Receiver**
* **DHT11 Temperature & Humidity Sensor**

I am also looking to see if I can power down most sensors and power them on later if an event occurs. So probably all the sensors could be sleeping except the **DHT11** and the **Radio Receiver**. Preferably though, if at all possible, the rest of the sensors should be on, if we can handle **5-7 days *without* the solar panel**. I don't know if more information is needed but I'd be pleased to help out in the comments, or provide more information by editing the question. :)

# Answer
> 2 votes
You have far too many variables and unknowns there. Primarily you need to know what the average current draw for your circuit is. Secondly you need to decide how long the solar powers are allowed to take to recharge the battery. You have to think not only about runtime but also charge time. The charge time dictates the maximum capacity of the battery, and that then dictates the runtime of the Arduino. So here's some napkin maths to illustrate:

Assuming you want the battery to charge from almost flat to full within 8 hours, and with a 1.1W 6V solar cell, that gives you a peak of 183mA.

Assuming the Arduino circuit takes 83mA on average (let's give ourselves nice round numbers here) that leaves 100mA peak for charging the battery.

If you're charging at, say, 0.2C, that gives a full charge in 5 hours. 100mA / 0.2C = 500mAh capacity (at *peak sunlight and current*).

At 500mAh capacity and 83mA average current draw that would give you (0.5/0.083) 6 hours of runtime without the solar panels.

So that's just not going to work. It'll be dead by morning.

Now assume that you can turn off *everything* for 99% of the time. That effectively reduces our average current draw to 0.083\*0.01 = 830µA. Let's plug that into the same reasoning as above.

* Current draw = 0.00083A
* Incoming peak current = 0.183
* Available charge current = 0.183-0.00083 = 0.18217
* Charge at 0.2C = 910mAh.
* 1Ah battery would charge in about 5.5 hours of peak sunlight.
* 1Ah would last about 1200 hours, or 100 days.

None of this takes into account varying light levels or light incidence angles. As a rule of thumb, take the light as averaging 50% over the course of the 8 hour period. You will only get 1.1W when the angle of incidence is 90° to the solar panel. At all other times it will be reduced. So if we reduce the current from 183mA to, say, 100mA, the charge capacity changes to:

* Incoming peak current = 0.100
* Available charge current = 0.100-0.00083 = 0.099
* Charge at 0.2C = 496mAh
* A 500mAh battery would charge in about 5 hours.
* A 500mAh battery would run for about 50 days at 830µA average current.

So you see everything really hinges around the current consumption of the Arduino. How much current it consumes dictates how much is available to charge the battery, which in turn dictates the size of battery you can support, which dictates the amount of current you can draw for your desired runtime, which in turn dictates the amount of charge current available, which determines the size of battery you can support, which dictates ... etc. You get the idea.

You can support larger batteries, of course - I illustrated this at 0.2C charge rate (that's 20% charge per hour to give a 5 hour charge time). As long as the net charge over time increases (so during the periods between the 5-7 days of complete darkness you gain more charge than is expended during the dark period - something which has not been specified) then it should function fine.

Also note that your battery voltage should be below your solar panel voltage. A 6V solar cell would be able to charge a 4.5V lead acid battery (assuming low dropout schottky protection diodes). Also the capacity of the battery depends also on what you determine your "cut-off" voltage to be. That's how low the battery voltage is allowed to go before your system is determined to be unworkable. This could be at a point where the battery is in danger of being damaged by over-discharge, or at a point where your circuit no longer receives enough voltage to function (which could be linked to oscillator frequency on ATMega chips), etc. For this reason it is often better to choose a board that is designed to run at a lower voltage (3.3V) and use high efficiency switching regulation to get the most out of your battery. A 5V Arduino is seldom a great choice.

Finding that right balance is now entirely up to you.

And, in answer to your other question, yes there are ways to turn things on and off. You can "sleep" the Arduino. You can use high efficiency power circuits. You can add power switching circuits (P-MOSFETs) to switch power on and off to other modules. All things can (and mostly should) be done to save power when running on batteries.

---
Tags: arduino-uno, sensors, battery, temperature-sensor, solar
---


# Question
Title: Why does Arduino IDE recommend storing 0-255 numbers in "byte" instead of "char"?
I bumped into `byte` datatype recently. My knowledge of C/C++ is shallow, but I know `char` and I couldn't find much on `byte` in C++ docs. I looked it up in the Arduino docs:

> It’s recommended to only use char for storing characters. For an unsigned, one-byte (8 bit) data type, use the byte data type.

Is `byte` datatype a solely Arduino construct? If so, why is it recommended over `char`? Both are 8-bit so why would it make any difference?

# Answer
> 3 votes
> Is byte datatype a solely Arduino construct?

Yes. Much of the Arduino "language" is "bent" to look like Java, since it originated from Processing, which is Java. So we have data types the "look like" Java ones, including "byte" for "unsigned char" and "boolean" for "bool".

> If so, why is it recommended over char?

Personally I don't ever recommend using it, since it's non-standard. Instead you should use `uint8_t` which is essentially the same thing, but portable.

It is recommended to use "hard signedness" data types for portability. The problem with `char` is that whether it is signed or not is entirely down to the compiler implementation. Some systems have it as signed, some as unsigned. By using `byte` (or better, `uint8_t`) you are always going to get an unsigned 8-bit value.

For just storing of binary data it doesn't really make any difference, but when it comes to doing mathematics with the stored data you may find you suddenly have negative values when you don't want negative values (a `char` *might* be storing your number as -128 to +127, not 0 to 255).

# Answer
> 0 votes
Just a little add-on to Majenko's answer:

If a function has a char\* parameter, it's usually expecting a zero-terminated text.

If a function has a byte\* parameter, it's usually any binary data, eventually containing '\0' bytes. The buffer size needs to be an additional parameter in this case.

If there's nothing else to consider, why not use that for your variable definition too: Use `char` only if it contains an 8bit character. Or something like `char text[]="hello";` For binary data it might be relevant if it's signed (int8\_t) or unsigned (uint8\_t).

---

"usually" implies of course that you *should* read the doc.

---
Tags: data-type
---


# Question
Title: How to multitask with interrupts on Arduino?
I am trying to build a cashless RFID based water dispensing unit. I am using Arduino mega 2560, PN532, relay, flow sensor. Here is the flow of the program in I2C mode; I have two functions, one to scan the card and the other for the flow sensor. As soon as the RFID card is placed on the NFC module, data stored in the card (i.e, date of expiry and balance amount) is obtained and is checked for validity. If the card is valid, then the relay is turned on. A flow sensor measures the quantity of water dispensed. As soon as the limit of 1000 ml is reached, the relay is turned off. The whole process happens serially, when the card scanning is complete, it waits for the entire 1000 ml of water to be dispensed. What I want to achieve is after one card is scanned, 1st relay with the flow sensor has to be turned on and simultaneously the scanning of the second card has to begin. If the first relay is busy, second relay has to be assigned to it. Can I achieve this using Arduino Mega? How do I manipulate the atmega to perform all these tasks at once?

# Answer
> 1 votes
You do not necessarily need a build a "multitask with interrupts on Arduino". Instead consider using a state machine. First define the problem by drawing a state diagram:

Consider all state you wish to be in. Including your example "...after one card is scanned, 1st relay with the flow sensor has to be turned on and simultaneously the scanning of the second card has to begin...". Once you have defined all states and the rules that need to be tested for before jumping to a new state you can start programming your state machine.

There are plenty of tutorials including this one on the web specifically for people who want to implement a state machine on an Arduino. But, briefly, you will want to create a loop that will execute with out stopping over and over again as fast as possible. This loop will (1) know what the current state is and (2) will repeatedly test to find out if the program can change to any of the possible next states. When you change states is when, if you need to, you perform tasks such at turning the water on or off.

If you forsake the state machine and only use interrupts, testing the code tends to be very difficult. As controlling exactly when an interrupt occurs relative to other interrupts and the state of the processor becomes problematic and nearly impossible to reliably repeat. This is why the state machine is suggested. Interrupts can still detect external events. But by using a state machine the program is in control of what happens next. Instead of leaving it up to luck.

# Answer
> 1 votes
There is no real multitask on Arduinos. The Arduino can only do one thing at a time.

But, you can do things sequentially, one after another, so fast, that a human will think, that it happens simultaneously. This involves a non-blocking coding style, which needs no interrupts

* Every delay in your code (at least the long onces) need to be removed. if you want to do timed things, you should use the coding principle from the `BlinkWithoutDelay` example, that comes with the Arduino IDE.
* Also no function should wait for something to happen. Think of a function, that waits for a command from the serial interface. Blocking code would wait indefinitely, until a command was received, preventing any other code from execute. Instead the function could exit fast, when there is currently no command to process, leaving time for the other code to execute.

The whole principle relies on the `loop()` function executing very fast, so that your code can still be reactive. This works for most of the situations. Only sometimes you need to react that fast, that you need interrupts. Your usecase doesn't seem to belong to the interrupt needed faction.

---
Tags: arduino-mega, interrupt, rfid
---


title: Streaming audio to ESP8266 over WiFi

text:
# Question
Title: Streaming audio to ESP8266 over WiFi
I am thinking of making a wireless speaker using the ESP8266 chip. I have some questions regarding this.

1. Which pin of the ESP8266 chip can be used as I²S output? I have an ESP chip of this type :
2. Which ESP chip would be the best choice for this purpose?
3. I know about the MAX98357A which is used to convert digital I²S data to analog. But, for stereo output I need to use 2 of those. Is there any alternative to this chip which supports stereo output by default?
4. I have found many tutorials which shows how to play audio from SD card of ESP8266. But, how can I stream audio over standard WiFi connection?

# Answer
> 2 votes
> Which pin of the ESP8266 chip can be used as I²S output?

I uses GPIOs 2, 3, and 15. You only have GPIO2 available, and that's also one half of the UART interface. Also you usually need to generate a "master" clock (usually something like 256x the bit clock) for oversampling. So you can't with that module.

> Which ESP chip would be the best choice for this purpose?

ESP32, without a shadow of a doubt.

> I know about the MAX98357A which is used to convert digital I²S data to analog. But, for stereo output I need to use 2 of those. Is there any alternative to this chip which supports stereo output by default?

Yes, there are plenty. The search term you want is "CODEC". Personally I use the TLV320DAC3101.

You never use two separate mono CODECs for stereo, since I²S is a (normally) stereo protocol for connecting to a stereo CODEC. Reliably splitting a stereo I²S stream into two mono ones is not easy.

> I have found many tutorials which shows how to play audio from SD card of ESP8266. But, how can I stream audio over standard WiFi connection?

By implementing a suitable protocol, and that depends entirely on what your audio is and how it is generated.

---
Tags: esp8266
---


# Question
Title: Atmega328 standalone not working unless Pin1 connected to Arduino RESET
I'm new into this domain field. My principal occupation is as a .NET developer. I'm trying to do a personal project in which a AtMega328 takes some output from a scale using HX711 and sends a SMS via SIM800L GSM module. Before creating the whole module I tested each part separately with Arduino and the specific modules directly on breadboard. Everything works fine.I created a standalone using the guide from Arduino website(16Mhz crystal, 2x22 picoFarad capacitors, 10k Resistor to PIN1, RX/TX connected to PIN2/3). I designed the circuit using EasyEDA, printed it into pcb and assembled it. The only issue is that, when the standalone is not connected to the Arduino, and powered up by an external 5V source, unless I connected the pin1 to Arduino(connectd to PC)RESET pin, it's not working. I tried to attach a button for RESET to PCB, and connected it to PIN1 and GND, but like this I cannot upload to Atmega328, unless i disconnect the button from 10k Resistor/PIN1 and GND. In the first picture is the standalone which is not working if powered by an externalSource, unless I remove the button and add wire between Arduino-RESET and Atmega-PIN1. In the 2nd picture is my circuit, without HX711 module and in the 3rd picture is my circuit, working only because I connected the ARDUIN-RESET to Atmega328-PIN1 .\[!\[ATmega328 powered by wallplug, not working\]\[2\]\]\[2\]\[!\[PCB schema, working, after connecting PIN1 to Arduino RESET\]\[4\]\]\[4\]enter image description here\]\[5\]\]\[5\]\[

# Answer
So, the comments went to chat. Somebody recommended to use decoupling caps as close as possible near the VCC/GND of Atmega. I have 10uF in my workbench, so I used on of these caps and the issue was solved.
> 2 votes

---
Tags: atmega328
---


# Question
Title: How to set a not plugged in pin to ground or Low
I have digital pin 7 when set to High it does and when set to low it does not.

The only way I can get consistent High or Low is to use a 2 position 3 pin switch with my pin 7 in the middle and ground on one side and 5v on the other.

Is there a way I can use an simple Open/Close switch and still get the same function?

As of not if I dont "pull" pin 7 to ground I get both open and close randomly.

# Answer
> 1 votes
Seems like you already found the solution. Without a pull-down of pull-up resistor, the voltage at pin 7 will float to some random voltage, when the switch is open.

Either add an (external) pull-down resistor. Or flip things around and use the **internal** pull-up resistor inside the ATMega328p. Then connect the other side of the switch to GND. Whenever the switch is pressed, your digitalWrite gives you a LOW.

To use the internal pull-up use `pinMode(7, INPUT_PULLUP);`

---
Tags: arduino-uno, pins
---


# Question
Title: when i compile my code i get th is error stating "checkbutton" not declared in this scope
```
// After 2 seconds have passed, stop ignoring the button.
  // If the button is pressed, call the checkbutton function.
  if (millis() > ignore && digitalRead(0) == LOW)
  {
    checkbutton();
  }
}
// This function waits for the button to be released,
// then waits for it to be pressed to start the next run.
void checkbutton(){
  delay (50);  // Button pressed, debounce.
  while (digitalRead(0) == LOW) // While button is pressed,
  {}                            // do nothing while waiting.
  delay (50);                   // Button pressed, debounce.
  while (digitalRead(0) == HIGH)// While button is released,
  {}                            // do nothing while waiting.

  ignore = 2000 + millis();     // Set the now ignore time,
}                              // and return to the main loop.

```

# Answer
> 2 votes
You are using `checkbutton()` before you have told the program what `checkbutton()` is.

You need to move the whole method definition `void checkbutton(){ ... }` more to the top, i.e. in front of any call to it (`checkbutton();`).

Another option would be a forward declaration, but I doubt it's widely used in Arduino projects.

---
Tags: arduino-uno
---


# Question
Title: Disable auto-reset Mega 2560 on serial monitor open using 60 ohm resistor
I tried preventing my Arduino Mega 2560 from restarting every time I open the serial monitor. This link didn't work for me at all.

I tried connecting the RESET pin to 3.3v pin via a 60 ohm resistor and it worked for me. The question is: If I leave that resistor permanently connected, will this solution damage my board as time passes?

# Answer
> 3 votes
A 22uF cap between reset and ground does work on my Mega 2560 - opening the serial monitor will not restart the program. However, the Mega is then not downloadable. Therefore, I grounded the cap thru a normally closed relay and connected its control to a digital output. I normally operate with the relay closed. When I want to download a new program I open the relay first. It works great :-)

---
Tags: arduino-mega, atmega2560
---


# Question
Title: Print 2 numbers stored in 24-bits in decimal format
An implementation function from the nice little Wiegand library YetAnotherArduinoWiegandLibrary prints a hexadecimal representation of a facility # & card # (8-bit facility #, 16-bit card #) — 24 bits of a 26-bit stream that comes across the wire.

Example encoded 24-bit number: 7111097 (decimal). Hex equivalent: 6C81B9. The 6C portion is the facility # (decimal: 108). 81B9 is card # (decimal 33209).

This function from the library's example usage serial prints the hexadecimal format of the number:

```
void receivedData(uint8_t* data, uint8_t bits, const char* message) {
    Serial.print(message);
    Serial.print(bits);
    Serial.print("bits / ");
    //Print value in HEX
    uint8_t bytes = (bits+7)/8;
    for (int i=0; i<bytes; i++) {
        Serial.print(data[i] >> 4, 16);  //1st, 3rd, 5th hex digit
        Serial.print(data[i] & 0xF, 16); //2nd, 4th, 6th hex digit
    }
    Serial.println();
}

```

What I've tried to do unsuccessfully so far is to loop over the bits to also serial print the two decimal formatted numbers (facility:card) in the final output form: **108:33209**

# Answer
Your code loops from the high order byte to the low order byte, printing each byte as 2 hex digits.

If you want instead to print the first byte as a decimal value, and then the remaining bytes as another decimal value, then do this:

Print byte 0 in base 10:

```
    Serial.print(data[0]);  //first byte
    Serial.print(":");

```

Then loop through the remaining bytes, building a result as a decimal value, and print that:

```
unsigned long total = 0;
for (int i=1; i<bytes; i++) //Skip the first byte
{
    total = total << 8;  //Shift the previous total by 8 bits.
                         //(The same as multiplying by 256, but faster)
    total += data[i];    //Add in the new value
}
Serial.println(total);

```

The sample code you posted is written to handle a variable number of bytes. The code above does the same thing with decimal results. It's much simpler if you know you will always have 3 bytes or 4 bytes:

For 3 bytes:

```
    Serial.print(data[0]);  //first byte
    Serial.print(":");
    long total = long(data[1])*256 + data[2]);
    Serial.println(long(total);

```
> 2 votes

---
Tags: arduino-uno, serial, rfid, bit
---


# Question
Title: Millis () funtion fails to perform for extended period of time
I'm using millis () function to control the timer of my LED. It is a very basic code that I used from the example libraries. The code worked well for 6 hours (On for 6 h, Off for the following 6 h and continues), however, when I set it up for 12 hours, the light failed to turn off when I checked on it. The designed time should have fit into the 2^32 bits for unsigned long which I have defined beforehand. Can someone please help on this issue? Thank you!

```
/*
  Blink without Delay

  Turns on and off a light emitting diode (LED) connected to a digital pin,
  without using the delay() function. This means that other code can run at the
  same time without being interrupted by the LED code.

  The circuit:
  - Use the onboard LED.
  - Note: Most Arduinos have an on-board LED you can control. On the UNO, MEGA
    and ZERO it is attached to digital pin 13, on MKR1000 on pin 6. LED_BUILTIN
    is set to the correct LED pin independent of which board is used.
    If you want to know what pin the on-board LED is connected to on your
    Arduino model, check the Technical Specs of your board at:
    https://www.arduino.cc/en/Main/Products

  created 2005
  by David A. Mellis
  modified 8 Feb 2010
  by Paul Stoffregen
  modified 11 Nov 2013
  by Scott Fitzgerald
  modified 9 Jan 2017
  by Arturo Guadalupi

  This example code is in the public domain.

  http://www.arduino.cc/en/Tutorial/BlinkWithoutDelay
*/

// constants won't change. Used here to set a pin number:
const int ledPin =  7;// the number of the LED pin

// Variables will change:
int ledState = LOW;             // ledState used to set the LED

// Generally, you should use "unsigned long" for variables that hold time
// The value will quickly become too large for an int to store
unsigned long previousMillis = 0;        // will store last time LED was updated

// constants won't change:
unsigned long interval = 12*60*60*1000UL;           // interval at which to blink (milliseconds)

void setup() {
  // set the digital pin as output:
  pinMode(ledPin, OUTPUT);
}

void loop() {
  // here is where you'd put code that needs to be running all the time.

  // check to see if it's time to blink the LED; that is, if the difference
  // between the current time and last time you blinked the LED is bigger than
  // the interval at which you want to blink the LED.
  unsigned long currentMillis = millis();

  if (currentMillis - previousMillis >= interval) {
    // save the last time you blinked the LED
    previousMillis = currentMillis;

    // if the LED is off turn it on and vice-versa:
    if (ledState == LOW) {
      ledState = HIGH;
    } else {
      ledState = LOW;
    }

    // set the LED with the ledState of the variable:
    digitalWrite(ledPin, ledState);
  }
}

```

# Answer
> 1 votes
In C++, the multiplication operator is “left-associative”. This means that the expression

```
12*60*60*1000UL

```

is interpreted as

```
((12*60)*60)*1000UL

```

The left factor, namely `(12*60)*60`, is computed using the `int` data type, but the result overflows that format, resulting in the problem you see.

The simple solution is to make one of the factors of the *first* product be an `unsigned long`. For example

```
1000UL*60*60*12

```

Then, `1000UL*60` is computed with the `unsigned long` data type. Since the result is itself an `unsigned long`, the next multiplication is also done as `unsigned long`, and likewise for the last one.

If you find this technique somewhat obscure, you can also add the `UL` suffix to every single factor. This would avoid implicit conversions by the compiler, making all the types explicit.

# Answer
> 0 votes
Did you try to change your variables so that the calculations would be in seconds instead of milliseconds ? IOW add "/1000" after millis() and reduce your constants accordingly.

millis() is overflowing periodically, but it only happens every 49 days or so, and that even shouldn't play a role in the way you use it (the difference will also kind of overflow in the other direction).

---
Tags: arduino-uno
---


# Question
Title: Firebase.failed() returns 0 after Firebase.begin(), but returns 1 while reading or writing from/to firebase from ESP8266
The program was running fine, a few days ago, but now it just wouldn't read/write to the database. I'm running on ArduinoJson 5.13.5 and using FirebaseArduino library. I have set all the rules to true, would love to know how to debug this error. Also Firebase.error() does not give any output at all!

# Answer
Apparently the Firebase's fingerprint has changed recently and has caused the above issue!

from here get the latest finger print and change it in the `...\Arduino\libraries\firebase-arduino-master\src\FirebaseHttpClient.h`

In the file mentioned above: update the value of `static const char kFirebaseFingerprint[]` to the new one mentioned above.

P.S. One issue going forward for me(planing on implementing it on a long term basis) is how to be ahead of this issue in the future, so that I can get the data uninterrupted!
> 0 votes

---
Tags: esp8266, iot
---


title: Using DHT11 and EMF - Lag issue

text:
# Question
Title: Using DHT11 and EMF - Lag issue
The code is working but there is a delay when the LED turns on and off (physically). Is there a more efficient way I could write this code? I assume it is the delay in reading the DHT11 causing it.

~Issue resolved

# Answer
Your question is a bit unclear (A delay is defined by two points in time or one point and a duration -- you only tell us one point).

Reading your code, I can only assume that you mean that an external event on `inPin` is delayed in showing up on the LED on `pin11`. This should come up when that external event is emitted just at the beginning of your `delay(1000)` (and is therefore randomly delayed between 0 and 1000ms).

You could get rid of the delay in your loop using a bit of timer math around the DHT11 reading code:

```
#define DHT11_SAMPLE_DELAY = 1000
uint32_t last_dht11_reading_ms = 0;

void loop() {
  uint32_t current_ms = millis();

  if( current_ms - last_dht11_reading_ms > DHT11_SAMPLE_DELAY ) {

    DHT.read11(dht_apin);
    Serial.println("....your output....");

    last_dht11_reading_ms = current_ms;
  }
  // also, remove the delay(1000) in your loop()
}

```

You get the current time (`millis()` gives you the uptime since boot in milliseconds) and subtract the time of last reading. If the result is bigger than a threshold (in this case: 1000 ms), you do a new reading of the DHT11 while setting the variable containing the time of last reading to the current time. When the `loop()` comes around again, the threshold will not be reached, so reading the DHT11 value is skipped until `millis()` returns a sufficiently big number again.
> 0 votes

---
Tags: arduino-nano
---


title: Running loop for a specific time period

text:
# Question
Title: Running loop for a specific time period
I currently have a loop that runs without a time condition:

```
unsigned long previousMillis = 0;        // will store last time LED was updated

int WET=4;//wet line
int DRY=5;//dry line
int Inhale=1000;//msec
int Exhale=1000;//msec
//int Noflow=3000;//msec

void setup() {
  // put your setup code here, to run once:
  pinMode (WET, OUTPUT);
  pinMode (DRY, OUTPUT);
}

void loop() {
  //inhale
  digitalWrite(WET,LOW);
  digitalWrite(DRY,HIGH);
  delay (Inhale);
  //exhale
  digitalWrite(WET,HIGH);
  digitalWrite(DRY,LOW);
  delay (Exhale);
  //No flow
  //digitalWrite(WET,HIGH);
  //digitalWrite(DRY,HIGH);
  //delay (Noflow);
}

```

Then i have tried to code a "timer" for each cycle,but i got error:" exit status 1 Error compiling for board Arduino/Genuino Uno."

Code with timer:

```
unsigned long previousMillis = 0;        // will store last time LED was updated

int WET = 4; //wet line
int DRY = 5; //dry line
//int Inhale=1000;//msec
//int Exhale=1000;//msec
//int Noflow=1000;//msec
int BPM = 60;
int IE = (((60 * 1000) / BPM) / 2);

void setup() {
  // put your setup code here, to run once:
  pinMode (WET, OUTPUT);
  pinMode (DRY, OUTPUT);
}

void loop() {
  for (int i = 0; i = 20;)
    int BPM = BPM + 10;
#include <elapsedMillis.h>

  elapsedMillis timeElapsed;
  unsigned int interval = 60000; //one minute in ms

  while (timeElapsed < interval) {

    //inhale
    digitalWrite(WET, LOW);
    digitalWrite(DRY, HIGH);
    delay (IE);
    //exhale
    digitalWrite(WET, HIGH);
    digitalWrite(DRY, LOW);
    delay (IE);
    //No flow
    //digitalWrite(WET,HIGH);
    //digitalWrite(DRY,HIGH);
    //delay (2000);
  }
}

```

Target ouput: to run every cycle of the loop for 1 min.

Any one familiar with this error? Many thanks for your help

# Answer
> 1 votes
Your code has a number of problems:

Don't put `#include` statements for header files in the middle of your code. They belong at the top, before any other code. (What is the header file `elapsedMillis.h`?)

Another thing: Your for loop is a mess. It should read something like: `for (int i = 0; i < 20; i++)` (That would cause the for loop to run 20 times, with the value of i ranging from 0 to 19.) However, what do you want to happen in your for loop? Without braces after that code, the ONLY line that will execute 20 times is the `int BPM = BPM + 10;` line (which doesn't make any sense.)

You really shouldn't use time-based while loops inside your main loop function. That defeats the purpose of using timers instead of delay statements. And you should get rid of your calls to `delay()` and use `millis()` to manage all your timing. Do a search on "Arduino blink no delay" and study the examples for information on how to restructure your code.

# Answer
> 1 votes
1. Your for loop won't run as initially i is equal to 0 and you are comparing it with 20 also you didn't have any 3rd variable refreshing condition in your for loop.
2. You are declaring BPM new every time your loop run which is wrong
3. Also you are including header file in between your program run which will mess up your code and it is totally wrong practice.

---
Tags: arduino-uno, timers, loop
---


# Question
Title: Keyboard.write writing ASCII integer value as a String
I have the following code:

```
#include <SoftwareSerial.h>
#include <Keyboard.h>

SoftwareSerial ttySerial(10, 11); // RX, TX
void setup()
{
  // Open serial communications and wait for port to open:
  Serial.begin(115200);
  while (!Serial) {
    ; // wait for serial port to connect. Needed for Native USB only
  }

  Serial.println("Serial Initialized");

  //Set the data rate for the SoftwareSerial port
  ttySerial.begin(115200);
  ttySerial.println("tty Initialized");

  Keyboard.begin();
}

void loop()
{
  while (ttySerial.available())
    //Serial.write();
    Keyboard.write(ttySerial.read());

//    if (Serial.available())
//      ttySerial.write(Serial.read());
}

```

my problem is that `ttySerial.read()` is an `int` and I thought that the `Keyboard.write` method could hand integer arguments: `Keyboard.write(32)` should write "\< space \>" not "32".

Any ideas what is going on?

# Answer
write will treat an int as a number and assume you want it converted to ascii. Try casting that to char:

```
Keyboard.write((char)ttySerial.read());

```

The print class treats char variables as if they are already ascii codes.
> -1 votes

---
Tags: serial, keyboard, data-type
---


# Question
Title: Passing a NeoPixel object reference to a custom library
I'm new to Arduino programming and haven't programmed in C++ in the past. I'm trying to create a custom library to cycle a rainbow on my NeoPixel LED strip. I want to pass a reference or pointer or whatever into the library class so I can keep the code in my project file as simple as possible.

Here is my current project code:

```
#include <YaNeoPixelCycle.h>
#include <Adafruit_NeoPixel.h>

#define CONTROL_PIN 3
#define LED_COUNT 8
Adafruit_NeoPixel neoPixel(LED_COUNT, CONTROL_PIN, NEO_RGBW + NEO_KHZ800);
YaNeoPixelCycle cycle = YaNeoPixelCycle(neoPixel,255,100,200);

void setup() {
}

void loop() {
  cycle.tryStep();
}

```

And here is the library I tried to create:

```
/*
    Youkai's Artificery NeoPixel cycle library.
    A super basic RGB LED cycle.
*/

#ifndef YaNeoPixelCycle_h
#define YaNeoPixelCycle_h

#include "Arduino.h"
#include <Adafruit_NeoPixel.h>

class YaNeoPixelCycle{
    public:
        YaNeoPixelCycle(Adafruit_NeoPixel& neoPixel, int saturation, int brightness, int hueStep);
        void tryStep();
    private:
        Adafruit_NeoPixel& _neoPixel;
        unsigned int _ledHue = 0;
        int _saturation;
        int _brightness;
        int _hueStep;
};

#endif

```

```
/*
    Youkai's Artificery timer library.
    Some basic non-blocking timer functions.
*/

#include "Arduino.h"
#include "YaNeoPixelCycle.h"

YaNeoPixelCycle::YaNeoPixelCycle(Adafruit_NeoPixel& neoPixel, int saturation, int brightness, int hueStep){
    _neoPixel = neoPixel;
    _saturation = saturation;
    _brightness = brightness;
    _hueStep = hueStep;
    _neoPixel.begin();
    _neoPixel.show();
}

void YaNeoPixelCycle::tryStep(){
    _ledHue += _hueStep;
    _neoPixel.fill(_neoPixel.ColorHSV(_ledHue, _saturation, _brightness));
    _neoPixel.show();
}

```

The first step would be getting this to function at all. Uploading this to my Sparkfun ProMicro bricks it and I have to reset it to upload code again.

After that it would be awesome if it was possible to declare the NeoPixel in the project file but not actually initialize it until the library file. I'd love to pass CONTROL\_PIN and LED\_COUNT as variables to the library with `YaNeoPixelCycle(..., int controlPin, int ledCount)` so I don't have to set up a bunch of duplicate variables in my main file if I'm running more than one NeoPixel strip.

This is my own custom library so I'm not too worried about it being obscure. If it's possible/easier I would be fine just moving all of the NeoPixel code entirely into the library and never creating it at all in the main file. Just passing the control pin and LED count as parameters and having to "know" that those refer to a NeoPixel would be fine too.

# Answer
> 2 votes
You call `_neoPixel.begin()` and `_neoPixel.show()` in the constructor of your class. This constructor runs before the Arduino is initialized. This is why `begin()` functions are used. Add a `begin()` function to your class and call `cycle.begin()` in `setup()`.

```
void YaNeoPixelCycle::begin() {
  _neoPixel.begin();
  _neoPixel.show();
}

```

Of course remove the `_neoPixel.begin()` and `_neoPixel.show()` from the constructor.

---
Tags: library, neopixel, pointer
---


# Question
Title: Keep 5V on while sleep with LowPower library
Is it possible to keep the 5V on, while putting the Arduino (ATMEGA328P) in sleep more, using LowPower library?

I'm trying to use this HAT:

https://spellfoundry.com/product/sleepy-pi-2-usb-c/

to control the power of my Raspberry Pi. But on top of it, I want to have a second HAT that I want to feed 5V input, event after I shut down Raspberry Pi and put the Arduino to sleep.

# Answer
If I read the schematics at https://spellfoundry.com/download/sleepy-pi-2-usb-c-schematic/ correctly, you need to draw continuous 5V power from the SUPPLY\_5V pin instead of the SUPPLY\_EXP\_5V pin (the latter seems to be switched via some MOSFETs connected to pin 2 of the ATMEGA328p). Which means that you need to connect the 5V power of your second HAT to JP4 pin 3 on the Sleepy Pi HAT (instead of JP5 pin 3).
> 0 votes

---
Tags: library, atmega328, sleep
---


# Question
Title: How far can a HC-SR04 can stand from the microcontroller?
I was wondering if I connect a HC-SR04 to an Arduino or any other microcontroller by normal cables, what would be the maximum length of this cable so that the measurements will still be true, and not affected by the length of this cable?

# Answer
this problem consists of 2 things :

1. supply level drop (this one has severe effect)
2. signal level drop (a little more forgiving)

as the signals on the cables don't have high frequencies, the problem narrows down to just voltage level drop due to cable resistance.

supply level drop: the datasheet for SR04 says a maximum active current of 20mA is required for device to work properly. the supply voltage is 4.5~5.5v. so if you provide a 5v power for it, the cable must not drop it under 4.5v. the maximum resistance for the cable is calculated

> R=V/I =\> R = (0.5/20)\*10^3 = 25 Ohms

. you can use this value to find out maximum cable length using resistance tables provided by cable makers. e.g. if you have bought a 5ohms/meter cable, the maximum length should be under 5 meters to ensure a good power delivery.

the signals on the other hand, have very little current going between them. as the MCU/Module pins have a very high input impedance. so they are not as severe as the supply drop.

using a 100uF cap near SR04's supply pins would be great.
> 0 votes

# Answer
I have a couple measuring the liquid level of two tanks.

The units are distanced from the microcontroller by 12' of 18ga solid-core copper cable.

Testing was done with another microcontroller with the sensor attached by 6" cable to ensure accurate readings.

That's the longest I needed, so I haven't tested beyond that.
> 2 votes

# Answer
The signal of an HC-SR04 is the pulse on the "Echo" wire. The length of that pulse is directly proportionate to the distance from the object.

Since cable length does not affect the duration of that pulse, measurement accuracy isn't affected either.
> 1 votes

---
Tags: arduino-uno, esp8266, esp32, hc-sr04
---


title: Convert float to char array on ATtiny85

text:
# Question
Title: Convert float to char array on ATtiny85
I'm having a hard time trying to convert a float into a char array so it's stored like '7.125' just like the float looks.

I'm trying to communicate with an ATtiny85 (slave) and a program on a Raspberry Pi (master) over I2C.

The master expects 31 bytes from the slave when data is sent to it.

When I use this code on the ATtiny85 everything works as it should, the Pi gets the data correctly.

```
    char computerdata[35];
    computerdata[0] = '3';
    computerdata[1] = '.';
    computerdata[2] = '8';
    computerdata[3] = '7';
    computerdata[4] = '7';

    TinyWire.send(1);
    TinyWire.send(computerdata,30);

```

Of course I need to put a float variable in the array and not define numbers like I have for testing and this is where it breaks.

When I do something like this, it doesn't work, the Pi reports parsing error yet when I do this on the Due with Serial prints the char array looks good but something is different about it.

```
  sprintf(computerdata, "%2.32f", pH);

OR

  snprintf (computerdata, 35, "%f", pH);

```

What am I missing? Any ideas?

Thanks

# Answer
> 0 votes
Just to complement Michel Keijzers’ answer: `sprintf()` or `snprintf()` are normally the right solution. On the AVR platform, however, float conversions are left out of their default implementation, because they take quite a lot of flash space, even when not used. On the other hand, the avr-libc provides the non-standard function `dtostrf()` for doing this conversion. The program

```
void setup() {
    float f = 3.877;
    char str[35];
    dtostrf(f, 0, 3, str);
    Serial.begin(9600);
    Serial.println(str);
}

void loop(){}

```

outputs

```
3.877

```

# Answer
> 0 votes
The reason is that the library which implements `snprintf` and `sprintf` can be dependent on the compiler used for your MCU, so in your case it's not supported.

If you always need the form `%2.32f` why not put it in directly, like:

```
int i = int(3.877 * 1000.0); // Assuming f of form a.bcd, i will be 3877
char str[6];
str[0] = (i / 1000) % 10;
str[1] = '.';
str[2] = (i / 100) % 10;
str[3] = (i /  10) % 10;
str[4] = (i      ) % 10;
str[5] = '0';

```

It will be much faster too.

---
Tags: attiny85
---


title: Set SPI MOSI pin to idle low on a Due?

text:
# Question
Title: Set SPI MOSI pin to idle low on a Due?
I have an SPI slave connected to Due. I send the SPI slave into sleep mode. During sleep, I need to pull all pins low, including MOSI. What's the best way to pull the SPI-4 pin low on a Due?

Here's a similar question but it's about an AVR chip and the answer obviously doesn't apply to SAM3X8 which is an ARM.

# Answer
> 1 votes
I have managed to set MOSI to low by setting bit 26 in `PIOA->PIO_PER`, `PIOA->PIO_OER` and `PIOA->PIO_CODR` registers. To use SPI again, bit 26 in `PIOA->PIO_PDR` has to be set (this cancels the effect of `PIOA->PIO_PER`).

---
Tags: arduino-due, spi
---


# Question
Title: How can I fix this error "invalid operands of types 'const char [17]' and 'float' to binary 'operator+'"?
```
#include <Wire.h>

long aX,aY,aZ,gX,gY,gZ;
float rtX,rtY,rtZ,gfX,gfY,gfZ;

void setup()
{
  Serial.begin(9600);
  Wire.begin();
  setupMPU ();
}

void loop()
{
  recordAccelregisters();
  recordGyroregisters();
  printData();
  delay(100);
}

void setupMPU()
{

  Wire.beginTransmission(0b1101000);
  Wire.write(0x6B);
  Wire.write(0b00000000);
  Wire.endTransmission();
  Wire.beginTransmission(0b1101000);
  Wire.write(0x1B);
  Wire.write(0b00000000);
  Wire.endTransmission();
  Wire.beginTransmission(0b1101000);
  Wire.write(0x1C);
  Wire.write(0b00000000);
  Wire.endTransmission();
}

void recordAccelregisters()
{
  Wire.beginTransmission(0b1101000);
  Wire.write(0x3B);
  Wire.endTransmission();
  Wire.requestFrom(0b1101000,6);
  while(Wire.available()<6)
  {
    aX = Wire.read()<<8|Wire.read();
    aY= Wire.read()<<8|Wire.read();
    aZ = Wire.read()<<8|Wire.read();
    processAData();
  }
}

void processAData()
{
  gfX= aX/16384.0;
  gfY = aY/16384.0;
  gfZ = aZ/16384.0;
}

void recordGyroregisters()
{
  Wire.beginTransmission(0b1101000);
  Wire.write(0x43);
  Wire.endTransmission();
  Wire.requestFrom(0b110100,6);
  while(Wire.available()>6)
  {
    gX = Wire.read()<<8|Wire.read();
    gY = Wire.read()<<8|Wire.read();
    gZ = Wire.read()<<8|Wire.read();
    processGdata();
  }

}

void processGdata()
{
  rtX= gX/131.0;
  rtY = gY/131.0;
  rtZ= gZ /131.0;
}

void printData()
{
  Serial.print("Gyro degree(x)= "+ rtX + " ");// this line shows error mentioned above in the question
  Serial.print("Gyro degree(y)= "+ rtY + " ");// this line shows error mentioned above in the question
  Serial.print("Gyro degree(z)= "+ rtZ + " ");// this line shows error mentioned above in the question
  Serial.print("Accel Gforce(x)= "+ gfX + " ");// this line shows error mentioned above in the question
  Serial.print("Accel Gforce(y)= "+ gfY + " ");// this line shows error mentioned above in the question
  Serial.print("Accel Gforce(z)= "+ gfZ + " ");// this line shows error mentioned above in the question
}

```

this is a code of mpu6050. Why am I getting this error and How Can I resolve it?

# Answer
These lines give you errors, because you cannot simply add character arrays (aka c-strings) and floats together with the `+` operator. C/C++ is very strict, when it comes to variable types. The compiler does not know, how it should add these types together.

In other high level languages a string literal (characters enclosed by `"` in the source code) are more complex types, than c-strings. They mostly have various different methods and also an implementation of the `+` operator for adding a float number in human readable form. This complex type in the Arduino world is the `String` type. You can convert the float variable into a `String` and then add them together. But that's not the way, that you should do it. Strings on AVR based Arduinos (like Uno, Nano, ...) can be very evil due to the limited RAM. See Majenko's blog entry about The Evils of Arduino Strings for more information.

Instead you should just use multiple print statements. As Serial data is send out serially (one byte after another), it doesn't matter, if you put all the data to send in one print statement, or in multiple onces. So each of the offending lines can be converted to something like this:

```
Serial.print("Gyro degree(x)= ");
Serial.print(rtX);
Serial.print(" ");

```

It does exactly, what your code does. But it will not produce an error, since the `Serial.print()` method is also implemented for using float arguments.
> 3 votes

---
Tags: mpu6050, error
---


title: MkrWan freezes after short power outage

text:
# Question
Title: MkrWan freezes after short power outage
My MkrWan running on 5v 3A external adapter without battery. When short time(15-20 second) power outage happens Mkrwan still seems running. I think it consumes power on capacitors on adapter but voltage value drops. When electric comes back, it doesnt work anymore. Why it doesnt reset itself ? How to solve this problem ?

# Answer
> 1 votes
I connected Lipo battery to device. On power outages it supply power to board and brown out problem solved. Thanks a lot

---
Tags: power
---