# Question
Title: Gratuitious instantiation of `Serial`, why?
Let's take a very simple sketch, any simple one-.ino sketch. Say, just a led blinker like this

```
void setup()
{
  pinMode(LED_BUILTIN, OUTPUT);
  digitalWrite(LED_BUILTIN, LOW);
}

void loop()
{
  static bool on;
  digitalWrite(LED_BUILTIN, (on = !on) ? HIGH : LOW);
  delay(1000);
}

```

Once compiled in Arduino IDE, compiler reports using 10 bytes for global variables. This is perfect for our purposes.

Now let's add an extra `.cpp` file to it. Let's call it `foo.cpp`. The file looks like follows

```
#include <Arduino.h>

int foo()
{
  return Serial.available();
}

```

Compile it all together. Now the compiler reports using 185 bytes for globals. But why?!

Clearly, this extra global memory usage is `Serial`. It is brought in by the fact that global object `Serial` is referenced from `foo`. In the original sketch `Serial` is not instantiated (or discarded) by the linker as an unreferenced symbol. In this case it is referenced from `foo`, so the linker keeps it.

But... But GCC linker is usually smarter than this. I'd expect it to see that symbol `foo` is not referenced anywhere, so the reference to `Serial` inside `foo` also "doesn't count" and should not require an instance of `Serial` in final code.

In fact, if I tried using my own "heavy" class, my own global variable of that class and reference it in `foo` (instead of `Serial`), GCC would work as expected: regardless of how "heavy" my global variable is, GCC linker would discard my global variable from the final code and report the same 10 bytes for globals, as expected. The global memory usage would remain at 10 until I'd actually reference `foo` from somewhere.

But `Serial` is somehow special. Even an "unused" mention of `Serial` causes it to appear in global memory. What is so special about it? What makes it behave that way?

# Answer
My guess (though I didn't check) is that it is a side effect of the fact that the same file contains the instantiation of `Serial` and the associated ISRs. The definition of the ISR macro looks roughly like this (slightly simplified):

```
#define ISR(vector) extern "C" \
    void __attribute__((signal, used, externally_visible)) vector(void)

```

The key here is the “used” attribute. It tells the compiler that the symbol should be considered to be used, even though no code calls the ISR (for a good reason: it's called by the hardware).

When your program is linked, the object file foo.o pulls in HardwareSerial0.o. The linker then sees the serial ISRs which are labeled as “used”. These in turn make use of the `Serial` object which then appears to also be used.
> 1 votes

# Answer
I compiled the examples with the microCore/attiny13 which has a different Serial implementation there the compiler behaves as expected.

So reducing in `HardwareSerial.h` the

```
 #define SERIAL_RX_BUFFER_SIZE 64

 to

#define SERIAL_RX_BUFFER_SIZE 0

```

does exactly 121 bytes used (which is 185-64) the same for

```
 #define SERIAL_TX_BUFFER_SIZE 64

 to

#define SERIAL_TX_BUFFER_SIZE 0

```

gives 57 bytes (121-64). This is used by `Stream protected`:

```
unsigned char _rx_buffer[SERIAL_RX_BUFFER_SIZE];
unsigned char _tx_buffer[SERIAL_TX_BUFFER_SIZE];

```

I did not go through all the used libs to find the rest, but I guess its the global defines (buffers) for the global object Serial. The microCore lib has all buffers set to 0 so thats how I found it.
> 0 votes

---
Tags: serial, arduino-ide, compile, memory-usage, avr-gcc
---


# Question
Title: DHT11 Humidity/Temp Sensor showing incorrect values
So I am trying to use a humidity sensor with an LCD, but have run into this problem I have yet to fix. My problem is that when it is turned on, it returns the values `Humidity: 255%` and `Temp: 255C`. I know for sure that I am getting a signal from the sensor and that is working 100% (I have tested it without an LCD display). I have asked about this in the Adafruit Discord server and someone brought up the possibility of the data being clipped somewhere in the data collection/signal processing/printing chain. Still very confused about how I can fix this, I ask for help.

Here is some code:

```
#include <dht11.h>
#include <LiquidCrystal.h>

LiquidCrystal lcd(12, 11, 5, 4, 3, 2);

dht11 DHT;

#define DHT11_PIN 7

void setup(){
  lcd.begin(16, 2);
}

void loop()
{
  int chk = DHT.read(DHT11_PIN);
  lcd.setCursor(0,0);
  lcd.print("Temp: ");
  lcd.print(DHT.temperature);
  lcd.print((char)223);
  lcd.print("C");
  lcd.setCursor(0,1);
  lcd.print("Humidity: ");
  lcd.print(DHT.humidity);
  lcd.print("%");
  delay(1000);
}

```

# Answer
Obviously the DHT sensor has not acquired data to make sure do as follows:

```
void loop() {
  float h = dht.readHumidity();
  float t = dht.readTemperature();

  if (isnan(h) || isnan(t) ) {
   lcd.setCursor(0,0);
    lcd.println("DHT not ready!");
    return;
  }
 lcd.setCursor(0,0);
  lcd.print("Temp: ");
  lcd.print(t);
  lcd.print((char)223);
  lcd.print("C");
  lcd.setCursor(0,1);
  lcd.print("Humidity: ");
  lcd.print(h);
  lcd.print("%");
  delay(1000);
}

```

Make sure you connected the DHT the right way and **initialized**

```
DTH11

    Pin1 --> 5v and 10k ohm resistor

    Pin2 --> Arduino Pin7 and 10k ohm resistor

    Pin3 --> no connection

    Pin4 --> Gnd

```

Initialize correctly

```
    DHT dht(DHT11_PIN, DHT11);

```

and in setup() you have to start like

```
 dht.begin();

```

Now test and report back
> 0 votes

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


# Question
Title: Serial communication with HC-05 - Arduino UNO
I am new to the site and this is my first question. I'm going to try to describe my issue the best I can.

I got the following code for my project, which consists basically of getting a car to have 2 driving modes, automatic and manual.

As far as I can tell, I got it all working except it's not. I got an HC-05 connected to my L293D motor shield (attached to an Arduino UNO), as well as 2 DC motors, an ultrasonic sensor HC-SR04 and a LED. The circuit part is not the problem, I’ve managed to connect it all and it's working (I tested the obstacle avoiding part by itself, before adding the mode selection code, so I know the motors and sensor do their job). I should also mention that I’m sending the information through the BT from an app I made in App Inventor. The app is working fine, and I do receive the correct data in the Serial Monitor.

What’s puzzling me is, why can’t I get to assign the `Serial.read();` value to my response variable (resp)? I’m going to try to explain this a bit further.

In my serial monitor I get the intended chars from the app buttons, however, my “resp” variable doesn’t seem to be getting any value from `Serial.read();` for some reason, because when it gets to the switch statement, even though the char is printed on the monitor, the cases don’t start. For instance, and I might be completely off here, once I get ‘1’ on the monitor I should also start getting the distance measurement printed in the monitor and it’s not.

For what I gather, I believe the issue is between the `Serial.write()` and the `Serial.println()/.read();`, since the `serial.write()` seems to be taking priority over all others, since setting these lines as comments don’t affect the writing in the monitor:

```
if(Serial.available()>0){
//resp = Serial.read();
//Serial.println(resp);

```

I’m out of ideas, so any help or guidance towards the right direction will be greatly appreciated.

```
//Incluir librerias para controlar motor shield y sensor ultrasonico.
#include <AFMotor.h>
#include <NewPing.h>
#include <SoftwareSerial.h>

//Definir constantes y variables.
#define TRIG_P A4
#define ECHO_P A5
#define MAX_DIST 300
#define MAX_Vel 200
int led = A0;
int speedSet;
int iteraciones = 5;
float distancia, duracion;
char resp;

//Inicializar objetos del sensor y motores.
NewPing sonar(TRIG_P, ECHO_P, MAX_DIST);
AF_DCMotor motorD(2);
AF_DCMotor motorI(1);
SoftwareSerial BTSerial(A1, A2); // RX | TX

void setup() {
  Serial.begin(9600);
  pinMode(led, OUTPUT);
  BTSerial.begin(9600);
}

void loop() {

  //Lee información del BT y la escribe en el monitor serial.
  if (BTSerial.available()){
    Serial.write(BTSerial.read());
    Serial.write('\n');
  }

  delay(24); //Tiempo maximo que tarda en recibir una medición.

      /*Calcular la distancia frente al sensor utilizando la duración de la señal,
      la cual mide ida y vuelva por lo cual se divide entre 2
      y se multiplica por la velocidad del sonido (343 m/s).
      */

      duracion = sonar.ping_median(iteraciones);
      distancia = (duracion/2)*0.0343;

  if(Serial.available()>0){
    resp = Serial.read();
    Serial.println(resp);

    switch(resp){

      case '1':

      delay(24); //Tiempo maximo que tarda en recibir una medición.

      /*Calcular la distancia frente al sensor utilizando la duración de la señal,
      la cual mide ida y vuelva por lo cual se divide entre 2
      y se multiplica por la velocidad del sonido (343 m/s).
      */

      duracion = sonar.ping_median(iteraciones);
      distancia = (duracion/2)*0.0343;

      Serial.print("Distancia: ");
      Serial.print(distancia);
      Serial.println(" cm");

      if(distancia!=0 && distancia<=20){
        digitalWrite(led,HIGH);
        ALTO();
        delay(100);
        REVERSA();
        delay(400);
        IZQUIERDA();
        delay(100);
      }else
        digitalWrite(led,LOW);
        ADELANTE();
      break;

      case '2':
      ALTO();

        switch(resp){

          case 'A':
            ADELANTE();
          break;
          case 'R':
            REVERSA();
          break;
          case 'I':
            IZQUIERDA();
          break;
          case 'D':
            DERECHA();
          break;
          case 'O':
            ALTO();
          break;
        }
        break;
       }
    }
 }

  // Inician metodos que definen las acciones del carro.

void ADELANTE(){
   motorD.run(FORWARD);
   motorI.run(FORWARD);
    for (speedSet = 0; speedSet < MAX_Vel; speedSet +=2){
      motorD.setSpeed(speedSet + 20);
      motorI.setSpeed(speedSet - 20);
    }
  }

void REVERSA(){
   motorD.run(BACKWARD);
   motorI.run(BACKWARD);
    for (speedSet = 0; speedSet < MAX_Vel; speedSet +=2){
      motorD.setSpeed(speedSet + 20);
      motorI.setSpeed(speedSet - 20);
    }
  }

void DERECHA() {
   motorD.run(RELEASE);
   motorI.run(FORWARD);
   delay(300);
   motorD.run(FORWARD);
   motorI.run(FORWARD);
  }

void IZQUIERDA() {
   motorD.run(FORWARD);
   motorI.run(RELEASE);
   delay(300);
   motorD.run(FORWARD);
   motorI.run(FORWARD);
  }

void ALTO(){
   motorD.run(RELEASE);
   motorI.run(RELEASE);
  }

```

Here is an image of what I get on my serial monitor.

UPDATE:

As suggested by @chrisl, I'm now looking at it from a different approach.

I was sending the BT information to the serial monitor, when the idea in the first place is having the car run around without being connected to the PCat all.

So instead of sending the information to serial monitor and trying to take it from there, I simply assigned the value from BTSerial to my variable and it kinda works as intended now.

"Automatic mode" is working, my switch statement recognises the resp value and starts measuring and prints the distance. However, once I push '2', the first command activates and the motors stop but none of the other instructions work. I even changed my second switch statemate to ifs but that didn't help either.

Here's my new Serial output (9600 / Newline / COM5):

```
1
Distancia: 46.84 cm
Distancia: 154.74 cm
Distancia: 154.33 cm
Distancia: 154.68 cm
Distancia: 154.33 cm
Distancia: 155.70 cm
Distancia: 13.09 cm
Distancia: 12.74 cm
Distancia: 155.16 cm
Distancia: 155.77 cm
Distancia: 155.22 cm
Distancia: 154.81 cm
Distancia: 155.29 cm
Distancia: 155.22 cm
Distancia: 155.22 cm
2
A
R
I
@
D
O
1
Distancia: 155.43 cm
Distancia: 155.50 cm
Distancia: 155.57 cm
Distancia: 155.50 cm
Distancia: 155.09 cm
Distancia: 155.50 cm
Distancia: 155.09 cm
Distancia: 156.32 cm
Distancia: 155.57 cm
Distancia: 155.16 cm
Distancia: 155.09 cm
Distancia: 155.09 cm
Distancia: 155.50 cm
2

```

And my updated code:

```
//Incluir librerias para controlar motor shield y sensor ultrasonico.
#include <AFMotor.h>
#include <NewPing.h>
#include <SoftwareSerial.h>

//Definir constantes y variables.
#define TRIG_P A4
#define ECHO_P A5
#define MAX_DIST 300
#define MAX_Vel 200
int led = A0;
int speedSet;
int iteraciones = 5;
float distancia, duracion;
char resp;

//Inicializar objetos del sensor y motores.
NewPing sonar(TRIG_P, ECHO_P, MAX_DIST);
AF_DCMotor motorD(2);
AF_DCMotor motorI(1);
SoftwareSerial BTSerial(A1, A2); // RX | TX

void setup() {
  Serial.begin(9600);
  pinMode(led, OUTPUT);
  BTSerial.begin(9600);
}

void loop() {

  //Lee información del BT y la escribe en el monitor serial.
  if (BTSerial.available()){
    resp = BTSerial.read();
    Serial.println(resp);
  }

//  if(Serial.available()>0){
//    resp = Serial.read();
//    Serial.println(resp);

    switch(resp){

      case '1':

      delay(24); //Tiempo maximo que tarda en recibir una medición.

      /*Calcular la distancia frente al sensor utilizando la duración de la señal,
      la cual mide ida y vuelva por lo cual se divide entre 2
      y se multiplica por la velocidad del sonido (343 m/s).
      */

      duracion = sonar.ping_median(iteraciones);
      distancia = (duracion/2)*0.0343;

      Serial.print("Distancia: ");
      Serial.print(distancia);
      Serial.println(" cm");

      if(distancia!=0 && distancia<=20){
        digitalWrite(led,HIGH);
        ALTO();
        delay(100);
        REVERSA();
        delay(400);
        IZQUIERDA();
        delay(100);
      }else
        digitalWrite(led,LOW);
        ADELANTE();
      break;

      case '2':
      ALTO();

       if(resp == 'A'){
         ADELANTE();
       } else if (resp == 'R'){
         REVERSA();
       } else if (resp == 'I'){
         IZQUIERDA();
       } else if (resp == 'D'){
         DERECHA();
       } else if (resp == 'O'){
         ALTO();
       }
      break;
       }
    }
// }

  // Inician metodos que definen las acciones del carro.

void ADELANTE(){
   motorD.run(FORWARD);
   motorI.run(FORWARD);
    for (speedSet = 0; speedSet < MAX_Vel; speedSet +=2){
      motorD.setSpeed(speedSet + 20);
      motorI.setSpeed(speedSet - 20);
    }
  }

void REVERSA(){
   motorD.run(BACKWARD);
   motorI.run(BACKWARD);
    for (speedSet = 0; speedSet < MAX_Vel; speedSet +=2){
      motorD.setSpeed(speedSet + 20);
      motorI.setSpeed(speedSet - 20);
    }
  }

void DERECHA() {
   motorD.run(RELEASE);
   motorI.run(FORWARD);
   delay(300);
   motorD.run(FORWARD);
   motorI.run(FORWARD);
  }

void IZQUIERDA() {
   motorD.run(FORWARD);
   motorI.run(RELEASE);
   delay(300);
   motorD.run(FORWARD);
   motorI.run(FORWARD);
  }

void ALTO(){
   motorD.run(RELEASE);
   motorI.run(RELEASE);
  }

```

# Answer
> 0 votes
I guess the main problem is, that you write your commands from the bluetooth app, but the HC-05 module is connected to `BTSerial`. Here you are reading from it and forwarding the data to `Serial` (serial monitor on your PC):

```
if (BTSerial.available()){
    Serial.write(BTSerial.read());
    Serial.write('\n');
}

```

You are not doing anything else with the bluetooth serial data, so you cannot change the `resp` variable over bluetooth. Instead you are doing this with `Serial` (not `BTSerial`). But as long, as you don't type the commands into the serial monitor, that code will never run. Thus the distance code will never be executed.

If you want to control the program from the bluetoooth app, you need to actually work with the data from the right serial interface.

---

Btw: Your serial monitor is configured for a newline as line ending character. Your `Serial` code does not discard these, so you might get undesired behavior there, when `resp` becomes `\n`.

---

About your new problem: This problem actually existed also with the old code, but you couldn't see it, because the you were reading from the wrong serial interface. Try to read this (compressed) snipped of your (old) code:

```
switch(resp){
   case '1':
       ...
       break;
   case '2':
       switch(resp){
           case 'A':
               ...

```

With the first switch statement you are checking the value of `resp`. If it is `'2'`, you will enter the second case. In there you are again checking the value of `resp` for the values `'A'`, ... . But when you already know, that `resp` is equal to `'2'`, how can it ever be equal to `'A'` or one of the other subcommands, since you don't change `resp` in between. Thus the code inside the second switch statement is unreachable.

**What to do now?** I guess you want the first switch statement to handle the modes and the second one to handle the move commands, while in second mode. For that you need to restructure your code, in the best case to an FSM (Finite State Machine). I already once wrote a good descriptions of how an FSM works in my answer to this question.

Introduce a state variable, which gets used in the first switch statement, and a command variable, that gets used in the second one. I would suggest a structure like this:

```
enum State {AUTOMATIC_MODE, MANUAL_MODE};

State state = AUTOMATIC_MODE;
char command = 0;

void loop(){
    if(BTSerial.available()){
        resp = BTSerial.read();
        Serial.println(resp);
        switch(resp){
            case '1':
                state = AUTOMATIC_MODE;
                break;
            case '2':
                state = MANUAL_MODE;
                break;
            case 'A':
            case 'R':
            case 'I':
            case 'D':
            case 'O':
                command = resp;
                break;
        }
    }

    switch(state){
        case AUTOMATIC_MODE:
            ...
            break;
        case MANUAL_MODE:
            switch(command){
                case 'A':
                    ...
            }
            break;
    }
}

```

Here the serial input will be put into the `state` or `command` variable, depending, on what exactly was send. The part with the main code comes after that. Depending on the state, the corresponding code is executed. When in manual mode, the code will look at the `command` variable to check, which function to execute.

---
Tags: arduino-uno, serial, softwareserial
---


# Question
Title: pubsubclient won't compile in Arduino and VSCode IDEs
I've compiled successfully a year ago in Arduino IDE, but lately I'm getting fatal errors:

```
/Users/davidjeffers/Documents/Arduino/libraries/PubSubClient/src/PubSubClient.cpp: At global scope:
/Users/davidjeffers/Documents/Arduino/libraries/PubSubClient/src/PubSubClient.cpp:473:8: error: redefinition of 'size_t PubSubClient::write(uint8_t)'
size_t PubSubClient::write(uint8_t data) {
^

In file included from /Users/davidjeffers/Documents/Arduino/libraries/PubSubClient/src/PubSubClient.cpp:7:0:
/Users/davidjeffers/Documents/Arduino/libraries/PubSubClient/src/PubSubClient.h:160:19: error: 'virtual size_t PubSubClient::write(uint8_t)' previously defined here
virtual size_t write(uint8_t) {};
^

```

I've tried using VSCode. I've tried opening an issue on GitHub.

Thanks for any thoughts.

# Answer
> 0 votes
The library is somehow modified. There should be no {} in `virtual size_t write(uint8_t) {};` or the whole line shouldn't be in this .h.

Reinstall the library.

---
Tags: esp8266, arduino-ide, compilation-errors
---


# Question
Title: Solution needed for sending HTTPs requests from multiple Arduino units in the field
I'm using the Arduino Wifi Nina Library to connect an Arduino Uno Wifi Rev2 to wifi and then using the Arduino HTTP Client library to make HTTP post calls to the internet. It is working. However when I switch from HTTP to HTTPs (ie: switching the port to 443 from 80) the code below fails. I understand This is because I don't have a cert on the Arduino. I need to purchase/obtain a cert and download it to the Arduino.

I need to find a solution to this problem that meets the following constraints I have:

1. I will only be sending https requests to one URL: https://api.mailgun.net
2. The amount of memory storage available on Arduinos is severely constrained
3. I plan to deploy this Arduino into the field. After I deploy it, I will no longer be able to physically access it to manually update any expired certificates. But the Arduino unit must be able to send HTTPs requests to https://api.mailgun.net in perpetuity.
4. I plan to deploy not just this Arduino unit, but a fleet of similarly functioning Arduino units with the same functionality. And I need to keep the costs of any certificate(s) to an absolute minimum.

```
    #include <WiFiNINA.h>
    #include <ArduinoHttpClient.h>

    #define REMOTE_SERVER_DOMAIN "api.mailgun.net"
    #define REMOTE_SERVER_PORT 443
    #define MAILGUN_USER "my-user"
    #define MAILGUN_PASSWORD "my-secret"

    bool sendEmailViaHTTPS()
    {
        WiFiClient wifiClient;
        HttpClient httpClient = HttpClient(wifiClient, REMOTE_SERVER_DOMAIN, REMOTE_SERVER_PORT);
        httpClient.beginRequest();
        httpClient.post("/v3/sandbox7d1aaf2f157f42d8844b1ac4c38a0ef7.mailgun.org/messages");
        httpClient.sendHeader("Content-Type", "application/x-www-form-urlencoded");
        httpClient.sendBasicAuth(MAILGUN_USER, MAILGUN_PASSWORD);
        String postData = String("from=Mailgun%20Sandbox%20%3Cpostmaster%40sandbox7d1aaf2f157f42d8844b1ac4c38a0ef7.mailgun.org%3E&to=Me%20%3Cmyemail%40gmail.com%3E&subject=Hello%20World1&text=Hello%20World2");
        httpClient.sendHeader("Content-Length", postData.length());
        httpClient.beginBody();
        httpClient.print(postData);
        httpClient.endRequest();
        int statusCode = httpClient.responseStatusCode();
        String response = httpClient.responseBody();
        Serial.print("Status code: ");
        Serial.println(statusCode);
        Serial.print("Response: ");
        Serial.println(response);
        return statusCode == 200;
    }

```

What is the best solution to enabling my Arduino to send HTTPs requests as stated above with the least cost and friction?

# Answer
For secure TCP connection with WiFiNINA library use WiFiSSLClient instead of WiFiClient.

The Arduino firmware in the NINA ESP32 module has certificates of well known CA authorities so the server's certificate verification should work. If necessary, you can add public keys of server certificates to NINA.
> 1 votes

---
Tags: arduino-uno-wifi
---


# Question
Title: Burn bootloader finishes with "avrdude done. Thank you." but bootloader didn't actually get flashed
I've built a a stripped down version of the Arduino Nano that has some peripherals removed and three connectors for analog sensors I want to use. I'm trying to burn the Arduino Nano bootloader onto this custom board using the sparkFun AVR Pocket Programmer and from the Arduino IDE console it seems to say that it was burned successfully. But when I plug the board back into the computer it still shows up as a COM port instead of an Arduino device. This is the output I get in the console after I press burn bootloader with "USBtinyISP" selected as programmer and Arduino Nano as the board.

```

avrdude: Version 6.3-20190619
         Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
         Copyright (c) 2007-2014 Joerg Wunsch

         System wide configuration file is "C:\Program Files (x86)\Arduino\hardware\tools\avr/etc/avrdude.conf"

         Using Port                    : usb
         Using Programmer              : usbtiny
avrdude: usbdev_open(): Found USBtinyISP, bus:device: bus-0:\\.\libusb0-0001--0x1781-0x0c9f
         AVR Part                      : ATmega328P
         Chip Erase delay              : 9000 us
         PAGEL                         : PD7
         BS2                           : PC2
         RESET disposition             : dedicated
         RETRY pulse                   : SCK
         serial program mode           : yes
         parallel program mode         : yes
         Timeout                       : 200
         StabDelay                     : 100
         CmdexeDelay                   : 25
         SyncLoops                     : 32
         ByteDelay                     : 0
         PollIndex                     : 3
         PollValue                     : 0x53
         Memory Detail                 :

                                  Block Poll               Page                       Polled
           Memory Type Mode Delay Size  Indx Paged  Size   Size #Pages MinW  MaxW   ReadBack
           ----------- ---- ----- ----- ---- ------ ------ ---- ------ ----- ----- ---------
           eeprom        65    20     4    0 no       1024    4      0  3600  3600 0xff 0xff
           flash         65     6   128    0 yes     32768  128    256  4500  4500 0xff 0xff
           lfuse          0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
           hfuse          0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
           efuse          0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
           lock           0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
           calibration    0     0     0    0 no          1    0      0     0     0 0x00 0x00
           signature      0     0     0    0 no          3    0      0     0     0 0x00 0x00

         Programmer Type : USBtiny
         Description     : USBtiny simple USB programmer, https://learn.adafruit.com/usbtinyisp
avrdude: programmer operation not supported

avrdude: Using SCK period of 10 usec
avrdude: AVR device initialized and ready to accept instructions

Reading | ################################################## | 100% 0.00s

avrdude: Device signature = 0x1e950f (probably m328p)
avrdude: NOTE: "flash" memory has been specified, an erase cycle will be performed
         To disable this feature, specify the -D option.
avrdude: erasing chip
avrdude: Using SCK period of 10 usec
avrdude: reading input file "C:\Program Files (x86)\Arduino\hardware\arduino\avr/bootloaders/optiboot/optiboot_atmega328.hex"
avrdude: writing flash (32768 bytes):

Writing | ################################################## | 100% -0.00s

avrdude: 32768 bytes of flash written
avrdude: verifying flash memory against C:\Program Files (x86)\Arduino\hardware\arduino\avr/bootloaders/optiboot/optiboot_atmega328.hex:
avrdude: load data flash data from input file C:\Program Files (x86)\Arduino\hardware\arduino\avr/bootloaders/optiboot/optiboot_atmega328.hex:
avrdude: input file C:\Program Files (x86)\Arduino\hardware\arduino\avr/bootloaders/optiboot/optiboot_atmega328.hex contains 32768 bytes
avrdude: reading on-chip flash data:

Reading | ################################################## | 100% 0.00s

avrdude: verifying ...
avrdude: 32768 bytes of flash verified
avrdude: reading input file "0x0F"
avrdude: writing lock (1 bytes):

Writing | ################################################## | 100% 0.01s

avrdude: 1 bytes of lock written
avrdude: verifying lock memory against 0x0F:
avrdude: load data lock data from input file 0x0F:
avrdude: input file 0x0F contains 1 bytes
avrdude: reading on-chip lock data:

Reading | ################################################## | 100% 0.00s

avrdude: verifying ...
avrdude: 1 bytes of lock verified

```

The burning is pretty much over instantly and you can see the reading and writing take 0.00s, it should be closer to a minute rather than an instantly. It's faster than uploading a simple sketch to the Arduino. When I unplug the programmer and plug the device back via USB, it just shows up as a COM port instead of "Arduino Nano" - which doesn't allow me to program it via the Arduino IDE.

What is very strange to me is that I can program the device over the command line. If I follow the AVR Pock Programmer instructions "Using AVRDUDE via Command Line" and use a hex file generated from the Arduino IDE, the code uploads fine and runs fine. I wrote a sketch that prints the ADC values over the command line and after flashing via command line it's running as expected.

I've tried to upload the Arduino booatloader via command line as shown in this tutorial under "Uploading Code - Hard Way" and this time it takes over 43 seconds to write to flash and 30 seconds to read from flash so I thought it worked. However when I plug it back in, it STILL just comes up on my computer and the Arduino IDE as COM9.

This is the output I get when trying to flash the bootloader via command line:

```
C:\Program Files (x86)\Arduino\hardware\arduino\avr\bootloaders\optiboot
λ avrdude -b 19200 -c usbtiny -p m328p -v -e -U efuse:w:0x05:m -U hfuse:w:0xD6:m -U lfuse:w:0xFF:m

avrdude: Version 5.10, compiled on Jan 19 2010 at 10:45:23
         Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
         Copyright (c) 2007-2009 Joerg Wunsch

         System wide configuration file is "C:\WinAVR-20100110\bin\avrdude.conf"

         Using Port                    : lpt1
         Using Programmer              : usbtiny
         Overriding Baud Rate          : 19200
         AVR Part                      : ATMEGA328P
         Chip Erase delay              : 9000 us
         PAGEL                         : PD7
         BS2                           : PC2
         RESET disposition             : dedicated
         RETRY pulse                   : SCK
         serial program mode           : yes
         parallel program mode         : yes
         Timeout                       : 200
         StabDelay                     : 100
         CmdexeDelay                   : 25
         SyncLoops                     : 32
         ByteDelay                     : 0
         PollIndex                     : 3
         PollValue                     : 0x53
         Memory Detail                 :

                                  Block Poll               Page                       Polled
           Memory Type Mode Delay Size  Indx Paged  Size   Size #Pages MinW  MaxW   ReadBack
           ----------- ---- ----- ----- ---- ------ ------ ---- ------ ----- ----- ---------
           eeprom        65     5     4    0 no       1024    4      0  3600  3600 0xff 0xff
           flash         65     6   128    0 yes     32768  128    256  4500  4500 0xff 0xff
           lfuse          0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
           hfuse          0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
           efuse          0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
           lock           0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
           calibration    0     0     0    0 no          1    0      0     0     0 0x00 0x00
           signature      0     0     0    0 no          3    0      0     0     0 0x00 0x00

         Programmer Type : USBtiny
         Description     : USBtiny simple USB programmer, http://www.ladyada.net/make/usbtinyisp/
avrdude: programmer operation not supported

avrdude: Using SCK period of 10 usec
avrdude: AVR device initialized and ready to accept instructions

Reading | ################################################## | 100% 0.06s

avrdude: Device signature = 0x1e950f
avrdude: safemode: lfuse reads as FF
avrdude: safemode: hfuse reads as DE
avrdude: safemode: efuse reads as 5
avrdude: erasing chip
avrdude: Using SCK period of 10 usec
avrdude: reading input file "0x05"
avrdude: writing efuse (1 bytes):

Writing | ################################################## | 100% 0.02s

avrdude: 1 bytes of efuse written
avrdude: verifying efuse memory against 0x05:
avrdude: load data efuse data from input file 0x05:
avrdude: input file 0x05 contains 1 bytes
avrdude: reading on-chip efuse data:

Reading | ################################################## | 100% 0.02s

avrdude: verifying ...
avrdude: 1 bytes of efuse verified
avrdude: reading input file "0xD6"
avrdude: writing hfuse (1 bytes):

Writing | ################################################## | 100% 0.02s

avrdude: 1 bytes of hfuse written
avrdude: verifying hfuse memory against 0xD6:
avrdude: load data hfuse data from input file 0xD6:
avrdude: input file 0xD6 contains 1 bytes
avrdude: reading on-chip hfuse data:

Reading | ################################################## | 100% 0.01s

avrdude: verifying ...
avrdude: 1 bytes of hfuse verified
avrdude: reading input file "0xFF"
avrdude: writing lfuse (1 bytes):

Writing | ################################################## | 100% 0.02s

avrdude: 1 bytes of lfuse written
avrdude: verifying lfuse memory against 0xFF:
avrdude: load data lfuse data from input file 0xFF:
avrdude: input file 0xFF contains 1 bytes
avrdude: reading on-chip lfuse data:

Reading | ################################################## | 100% 0.02s

avrdude: verifying ...
avrdude: 1 bytes of lfuse verified

avrdude: safemode: lfuse reads as FF
avrdude: safemode: hfuse reads as D6
avrdude: safemode: efuse reads as 5
avrdude: safemode: Fuses OK

avrdude done.  Thank you.

C:\Program Files (x86)\Arduino\hardware\arduino\avr\bootloaders\optiboot
λ avrdude -b 19200 -c usbtiny -p m328p -v -e -U flash:w:optiboot_atmega328.hex -U lock:w:0x0F:m

avrdude: Version 5.10, compiled on Jan 19 2010 at 10:45:23
         Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
         Copyright (c) 2007-2009 Joerg Wunsch

         System wide configuration file is "C:\WinAVR-20100110\bin\avrdude.conf"

         Using Port                    : lpt1
         Using Programmer              : usbtiny
         Overriding Baud Rate          : 19200
         AVR Part                      : ATMEGA328P
         Chip Erase delay              : 9000 us
         PAGEL                         : PD7
         BS2                           : PC2
         RESET disposition             : dedicated
         RETRY pulse                   : SCK
         serial program mode           : yes
         parallel program mode         : yes
         Timeout                       : 200
         StabDelay                     : 100
         CmdexeDelay                   : 25
         SyncLoops                     : 32
         ByteDelay                     : 0
         PollIndex                     : 3
         PollValue                     : 0x53
         Memory Detail                 :

                                  Block Poll               Page                       Polled
           Memory Type Mode Delay Size  Indx Paged  Size   Size #Pages MinW  MaxW   ReadBack
           ----------- ---- ----- ----- ---- ------ ------ ---- ------ ----- ----- ---------
           eeprom        65     5     4    0 no       1024    4      0  3600  3600 0xff 0xff
           flash         65     6   128    0 yes     32768  128    256  4500  4500 0xff 0xff
           lfuse          0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
           hfuse          0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
           efuse          0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
           lock           0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
           calibration    0     0     0    0 no          1    0      0     0     0 0x00 0x00
           signature      0     0     0    0 no          3    0      0     0     0 0x00 0x00

         Programmer Type : USBtiny
         Description     : USBtiny simple USB programmer, http://www.ladyada.net/make/usbtinyisp/
avrdude: programmer operation not supported

avrdude: Using SCK period of 10 usec
avrdude: AVR device initialized and ready to accept instructions

Reading | ################################################## | 100% 0.05s

avrdude: Device signature = 0x1e950f
avrdude: safemode: lfuse reads as FF
avrdude: safemode: hfuse reads as D6
avrdude: safemode: efuse reads as 5
avrdude: erasing chip
avrdude: Using SCK period of 10 usec
avrdude: reading input file "optiboot_atmega328.hex"
avrdude: input file optiboot_atmega328.hex auto detected as Intel Hex
avrdude: writing flash (32768 bytes):

Writing | ################################################## | 100% 43.63s

avrdude: 32768 bytes of flash written
avrdude: verifying flash memory against optiboot_atmega328.hex:
avrdude: load data flash data from input file optiboot_atmega328.hex:
avrdude: input file optiboot_atmega328.hex auto detected as Intel Hex
avrdude: input file optiboot_atmega328.hex contains 32768 bytes
avrdude: reading on-chip flash data:

Reading | ################################################## | 100% 30.69s

avrdude: verifying ...
avrdude: 32768 bytes of flash verified
avrdude: reading input file "0x0F"
avrdude: writing lock (1 bytes):

Writing | ################################################## | 100% 0.02s

avrdude: 1 bytes of lock written
avrdude: verifying lock memory against 0x0F:
avrdude: load data lock data from input file 0x0F:
avrdude: input file 0x0F contains 1 bytes
avrdude: reading on-chip lock data:

Reading | ################################################## | 100% 0.01s

avrdude: verifying ...
avrdude: 1 bytes of lock verified

avrdude: safemode: lfuse reads as FF
avrdude: safemode: hfuse reads as D6
avrdude: safemode: efuse reads as 5
avrdude: safemode: Fuses OK

avrdude done.  Thank you.

```

I've reviewed my schematic multiple times, comparing it to the actual Nano schematic but I can't see anything that would cause it to fail - it's almost identical ! I've built two of these boards and they behave the same exact same way. Schematic shown below.

# Answer
> 1 votes
The Arduino 'device' is identified by the USB device code of the USB to TTL Serial on Arduino or by core code in case of MCU with native USB. The USB ids are written to the USB chip in factory or are part of the firmware/core and they are listed in boards.txt file so that the IDE then knows what Arduino is attached. If you use a common FTDI it doesn't have this Arduino vid and pid codes, which identifies the device as Arduino.

Note: I think you asked a different question then your real problem is, because you assumed that the name of the port not showing Arduino is the reason why the upload doesn't work. It is so called X-\>Y problem. You have a problem X but asked about problem Y. I answered the question asked.

---
Tags: arduino-uno, arduino-nano, bootloader, avrdude
---


# Question
Title: Arduino Timer 1 Library manipulate Timer value
I'm using Timer1 library for generation of pulse. But in my code, at some places i need to change the timer values. Can anyone suggest the ways to do it.

In below code in place of 370000, I need to change the value after getting some inputs in conditional loops. Ex. if (x==1) Timer value should be 370000 else 185000.

```
#include <TimerOne.h>

int count = 0;
int LED = 13;

void setup() {
 pinMode(LED, OUTPUT);
 Timer1.initialize(370000);
 Serial.begin(9600);
}

void loop() {
 Serial.print("Count Value: ");
 Serial.println(count++);
}

```

# Answer
> 2 votes
When you look into TimerOne.h, which is the header file for the TimerOne library, you can see at line 55 the method

```
void setPeriod(unsigned long microseconds)

```

which can be used to set the period of the timer at any time in your program. The method `TimerOne.initialize()` also calls this method to set the timer period.

# Answer
> -1 votes
Just use a variable...

```
unsigned long val = 0;

void setup(){
  if(something){
    val = 370000;
  }
  else {
    val = 185000;
  }
  Timer1.initialize(val);
}

```

---
Tags: arduino-uno, library, timers
---


# Question
Title: New to Arduino and I have a WIP code for a class. ERROR with LEDs working?
(EDIT) My goal with this code is to use two potentiometers, pot0 and pot1 respectively, to control 8 leds. Pot0 controls which sequence the leds are running (1, 2, or 3) and pot1 controls which LEDs within each sequence are active. Currently, I am having a problem because I am running Sequence 1 (the first if statement) to my arduino, but I can't seem to make the LEDs light up when being called out by the potentiometer. The only LED that works is LED 0, and that's only if both potentiometers were in the proper positions when the code begins running.

```
int pot0 = 0;
int pot1 = 1;
int led[] = {7, 6, 5, 4, 3, 2, 1, 0};

void setup() {

for (int i = 0; i < led; i++){
  pinMode(led, OUTPUT)
;}
}
void loop() {
  int potread = analogRead(pot0);
  int val = analogRead(pot1);
  int potR = map(val, 0, 1023, 0, 7);

if (potread <= 341) {
  for (int i; i == potR;)
  digitalWrite(led[i], HIGH);

}

else if (potread <= 682) {

}
else {

}
}

```

# Answer
For this, you should be using `map()`. Instead of `int potR = val % 8;` try `int potR = map(val, [minimum pot value], [maximum pot value], 0, 7)`. Also, I'm pretty sure you don't need the for loop if all you're doing is `led[i]`. In that case, you could use `led[potR]`.
> 1 votes

# Answer
I spoke to someone the other night while working on this who was able to help me, and have since resolved all of my issues. Thank you to everyone who helped me fix the issues that I was having!

For those interested in how my final code came out -\>

```
int pot0 = 0;
int pot1 = 1;
int led[] = {7, 6, 5, 4, 3, 2, 8, 9};
const int DelayPeriod = 100;

void setup() {
pinMode(pot0, INPUT);
pinMode(pot1, INPUT);
for (int i = 0; i < led; i++){
  pinMode(led, OUTPUT)
;}
}
void loop() {
  int potread = analogRead(pot0);
  int val = analogRead(pot1);
  int potR = map(val, 0, 1023, 0, 7);
if (potread <= 341) {
  for (int i = 0; i <= led; i++){
    if (i == potR){
      digitalWrite(led[i], HIGH);
    }
    else {
      digitalWrite(led[i], LOW);
    }
  }

}
else if (potread <= 682) {
  for (int i = 0; i <= led; i++){
    if (i <= potR){
      digitalWrite(led[i], HIGH);
    }
    else {
      digitalWrite(led[i], LOW);
    }
  }

}
else {
  for (int i = 0; i <= led; i++){
    if ((i <= (potR + 1)) && (i >= (potR - 1))){
      digitalWrite(led[i], HIGH);
    }
    else {
      digitalWrite(led[i], LOW);
    }
  }
}
}

```
> 1 votes

---
Tags: error
---


title: ADXL345 gives wiring error in SPI mode

text:
# Question
Title: ADXL345 gives wiring error in SPI mode
I get the following output from serial monitor when trying to use the ADXL345 with Arduino Uno in SPI mode (I2C mode works fine):

```
CA
Ooops, no ADXL345 detected ... Check your wiring!

```

See photos for wiring. I have tried it with another breakout board, and that produces the same results. Interestingly this tutorial says the breakout should work in SPI mode, but it's only illustrated for I2C. https://learn.adafruit.com/adxl345-digital-accelerometer?view=all#assembly-and-wiring

```
#include <Wire.h>
#include <Adafruit_Sensor.h>
#include <Adafruit_ADXL345_U.h>
/* Assign a unique ID to this sensor at the same time */
Adafruit_ADXL345_Unified accel = Adafruit_ADXL345_Unified(13,12,11,9);
//Adafruit_ADXL345_Unified accel = Adafruit_ADXL345_Unified();

//Adafruit_ADXL345_Unified accel = Adafruit_ADXL345_Unified(clock,miso,mosi,cs,sensorID);
void displaySensorDetails(void)
{
  sensor_t sensor;
  accel.getSensor(&sensor);
  Serial.println("------------------------------------");
  Serial.print  ("Sensor:       "); Serial.println(sensor.name);
  Serial.print  ("Driver Ver:   "); Serial.println(sensor.version);
  Serial.print  ("Unique ID:    "); Serial.println(sensor.sensor_id);
  Serial.print  ("Max Value:    "); Serial.print(sensor.max_value); Serial.println(" m/s^2");
  Serial.print  ("Min Value:    "); Serial.print(sensor.min_value); Serial.println(" m/s^2");
  Serial.print  ("Resolution:   "); Serial.print(sensor.resolution); Serial.println(" m/s^2");
  Serial.println("------------------------------------");
  Serial.println("");
  delay(500);
}

void displayDataRate(void)
{
  Serial.print  ("Data Rate:    ");

  switch(accel.getDataRate())
  {
    case ADXL345_DATARATE_3200_HZ:
      Serial.print  ("3200 ");
      break;
    case ADXL345_DATARATE_1600_HZ:
      Serial.print  ("1600 ");
      break;
    case ADXL345_DATARATE_800_HZ:
      Serial.print  ("800 ");
      break;
    case ADXL345_DATARATE_400_HZ:
      Serial.print  ("400 ");
      break;
    case ADXL345_DATARATE_200_HZ:
      Serial.print  ("200 ");
      break;
    case ADXL345_DATARATE_100_HZ:
      Serial.print  ("100 ");
      break;
    case ADXL345_DATARATE_50_HZ:
      Serial.print  ("50 ");
      break;
    case ADXL345_DATARATE_25_HZ:
      Serial.print  ("25 ");
      break;
    case ADXL345_DATARATE_12_5_HZ:
      Serial.print  ("12.5 ");
      break;
    case ADXL345_DATARATE_6_25HZ:
      Serial.print  ("6.25 ");
      break;
    case ADXL345_DATARATE_3_13_HZ:
      Serial.print  ("3.13 ");
      break;
    case ADXL345_DATARATE_1_56_HZ:
      Serial.print  ("1.56 ");
      break;
    case ADXL345_DATARATE_0_78_HZ:
      Serial.print  ("0.78 ");
      break;
    case ADXL345_DATARATE_0_39_HZ:
      Serial.print  ("0.39 ");
      break;
    case ADXL345_DATARATE_0_20_HZ:
      Serial.print  ("0.20 ");
      break;
    case ADXL345_DATARATE_0_10_HZ:
      Serial.print  ("0.10 ");
      break;
    default:
      Serial.print  ("???? ");
      break;
  }
  Serial.println(" Hz");
}

void displayRange(void)
{
  Serial.print  ("Range:         +/- ");

  switch(accel.getRange())
  {
    case ADXL345_RANGE_16_G:
      Serial.print  ("16 ");
      break;
    case ADXL345_RANGE_8_G:
      Serial.print  ("8 ");
      break;
    case ADXL345_RANGE_4_G:
      Serial.print  ("4 ");
      break;
    case ADXL345_RANGE_2_G:
      Serial.print  ("2 ");
      break;
    default:
      Serial.print  ("?? ");
      break;
  }
  Serial.println(" g");
}

void setup(void)
{
#ifndef ESP8266
  while (!Serial); // for Leonardo/Micro/Zero
#endif
  Serial.begin(9600);
  Serial.println("Accelerometer Test"); Serial.println("");
  pinMode(9,OUTPUT);
  /* Initialise the sensor */
  if(!accel.begin())
  {
    /* There was a problem detecting the ADXL345 ... check your connections */
    Serial.println("Ooops, no ADXL345 detected ... Check your wiring!");
    while(1);
  }

  /* Set the range to whatever is appropriate for your project */
  accel.setRange(ADXL345_RANGE_16_G);
  // displaySetRange(ADXL345_RANGE_8_G);
  // displaySetRange(ADXL345_RANGE_4_G);
  // displaySetRange(ADXL345_RANGE_2_G);

  /* Display some basic information on this sensor */
  displaySensorDetails();

  /* Display additional settings (outside the scope of sensor_t) */
  displayDataRate();
  displayRange();
  Serial.println("");
}

void loop(void)
{
  /* Get a new sensor event */
  sensors_event_t event;
  accel.getEvent(&event);

  /* Display the results (acceleration is measured in m/s^2) */
  Serial.print("X: "); Serial.print(event.acceleration.x); Serial.print("  ");
  Serial.print("Y: "); Serial.print(event.acceleration.y); Serial.print("  ");
  Serial.print("Z: "); Serial.print(event.acceleration.z); Serial.print("  ");Serial.println("m/s^2 ");
//  delay(500);
}

```

# Answer
I got it to work using the Sparkfun library in stead of the Adafruit library, and by inserting a couple of delay(100) statements in the setup (without them the output was continuously -13365, -13365, -13365). I still don't fully understand why the delay statements would be necessary in the first place though.

```
/*  *********************************************
 *  SparkFun_ADXL345_Example
 *  Triple Axis Accelerometer Breakout - ADXL345
 *  Hook Up Guide Example
 *
 *  Utilizing Sparkfun's ADXL345 Library
 *  Bildr ADXL345 source file modified to support
 *  both I2C and SPI Communication
 *
 *  E.Robert @ SparkFun Electronics
 *  Created: Jul 13, 2016
 *  Updated: Sep 06, 2016
 *
 *  Development Environment Specifics:
 *  Arduino 1.6.11
 *
 *  Hardware Specifications:
 *  SparkFun ADXL345
 *  Arduino Uno
 *  *********************************************/

#include <SparkFun_ADXL345.h>         // SparkFun ADXL345 Library

/*********** COMMUNICATION SELECTION ***********/
/*    Comment Out The One You Are Not Using    */
ADXL345 adxl = ADXL345(9);           // USE FOR SPI COMMUNICATION, ADXL345(CS_PIN);
//ADXL345 adxl = ADXL345();             // USE FOR I2C COMMUNICATION

/****************** INTERRUPT ******************/
/*      Uncomment If Attaching Interrupt       */
//int interruptPin = 2;                 // Setup pin 2 to be the interrupt pin (for most Arduino Boards)

/******************** SETUP ********************/
/*          Configure ADXL345 Settings         */
void setup(){

  Serial.begin(9600);                 // Start the serial terminal
  Serial.println("SparkFun ADXL345 Accelerometer Hook Up Guide Example");
  Serial.println();

  adxl.powerOn();                     // Power on the ADXL345
  delay(100);
  adxl.setRangeSetting(16);           // Give the range settings
                                      // Accepted values are 2g, 4g, 8g or 16g
                                      // Higher Values = Wider Measurement Range
                                      // Lower Values = Greater Sensitivity
  delay(100);
  adxl.setSpiBit(0);                  // Configure the device to be in 4 wire SPI mode when set to '0' or 3 wire SPI mode when set to 1
                                      // Default: Set to 1
                                      // SPI pins on the ATMega328: 11, 12 and 13 as reference in SPI Library
  delay(100);
//  Set SPI mode to that matching ADXL345 (I guess this would be in here by default? )

  adxl.setActivityXYZ(1, 0, 0);       // Set to activate movement detection in the axes "adxl.setActivityXYZ(X, Y, Z);" (1 == ON, 0 == OFF)
  adxl.setActivityThreshold(75);      // 62.5mg per increment   // Set activity   // Inactivity thresholds (0-255)

  adxl.setInactivityXYZ(1, 0, 0);     // Set to detect inactivity in all the axes "adxl.setInactivityXYZ(X, Y, Z);" (1 == ON, 0 == OFF)
  adxl.setInactivityThreshold(75);    // 62.5mg per increment   // Set inactivity // Inactivity thresholds (0-255)
  adxl.setTimeInactivity(10);         // How many seconds of no activity is inactive?

  adxl.setTapDetectionOnXYZ(0, 0, 1); // Detect taps in the directions turned ON "adxl.setTapDetectionOnX(X, Y, Z);" (1 == ON, 0 == OFF)

  // Set values for what is considered a TAP and what is a DOUBLE TAP (0-255)
  adxl.setTapThreshold(50);           // 62.5 mg per increment
  adxl.setTapDuration(15);            // 625 μs per increment
  adxl.setDoubleTapLatency(80);       // 1.25 ms per increment
  adxl.setDoubleTapWindow(200);       // 1.25 ms per increment

  // Set values for what is considered FREE FALL (0-255)
  adxl.setFreeFallThreshold(7);       // (5 - 9) recommended - 62.5mg per increment
  adxl.setFreeFallDuration(30);       // (20 - 70) recommended - 5ms per increment

  // Setting all interupts to take place on INT1 pin
  //adxl.setImportantInterruptMapping(1, 1, 1, 1, 1);     // Sets "adxl.setEveryInterruptMapping(single tap, double tap, free fall, activity, inactivity);"
                                                        // Accepts only 1 or 2 values for pins INT1 and INT2. This chooses the pin on the ADXL345 to use for Interrupts.
                                                        // This library may have a problem using INT2 pin. Default to INT1 pin.

  // Turn on Interrupts for each mode (1 == ON, 0 == OFF)
  adxl.InactivityINT(1);
  adxl.ActivityINT(1);
  adxl.FreeFallINT(1);
  adxl.doubleTapINT(1);
  adxl.singleTapINT(1);

//attachInterrupt(digitalPinToInterrupt(interruptPin), ADXL_ISR, RISING);   // Attach Interrupt

}

/****************** MAIN CODE ******************/
/*     Accelerometer Readings and Interrupt    */
void loop(){

  // Accelerometer Readings
  int x,y,z;
  adxl.readAccel(&x, &y, &z);         // Read the accelerometer values and store them in variables declared above x,y,z

  // Output Results to Serial
  /* UNCOMMENT TO VIEW X Y Z ACCELEROMETER VALUES */
  Serial.print(x);
  Serial.print(", ");
  Serial.print(y);
  Serial.print(", ");
  Serial.println(z);

//  ADXL_ISR();
  // You may also choose to avoid using interrupts and simply run the functions within ADXL_ISR();
  //  and place it within the loop instead.
  // This may come in handy when it doesn't matter when the action occurs.

}

/********************* ISR *********************/
/* Look for Interrupts and Triggered Action    */
void ADXL_ISR() {

  // getInterruptSource clears all triggered actions after returning value
  // Do not call again until you need to recheck for triggered actions
  byte interrupts = adxl.getInterruptSource();

  // Free Fall Detection
  if(adxl.triggered(interrupts, ADXL345_FREE_FALL)){
    Serial.println("*** FREE FALL ***");
    //add code here to do when free fall is sensed
  }

  // Inactivity
  if(adxl.triggered(interrupts, ADXL345_INACTIVITY)){
    Serial.println("*** INACTIVITY ***");
     //add code here to do when inactivity is sensed
  }

  // Activity
  if(adxl.triggered(interrupts, ADXL345_ACTIVITY)){
    Serial.println("*** ACTIVITY ***");
     //add code here to do when activity is sensed
  }

  // Double Tap Detection
  if(adxl.triggered(interrupts, ADXL345_DOUBLE_TAP)){
    Serial.println("*** DOUBLE TAP ***");
     //add code here to do when a 2X tap is sensed
  }

  // Tap Detection
  if(adxl.triggered(interrupts, ADXL345_SINGLE_TAP)){
    Serial.println("*** TAP ***");
     //add code here to do when a tap is sensed
  }
}

```
> 0 votes

---
Tags: arduino-uno, spi, adafruit, accelerometer
---


# Question
Title: Data in two 8 bit shift registers won't change
I'm trying to output 16 bits of data to two 8 bit shift registers (74HC595), which drive a 8x8 led matrix. There is a problem with the way the code outputs data to the registers, its like no data is even shifted onto them. The first 8 bits handle the rows and the last 8 bits handle the columns.

I have already written this code in Arduino, but I am trying to re-write in it C (we have to learn AVR programming in C for college). The Arduino version works fine, so I know the circuit is correct. I'm using Atmel Studio.

For example, I replaced all the `digitalWrite(clockPin, HIGH)`'s with `PORTD = PORTD | (1<<clockPin)`. But I can't get anything to output with my code. For refreshing the led display the variable `refreshFlag` is used. For updating the game state (which hasn't been implemented yet) the variable `updateFlag` is used.

```
#include <avr/io.h>
#include <avr/interrupt.h>
#include <stdlib.h>

//portd 2(latch), 4(clock), 7(data). Same as pins on arduino board
#define latchPin 2
#define clockPin 4
#define dataPin 7

//functions
void init_ports(void);
void init_USART(void);
void init_timer0(void);
void sendmsg (char *s);
void drawData(uint8_t myData[]);
void shiftOut(uint8_t myDataOut);

unsigned char qcntr = 0,sndcntr = 0;   /*indexes into the queue*/
unsigned char queue[100];       /*character queue*/

int updateTimeCount;
int updateDelay;
int updateFlag; // Flag for updating game state
int refreshFlag;// Flag for refreshing display

uint8_t data[] = {0b00000001,
                  0b01111110,
                  0b11000110,
                  0b01001010,
                  0b01010010,
                  0b11100010,
                  0b01111110,
                  0b01000010};

int main(void) {
    //init_USART();// Serial for debugging purposes
    init_ports();
    init_timer0();
    clearData();
    newBlock();

    sei();

    PORTB = 0; //PortB for debugging
    updateTimeCount = 0;
    updateDelay = 13; // Game updates every 13* 16ms = 208ms.
    updateFlag = 0;
    refreshFlag = 0; // Display updates every 16ms

    while (1) {

        if(updateFlag) { //updates game state
            PORTB = (1<<5); //debugging led
            updateFlag = 0;
        }

        if(refreshFlag) { //refreshes display
            drawData(data); //output data array

            refreshFlag = 0;
        }
    }
    return 0;
}

void drawData(uint8_t myData[]) { //takes data and outputs it
  for (uint8_t j = 0; j <= 7; j++) {

    //ground latchPin and hold low for as long as you are transmitting
    PORTD = PORTD & ~(1<<latchPin); //latch pin low

    //shift data into regs

    shiftOut(~(1<<j)); //grounds row. For example 10111111 means 6th row is on

    shiftOut(myData[j]);  //outputs column data.

    //return the latch pin high to signal chip that it
    //no longer needs to listen for information
    PORTD = PORTD | (1<<latchPin); //latch pin high
  }
}

void shiftOut(uint8_t myDataOut) { //shifts 8 bits out to register

  // This shifts 8 bits out LSB first,
  //on the rising edge of the clock,
  //clock idles low

//internal function setup
  uint8_t i=0;
  int pinState;

//prepare shift register for bit shifting
  PORTD = PORTD & ~((1<<dataPin) | (1<<clockPin)); //clock & data pin low

  //for each bit in the myDataOut
  for (i=0; i<=7; i++)  {

    PORTD = PORTD & ~(1<<clockPin); //clock low

    //if the value passed to myDataOut and a bitmask result
    // true then... so if we are at i=6 and our value is
    // %11010100 it would the code compares it to %01000000
    // and proceeds to set pinState to 1.
    if ( myDataOut & (1<<i) ) {
      pinState= 1;
    }
    else {
      pinState= 0;
    }

    //Sets the pin to HIGH or LOW depending on pinState
    PORTD = PORTD | (pinState<<dataPin);

    //register shifts bits on upstroke of clock pin
    PORTD = PORTD | (1<<clockPin);

    //zero the data pin after shift to prevent bleed through
    PORTD = PORTD & ~(1<<dataPin);
  }

  //stop shifting
  PORTD = PORTD & ~(1<<clockPin);
}

void sendmsg (char *s) { //create serial message
    qcntr = 0;    /*preset indices*/
    sndcntr = 1;  /*set to one because first character already sent*/

    queue[qcntr++] = 0x0d;   /*put CRLF into the queue first*/
    queue[qcntr++] = 0x0a;
    while (*s)
    queue[qcntr++] = *s++;   /*put characters into queue*/

    UDR0 = queue[0];  /*send first character to start process*/
}

/*this interrupt occurs whenever the */
/*USART has completed sending a character*/

ISR(USART_TX_vect) {
    /*send next character and increment index*/
    if (qcntr != sndcntr)
        UDR0 = queue[sndcntr++];
}

ISR(TIMER0_OVF_vect) { //overflow every 16ms
    TCNT0 = 6; // 256-250 = 6
    ++updateTimeCount;
    if(updateTimeCount >= updateDelay) { //after 208ms, update game state
        updateFlag = 1; // Call for updating game
        updateTimeCount = 0;

    }

    refreshFlag = 1; // Call for updating screen
}

void init_ports() {
    DDRD = (1<<latchPin) | (1<<clockPin) | (1<<dataPin); //enable pins
    PORTD = 0; //set all pins low
    DDRB = (1<<5); //enable the built-in led for debugging
    PORTB = 0; //set all pins low
}
void init_USART() {
    UCSR0B = (1<<TXEN0) | (1<<TXCIE0); //enable transmitter and tx interrupt
    UBRR0 = 103; //baud 9600
}
void init_timer0() {
    TCCR0A = 0;
    TIMSK0 = (1<<TOIE0);    // enable interrupt
    TCCR0B = (5<<CS00); // prescalar 1024. 16Mhz/1024 = 15625Hz = 0.064ms
    // For refresh rate of 62.5Hz, 16ms /0.064ms = 250
    TCNT0 = 6; // 256-250 = 6
}

```

I really can't tell what the problem is and I don't what to look up either. I think the problem is in the functions `drawData` and `shiftOut`, because that's where all the data is shifted out. I tested the timer0 interrupt by flipping the built-in led and that seems to be working fine.
Are the ports flipping too fast for the shift regs to receive the data? Is there a semantic error somewhere? Can you see any problems. Thanks for any help!

# Answer
> 1 votes
Thanks to everyone who commented on my question, I was able to solve the problem with your help!

The first issue was that the compiler interpreted the `if(refreshFlag) {...}` as `if(0) {...}` so the data would have never been outputted to the display.

This happens is because the compiler doesn't see that the `refreshFlag` can be set to 1 in the timer0 interrupt service routine. From its perspective I have written an if statement that never runs.

As @KIIV pointed out, if the `volatile` keyword is used when declaring `refreshFlag`, this tells the compiler that this variable can change at any time.

The second and more embarrassing issue was that I forgot to remove a call to `clearData()` function which clears the data array. So I was just outputting nothing to the registers!

This is what the fixed variables and main should look like:

```
int updateTimeCount;
int updateDelay;
volatile int updateFlag; // Flag for updating game state
volatile int refreshFlag;// Flag for refreshing display

uint8_t data[] = {0b00000001,
                  0b01111110,
                  0b11000110,
                  0b01001010,
                  0b01010010,
                  0b11100010,
                  0b01111110,
                  0b01000010};

int main(void) {
    //init_USART();// Serial for debugging purposes
    init_ports();
    init_timer0();

    sei();

    PORTB = 0; //PortB for debugging
    updateTimeCount = 0;
    updateDelay = 13; // Game updates every 13* 16ms = 208ms.
    updateFlag = 0;
    refreshFlag = 0; // Display updates every 16ms

    while (1) {

        if(updateFlag) { //updates game state
            PORTB = (1<<5); //debugging led
            updateFlag = 0;
        }

        if(refreshFlag) { //refreshes display
            drawData(data); //output data array

            refreshFlag = 0;
        }
    }
    return 0;
}

```

---
Tags: led, c, timers, shift-register, port-mapping
---


# Question
Title: Alternatives to read mp3 without using an sdcard as source for the files?
I am making a project that plays several sounds using a DFPlayer Mini mp3 player and a micro sd card. The size of the sounds I normally play is less than 20 MB, so a lot of space in the sd card is unused. I was wondering if there is an alternative to use an SD card to store the mp3 files, and if there is, what would be the best approach to switch to use this alternative.

Cheers!

# Answer
The problem of all alternatives I can think of is a commercial one:
Its more expensive than to waste space. So if you look up your facvorite online dealer you will quickly find out that e.g. buying the cheapest 1GB SD card costs double than buying the cheapest 32GB card (6$). So the more space you waste the cheaper.
Get an used 512MB or 1GB card (cost in my country around 1$) and be happy with the space reserve.
Of course if saving space is a topic and not money get 20 x 1MB eeprom I2C boards (20\*3$ from china), solder the hardware (you'll need some more parts to manage the board addresses), get a power source, write a library for managing the memory and after spending around 100$ and a lot of time you saved up to around 15.98 GB of free space but not the environment.
> 1 votes

---
Tags: arduino-uno
---


# Question
Title: How can I stop SoftwareSerial from receiving data and re-enable it at some other point?
My project involves and RFID reader connected to an Arduino Pro Mini (5V, 16MHz) and an Adafruit CC3000 breakout WiFi chip. The device reads RFID tags and sends them to my web service. I am using Software Serial to read the RFID device data.

After I scan something, the Arduino tries to send the value that was read to the web service. This obviously causes a delay and the program only continues execution (i.e. next iteration of the loop() function) after the data has been sent.

My problem is simple. While the value is being sent, the serial buffer is can still accept scans from the RFID reader and on subsequent iterations, because there is data in the buffer the device attempts to send data again.

My question is how can I stop the software serial port from receiving data while I am trying to send data to the web service? Then when the data is sent successfully, how can I re-enable the software serial port from accepting data?

# Answer
> 9 votes
Call serial.end() to stop receiving.

Then call `serial.begin(...)` again when you want to start listening again.

# Answer
> 3 votes
According to the docs, SoftwareSerial doesn't support `.end()`, so Gerben's answer won't work here, I think.

It's hacky, but you could exploit the fact that only one SoftwareSerial can receive data at a time, and create a second one, activating it with `SoftwareSerial.listen()`. Then `.listen()` again on your original SoftwareSerial, when you want to resume listening.

Or, you could do as Marty Grogan says, and flush the read buffer before starting a new read. Again, I don't think SoftwareSerial supports a flush method as such, so you'd need to just `.read()` until there's nothing `.available()`.

# Answer
> 2 votes
Whether or not the serial data becomes available really does not matter. If you flush the port before every read rather than consuming the data, let 'er rip. If you are using interrupts, toggle interrupts on the serial pin.

# Answer
> 0 votes
The important parts are the `GPS.end()` which removes the interrupt routine and effectively stops listening to input although the data continues and the `GPS.begin(baud)` which reinstates the interrupt routine. The other statements are program specific and could be anything that you want to do while the input data processing is off.

I am using it on a project where I smooth scroll time/date on an LED matrix but the SoftwareSerial interrupt routine makes the scrolling jerky. I have reduced the NMEA sentences to just one but it still takes a noticeable amount of time to process it. So the GPS is always on and sending but I only listen 4 times per hour by doing an `ss.begin()` for 5 second (or until valid data), save it then do the `ss.end()`. Problem solved. I get mildly jerky scrolling for 5 seconds but it is rarely noticed and my time is always right.

I will post the routine on my web site, ILikeTheInternet.com, in a few days.

# Answer
> 0 votes
I have successfully used two Software Serial interfaces by using the .listen() method.

```
SoftwareSerial swSerial1(4,5);
SoftwareSerial swSerial2(6,8);

swSerial1.begin(9600);
swSerial2.begin(9600);

```

At this point the Arduino is listening to swSerial2 because it was defined last. If I wanted to use swSerial1 in the loop I would call

```
swSerial1.listen();

```

And switch back with

```
swSerial2.listen();

```

This avoids the significant overhead of ending and re-beginning software serial connections.

# Answer
> 0 votes
Just a guess but I believe the current version of SoftSerial actually uses PCINT to detect the individual bits. I believe if that were disabled you would stop reception. It will take some work to get it to work without problems. This is just a guess.

# Answer
> -1 votes
I had the same problem with reading GPS-Data on Port 11 while sending APRS-Data out. This code worked for me:

```
GPS.end();

aprs_send();
while (afsk_busy());

GPS.begin(GPS_BAUDRATE);

```

---
Tags: serial, arduino-pro-mini, softwareserial, rfid
---


# Question
Title: How to bridge free-running multichannel adc to serial?
I want to get meteo sensors values, and turn avr based 16mhz arduino (i have mega, but that seems not matter alot vs uno) into multichannel oscilloscope.

Task details. Desired data rate is 8(uno) to 16(mega) analog channels divide by 4 to 16 reads per second. Extra adc "speed capacity" must be spent on summing up on arduino. Prescale is almost not needed. Each reading is 32bit, lsb is always zeroed. Plus there is 0xffffffff between packets (easiest binary proto, i really hate those ascii low-quality slow shit, but this is personal and offtopic). So now you got the setup and purpose, lest get down to my simple sketch

```
// defines for setting and clearing register bits
#ifndef cbi
#define cbi(sfr, bit) (_SFR_BYTE(sfr) &= ~_BV(bit))
#endif
#ifndef sbi
#define sbi(sfr, bit) (_SFR_BYTE(sfr) |= _BV(bit))
#endif

// packet starts after indicator and goes before next such indicator.
const long packetStartIndicator = 0xFFFFFFFFl;

// values are fixed point ints 0..65534 (with LSB always cleared)
// such descision is made because least significant bit almast always == noise;
// also its just easist pck splitting scheme
const long packetValueMask = 0xFFFFFFFEl;

const int numPins = 8;

long sensorValues[numPins+1];

// TODO: configure this from host via serial (inside setup)
int pinNumbers[] = {A0, A1, A2, A3, A4, A5, A6, A7, A8};
//int pinNumbers[] = {A0, A1, A2, A3, A4, A5, A6, A7, A8, A9, A10, A11, A12, A13, A14, A15};

// 1 reading is 10 bit. we can make 2^6==64 readings and sum them up (to top up to full 16 bit, to make kind of digital expoure)
// upd. 1 reading is counted as 16 bit, for host convenience (no matter or real adc)
// sum up like 256 of 16-bit readings to get 24bit value. send as 32bit long variable.
const int adcOrder = 10;
const int readingsOrder = 8;
const int targetOrder = 24;
const int numReadings = 1 << readingsOrder; //64;

void setup() {
  // TODO: reset ADCSRA, or it would not work. Also: get clue on free run mode
// sampling rate is [ADC clock] / [prescaler] / [conversion clock cycles]
// for Arduino Uno ADC clock is 16 MHz and a conversion takes 13 clock cycles
//ADCSRA |= (1 << ADPS2) | (1 << ADPS0);    // 32 prescaler for 38.5 KHz
//ADCSRA |= (1 << ADPS2);                     // 16 prescaler for 76.9 KHz
//ADCSRA |= (1 << ADPS1) | (1 << ADPS0);    // 8 prescaler for 153.8 KHz

//sbi(ADCSRA,ADPS2); cbi(ADCSRA,ADPS1); sbi(ADCSRA,ADPS0); // set prescale to 32 for 38.5 KHz
//sbi(ADCSRA,ADPS2); cbi(ADCSRA,ADPS1); cbi(ADCSRA,ADPS0); // set prescale to 16 for 76.9 KHz
//cbi(ADCSRA,ADPS2); sbi(ADCSRA,ADPS1); sbi(ADCSRA,ADPS0); // set prescale to 8 for 153.8 KHz

  sensorValues[numPins] = packetStartIndicator;
  //analogReadResolution(10);
  Serial.begin(115200, SERIAL_8N1);
  //Serial.begin(250000, SERIAL_8N1);
  //Serial.begin(500000, SERIAL_8N1);
}

void zero_values() {
  int i;
  for(i=0; i<numPins; i++) {
    sensorValues[i] = 0;
  }
}

void clear_lsb() {
  int i;
  int shiftOrder = targetOrder - (adcOrder + readingsOrder);
  for(i=0; i<numPins; i++) {
    sensorValues[i] <<= shiftOrder;
    sensorValues[i] &= packetValueMask;
  }
}

void serial_write() {
  Serial.write( (uint8_t*)sensorValues, sizeof(long)*(numPins+1) );
}

void loop() {
  int i, j;
  zero_values();
  for(i=0; i<numPins; i++) {
    for (j=0;j<numReadings; j++) {
      sensorValues[i] += analogRead(pinNumbers[i]);
    }
  }
  clear_lsb();
  serial_write();
}

```

I am weak with reading avr datasheets and lacking of knowledge on internals. My question is tied with my desire to switch it to freerun mode. I really dislike analogRead, seems it was written by real juniors, and is real slow. AFAIK free run mode is something when you have interrupt function running when conversion is done. I feel (dont know but really feel) that working with serial inside interrupt is a bad idea. How, in somple words, this can be reworked to event-based ISR with sending over serial when you would encounter inside your interrupt following: `currentPin == lastPin && currentReading == numReading` means *you have summed up desired bumber of readings, and this is last pin, so its time to post it over serial*.

# Answer
> 1 votes
In the Arduino environment sending data over serial inside an interrupt is seldom a good idea. That's not to say it's impossible, you just need to keep certain caveats in mind.

The chief of which is that when the TX buffer fills up everything will lock up.

So with that in mind, if you can *guarantee* that all your data from one interrupt will be completely sent out before the next interrupt occurs then sending serial in an interrupt can be used.

And yes, `analogRead()`, like many things in the Arduino API, is not fast. It's not intended to be fast. It is, though, intended to be simple. And also like many things in the Arduino API it's easy to out-grow them.

I am not familiar with the Atmel ADC registers (preferring PIC32 to AVR any day...) but looking at the datasheet I can see a few points of interest.

* First set the trigger source to "free running" (ADCSRB):

> * Bit 2:0 – ADTS2:0: ADC Auto Trigger Source
>
> If ADATE in ADCSRA is written to one, the value of these bits selects which source will trigger an ADC conversion. If ADATE is cleared, the ADTS2:0 settings will have no effect. A conversion will be triggered by the rising edge of the selected Interrupt Flag. Note that switching from a trigger source that is cleared to a trigger source that is set, will generate a positive edge on the trigger signal. If ADEN in ADCSRA is set, this will start a conversion. Switching to Free Running mode (ADTS\[2:0\]=0) will not cause a trigger event, even if the ADC Interrupt Flag is set.

Then set it to use the trigger source for starting conversions (ADCSRA):

> * Bit 5 – ADATE: ADC Auto Trigger Enable
>
> When this bit is written to one, Auto Triggering of the ADC is enabled. The ADC will start a conversion on a positive edge of the selected trigger signal. The trigger source is selected by setting the ADC Trigger Select bits, ADTS in ADCSRB.

And enable interrupts (ADCSRA):

> * Bit 3 – ADIE: ADC Interrupt Enable
>
> When this bit is written to one and the I-bit in SREG is set, the ADC Conversion Complete Interrupt is activated

Alternatively you could set it to use a timer for the trigger source so you have finer control over when a conversion is performed. That will help you to ensure that all of the previous data set has been sent over serial before the next interrupt occurs.

---
Tags: serial, interrupt, adc, isr
---


# Question
Title: ESP 8266 reverse digitalWrite behaviour on which pins?
I am using a device with an ESP 8266 microcontroller. I have discovered that setting `LED_BUILTIN` to `HIGH` turns the built-in LED **off** and setting `LED_BUILTIN` to `LOW` turns the built-in LED **on**. This seems to be because the microcontroller can sink more current than it can source.

Before I start using this microcontroller, I would like to know which other pins have this reverse behaviour. I've looked up datasheets for the ESP 8266 but I don't see how to discern this information. I would simply write a sketch to test, but I'm not sure what I might damage, and I'm not sure how to determine when an output pin is in the high-impedance state anyway.

**On the ESP 8266, how to know which pins are `HIGH -> 0v` and which pins are `HIGH -> 5v`?** Are the `HIGH -> 0v` pins necessarily `LOW -> 5v`? Where is this documented?

# Answer
> 2 votes
The esp8266 must have a pull-up on io 2 for boot configuration. The Wemos D1 boards put the LED in series with the pull-up resistor on io 2. This creates the 'reversed' LED behavior.

The large D1s are retired and it is hard to find a good and readable schematics. The cut out is from D1 mini schematics.

---
Tags: esp8266, pins, digitalwrite
---


title: Use of "static" with "RTClib"

text:
# Question
Title: Use of "static" with "RTClib"
I've got a question concerning the Arduino library "RTClib" by Adafruit and the use of the word "static".

Here you can see an excerpt from the example provided for the pcf8523 real-time clock:

```
#include "RTClib.h"

RTC_PCF8523 rtc;

void setup () {

  while (!Serial) {
    delay(1);  // for Leonardo/Micro/Zero
  }

  Serial.begin(57600);
  if (! rtc.begin()) {
    Serial.println("Couldn't find RTC");
    while (1);
  }

  if (! rtc.initialized()) {
    Serial.println("RTC is NOT running!");
  }
}

void loop () {
    DateTime now = rtc.now();

    Serial.print(now.year(), DEC);
    /*
    do some more stuff
    */
}

```

In the beginning of loop() they wrote:

```
DateTime now = rtc.now();

```

Thus, with every iteration of loop() "new" gets defined anew (on the heap?!), right? This appears inefficient to me.

I thought about rewriting it this way:

```
static DateTime now;    // static declaration, executed only once
now = rtc.now();    // assignment to "now" every time loop() starts over

```

In this case "new" should be allocated on the stack like a global variable, right?

I want to use "static" to increase overall performance by reducing work for the processor and the heap (thereby avoiding heap fragmentation). Does this make sense or will it cause more problems than it solves? Keep in mind that I want to learn both proper programming for Arduino and proper coding in general.

Link to the library: https://github.com/adafruit/RTClib

Thank you! :-)

**EDIT:** For some reason I CAN NOT declare `DateTime now;` in global scope or else the program won't run. Don't know why though. This is why I want to use static in the first place.

# Answer
You wrote:

> ```
> DateTime now = rtc.now();
>
> ```
>
> Thus, with every iteration of loop() "now" gets defined anew (on the heap?!), right?

No. Local variables like this are usually allocated on the stack, although the compiler may keep them in CPU registers if that helps optimization.

> ```
> static DateTime now;    // static declaration, executed only once
>
> ```
>
> In this case "new" should be allocated on the stack like a global variable, right?

No. It is allocated statically, in the .bss section, like uninitialized global variables.

> I want to use "static" to increase overall performance by reducing work for the processor

Not sure it will make much difference. Static allocation may save you a few CPU instructions compared to stack allocation (the instructions that move the stack pointer). On the other hand, it will cost you a few instructions compared to register allocation (the instructions to access the RAM).

> avoiding heap fragmentation

Stack allocation does not use the heap, and the stack never fragments.

> Does this make sense or will it cause more problems than it solves?

If you really care about sub-microsecond differences in the execution time, you should either look and the disassembly of the program, or do some benchmarking. Otherwise just write whatever makes more sense from the point of view of the program's logic: does the variable need to keep its value across calls to `loop()`? If the answer is “no”, do not use `static`.
> 2 votes

# Answer
You don't need to use the `static` keyword.

The cleanest solution is to define `DateTime` outside of the `loop` function:

```
DateTime now;

```

This will allocate the memory, and call the constructor of the class `DateTime` initializing it.

In case you would need a basic variable (like an `int`), you should initialize it, like:

```
int now = 0;

```

When you use it in `setup` or `loop` you use the created instance (without the class name to declare it):

```
void loop() {
   ...
   now = rtc.now();
}

```

Also, find a better name for `now`, because the variable is the same as the `rtc`'s function `now`.

**Update**

after your comment, it cannot be used as a global variable:

I didn't try it myself, but I suspect, the constructor calls a function that uses variables or a function that is not initialized at that point. Actually, it's quite bad practice.

Anyway, one way to circumvent and stick as much to what I wrote above, is to use a pointer instead:

```
RTC_PCF8523* rtc = NULL;

```

Than you create an empty pointer, without calling the constructor. You will do this at the end of `setup`:

```
void setup() {
   ...
   rtc = new RTC_PCF8523();
}

```

This will cause the variable to be put on the stack.

Than when using it, you call:

```
now = rtc->now();

```

Note you have to use the -\> notation, as rtc is a pointer.
> 1 votes

---
Tags: c++, arduino-due, rtc, performance
---


title: Servo motor troubles

text:
# Question
Title: Servo motor troubles
The image is as clear as I can make it.

Here are the basics of my problem. My program is meant to make 6 red LED lights in sequence fade in and out, toggle 5 white LED's on and off with a button, and make a servo rotate from 90 to 15 degrees on a button press, and revert to 0 degrees when the button is no longer pressed.

All of my code has compiled correctly, the LED's do what they are supposed to do, but the servo is acting strange. At first, it would move fine but then after a few button presses it would kind of spaz out and glitch back to place instead of smoothly move, which will not work for my purposes. After even more time, the servo stopped working at all. I looked around and found some answers saying to route it through an alternative power source, but I did that with the power module that came with my kit and it still refuses to move. I swapped it out with a different servo and that one won't work either, which makes me wonder if my wiring is incorrect - and yet the motor is on and makes vibrations, instead of moving, so I know power is getting through. In addition, the onboard LED's on the mega2560 are turning on and off in response to my button, so I know that's wired in correctly as well! So why won't the servo move, and why won't it respond to my button presses?

Basically, using a 3.3V - 5.0 volt Elegoo power module, how do I correctly wire the servo to only draw power from the 9v battery I attach to said module? I've seen people saying something about putting the grounds of the board and the module together but I don't know how to do that and I'm getting frustrated looking all over the internet trying to find out how so I figured I would just ask a question.

Wiring details:

The 5 white LED's are in parallel, and the red LED's are in series; they are all powered by the arduino's 5V power source, and wired into the arduino GND pin. Servo is connected by to pin 10, and the ground and power are both routed through the 5V power module which is attached to a 9V battery. The light on the module is on, and I have used the included jumpers to make sure I'm using the 5V source and not the 3.3V one.

Here is my code:

#include <Servo.h>
Servo servo1;
//------------------------
// White LED's:
int wL1 = 3;
int wL2 = 4;
int wL3 = 5;
int wL4 = 6;
int wL5 = 7;
//------------------------
// Red LED's:
int rL1 = 8;
//------------------------
// Buttons:
int wLbutton = 2;
int wLreading;
int wL1state = HIGH;
int wL2state = HIGH;
int wL3state = HIGH;
int wL4state = HIGH;
int wL5state = HIGH;
int wLprevious = LOW;

int servoButton = 1;
int servoState = false;
int servoReading;
int servoPrevious = LOW;
//--------------------------
// Fading:
int brightness = 0;
int fade = 1;
//--------------------------
// Delays:
long time = 0;
long time2 = 0;
long debounce = 100;

unsigned long previousMillis = 0;
const long interval = 1000;
//--------------------------

// Setup ======================================================================================================================================

void setup()
{
  pinMode(wL1,OUTPUT);          // White LED's
  pinMode(wL2,OUTPUT);
  pinMode(wL3,OUTPUT);
  pinMode(wL4,OUTPUT);
  pinMode(wL5,OUTPUT);

  pinMode(rL1,OUTPUT);          // Red LED's

  pinMode(wLbutton, INPUT);     // Buttons
  pinMode(servoButton, INPUT);

  servo1.attach(10);
  servo1.write(90);             // Servo

  if (wL1state = HIGH)
{
  wL1state = LOW;                                                              // Set the state of the all White LED buttons to low at the beginning of the circuit (this doesnt run after the first time).
  wL2state = LOW;
  wL3state = LOW;
  wL4state = LOW;
  wL5state = LOW;
}
}

// Loop =========================================================================================================================================

void loop() {

// White LED Button -----------------------------------------------------------------------------------------------------------------------------

wLreading = digitalRead(wLbutton);                                             // Read the state of the White LED Button

if (wLreading == HIGH && wLprevious == LOW && millis() - time > debounce)      // If the button is different state from last reading and ignores noise
{
  if (wL1state == HIGH)                                                        // If the current button state of the White LED button is high
  {
  wL1state = LOW;                                                              // Set the state of the all White LED buttons to low
  wL2state = LOW;
  wL3state = LOW;
  wL4state = LOW;
  wL5state = LOW;
  }
  else {
    wL1state = HIGH;                                                           // Otherwise, set the state of the White LED button to high
  }
  time = millis();                                                             // Set the last time the button was pressed to the current time
}

digitalWrite(wL1,wL1state);
digitalWrite(wL2,wL1state);
digitalWrite(wL3,wL1state);
digitalWrite(wL4,wL1state);
digitalWrite(wL5,wL1state);

wLprevious = wLreading;                                                        // Set the previous reading of the White LED button to current reading

// Servo Button ----------------------------------------------------------------------------------------------------------------------------------

servoState = digitalRead(servoButton);

if (servoState == HIGH)
  {
    servo1.write(75);
  }
  else
  {
    servo1.write(0);
  }

// Red LED'S breathing ----------------------------------------------------------------------------------------------------------------------------

 analogWrite(rL1,brightness);                                                 // Write the set brightness to the red LED
 brightness = brightness + fade;                                              // Set new brightness to brightness value + fade value

 if (brightness <= 0 || brightness >=255)                                     // If brightness is less than 0 or more than 255
  {
  fade = -fade;                                                               // Negate the fade value, reversing the direction of the fade
  }
  delay(10);                                                                  // Wait a short delay to see the fade
}```

# Answer
> I've seen people saying something about putting the grounds of the board and the module together

Yes, I believe this is what you need to do.

> Servo is connected by to pin 10, and the ground and power are both routed through the 5V power module which is attached to a 9V battery.

From what I understand, you are wiring like this

Servo 5V - 5V Power module

Servo GND - GND Power module

Servo Signal - pin 10 Arduino

If so, you need to make a Y-connection like this:

Servo GND - Power module GND - Arduino GND (these 3 pins should be connected together)
> 2 votes

---
Tags: power, servo, atmega2560
---


title: Can't move servo with my Nano

text:
# Question
Title: Can't move servo with my Nano
I'm new to this kind of thing. My code works on my Uno without problem with two separate servos. I've ensured that it's not any faulty leads, having tried a few other circuits with LEDs, buttons and potentiometers as well, simply switching between my Uno (which works fine) and the Nano.

I've chosen the correct port, chipset and board each time and the code uploads fine to the Nano. The Nano simply refuses to do anything I tell it.

* Digital PIN of servo goes to designated D5 pin.
* Ground goes to the GND near the Analog pins (shouldn't matter which I imagine).
* Power goes to 5V.

The code above simply tells the servo to go to a certain degree when uploaded. Could anybody tell me why the servo will not move at all with the Nano? I just bought it and I haven't hooked up any power to it other than the USB, surely it isn't fried. It lights up and flashes as well.

```
#include <Servo.h>
Servo my_servo;

void setup() {
  my_servo.attach(5);
  // Pin definition
}

void loop() {
  my_servo.write(60);
  // No. of degrees
}

```

# Answer
Connect a multi meter in series with the servo connection from the uno to the servo and see how much current it draws when working (probably less than 20ma, definitely less than 40ma). Then connect it in series with the nano and see what happens. If you get no current then you're activating the wrong pin.

If you see a current draw but the servo doesn't move then you need to use some sort of switch (transistor, FET, relay) to switch the servo. You could also compare the voltage and current read off the nano to the requirement in the datasheet for the servo. Again, this may lead you to needing a switch.

Edit based on comments above... Also try your 5v directly to the servo, then add a forward biased diode in series which should simulate the voltage drop to the level of your nano (0.4-0.6v). If the servo doesn't work with the diode and does without then you can be pretty sure the issue is insufficient volts (which is likely given the rating of 4.8v you mentioned in comments).
> 1 votes

# Answer
I has the same problem. Example: With Arduino Uno only conected to 5V from PC, the servos run perfectly, but with Nano no, maybe the servos try to move, but not. I charged the skecth on the arduino Nano and deesconect form pc, and then i supply Arduino Nano with baterry Li-ion 2s. In another words, for servos you must to supply over 6 volts. Be careful because the max voltage of servos,can be 6 volts, you can use the regulator of Arduino, severals servos produce overheating in this regulator. Yes my english is noob.
> 0 votes

---
Tags: arduino-uno, arduino-nano, servo
---


# Question
Title: How to: soil moisture measurement with WaterMark?
I am new with Arduino, and i cant find documentation about how to connect Arduino with Watermark successfully.

I would like to connect my Arduino UNO with a watermark like this:

http://guideimg.alibaba.com/images/shop/72/08/19/4/watermark-soil-moisture-sensor-w-15-cable\_3234944.jpg

Does anyone know any schema or documentation about how to do it? Have anyone tried it before?

I have found this: https://oceancontrols.com.au/datasheet/davis/ECS-014\_07395-158\_IM\_06440\_6470.pdf

but still not clear how to do it in Arduino.

Thanks you for your time.

# Answer
> 0 votes
You can google "Arduino-based system for soil moisture measurement" and the author about this paper is "Vuk Radman" .  Now, I am also try to find the method using Arduino to connect WaterMark 200ss Sensor. The paper I share to you is what I have found from GoogleScholar, but I haven't used this method yet. Nevertheless, I think the method mentioned in the paper is feasible. Hopefully, this information can help you.

---
Tags: sensors
---


# Question
Title: How to convert four uint16_t to double float IEEE754?
I am working in a Modbus project where I have to read modbus Holding and Input registers using ESP8266, I am using ModbusMaster232 library. I returns a response buffer array of uint16\_t. I need to convert the uint16\_t to double precision float. A quick test in ESP8266 shows double datatype in ESP8266 stores 8 bytes.Does anybody know how to convert four uint16\_t to double in Arduino. If so please share your knowledge.

# Answer
Here's a code fragment for converting a uint16\_t. Expand this to work with your array of ints from the library. Remember that on Arduino, - Uno and Mega, at least - doubles are implemented as floats. You won't get the precision you might be expecting.

```
double xAsDouble;    // ** only float precision despite 'double' declaration
uint16_t xAsInt;

xDouble = xInt;      // the compiler knows how to make this conversion.

```

Update: After re-reading your question, I realize you're using an ESP8266. My comments about Uno's float precision may not apply.

Update 2: After some discussion, I've learned that the Modbus return is not 4 integers, but a double being passed as 4 words, which need to be reassembled to recreate the original double. The solution will depend on the order in which the words comprising the original double are sent.

Update 3: I suggested the OP try using this general scheme:

```
// A union lets you look at memory as either (in this case) 4 ints or 1 double
union {
   uint16_t data_out[4];
   double x;
} buffer;

// Assign the data from modbus using the 'int' way of viewing menmory.
// Note I might have the ordering wrong but this is the idea:
buffer.data_out[i] = data_in[i];

```

Then reading 'buffer.x' would get the 4 words of memory as a double.

... After trying both orderings, the OP reports he is obtaining the expected result,
> 0 votes

---
Tags: esp8266, data-type, float
---


# Question
Title: Using L298N bridge to control smart lock
I want to use L298N bridge to power up and control simple smart lock. It requires 12V power supply, so I've used L298N bridge to power this smart lock.

I removed jumper from enA pin and connected enA 12V to Arduino Nano D8 pin.

I sent value 255 through this pin but smart lock did nothing. Any suggestions?

I'm using BLE controller to send turn on/off signal from Android App (but its not relevant in this case, because **analogWrite** is called).

Lock: https://www.aliexpress.com/item/32949292074.html

Here is code:

```
#define enA 8

void setup() {
  pinMode(enA, OUTPUT);
}

void loop() {
 String msg = bluetooth.read(); //using BLE controller to get message from Android app.

 if(msg == "ON"){
   analogWrite(enA, 255);
 } else if(msg == "OFF"){
   analogWrite(enA, 0);
 }

}

```

Here is setup:

# Answer
> 0 votes
You really don't want an L239D to control that lock. It's overkill. The L239D is a H-bridge that is designed to drive loads in two different polarities (forward / backwards on a motor for example).

That lock is merely a spring-loaded solenoid. You give it power and it pulls the lock back. You remove power and the spring closes it again.

All you need is a simple transistor circuit just like you'd use for a relay.

---

Since you insist on using an L239D, here's a schematic for you:

simulate this circuit – Schematic created using CircuitLab

---
Tags: arduino-nano, l298n
---