# Question
Title: Did not find fingerprint sensor :( Arduino Mega 2560 Adafruit Fingerprint Sensor
I'm getting the following error when I try to enroll fingerprints using the Arduino Mega 2560 microcontroller along with a Fingerprint Scanner:

> Did not find fingerprint sensor :(

The exact devices I'm using are as shown in the links below:

https://www.gearbest.com/development-boards/pp\_70487.html?lkid=11637831 https://www.gearbest.com/boards-shields/pp\_009769796663.html?wid=1433363

My circuit connection is:

* (Green) TX =\> Pin 0 \[PWM\]
* (White) RX =\> Pin 1 \[PWM\]

//It doesn't respond when connected to 5V, it only heats up

* (Red) VCC =\> 3.3v
* (Black) GND =\> GND

The connection is illustrated below:

The code is shown below:

```
#include <Adafruit_Fingerprint.h>

// On Leonardo/Micro or others with hardware serial, use those! #0 is green wire, #1 is white
// uncomment this line:
 #define mySerial Serial1

// For UNO and others without hardware serial, we must use software serial...
// pin #2 is IN from sensor (GREEN wire)
// pin #3 is OUT from arduino  (WHITE wire)
// comment these two lines if using hardware serial
//#include <SoftwareSerial.h>
//SoftwareSerial mySerial(10, 11);

Adafruit_Fingerprint finger = Adafruit_Fingerprint(&mySerial);

uint8_t id;

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

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

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

uint8_t readnumber(void) {
  uint8_t num = 0;

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

void loop()                     // run over and over again
{
  Serial.println("Ready to enroll a fingerprint!");
  Serial.println("Please type in the ID # (from 1 to 127) you want to save this finger as...");
  id = readnumber();
  if (id == 0) {// ID #0 not allowed, try again!
     return;
  }
  Serial.print("Enrolling ID #");
  Serial.println(id);

  while (!  getFingerprintEnroll() );
}

uint8_t getFingerprintEnroll() {

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

  // OK success!

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

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

  // OK success!

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

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

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

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

```

I used the Adafruit Fingerprint library found here:

https://github.com/adafruit/Adafruit-Fingerprint-Sensor-Library

I also soldered the wires from the sensor onto Male Pin Headers for greater connection stability.

All I get is the fingerprint sensor blinking continuously which makes me think it's not faulty but when I try to run the enroll code I get the error message highlighted above.

I also tried connecting using the Software Serial approach like below but that wasn't the solution either:

```
#include <SoftwareSerial.h>
SoftwareSerial mySerial(10, 11);

```

What could be the problem? Is my connection and code okay? Anyone have an idea on how to fix this?

The heat occurs on the encircled area below:

# Answer
Thanks for your responses @HavocRC and @Juraj

I've successfully come to the following working parameters that I have tested and have given positive results:

> **When using Arduino Mega 2560 with the SFG Demo, we use:**
>
> (Green) TX =\> Pin 1
>
> (White) RX =\> Pin 0
>
> (Red) VCC =\> 5V
>
> (Black) GND =\> GND
>
> **When using Arduino Mega 2560 with the Adafruit Library, we use:**
>
> **Using Hardware Serial Port (Serial1) \[Recommended\]**
>
> (Green) TX =\> Pin 19
>
> (White) RX =\> Pin 18
>
> (Red) VCC =\> 5V
>
> (Black) GND =\> GND
>
> //Note that you'll comment out the Software Serial initialization
>
> //as directed by the code in the Adafruit Library
>
> ```
> #define mySerial Serial1
>
> ```
>
> **When using Arduino Mega 2560 with the Adafruit Library, we use:**
>
> **Using Software Serial**
>
> (Green) TX =\> Pin 10
>
> (White) RX =\> Pin 11
>
> (Red) VCC =\> 5V
>
> (Black) GND =\> GND
>
> //The order of the PINs in the code is
>
> ```
> SoftwareSerial mySerial(10, 11);
>
> ```

In the process of testing I also used an older version of Arduino IDE, version 1.0.5 which may have helped to get the sensor working (just a hunch). It turns out the sensor only works with 5V although it heats up a bit (not to fiery levels at a go but I wouldn't leave it turned on if I was away from my laptop for a while).

By the way, for the SFG Demo to work, upload the 'blank' example first, close Arduino and then run SFG Demo. If it works then your fingerprint scanner is in working order.

For the hardware Serial options you can also use alternative PINs as follows:

> **Serial2 on pins 17 (RX) and 16 (TX)**
>
> **Serial3 on pins 15 (RX) and 14(TX)**

Links

http://www.adafruit.com/datasheets/SFGDemoV2.0.rar

https://www.arduino.cc/en/main/OldSoftwareReleases

https://www.arduino.cc/reference/en/language/functions/communication/serial/
> 1 votes

---
Tags: serial, arduino-mega, softwareserial, adafruit, heat
---


# Question
Title: Arduino MKR GSM 1400 SSL client example fails to connect
I am using the GsmSSLWebClient example which comes with the MKRGSM library. The original example works just fine, I get the arduino ascii logo. But when I change the URL the arduino doesn't get any answer:

```
//char server[] = "arduino.cc";
//char path[] = "/asciilogo.txt";
char server[] = "wepardi.fi";
char path[] = "/robots.txt";

Starting Arduino web client.
connecting...
connected
GET /robots.txt HTTP/1.1
Host: wepardi.fi
Connection: close

disconnecting.

```

From Firefox https://www.wepardi.fi/robots.txt is displayed correctly. I tried also some other sites, and from some of them I get the ascii file content correctly, and from some others not.

Something wrong with my settings?

Prints from debug mode:

```
connecting...

```

...

```
AT+USECMNG=0,0,"VeriSign_Class_3_Public_Primary_Certification_Authority_G5",1239
>
+USECMNG: 0,0,"VeriSign_Class_3_Public_Primary_Certification_Authority_G5","cb17e431673ee209fe455793f30afa1c"

OK
AT+USOCR=6

+USOCR: 0

OK
AT+USOSEC=0,1,0

OK
AT+USECPRF=0,0,1,4,"www.wepardi.fi"

OK
AT+USOCO=0,"www.wepardi.fi",443

ERROR

+UUSOCL: 0
AT+USOCL=0

ERROR
connected
GET /robots.txt HTTP/1.1
Host: www.wepardi.fi
Connection: close

disconnecting.

```

Command AT+USOCO=0,"www.wepardi.fi",443 fails

GsmWebClient (no SSL) example works fine with any hosts I have tried.

# Answer
> 1 votes
I finally found a solution to this problem. Disabling certificate validation in MKRGSM library makes the SSL connection succeed also to this site. In MKRGSM/src/GSMClient.cpp I changed

```
//     MODEM.sendf("AT+USECPRF=0,0,1,4,\"%s\"", _host);
       MODEM.sendf("AT+USECPRF=0");

```

to use modem factory settings. I still don't know what was the problem with the certificates. Thanks to everyone who tried to help with this.

# Answer
> 0 votes
The problem you have is that of redirection.

You connect to `wepardi.fi` and request the file `/robots.txt` from that host. It immediately tells you "Ok, but that file is actually on `www.wepardi.fi/robots.txt`. Go get it from there.

But it won't.

You have to go direct to the source.

Here's a trace:

```
GET /robots.txt HTTP/1.1
Host: wepardi.fi
Connection: close

HTTP/1.1 302 Found
Date: Tue, 08 Jan 2019 14:26:51 GMT
Server: Apache/2.4.6 (CentOS) OpenSSL/1.0.2k-fips PHP/7.0.32
Strict-Transport-Security: max-age=63072000; includeSubdomains;
X-Powered-By: PHP/7.0.32
Location: https://www.wepardi.fi/
Cache-Control: max-age=1296000
Expires: Wed, 23 Jan 2019 14:26:51 GMT
Content-Length: 0
Connection: close
Content-Type: text/html; charset=UTF-8

```

And when you change to `www.wepardi.fi`:

```
GET /robots.txt HTTP/1.1
Host: www.wepardi.fi
Connection: close

HTTP/1.1 200 OK
Date: Tue, 08 Jan 2019 14:27:49 GMT
Server: Apache/2.4.6 (CentOS) OpenSSL/1.0.2k-fips PHP/7.0.32
Strict-Transport-Security: max-age=63072000; includeSubdomains;
X-Powered-By: PHP/7.0.32
X-Robots-Tag: noindex, follow
Link: <https://www.wepardi.fi/wp-json/>; rel="https://api.w.org/"
Cache-Control: max-age=300
Expires: Tue, 08 Jan 2019 14:32:49 GMT
Content-Length: 67
Connection: close
Content-Type: text/plain; charset=utf-8

User-agent: *
Disallow: /wp-admin/
Allow: /wp-admin/admin-ajax.php
read:errno=0

```

---
Tags: mkr-gsm-1400
---


# Question
Title: Leonardo - always on power, status remains between computer reboots?
I'm looking for two answer here.

1. Is it possible to power a Leonardo to be always on, separate from the power from the USB host - I've tried with a full size Leonardo and a power adapter but for some reason the code didn't run when I did that. I've bought a battery shield too which will be arriving soon.
2. I want it be power-able via a switch with batteries so that I do a few things. For a start avoid it's boot up time and have it pressing a key as soon as the booted computer sees it (I'm running it as a keyboard/mouse via USB-HID) and also at one point I have the computer send serial data to have the Arduino run a different part of it's code...at this point the host computer reboots. Obviously that means the Arduino will see it's USB host disappear then come back online, will that automatically reset it and thus start it from the beginning again, or can I set it so that with always on power it will carry on doing what it is, irregardless of it's connecting to the host?

Do I need to change code, or libraries to achieve any of this?

With the theory intact answered, here is some of my actual code, i've stripped most of it out as it's just a bunch of keyboard presses

```
#include <Keyboard.h>
#include <Mouse.h>
char returnKey = KEY_RETURN;
char tabKey = KEY_TAB;
void setup() {
Keyboard.begin();
Mouse.begin();
// delay(60000); //Deploy Delay
delay(3000); //Testing Delay
// Keyboard commands
Keyboard.write(returnKey);
delay(14000);
// Welcome Screen
Mouse.click(MOUSE_LEFT);
delay(100);
}

void loop() {
}

```

# Answer
> Is it possible to power a Leonardo to be always on, separate from the power from the USB host

Yes, that is what the barrel jack is for.

> I've tried with a full size Leonardo and a power adapter but for some reason the code didn't run when I did that.

Then your code is wrong. Are you using `while (!Serial);` or something similar near the top of your code?

> For a start avoid it's boot up time

The most certain way of doing that is to not use the bootloader. Instead program the board directly with a hardware programmer disabling (or erasing) the bootloader.

> Obviously that means the Arduino will see it's USB host disappear then come back online, will that automatically reset it and thus start it from the beginning again, or can I set it so that with always on power it will carry on doing what it is, irregardless of it's connecting to the host?

The Leonardo only reboots if you open the serial port at 1200 baud, or toggle the RESET pin / button.

> Do I need to change code, or libraries to achieve any of this?

It sounds like you may need to, yes - since it's not working at the moment when if the code were correct it should work.

---

**IMPORTANT**

**Most computers will not recognize the Leonardo until the operating system is fully booted. This means you cannot use the Leonardo to interact with the BIOS or boot menu. The Leonardo does not implement the "Boot Protocol" keyboard which is required to interact with the BIOS or other pre-boot environment.**
> 1 votes

# Answer
It is possible to tell if the computer has opened or closed the serial port.

The serial port is located on the Arduino board.
By testing `if(Serial)` you can check if the serial port has been made active by the computer.
You could send keyboard and mouse events after it became active.

The fading in and out of the led at pin 13 is done by the bootloader. You could upload the sketch with a programmer to run without bootloader.

As far as I know, even without bootloader the serial port is still created.
The Teensy boards have a little more control over the USB interface.

To know what is going on and when a computer is connected, a mini linux computer is a lot easier. For example a Raspberry Pi.
The ATmega32u4 of the Arduino Leonardo has the possibilities and the information is available, but as far as I know, there are no libraries functions to use it.
> 0 votes

---
Tags: power, usb, arduino-leonardo
---


# Question
Title: Can Arduino Uno R3 board remove chip on the board
First off, got my Elegoo Uno board as Christmas gift, so this is all new to me.

Here is my problem, I built an motor project and the chip has been programmed. Can I remove the chip from the Uno board?

Or can I placing a new chip onto the Uno board?

Best regards.

# Answer
It depends, if the chip has not been soldered, but placed in an IC (DIP) socket, than you can remove the programmed chip, and use it in another circuit and place another (same) IC in the IC socket of the Uno to be reprogrammed.

You also could desolder it, but I would not advice that; also most of the Uno's having a soldered IC use SMD instead of DIP.

Also, to replace the IC, you need to install a bootloader on the IC to be placed in the new Arduino (thanks for the addition Roberto Lo Giacco).

Below is a version with DIP that easily can be replaced, hence the big IC and the socket:

Below is a version with SMD that cannot easily be replaced, hence the small IC without a socket:
> 4 votes

# Answer
Yes, you can pull the DIP chip off the board, and use it elsewhere. It will require a 16 MHz crystal and two 22pF caps (or a 16MHz resonator), at least three 0.1uF (aka 100nF) caps (connect one each from VCC, AVCC, AREF to gnd - do not connect Aref to VCC), a 10K resistor from Reset to Vcc.

If you have a hot air rework station and decide to pull off the SMD part, that chip has two VCC pins, so another 0.1uF cap is needed.
> 1 votes

---
Tags: arduino-uno
---


# Question
Title: Arduino Uno: avrdude: stk500_recv(): programmer is not responding
I have an original Arduino Uno board purchased directly from the official arduino website. I have used it successfully with IDE v1.8.5 on my Windows 10 laptop for various projects in the last 6 months.

Recently my laptop stopped working and I tried shifting the IDE to my old windows 8 laptop. I installed the latest IDE v1.8.8 on it. But whenever I am trying to upload the sample blink code to the arduino, I am getting the following - "stk500\_recv(): programmer is not responding" error.

I have verified that the I have selected the right board - "Arduino/Genuino Uno" in the IDE. I can also see the driver installed in the windows "Device Manager" with COM3 as the port. I have selected COM3 as the port in the IDE as well.

Thinking that its a bit old windows 8 laptop, I tried installing the IDE on two other newer laptops (windows 7 and 10) along with the same troubleshooting steps as above. But unfortunately, same results.

I looked at the many links on internet and tried the following steps, but no luck so far.

* Resetting the board: It flashes the LED on the pin 13 twice which means the chips are ok and resetting the board. This where I think the board is functioning well.
* Tried using both "Upload" and "Upload using programmer" mode from IDE.
* Restarting laptops multiple times.
* Unplugging USB cable between laptop and arduino several times.
* Reinstalled arduino ide version 1.8.5 which was on my old laptop.

Do I need to choose Tools --\> Programmers? I guess this is not needed as I am using USB to upload code, but please advice. What else can I try? Please help !!

Here is the complete error:

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

         System wide configuration file is "C:\Users\Anurag\AppData\Local\Arduino15\packages\arduino\tools\avrdude\6.3.0-arduino14/etc/avrdude.conf"

         Using Port                    : COM3
         Using Programmer              : arduino
         Overriding Baud Rate          : 115200
         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 : Arduino
         Description     : Arduino
         Hardware Version: 3
         Firmware Version: 4.4
         Vtarget         : 0.3 V
         Varef           : 0.3 V
         Oscillator      : 28.800 kHz
         SCK period      : 3.3 us

avrdude: AVR device initialized and ready to accept instructions

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

avrdude: Device signature = 0x1e950f (probably m328p)
avrdude: reading input file "C:\Users\Anurag\AppData\Local\Temp\arduino_build_337690/Blink.ino.hex"
avrdude: writing flash (930 bytes):

***Writing | avrdude: stk500_recv(): programmer is not responding
######avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_recv(): programmer is not responding***
================================================================

```

**UPDATE 1:** In the meanwhile -

* I also changed my USB cable.
* Tried on a MAC laptop as well.

No luck with these approaches as well.

I also tried the Arduino loopback test with my board and it is giving me positive results which suggests that my board is processing the data. May be the problem is only when uploading the code. I have updated my original post as well with these steps.

Still need help!

Thanks in advance,

Anurag

# Answer
> 1 votes
The output shows that avrdude (the uploading program) can contact your Arduino and is able to detect some settings. But as soon as it tries to upload it doesn't get the correct answers. Seems like the bootloader is damaged. Try to burn a new bootloader (you need an ICSP programmer for that, another Arduino with a special sketch and some basic hardware might do the job too).

---
Tags: arduino-uno, arduino-mega, arduino-ide, arduino-nano, arduino-due
---


# Question
Title: Calling external function from a class function
I'll try to explain my need:

1. I have a generic library I created, called `myIOT.h`.
2. This class have a pre-configured MQTT and wifi setup.
3. Inside this library there is a `mqtt_callback` function, for all generic commands, such as `boot_time` and `connection_status`.
4. BUT, this library serves in several of my iot device's code, that each one has a few more mqtt commands, that is tailored just for s specific device, and I looking for a way that `iot.mqtt_callback(ext_mqtt_func)` will get as parameter a local ( which belong to the sketch and not to the library ), that will have the additional code needed.

I'll try to explain more clearly:

```
void myIOT::mqtt_callback(ext_mqtt_func){
if (a == true ) {
do something

};

else {

ext_mqtt_func()); // calling another fucntion that belongs to sketch and not library

}

```

# Answer
> 1 votes
Yes, you can do it.

You pass function pointer as function parameter.

See this stackoverflow question:

https://stackoverflow.com/questions/2582161/c-function-pointer-as-parameter

---
Tags: library
---


# Question
Title: Dynamic allocation/ Pointer to Pointer to update an Array containing parameter
`topicArray` defined as follows:

```
const char* msgTopic = "Home/Messages";
const char* groupTopic = "Home/All";
char* deviceName = deviceTopic;
const char* topicArry[2] = {deviceTopic, groupTopic};

```

But `deviceTopic` can be changed during code run, and I wish that `topicArray` containg `deviceTopic` will have the correct value after `deviceTopic` has changed.

What is the right way doing so ?

# Answer
> 2 votes
You may try something like this:

```
const char* topicArry[2] = {NULL, groupTopic};
const char** const pDeviceTopic = &topicArry[0];
#define deviceTopic (*pDeviceTopic)

```

Arguably not very elegant, but now when you assign, e.g.

```
deviceTopic = msgTopic;

```

you are actually writing into `topicArry[0]`.

---
Tags: programming, array, pointer
---


# Question
Title: Attempting to read random string from SD card
I was wondering if anyone knew how to read in a random string from a file named "PhraseList.csv" or "PhraseList.xlsx" (whatever is easier)? There is a list of 10k.

```
#include <SD.h>
#include <SPI.h>

File myFile;

void setup()
{

 // Open serial communications and wait for port to open:
  Serial.begin(9600);
   while (!Serial) {
    ; // wait for serial port to connect. Needed for Leonardo only
  }

  Serial.print("Initializing SD card...");

  if (!SD.begin(chipSelect)) {
    Serial.println("initialization failed!");
    return;
  }
  Serial.println("initialization done.");

  // re-open the file for reading:
  myFile = SD.open("PhraseList.xlsx");
  if (myFile) {
    Serial.println("PhraseList.xlsx":);

    // read from the file until there's nothing else in it:
    while (myFile.available()) {
        Serial.write(myFile.read());
    }
    // close the file:
    myFile.close();
  } else {
    // if the file didn't open, print an error:
    Serial.println("error opening Phrase List");
  }
}

void loop()
{
    // nothing happens after setup
}

```

# Answer
Reading an individual string from a list in a file is not a simple operation. Well, it's "simple", but takes a lot of work.

It's not possible to say "Get me line number 2984 from the file" with a normal text file. You, instead, have to get each line in turn, discarding the ones you don't want, until you get to line 2984.

A better way would be to create custom "indexed" file format with a file header structure describing the rest of the file. That header structure would contain (amongst other possible things) the offset within the file of each string it contains.

For example you may choose to have the simplest arrangement - a list of 32 bit integers (4 bytes each), each one a simple offset from the start of the file for the string that corresponds to the same number, and have the strings NULL terminated in the file.

Such as:

```
00000000: 0c000000 17000000 22000000 53747269  ........"...Stri
00000010: 6e67206f 6e650053 7472696e 67207477  ng one.String tw
00000020: 6f005374 72696e67 20746872 656500    o.String three.

```

The idea with this now is you can seek in the file to "String no * 4" and read 4 bytes as an `unsigned long` (arranged *little endian*, like the Arduino uses), then use that value to do another seek. From there you can read bytes until you hit `\0`, at which point you know you have finished the string.

In the example above the string "String one" is located at offset 12 within the file. That's 0x0C in hexadecimal, or 0x0c 0x00 0x00 0x00 as a little-endian 32-bit integer. That's the first 4 bytes in the file. So you read those, interpret them as a 32-bit integer (12), then seek to that location in the file to get your string.

```
void readString(int num) {
    // Seek to the index entry
    myFile.seek(num * 4);

    // Read the index entry
    unsigned long offset = 0;
    myFile.read(&offset, 4);

    // You might want to add some sanity checking here

    // Seek to where the index points to
    myFile.seek(offset);

    // Read each character until you get a NULL.
    char c = myFile.read();
    while (c > 0) {
        Serial.write(c);
        c = myFile.read();
    }
    Serial.println();
}

```
> 1 votes

---
Tags: arduino-uno, sd-card, string, sd
---


# Question
Title: Am I able to set up a code where I can have two ways of turning something on?
I am pretty new to Arduino.

I've created a code with the help of many YouTube tutorials to control a servo with a button. I decided it has gotten a little un-exciting so I've been trying to add a sound sensor module to it so that if you clap or whatever, it will control the servo in the same way the servo did. Is it possible to control the servo with the button *and* the sound sensor so that I have to ways of turning on the servo at the same instance.

The code I currently have just runs the servo constantly and does not stop, you'll probably see what I mean when I attach the code below. I'm just looking for help on this issue as I don't have a lot of experience with this, but my guess is it is not possible.

```
    #include <Servo.h>;

    const int buttonPin = 8;
    int soundSensor = 2;
    Servo servo;

    int buttonState = 0;

    void setup()
    {
      servo.attach(3);
      servo.write(80);

      pinMode(buttonPin, INPUT);

      pinMode (soundSensor, INPUT);
    }

    void loop() {
      int statusSensor = digitalRead (soundSensor);

      if (statusSensor == 1)
      {
        servo.write(0);
        delay(1000);
        servo.write(180);
        delay(500);
      }
      else
      {
        servo.write(80);
      }

      buttonState = digitalRead(buttonPin);
      if (buttonState == HIGH)
      {
        servo.write(80);
      }
      if (buttonState == LOW)
      {
        servo.write(0);
        delay(1000);
        servo.write(180);
        delay(500);
      }
    }

```

# Answer
> 1 votes
Just cobled this together, untested but should give you some hints in the right direction.

In the main loop it checks the condition of the button and also the sound detector. If either are active it sets a bool to true. at the end of the loop, if either are true it calls the servo function that then powers the servo. hopefully you will be able to pull this apart to add more triggers

```
#include <Servo.h>;

const int buttonPin = 8;
int soundSensor = 2;
Servo servo;

int buttonState = 0;
int statusSensor = 0;

bool runServo = false;  // bool setting to start the servo

void setup()
{
  servo.attach(3);
  servo.write(80);

  pinMode(buttonPin, INPUT);
  pinMode (soundSensor, INPUT);
}

void loop() {
  statusSensor = digitalRead (soundSensor);
  buttonState = digitalRead(buttonPin);

    runServo = false;  // start of loop reset the runServo flag

  if (statusSensor == 1)
  {
    runServo = true;
  }

  if (buttonState == HIGH)
  {
    runServo = true
  }

  if (runServo == true)
  {
    servoFunction();//call the servoFunction code
  }

};

void servoFunction(){
    servo.write(0);
    delay(1000);
    servo.write(180);
    delay(500);

}

```

Spriggsy

---
Tags: arduino-uno, code-review
---


title: Can the IDE handle a 32khz main clock?

text:
# Question
Title: Can the IDE handle a 32khz main clock?
I read somewhere that having the main clock be 32768Hz messes not only with micros() and millis(), but with some other stuff too. Is this true? Will I have to forgo the Arduino IDE to program for an avr running at 32768Hz?

# Answer
> 3 votes
Yes, things will break. The main culpret is this:

```
#define clockCyclesPerMicrosecond() ( F_CPU / 1000000L )

```

With any value below 1000000 the result of that calculation will be 0.

That means code like `micros()` will break, since it uses:

```
return ((m << 8) + t) * (64 / clockCyclesPerMicrosecond());

```

64/0 is ... um ... yes... And whatever that ends up being is then multiplying the tick count. So ... the result of `micros()` is ... um ... yes...

In fact, when trying to compile anything you get (certainly on UECIDE):

```
• Error at line 103 in file wiring.c:
    ‣ division by zero [-Werror=div-by-zero]

```

Since that's erroring when compiling code there's not a lot you can do about it.

However, one idea does spring to mind - one that is a little "crazy" I guess.

* Set your boards.txt entry to 3276800Hz

The calculations will all then be valid - however, they will all be *out by a factor of 100*.

With the board actually running at 32768, and the API thinking it runs at 3276800, all you need to do is use values 100x less than you would normally in your calculations.

For instance, to delay 1 second you'd use `delay(10);` instead of `delay(1000);`. Or you'd multiply the return value of `millis()` by 100 to get the real number of milliseconds.

Baud rates will have to be 100x faster - so use `Serial.begin(960000);` instead of `Serial.begin(9600);`.

Of course, the `clockCyclesPerMicrosecond()` is not geared towards working with values like 3276800, and `F_CPU/1000000L` will result in `3` not `3.2768` as you'd like, so timing calculations will be a little bit off. You may need to tweak things like baud rates accordingly to compensate.

---
Tags: avr, oscillator-clock
---


# Question
Title: Can I control 4 DC Brushless motors with arduino uno and Adafruit motor shield?
I need to control 4 DC brushless motors. I have no experience with arduino or coding. After some research the cleanest setup seems to be using the Adafruit motor shield, however the motors I'm using have 5 wires. Can I still make this work? I envision the motors being connected to the shield via the negative and positive power wires, but what do I do with the rest? Thank you in advance.

# Answer
You don't need the motor shield at all. The motor you link to has its own driver built in.

According to the connection table on the page you link to:

* Red wire to +24V
* Green wire is for sensing the RPM - you can ignore it
* Yellow wire is the direction select - connect to any GPIO
* Black wire is ground - connect to 24V GND *and* Arduino GND.
* Blue wire is PWM control. Connect to any PWM output on the Arduino

Note that the motor will probably spin immediately power is applied until your sketch tells it to stop by driving the PWM output LOW (or 0% duty cycle). There appears to be a 15-25kΩ (typical) pullup resistor on that pin, so adding a smaller pulldown resistor (say 1kΩ) on it should force it to be off until you turn it on.
> 0 votes

---
Tags: arduino-uno, arduino-ide, motor, adafruit, arduino-motor-shield
---


# Question
Title: Generating a 38 KHz signal without timers
I am currently trying to generate a 38 KHz signal for my TSOP4838 (http://www.vishay.com/docs/82459/tsop48.pdf) with an ATtiny84A.

I know the real thing would be to utilize a timer but the ATtiny only has 2 Timers (T0 and T1). Timer1 can not be used because it is already used by other features.

I don't want to transmit actual data to the TSOP4838. I only want to use it as a light barrier (Iknow there are better ICs for that but I am stuck with the ones I already have).

So what I have tried so far is setting up timer0 for my PWM stuff and everything worked IR LED-wise. The delay functions (`micros()`, `millis()` etc.) stopped working and prevented me from using my serial communication. I tried to change the code in `wiring.c` to use a prescaler of 1 instead of 64 by changing the defines but that didn't work out.

I am now stuck with two options I guess:

A: somehow modify timer0 to generate my 38 KHz signal and still provide correct functionality for the timing functions.

B: let timer0 be initialized the way the Arduino wants it and utilize the delay functions to blink the IR LED.

I would prefer A but Google didn't give me a solution. Maybe some of the gurus around here could help?

If A is not possible can somebody give me a hint how to "bit bang" the IR LED with delay? (I guess that is a silly question but I can't figure it out at the moment :()

# Answer
> 1 votes
A 38kHz square wave at 50% duty cycle would be a transition running at 38x2=76kHz. That is 1/76,000 = 0.000013158s, or 13.158µs. That's quite a high accuracy to try and achieve with delays on a small chip like the 84A.

I assume you are running it at 8Mhz (internal calibrated RC oscillator) - that means each clock tick is 1/8000000=125ns long. so 13156ns would equate to 105.248 clock cycles. That can't happen, so the closest you would get is 105 clock cycles, which would be 13125ns, or 76.190kHz, or an end frequency of 38.095kHz. So fairly close.

So now you need to create a tight loop that is *exactly* 105 clock cycles long *including* the toggling of the IO pin *and* the comparisons and branches for the loop. For that you need to do some careful instruction cycle counting and work in assembly language. Page 268 of the data sheet details the clock cycles used for each instruction.

The simplest (though most long winded) loop would be an OUT or SBR (depending on port) instruction (1 clock) to set the IO pin HIGH, then 104 NOPs (1 clock each), then an OUT or CBR to set it LOW (1 clock), then 102 NOPs (1 clock each), then an RJMP to go back to the start (2 clocks). That is then a grand total of 210 clock cycles, or 1/(210\*0.000000125) = 38.095kHz.

You could compress all the NOP instructions down into a tight loop themselves by setting a register to a pre-defined loop count value, decrement it each pass - repeat if it's not 0. That means even more careful instruction counting to get that loop to equal the 104 or 102 clock cycles needed for the precise timing.

**However** all that is pretty much academic, because the loop will keep being interrupted by your timer 0 interrupt and cause *jitter* in your output as the interrupt routine is being run instead of your IO pin driving loop.

If you don't need absolutely reliable timing anyway it might be easier (though far less accurate) to use the `micros()` function to find when 13µs have elapsed and do it all in C instead of assembly. You will still need high speed direct port access rather than using `digitalWrite()` since `digitalWrite()` adds way too much overhead to be able to do that kind of timing reliably. Something like:

```
uint32_t start = micros();
while(1) {
    if (micros() - start >= 13) {
        start = micros();
        PORTB ^= 1<<4; // toggle B4
    }
}

```

Note the use of `while (1)` there rather than relying on the `loop()` function repeating itself. There is quite a large overhead in using the auto-repeating of `loop()` that can be avoided by looping within it with a `while (1)` like that. Of course, anything else you want to happen repeatedly would have to be inside that `while` loop, and most likely would impact your output timing somewhat.

So a much better solution would be to use a timer, since that is what they are there for. But fidding with timers breaks things like `millis()` and `delay()`. So the answer to that is *don't use `millis()` and `delay()`*. Instead create your own timing functions that are controlled by your own interrupt that does the pin IO - instead of relying on a system provided tick you create your own. If your interrupt is firing every 13µs then add 13 to a global counter - that counter is then the number of microseconds that have passed. When that count exceeds 1000 you subtract 1000 (*don't* zero it) and add 1 to a millisecond counter. Now you have the equivalent to `millis()` in a global (*remember to make it volatile*) variable that you can use instead of `millis()`.

# Answer
> 1 votes
It would be much easier to use a dedicated IC such as a 555 or a 556. I built such a system based on these circuits IR Bream Break Detector

# Answer
> 0 votes
Several approaches are possible, some of which, but far from all, have been listed in previous answers. In following, I assume that by “use it as a light barrier” you mean that the TSOP4838 will be part of an object-intrusion detection system, rather than for transmitting data. As a consequence, some jitter and/or inaccuracy is acceptable. Note, all of the following methods assume that Arduino core code has set up timer 0 to support ordinary micros() and millis() calls.

Approach 1: Compute or calibrate a simple loop: In `setup()`, run a series of tests that find a value `k` to minimize error, via C code equivalent to the following Python:

```
for k in plausibleRange():
  err = genBurst19(k)
  if err < bestErr:
    bestErr = err
    bestK = k

```

where `genBurst19()` is like the following:

```
def genBurst19(k):
  t1=micros()
  for i in range(38):
    setPortBit(i&1)
    for j in range(k):
      nop
  t2=micros()
  return abs(t2-t1-500)

```

In other words, `genBurst19()` sends a burst of 19 cycles, which at 38 KHz should take 500 microseconds. It returns a measure of error to the caller.

After finding `bestK`, you can subsequently use it as a limit for other delay loops, or could just use repeated calls to `genBurst19(bestK)` whenever you want to generate some "38KHz".

Note, you might wish to try some minor variations, such as adding a second or third `nop` in the inner delay loop, or generating some higher multiple of 19 cycles. While a delay loop containing a single `nop` (or no `nop` at all, just an empty loop) has finer resolution than a loop with multiple `nop`s, it may happen (depending on loop code) that a smaller error occurs with more. \[But also see Approach 3 regarding fine tuning.\]

Summary: This method is easy to use, has low jitter, but is limited in the accuracy it can attain.

Approach 2: Use a method analogous to Bresenham's to produce a signal with high-accuracy period, on the average, but with more jitter than Approach 1. Bresenham's algorithm tries to draw a straight line, on an x-y grid of pixels; you are trying to draw a straight line, on a time-vs-cycles grid.

In this method, you keep track of how many microseconds total should have elapsed, and when you fall too far behind, issue a delay with `k-1` instead of `k`, to catch up; or if too far ahead, with `k+1`, to drop back. See my answer to stackoverflow 8113883 for a little more re Bresenham's method, in the line drawing context.

Summary: By applying Bresenham's method, you can get the average frequency as close as you like (when averaged over a few milliseconds).

Approach 3: This is more of a fillip than a whole approach. It modifies Approach 1 by adding the following C code before the `for j in range(k): nop` loop. It also needs a second parameter, `l`.

```
switch (l) {
  case 9: nop;
  case 8: nop;
  case 7: nop;
  case 6: nop;
  case 5: nop;
  case 4: nop;
  case 3: nop;
  case 2: nop;
  case 1: nop;
  case 0: ;
}

```

To use this approach, first find the best `k` using a series of calls like `err = genBurst19(k,5)`. Then find the best `l` via `err = genBurst19(bestK,l)` for `l` from 0 to 9. \[Note, a number smaller than 9 can be used in the above, if the `for j in range(k): nop` loop uses fewer cycles.\]

Summary: This fillip can tune `genBurst19()` closer to single-nop accuracy.

# Answer
> 0 votes
I just built an NE555 based circuit for 38 kHz. Sender is a 950 nm IR diode, receiver is said TSOP4838. According to the NE555 Data Sheet, the frequency in astable mode is *approximately*

f ≈ 1.44 / (C (RA \+ 2 RB) )

Using values of RA = 1.8 kΩ, RB = 18 kΩ, C = 1 nF, the NE555 should generate a frequency of 38.095 kHz. Using these values, my circuit generated 34 kHz with some small changes of a few 100 Hz when using different resistors/capacitors (due to tolerance), but it came nowhere close to 38 kHz. This is probably because the frequency formula is an approximation. The easiest fix is probably to put a variable capacitor in parallel to C and use it for fine tuning, or a variable resistor to RB.

This may not be necessary in every case as the TSOP48xx uses a band pass filter, and 34 kHz are still recognized, only at lower responsivity. Note that this IR receiver (as well as others) have some limitations on pulse length, so you cannot constantly send 38 kHz but only for up to 70/f, which is around 1.8 ms. After that, the TSOP output switches off again, probably because the internal threshold is raised.

## Measurements

Some measurements from a logic analyzer (PulseView). This is from the above NE555 circuit which should yield 38 kHz.

I used an AND IC (74HCT08) to modulate a signal, generated by an Arduino, on top of the 38 kHz carrier. Sampling rate is 12 MHz. The probes measure:

* D0: TSOP4838 output signal
* D1: IR signal (`carrier AND signal`)
* D2: Arduino `signal`
* D3: 38 kHz `carrier` from NE555

---
Tags: pwm, timers, attiny, ir
---


# Question
Title: Creating a webserver on a Wemos D1 mini pro
I am trying to put a web server on my Wemos D1 mini pro. I am using this example for the Arduino code: https://github.com/wemos/Arduino\_D1/blob/master/doc/esp8266wifi/server-examples.rst

```
#include <ESP8266WiFi.h>

const char* ssid = "GL-AR300M-ceb";
const char* password = "********";

WiFiServer server(80);

void setup()
{
  Serial.begin(115200);
  Serial.println();

  Serial.printf("Connecting to %s ", ssid);
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED)
  {
    delay(500);
    Serial.print(".");
  }
  Serial.println(" connected");

  server.begin();
  Serial.printf("Web server started, open %s in a web browser\n", WiFi.localIP().toString().c_str());
}

// prepare a web page to be send to a client (web browser)
String prepareHtmlPage()
{
  String htmlPage =
     String("HTTP/1.1 200 OK\r\n") +
            "Content-Type: text/html\r\n" +
            "Connection: close\r\n" +  // the connection will be closed after completion of the response
            "Refresh: 5\r\n" +  // refresh the page automatically every 5 sec
            "\r\n" +
            "<!DOCTYPE HTML>" +
            "<html>" +
            "Analog input:  " + String(analogRead(A0)) +
            "</html>" +
            "\r\n";
  return htmlPage;
}

void loop()
{
  WiFiClient client = server.available();
  // wait for a client (web browser) to connect
  if (client)
  {
    Serial.println("\n[Client connected]");
    while (client.connected())
    {
      // read line by line what the client (web browser) is requesting
      if (client.available())
      {
        String line = client.readStringUntil('\r');
        Serial.print(line);
        // wait for end of client's request, that is marked with an empty line
        if (line.length() == 1 && line[0] == '\n')
        {
          client.println(prepareHtmlPage());
          break;
        }
      }
    }
    delay(1); // give the web browser time to receive the data

    // close the connection:
    client.stop();
    Serial.println("[Client disonnected]");
  }
}

```

It uploads fine and when I open the serial monitor get this:

Connecting to GL-AR300M-ceb . connected Web server started, open 192.168.8.119 in a web browser

When I go to the IP address that it gives in the monitor, I only see a blank page. I also can't inspect element, so it doesn't load the HTML part I guess.
When I change the code like this:

```
if (client.available())
{
//        String line = client.readStringUntil('\r');
//        Serial.print(line);
//        // wait for end of client's request, that is marked with an empty line
//        if (line.length() == 1 && line[0] == '\n')
//        {
//          client.println(prepareHtmlPage());
//          break;
//        }
          client.println(prepareHtmlPage());
      }

```

then i see this

And when i add the break in the code like so:

```
client.println(prepareHtmlPage());
break;

```

in the code, i get the blank page again.

Does someone have an idea what the problem might be?

# Answer
you should go for the "Advanced Webserver" example provided by the ESP8266 libraries in your Arduino IDE. The webserver is using callbacks like

```
server.on ( "/", handleRoot );
server.on ( "/test.svg", drawGraph );

```

and so on. Then you can use these handles to give back a html page to your browser like

```
server.send(200, "text/plain", message);       //Response to the HTTP request

```

**Note how the function returns an 200 http code to your browser, which is mandatory for showing up your web page!**
> 1 votes

---
Tags: esp8266, web-server
---


# Question
Title: Keyboard.h: No such file or directory - Arduino pro micro (leonardo)
I've just bought a new pro-micro and I want to simulate some keyboard inputs with it, the thing is the Arduino IDE (version 2:1.0.5) can't seem to find neither HID.h or Keyboard.h libraries. The steps to reproduce the problem are:

* plug the device using usb cable on the pc
* Open arduino ide
* try to compile my code
* it fails with the error

> test\_keyboard.ino:27:22: fatal error: Keyboard.h: No such file or directory compilation terminated.

The code is:

```
#include <Keyboard.h>

void typeKey(int key)
{
  Keyboard.press(key);
  delay(50);
  Keyboard.release(key);
}

/* Init function */
void setup()
{
  // Begining the Keyboard stream
  Keyboard.begin();

  delay(400);

  //Keyboard.press(KEY_LEFT_GUI);

  Keyboard.press(KEY_CTRL);
  Keyboard.press(KEY_ALT);
  Keyboard.press(KEY_T);

  Keyboard.releaseAll();

  delay(100);

  Keyboard.print("echo 'hello world'");

  typeKey(KEY_RETURN);

  delay(100);

  // Ending stream
  Keyboard.end();
}

/* Unused endless loop */
void loop() {}

```

By the way, I'm running this on linux, after pluging it and running `lsusb` on terminal I got: `Bus 002 Device 071: ID 2341:8036 Arduino SA Leonardo (CDC ACM, HID)`

# Answer
The Keyboard functions were moved into their own library in Arduino IDE 1.6.6/Arduino AVR Boards 1.6.9. In previous Arduino AVR Boards versions, those functions were part of the core library and there was no Keyboard library or Keyboard.h. Since you're using a very outdated version of the Arduino IDE, you don't have a Keyboard library, thus the error. There are two options to solve this problem:

---

For anyone wanting to write code that's backwards compatible with old IDE versions, you can do this:

```
#if ARDUINO > 10605
#include <Keyboard.h>
#endif

```

---

Reference: https://github.com/arduino/Arduino/pull/3304
> 2 votes

# Answer
Don't hang around in the stone age, step forward to 2019 and join us with the newest Arduino IDE.

Do you use the newest linux version, for example Ubuntu 18.10?

Remove all arduino related packages from the repositories.
Be sure to remove the package librxtx-java.
You don't need to install Java, jdk, openjdk, jre or any of those.
If you use snap, remove the Java and Arduino from the snap as well.

When you have used such an old version, I suggest to delete the hidden `.arduino15` folder from your HOME folder.

Perhaps you have downloaded libraries that are now included with the Arduino IDE. You could check the "libraries" folder (in the same folder as the folders of your projects) and delete unused libraries.

Download the Arduino IDE from the arduino.cc website.
The 32-bit version for a 32-bit linux system, and the 64-bit version for a 64-bit linux system.
Unpack it somewhere in under your HOME folder. You can make a shortcut to the file "arduino" and run the shortcut.
Don't make changes to the stardard Arduino system files (the Arduino IDE that you have downloaded and unpacked). Sometimes it is needed to make changes to the files in the hidden `.arduino15` folder.
> 0 votes

---
Tags: arduino-leonardo, arduino-pro-micro
---


title: Array is affecting digitalread values

text:
# Question
Title: Array is affecting digitalread values
i want to turn on an led with two buttons. If either of the buttons is pressed i want the led to turn on while the button is pressed and stay off if nothing is pressed. i have two sets of code, they both do the same thing, but the second set of code causes the led to stay in the on position even when nothing is being pushed and i dont understand why.. i am using pulldown resistors on both the buttons.

This is the first set of code that works properly:

```
class Button {

  public:

    int pin;
    int state;
    int location;
    int Speed;
    int Direction;
    int active;
    int prevstate;

    Button(int pin1, int state1, int location1, int active1, int previousState)
    {
      pin = pin1;
      state = state1;
      location = location1;
      active = active1;
      prevstate = previousState;
    }
};

Button button(7,0,0,0,0);
Button button2(8,0,0,0,0);
Button buttons[2] = {button, button2};

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

void loop() {
   if (digitalRead(button2.pin) == HIGH){
             digitalWrite(ledPin, HIGH);
          } else {
          // turn LED off:
          digitalWrite(ledPin, LOW);
          }
       if (digitalRead(button.pin) == HIGH){
             digitalWrite(ledPin, HIGH);
          } else {
          // turn LED off:
          digitalWrite(ledPin, LOW);
          }
}

```

this is the code i want to use but it is not working.. the led stays in the on position:

```
void loop(){
  for (int i = 0; i<sizeof(buttons); i++){
    if(digitalRead(buttons[i].pin) == HIGH){
          digitalWrite(ledPin, HIGH);
          } else {
          // turn LED off:
          digitalWrite(ledPin, LOW);
          }
    }
}

```

also if i change

```
if(digitalRead(buttons[i].pin) == HIGH)

```

to

```
if(digitalRead(buttons[0].pin) == HIGH)

```

the code works for the first or second button alone in the array.. but not both???

# Answer
You seem to have made 4 button objects: button, button2, and buttons\[2\]. buttons\[0\] and buttons\[1\] are full button objects whose first member, .pin, is initialized to the addresses of `button` and `button2`, respectively. This is probably not what you intended.

Did you mean to create:

```
Button buttons[2] = {
   {7,0,0,0,0},
   {8,0,0,0,0}
};

```

, an array of two initialized button objects?
> 1 votes

# Answer
I have to disagree that your first sketch is working. I suppose that a very fast blinking led seems to be "on".

When you describe what should happen in a logic way, then you can put that into code.

The logic is: The led is on, if at least one of the buttons is pressed.
In other words: The led is off, if no button is pressed, else the led is on.

This logic has as a result that the led stays on if a second button is pressed and after that the first button is released. I assume this is okay.

For **two buttons** it is possible to check both conditions.

```
if (digitalRead(button.pin) == HIGH || digitalRead(button2.pin) == HIGH)
  digitalWrite(ledPin, HIGH);
else
  digitalWrite(ledPin, LOW);

```

Or test for LOW:

```
if (digitalRead(button.pin) == LOW && digitalRead(button2.pin) == LOW)
  digitalWrite(ledPin, LOW);
else
  digitalWrite(ledPin, HIGH);

```

For **multiple buttons**, a `bool` can be used or the number of pressed buttons can be counted.

A fixed number for the array size is easy and has less chance for a mistake:

```
#define BUTTONS_COUNT 2

```

It is also possible to use `sizeof()`. The total size has to be divided by the size of one element:

```
int count = 0;
for (int i = 0; i<sizeof(buttons)/sizeof(Button); i++) {
  if (digitalRead(buttons[i].pin) == HIGH) {
    count++;
  }
}

if (count == 0)
  digitalWrite(ledPin, LOW);
else
  digitalWrite(ledPin, HIGH);

```
> 0 votes

---
Tags: arduino-uno
---


# Question
Title: How to handle concurrent HTTP request when using interrupt
I'm trying to make a door sensor with a reed switch. Each time the there is a change, the ESP8266 sends an HTTP request to web service.

Unfortunately, the ESP8266 serial monitor dumps a huge stack trace when I'm approaching the magnet to the reed switch:

```
Exception (9):
epc1=0x40104b14 epc2=0x00000000 epc3=0x00000000 excvaddr=0x00000003 depc=0x00000000

ctx: sys
sp: 3fffeb20 end: 3fffffb0 offset: 01a0

>>>stack>>>
3fffecc0:  00000002 00000006 3ffefdc4 40227108
3fffecd0:  3ffefa74 00000002 00000014 401004e4
3fffece0:  3ffeffbc 3ffeffc0 00000006 00000001
3fffecf0:  402253bc 00000000 00000010 00000000
3fffed00:  00000000 4bc6a7f0 81cac083 00000000
3fffed10:  00000000 00000000 4bc6a7f0 00000000
3fffed20:  40104d40 0037d809 3ffeecd0 00000000
3fffed30:  3ffee520 3ffeecd0 3ffeffbc 40224398
3fffed40:  00000000 00200085 40201578 00001388
3fffed50:  3ffeecd0 00000000 00000050 00000050
3fffed60:  00000000 3fffedd0 3ffefd34 402032e5
3fffed70:  1301a8c0 00000031 3ffeebbc 402039cc
3fffed80:  3ffeedb8 000000ef 000000ef 00000020
3fffed90:  ffffffff 00000050 3fffedd0 40202d5c
3fffeda0:  40204738 1301a8c0 40204738 1301a8c0
3fffedb0:  3ffe8a64 00000005 000...

```

I think it's because the ESP8266 tries to make concurrent HTTP calls... How can I solve this?

Here is the code:

```
// https://www.instructables.com/id/Arduino-Software-debouncing-in-interrupt-function/
// #include "util/atomic.h"
#include "ESP8266WiFi.h"
#include "ESP8266HTTPClient.h"
#include "Wire.h"

const char* ssid = "****";
const char* pass = "****";
const byte interruptPin = 5;
long debouncing_time = 50; //Debouncing Time in Milliseconds
volatile unsigned long last_micros;
const char* host= "192.168.1.19";
const char* doorStates[2] = {"closed", "opened"};

void connection()
{
  // Establish a WIFI connection
}

void setup()
{
  Serial.begin(115200);
  connection();
  pinMode(interruptPin, OUTPUT);

  // Attaching interrupt
  attachInterrupt(digitalPinToInterrupt(interruptPin), handleInterrupt, CHANGE);
}

void loop()
{
  delay(1000);
}

void handleInterrupt() {
  if ((long)(micros() - last_micros) >= debouncing_time * 1000) {
    int val = digitalRead(interruptPin);
      notify(val);
  }
  last_micros = micros();
}
// Make HTTP Call to web service
void notify(int val)
{
  WiFiClient client;
  const String frontDoorState = doorStates[val];
  String url = "http://192.168.1.19/alarm/front-door/state/" + frontDoorState;
  client.connect(host, 80);
    client.print(String("GET ") + url + " HTTP/1.1\r\n" +
                 "Host: 192.168.1.19\r\n" +
                 "Connection: close\r\n\r\n");
                 client.stop();
}

```

# Answer
Simple: don't do HTTP requests in the interrupt.

It's usually bad to do anything heavy like that in an interrupt. Instead you should just set a flag in the interrupt (`volatile bool`) and examine that flag in `loop()`.

```
volatile bool sendNotification = false;
volatile int notifyVal = 0;

void loop() {
    if (sendNotification) {
        notify(notifyVal);
        sendNotification = false;
    }
}

void handleInterrupt() {
    if ((long)(micros() - last_micros) >= debouncing_time * 1000) {
        notifyVal = digitalRead(interruptPin);
        sendNotification = true;
    }
    last_micros = micros();
}

```
> 1 votes

---
Tags: esp8266, interrupt, c, http
---


# Question
Title: NodeMCU ESP8266 on Arduino IDE doesn't detect Wifi
I am using a NodeMCU 1.0 v3 and I am trying the example sketch (wifiscan) but it just doesn't pick up any AP in the house. My phone and laptops etc are able to pick up the APs though.

Other sketches upload and work fine but the wifi aspect of it doesn't work. I even got an LCD sketch to work properly but it isn't able to find any access points or even join any access points. I have been trying to get it to work for hours now.

I first tried using the latest Arduino IDE (1.6.12), then I uninstalled and tried using 1.6.1 but no luck. My upload settings are NodeMCU 1.0 (ESP-12E module), 80Mhz, 115200, 4M (3M SPIFFS).

# Answer
> 1 votes
Your router might be using 5GHz Wifi which the ESP8266 doesn't support but your other devices likely do. Try setting your wifi network to 2.4GHz.

# Answer
> 0 votes
My gut feeling is that your hardware is just flakey. I have one NodeMCU 1.0 that occasionally works, and occasionally does not.

On that one, it requires power cycling (unplugging and replugging) it a couple of times for it to start working.

The Arduino ESP8266 core is pretty solid, and wifi support should just work in it.

Just to make sure, you could post your simplest sketch which doesn't work (one that lists AP's, so that it can't be a ssid/password kind of issue), so people can check if there's a problem in the code..

Also, to be really sure, you could check your power system. NodeMCU has a 5v to 3.3v converter in it, and a usb plug, so that part should be ok. How many amps is the USB power supply rated at? If it's very low (\<250ma) it could be an issue. You can also try adding a capacitor (something decent sized, \>220uf at a random guess? I tend to go for ~1000uf) between gnd and 3.3v, and one between gnd and 5v pins. Watch polarity of-course, and double check, you don't want to short the power lines :) There's a very small chance stabilizing the power in that way might help..

# Answer
> 0 votes
My DHCP table was full. I rebooted router and added more values for dhcp range (192.168.1.100-192.168.1.150) and the device now connects.... took me a day to figure this out.

---
Tags: arduino-ide, esp8266
---


title: ESP8266 and Python Communication

text:
# Question
Title: ESP8266 and Python Communication
I'm new to networking and working with ESP8266. I have successfully setup my ESP8266 and can program it from Arduino IDE (tested a blinky code).

I want to send some data from a Python script running on my PC to ESP8266. Similar to a setup where use PySerial in Python, open a COM port and send my serial data to an Arduino. Arduino will parse my data bytes and will perform some action. Now, I am trying to achieve the same with ESP8266 and UART replaced with wireless communication.

First, I would like to connect my PC to ESP which will have its own SSID and password. Once connected, I would like to send my data bytes from Python script to ESP8266 wirelessly. Now, similarly, ESP will parse this received data and perform some function (like control its GPIOs).

How can I achieve this? It seems like a pretty simple task, but I'm really confused with what mode I've to use (AP? Client? Server?). What protocol for communication is the best (TCP? MQTT?). What do functions like Handle client/root do? I understand I've to use socket programming on Python, how to do that specifically in my case? How do I buffer my incoming data on ESP, so that I don't miss the bytes?

Could anyone please explain using an analogy with wireless communication and UART? Any links to tutorials will be helpful too. There are some tutorials online where they do this using a HTTP server and control the GPIOs from the browser, but no, I don't want this. I just simply want to send my data as I would with COM Port/UART/Arduino!

# Answer
## Check my project: "Esp 2 Python"

https://github.com/KebabLord/esp\_to\_python

The theori is you can create a localhost and get the sensor data or manage the module through arduino requests or urllib modules with a simple local mDNS server. This project allows you to control and read ESP.
> 1 votes

# Answer
The simplest IP equivalent to UART is TCP/IP sockets. Create a listening socket on the ESP8266 and connect to it from the PC (or do it the other way around if you like). Data fed in one end comes out the other - just like a serial port.

There's examples with the ESP8266 core that do just that.
> 0 votes

# Answer
You must configure the ESP as an AP, if you want it to have its own IP. You **then** set up a tcp-server on the ESP (i think there are example functions in the IDE).

Keep in mind, that the communication (server/client you mentioned) has nothing to do with the way PC and ESP are connected with (whether the ESP is providing an Access Point or logged into your WiFi). Those are different protocol layers, which means you will not need to make any changes if you want PC and ESP communicate over your router at all.

Actually the ESP (or at least for the ESP8266-12F I know for sure) is capable of running both ap and wificlient **at the same time**.

It's not a big difference to serial communication, you will need to poll for incomming messages in your loop if you want to run a server. Sending messages to your PC is like printing to the serial interface.
> 0 votes

---
Tags: esp8266, python
---


# Question
Title: How to drive N channel gate correctly from Adafruit Feather pinout?
I am learning how to create a soft latch power switch, using an N channel mosfet.

Currently, I have this:

simulate this circuit – Schematic created using CircuitLab

The idea is (so far) that I can turn it on with the switch, the Arduino immediately brings the power control high (ensuring the FET stays on), and brings that same pin low after 1.5s (simulating a timed shutdown).

However; when the power control goes low, I still see about 1.8v in the power control line (I'm presuming its floating?), which leaves this particular FET partially open.

If I disconnect the power control line from the MCU, I get the behaviour I expect. I can touch the power control to +ve and the FET will switch on. If I lift the control line from +ve, the FET closes the gate, due to the pull down resistor.

I'm struggling to understand why the FET works in isolation, but does not work when connected to the MCU output pin. The pinMode is OUTPUT.

FET (3055VL): https://www.onsemi.com/pub/Collateral/MTP3055VL-D.PDF

Here's the test code I'm using. It simply flashes a build in LED 10 times then does a power off.

```
int ledPIN = 17;
int controlPin = 11;
int lDelay = 150;

bool shouldBeUp = true;

void setup()
{
  pinMode(ledPIN, OUTPUT);
  pinMode(controlPin, OUTPUT);
  digitalWrite(controlPin, HIGH);
}

void loop()
{
  if (shouldBeUp) {
    for (int i = 0; i < 10; i++)
    {
      digitalWrite(ledPIN, LOW); // on
      delay(lDelay);
      digitalWrite(ledPIN, HIGH); // off
      delay(lDelay / 2);
    }

    // Leave the LED low
    digitalWrite(ledPIN, LOW);
    digitalWrite(controlPin, LOW);
    shouldBeUp = false;
  }
}

```

Any help is appreciated! Thank you :)

# Answer
Your problem is that the GPIO pin is referenced to ground - and the MOSFET is isolating that ground.

You need instead to switch the power not the ground - and for that, you use a P-channel MOSFET.

simulate this circuit – Schematic created using CircuitLab

To hold the power on you now set the GPIO LOW instead of HIGH.

If you need to switch a higher voltage than the operating voltage of the MCU you will need to add another N-channel MOSFET to pull down the P-channel's gate.
> 1 votes

---
Tags: power, adafruit, mosfet
---


# Question
Title: Please Correct my Delay Code without using delay();
This is my `loop()`function:

```
if(Serial.read() == 't') {
  tarestate = true;
}

while(tarestate == true) {
  timeNowTare = mills();
  if(mills() - timeNowTare >= 3000) {
    Serial.println("Tare");
  }
  tareState = false;
}

```

Where `tareStare` is a boolean, `timeNowTare` is a long.

I need to print on serial:

> Tare

three seconds after I enter "t" into serial.

With everything I have tried to date, the program either stops or tares immediately after entering “t”.

EDIT: Thanks to everyone who responded with answers. The solution was simply to move the timeNowTare = true; declaration up to the Serial.read() if statement. I also changed the while loop to an if statement because it seemed to make my code run quicker.

# Answer
> 1 votes
Move `timeNowTare = millis();` inside first `if`:

```
if (Serial.read() == 't') {
  tareState = true;
  timeNowTare = millis();
}

```

and `tareState = false` inside second `if`:

```
while (tareState) {
  if (millis() - timeNowTare >= 3000) {
    Serial.println(F("Tare"));
    tareState = false;
  }
}

```

# Answer
> 1 votes
The easiest solution is to just use `delay()`:

```
if (Serial.read() == 't') {
    delay(3000);
    Serial.println(F("Tare"));
}

```

What? You said “no `delay()`”? OK, then just write your own implementation of `delay()` and inline it in place of the actual call to `delay()`:

```
if (Serial.read() == 't') {
    uint32_t timeNowTare = millis();
    while (millis() - timeNowTare < 3000) continue;  // wait
    Serial.println(F("Tare"));
}

```

This seems to be more or less what you attempted. You write a `while` loop that blocks the program for three seconds. It is also what leoc7's answer does.

However, doing so is completely foolish. Why would you write your own version of `delay()` when the Arduino core provides you with a well tested one? Why would you want to avoid the standard `delay()` in the first place?

It turns out there is a very good reason to avoid `delay()`. The reason is that `delay()` *blocks* your program for the entire delay duration. If your code needs to be responsive to some external inputs (as any non trivial program at some point needs), this means within that time window the program will be completely unresponsive. The bad thing about `delay()` is not the implementation (there is no point in replacing it with your own), it's the fact that it blocks your program. If you replace `delay()` by your own blocking code you have won nothing.

The real solution is to think in terms of a finite state machine. Either the program is running in “tare mode” or not. The possible state transitions are:

* upon reading a `'t'` on the serial port, you enter tare mode and take note of the current time
* if you are already in tare mode and three seconds have elapsed since you entered that mode, then you print out `"Tare"` and exit tare mode.

Here is a straight forward implementation of such state machine:

```
static bool tare_mode = false;
static uint32_t tare_start_time;  // meaningful only in tare_mode
if (Serial.read() == 't') {
    tare_mode = true;
    tare_start_time = millis();
}
if (tare_mode && millis() - tare_start_time >= 3000) {
    Serial.println(F("Tare"));
    tare_mode = false;
}

```

Now you can add more code to `loop()` and this extra code will never be blocked by your “tare” feature.

---
Tags: timers
---


# Question
Title: C: No communication to a connected serial port?
I'm trying to connect to an arduino Mega At2560 unit connected via usb serial port in my linux based PC. Using C code, I'm trying to send and receive simple text strings, just I'm able to send and receive on both sides.

On arduino:

```
int incomingByte = 0;    // for incoming serial data

void setup() {
    Serial.begin(19200);    // opens serial port, sets data rate to 9600 bps
}

void loop() {
  // send data only when you receive data:
  if (Serial.available() > 0) {

    // read the incoming byte:
    incomingByte = Serial.read();

    // say what you got:
    Serial.print((char)incomingByte);
  }

}

```

basically just a loop that checks if there is serial data, and if so reads it and prints it back. there's a (char) conversion so I'll see right away the sent data is what I got back (linux side)

For the linux code I use the pretty standard code for opening a port which I found here

I call the Arduino "Table" as it will eventually operate a moving table through USB commands.

C file:

```
#include "TableFunctions.h"

bool connected=false;
int fd;
char *portname;

int set_interface_attribs (int fd, int speed, int parity)
{
        connected=false;
        struct termios tty;
        struct termios tty_old;
        memset(&tty, 0, sizeof tty);
        if (tcgetattr (fd, &tty) != 0)
        {
                printf("PC: Error %d from tcgetattr  \n", errno);
                return -1;
        }
        tty_old = tty;

        cfsetospeed (&tty, (speed_t)B19200);
        cfsetispeed (&tty, (speed_t)B19200);

        //tty.c_cflag |= B19200;
        tty.c_cflag     &=  ~PARENB;            // Make 8n1
        tty.c_cflag     &=  ~CSTOPB;
        tty.c_cflag     &=  ~CSIZE;
        tty.c_cflag     |=  CS8;

        tty.c_cflag     &=  ~CRTSCTS;           // no flow control
        tty.c_cc[VMIN]   =  1;                  // read doesn't block
        tty.c_cc[VTIME]  =  5;                  //
        tty.c_cflag     |=  CREAD | CLOCAL;     // turn on READ & ignore ctrl lines
        cfmakeraw(&tty);
        tcflush( fd, TCIFLUSH );

        if (tcsetattr (fd, TCSANOW, &tty) != 0)
        {
                printf("PC: Error %d from tcsetattr  \n", errno);
                return -1;
        }
        return 0;
}

void set_blocking(int fd, int should_block)
{
        struct termios tty;
        memset(&tty, 0, sizeof tty);
        if (tcgetattr (fd, &tty) != 0)
        {
                printf("PC: Error %d from tggetattr  \n", errno);
                return;
        }

        tty.c_cc[VMIN]  = should_block ? 1 : 0;
        tty.c_cc[VTIME] = 10;            // 0.5 seconds read timeout

        if (tcsetattr (fd, TCSANOW, &tty) != 0)
                printf("PC: Error %d setting term attributes  \n", errno);
}

void OpenSerialPort()
{
    char *portname = "/dev/ttyACM0";

    printf("PC: Opening port to table \n");

    int fd = open(portname, O_RDWR | O_NOCTTY | O_SYNC);

    usleep(2000000);
    if (fd < 0)
    {
        printf("PC: Error %d opening %s: %s  \n", errno, portname, strerror(errno));
        return;
    }

    set_interface_attribs(fd, B19200, 0);  // set speed to 19,200 bps, 8n1 (no parity)
    set_blocking(fd, 0);                // set no blocking
    printf("PC: Connected\n");
    connected = true;
}
void PrepareWriteCommand(int numberOfCommands, const char *commands[numberOfCommands])
{
    if(connected) //check if arduino still connected
    {
        for(int i = 0; i<numberOfCommands; i++) //go through commands
        {
            int bufferSize = strlen(commands[i]); //get the buffer size needed for this command
            char charArray[bufferSize]; //helper char array
            memcpy(charArray,commands[i],bufferSize);//copy command to the char array
            charArray[bufferSize]=0; //make sure there is a stop symbok at the end
            WriteSerialPort(charArray); //command is ready to be sent, send it.
        }
    }
}
int WriteSerialPort(const char *buffer)
{
    printf("PC: Now writing: ");
    int n_written = 0; //how many bytes were written

    n_written = write(fd, buffer, strlen(buffer)); //write the command and return how many bytes were written

    printf("\n");

    //check bytes send and return ouput (error, nothing or x bytes sent)
    if(n_written<0)
    {
        printf("PC: Error %d from %s \n",errno, strerror(errno));
    }
    else if(n_written == 0)
    {
        printf("PC: Nothing was written  \n");
    }
    else
    {
        printf("PC: Written %i bytes  \n", n_written);
    }

}

int ReadSerialPort(char *buffer, unsigned int buff_size)
{
    //check if arduino still connected
    if(connected)
    {
        //read the serial data
        if(read(fd,buffer,buff_size))
            return sizeof(buffer); //return how much bytes were read
        else
        {
            //else print nothing received
            printf("PC: Arduino not Connected (ReadSerialPort) \n");
        }
    }
}

```

in OpenSerialPort I basically open a new fd, and call the functions that set the communication settings. I use PrepareWriteCommand to make sure commands input from users are with a stop symbol and send them to WriteSerialPort where I use write() and print how many bytes were sent.

H file:

```
#include <errno.h>
#include <fcntl.h>
#include <termios.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <stdbool.h>

#define MAX_DATA_LENGTH 256

int set_interface_attribs (int fd, int speed, int parity);
void set_blocking(int fd, int should_block);
void OpenSerialPort();
void PrepareWriteCommand(int numberOfCommands, const char *commands[numberOfCommands]);
int WriteSerialPort(const char *buffer);
int ReadSerialPort(char *buffer, unsigned int buff_size);

```

Main:

```
#include "TableFunctions.h"
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[])
    {
        char output[MAX_DATA_LENGTH]; //char array to hold arduino output
        int received = 0; // check if read() got any bytes
        const char* commands[]={"test"}; //test command

        OpenSerialPort(); // open serial port

        PrepareWriteCommand((sizeof(commands)/sizeof(commands[1])),commands); //prepare command for sending

        usleep(500000); //wait for arduino response

        while(true)
        {
            ReadSerialPort(output,MAX_DATA_LENGTH);//check serial port for response
            if(strlen(output)>0) //if anything received
            {
                printf("PC: received %i\n",received); //if yes, how many bytes
                printf("PC: %s\n",output); //and what was received
                usleep(500000);
            }
            else if(strlen(output)<=0) //else print nothing received
            {
                printf("PC: Nothing received\n");
            }
        }
        return 0; //finish program
    }

```

I tried tweaking the tty flags settings with no success. Each time I run the C code I see the arduino resets (and after opening a new fd I give it some time for bootloading) but no communication is sent between the two.

Output:

```
PC: Opening port to table
PC: Connected
testPC: Now writing:
PC: Written 4 bytes

PC: received 0
PC:

```

Any help with understanding why the C code can't communicate with the Arduino will be highly appreciated!

# Answer
Problem was in OpenSerialPort(). I set another variable fd which is local, thus given priority. then when OpenSerialPort() is done, it is deleted, and the global fd remain unset. This is why I can't send anything from or to the PC.

Thanks.
> 1 votes

---
Tags: serial, arduino-mega, c, linux
---


# Question
Title: Can't get 4 digit 7 segment display to show different values
I'm an Arduino newbie having problems getting a 4 digit 7 segment display to work. The display is connected to a 74HC595 and the setup is from the elegoo tutorial 28 (I think it is download only).

I figured how to control which number to display, but all 4 digits always share the same number, so it is always like 1111, 5555, 9999 etc.

I've heard about something called multiplexing which might do the trick, but I can't adapt it to my project yet, missing too much experience.

This is the code that toggles between 2222 and 8888. I want to be able to display any number like 1234 though.

Any help is very appreciated.

```
int latch=9;  //74HC595  pin 9 STCP
int clock=10; //74HC595  pin 10 SHCP
int data=8;   //74HC595  pin 8 DS

void setup()
{
  pinMode(latch,OUTPUT);
  pinMode(clock,OUTPUT);
  pinMode(data,OUTPUT);
}

void Display(unsigned int num)
{
  digitalWrite(latch,LOW);
  shiftOut(data,clock,MSBFIRST,num);
  digitalWrite(latch,HIGH);
}

void loop()
{
    Display(91);
    delay(1000);
    Display(127);
    delay(1000);
}

```

# Answer
> 5 votes
You have a common cathode display and all your cathodes are tied to ground through resistors. You have no way at all of separating out the different digits.

You cannot directly drive such a display with a shift register like that - you need a more direct connection to the Arduino (it needs to be high speed) and rapidly switch each cathode on and off in sequence to display each of the four numbers one after another.

Also the resistors should be in the 8 anodes, not the 4 cathodes.

# Answer
> 1 votes
> but all 4 digits always share the same number, so it is always like 1111, 5555, 9999 etc.

because that's how this particular circuit is designed for.

> I've heard about something called multiplexing which might do the trick, but I can't adapt it to my project yet, missing too much experience.

multiplexing is no different than displaying each digit quickly (as you are doing now), and then display the next digit quickly, ....

what you are doing now will contribute to your learning multiplexing.

# Answer
> 1 votes
The problem with this setup is the circuit.

The Master Reset Pin 10 on the 595 is floating.

Use a 10K resistor to pull it up to VCC (+5V) and it will work.

I was getting all sorts of odd characters until I checked out the data sheet on the 595.

# Answer
> -1 votes
That circuit needs a 0.1uF cap from '595 VCC to Gnd for consistent operation. Ideally a resistor between each '595 output and the anode pin, and a transistor or other higher current device able to sink the current from 8 anodes being driven at once (i.e. ULN2003). Once the cathodes can be driven seperately, to allow each digit to be selected individually, than an array can be used to map the digit to be displayed to the segments in a display:

```
// add before setup()
byte fontArray[] = {
0b00111111, // 0  where the bits represent dp-g-f-e-d-c-b-a
0b00000110, // 1  and 1 = segment turned on
0b01011011, // 2
// etc.
};

// and change this line in display() to display a number

shiftOut(data,clock,MSBFIRST,fontArray[num); // looks up mapping from above

// then turn on a cathode to display it for 2-3mS, then back off, and send
// out the info for the next digit

```

---
Tags: display
---


title: EEPROM endurance and page size

text:
# Question
Title: EEPROM endurance and page size
I would like to estimate the effective (minimum) endurance of the EEPROM of the Arduino in terms of single-byte writes.

The datasheet of the ATmega used on many Arduino boards says (page 20):

> The ATmega48A/PA/88A/PA/168A/PA/328/P contains 256/512/512/1Kbytes of data EEPROM memory. It is organized as a separate data space, in which single bytes can be read and written. The EEPROM has an endurance of at least 100,000 write/erase cycles.

Consider the ATmega328P with 1 kB of EEPROM. As I can write single bytes, if I loop through the EEPROM, writing every byte position the same number of times, that would make 1024 * 100,000 writes (assuming the nominal endurance).

But as far as I know not single bytes are erased before a write, but pages / cells. On page 285 / table 28.12 of the datasheet, the page size is specified to be 4 bytes. Does that mean the specified minimum endurance amounts to 1024 * 100,000 / 4 single-byte writes?

# Answer
## Testing a single byte write

I ran some test code overnight to try to get to the bottom of this. Somewhat surprisingly perhaps, I got up to over 11 million writes before a read-back failed:

```
Current count = 11514199
Writes per minute: 17550
....................
Current count = 11538199
Writes per minute: 17550
....................
Current count = 11562199
Writes per minute: 17549
...................
Failed readback!
Expected: FF
Got: 7F
Current count = 11585314
Halted.

```

So, 11.5 M writes. Still, as pointed out on the AVR Freaks thread, the guarantee of 100,000 writes to EEPROM gives you a data retention time of 20 years. Possibly if you exceed that limit, the data retention time will go down. It isn't particularly practical for me to test whether or not the EEPROM will still be valid after 20 years. ;)

Interestingly, the next day (as I write this) the EEPROM seems to have recovered and is now still writing and reading back OK. So it would appear that after 11 M writes you may *sometimes* get a bad read-back.

On the AVR Freaks thread they seemed to get somewhere between 5 M and 8 M writes before failure.

---

A number of hours later (2.4 hours), the same byte failed again, after a further 2,559,219 writes!

```
Current count = 14033314
Writes per minute: 17549
....................
Current count = 14057314
Writes per minute: 17549
....................
Current count = 14081314
Writes per minute: 17549
....................
Current count = 14105314
Writes per minute: 17549
....................
Current count = 14129314
Writes per minute: 17549
............
Failed readback!
Expected: FF
Got: 7F
Current count = 14144533
Halted.

```

---

Somewhat more quickly the third failure after a further 149,703 writes:

```
Current count = 14312533
Writes per minute: 17550
....
Failed readback!
Expected: FF
Got: 7F
Current count = 14318236
Halted.

```

---

And another failure (in 2.3 minutes) after a further 41757 writes:

```
Starting.
Current count = 14318236
Waiting for pin 2 to go LOW.
Started.
....................
Current count = 14342236
Writes per minute: 17551
..............
Failed readback!
Expected: FF
Got: 7F
Current count = 14359993
Halted.

```

---

## Testing the adjacent byte

Now that I got a failure fairly quickly on the somewhat overworked byte, I adjusted the code to write to the next one up (1021) which would be in the same 4-byte "page".

Four hours later, the adjacent byte has been written to 4.36 million times without any errors, so this would appear to support the idea that each byte of EEPROM can be written individually without affecting its neighbours.

**Next morning**

The adjacent byte (address 1021) finally failed after 12,161,565 writes. So the proposition that each byte can be individually addressed, and has an individual lifetime, seems to be supported.

```
Current count = 12120000
Writes per minute: 17562
....................
Current count = 12144000
Writes per minute: 17562
..............
Failed readback!
Expected: FF
Got: 7F
Current count = 12161565
Halted.

```

---

## Code

### Main sketch

```
// EEPROM tester

// Author: Nick Gammon
// Date: 22 August 2015

// Connect a jumper from GND to pin D2 when ready to run.
// Remove the jumper for a clean wrap-up (saving the current count into EEPROM)

// Single flash, repeated every half second: ready to go
// Two flashes, stopped on request
// Three flashes, error
// Occasional flash: working

#include <EEPROMAnything.h>
#include <EEPROM.h>

const unsigned int WRITE_COUNT_ADDRESS = 1010;
const unsigned int TEST_ADDRESS = 1020;
const unsigned int ITERATIONS = 200;
const unsigned long MAX_DOTS = 20;
const byte TESTS [] = { 0x55, 0x00, 0xFF, 0x66, 0xAA, 0x11 };
const byte ACTIVATE_PIN = 2;
const byte LED = 13;

unsigned long dots = 0;
unsigned long writeCount;
unsigned long startTime;
unsigned long initialCount;

void showCount ()
  {
  Serial.print ("Current count = ");
  Serial.println (writeCount);
  } // end of showCount

// flash the LED the required number of times
void flashLED (const int times,
               const unsigned long interval = 100,
               const unsigned long delayTime = 500)
  {
  for (int i = 0; i < times; i++)
    {
    digitalWrite (LED, HIGH);
    delay (interval);
    digitalWrite (LED, LOW);
    delay (interval);
    }  // end of for each iteration
  delay (delayTime);  // delay between iterations
  }  // end of flashLED

// check our memory agrees with what we expect
void checkMemory (const byte target)
  {
  byte found = EEPROM.read (TEST_ADDRESS);
  if (found != target)
    {
    Serial.println ();
    Serial.println ("Failed readback!");
    Serial.print ("Expected: ");
    Serial.println ((int) target, HEX);
    Serial.print ("Got: ");
    Serial.println ((int) found, HEX);
    showCount ();
    EEPROM_writeAnything (WRITE_COUNT_ADDRESS, writeCount);
    Serial.print ("Halted.");
    Serial.flush ();
    while (true)
      flashLED (3);  // three flashes
    }
  }   // end of checkMemory

void setup ()
  {
  Serial.begin (115200);
  Serial.println ();

  // get write count from previous run
  EEPROM_readAnything (WRITE_COUNT_ADDRESS, writeCount);
  initialCount = writeCount;

  // if all 1 bits, variable was never initialized
  if (writeCount == 0xFFFFFFFF)
    writeCount = 0;

  // tell them we are starting
  Serial.println ("Starting.");
  pinMode (2, INPUT_PULLUP);
  pinMode (LED, OUTPUT);
  showCount ();

  // wait for them to unplug pin 2
  Serial.println ("Waiting for pin 2 to go LOW.");
  while (digitalRead (ACTIVATE_PIN) == HIGH)
    flashLED (1);  // one flash

  Serial.println ("Started.");
  startTime = millis ();
  }  // end of setup

void loop ()
  {

  // write to EEPROM, checking each write
  for (unsigned int i = 0; i < ITERATIONS; i++)
    {
    for (unsigned int j = 0; j < sizeof (TESTS); j++)
      {
      EEPROM.write (TEST_ADDRESS, TESTS [j]);
      writeCount++;
      checkMemory (TESTS [j]);
      }  // end of doing each test pattern
    }  // end of loop of x ITERATIONS

  // save the current write count so we can pick up the count next time
  EEPROM_writeAnything (WRITE_COUNT_ADDRESS, writeCount);
  Serial.print (".");
  dots++;

  // confirming we are working
  flashLED (1, 10, 0);  // flash once, for 10 ms, no extra delay

  // newline, show counter
  if (dots >= MAX_DOTS)
    {
    Serial.println ();
    dots = 0;
    showCount ();
    unsigned long writes = writeCount - initialCount;
    unsigned long timeTaken = millis () - startTime;
    float writesPerMinute = float (writes) / float (timeTaken) * 60.0 * 1000.0;
    Serial.print ("Writes per minute: ");
    Serial.println ((int) writesPerMinute);
    }  // end of needing a newline and counter output

  // check if user wants us to stop by disconnecting the jumper from Gnd to D2
  if (digitalRead (ACTIVATE_PIN) == HIGH)
    {
    Serial.println ();
    Serial.println ("Stop request detected.");
    showCount ();
    Serial.print ("Halted.");
    Serial.flush ();
    while (true)
      flashLED (2);  // two flashes
    }
  }  // end of loop

```

### EEPROMAnything.h

```
#include <Arduino.h>  // for type definitions
#include <EEPROM.h>

template <typename T> unsigned int EEPROM_writeAnything (int ee, const T& value)
{
    const byte* p = (const byte*)&value;
    unsigned int i;
    for (i = 0; i < sizeof(value); i++)
        EEPROM.write(ee++, *p++);
    return i;
}

template <typename T> unsigned int EEPROM_readAnything (int ee, T& value)
{
    byte* p = (byte*)&value;
    unsigned int i;
    for (i = 0; i < sizeof(value); i++)
        *p++ = EEPROM.read(ee++);
    return i;
}

```

---

The code is designed to wait until you connect pin 2 (digital pin 2) to ground before starting. This is to stop it executing immediately after being uploaded, before you start the serial monitor. So, upload the code, open the serial monitor, and then connect Gnd to pin D2, and watch the results.

---

## Error correction

If the concern is that the EEPROM reads may deteriorate, once could use Reed Solomon error correction to recover. That is the method used for correcting bad reads on compact disks, and also QR codes. It can recover from a number of errors (you choose the level of error correction you want - the more error correction, the more memory it takes).

My tests so far have shown that failure involves single bits (as did the AVR Freaks tests) so this may well be a way of extending EEPROM life and reliability.

Testing of some Reed Solomon code that I found, would appear to indicate that adding the encoding and decoding would take around 4800 bytes of program memory, plus around 600 bytes of RAM (512 bytes needed for the internal tables, plus some extra work space). In addition you need 256 bytes of RAM for the code block. Those figures could be reduced by using less bits per "symbol". For example, if you stored 4-bit symbols (such as BCD numbers) then the memory requirements would reduce somewhat.
> 7 votes

# Answer
In the arduino forum http://forum.arduino.cc/index.php?topic=293472.0 someone states that is 1 byte size (each "page") - each write writes and spends a cycle for a single byte. There it also says that SPI access to eeprom uses a 4 bytes page size. I did not went further reading since my doubt was same as here, writing a byte to arduino eeprom.
> 0 votes

---
Tags: eeprom
---


# Question
Title: How to use variables and functions across multiple .ino files
I have 2 .ino files (2 tabs) for one Arduino project/sketch: MySketch\_File1.ino and MySketch\_File2.ino.

I declared in MySketch\_File2 variables and functions which I want to use in MySketch\_File1, but I get this error massage:

> error: 'a' was not declared in this scope

```
//MySketch_File1.ino
void setup(){
Serial.begin(9600);
Serial.println(String(a));
}

void loop(){

}

```

Second file:

```
//MySketch_File2.ino
int a;

```

How can I declare variables and functions one time in one .ino file and use it across multiple .ino files?

# Answer
When you compile multiple files in the Arduno IDE the files first get concatenated together.

It happens in alphabetical order, *except* the main INO file (the one named the same as the folder it's in) is placed first.

In C the order in which things appear in the file matters. Basically you have to make sure that things (like variables, functions, etc) are defined *before* they are used.

This gets more complex when you have a hidden thing like file concatenation messing things up.

The Arduino IDE tries to hide some of it from you too by making *function prototypes*, so it doesn't matter what order you define functions in - however that "helpfulness" means you don't learn about the proper structure of a C program.

So what can you do? Well, simply make sure that all your global variables are defined in the *main* file, unless you know they are only going to be used within the file they are defined in.
> 2 votes

# Answer
In Arduino the `sketch.ino` is the main (and only) program, which runs on the processor.

If you upload another sketch to HW, then the previous one is overwritten and does not longer exist on the HW. So there is no way, they can share variables, as they never are run at the same time. (You can store some values to EEPROM or to external devices, but it is other thing).

What you probabely want to do is use the second file as a `library`, which is collection of variables and functions, that more then one program can use. Anyway what is used is the text of the library, not the values assigned to variables in one `sketch.ino` \- so other `sketch.ino` using the same library would have the functions and variables of the same name accessible, but as it is compiled to othe program, the values assigned in one sketch would not be visible in other sketch.

Can you specify, why you want to use variables and functions accross multiple .ino files?

If it is just to not have type it again and again and fix found bugs in each aned every copy separately, then you are looking for `libraries`.

If you want to share also values (like read and compute value in one .ino then upload another .ino and use the result) you are looking for `persistent storages` (EEPROM on the chip, SD card via some reader or something like that.

If you want have more Arduinos running at the same time and sharing some values, you are looking for `networks`, like I2C, Serial communication, Ethernet and such.

If you want run mor programs on one arduino at the same time, you are looking for `multitasking` where each program is interrupted repeatedly and other one is continued, fast enought to user not notice, or for creatinig more functions and call them from loop() one after one to eg. read sensors, then light LEDs then run motors. `State automats` can make your way here easier.
> 1 votes

# Answer
It is simplest to put only one .ino file in a directory with the filename. Why does an \`.ino\` file have to be in a folder of the same name?

**Option 1 (cleanest option):** Create a user library.

**Option 2 (workaround):** Relative paths for #include aren't supported but you can use a symlink to make it appear that there is the same header file in every directory:

```
sketch1/
  sketch1.ino
  mylib.h
sketch2/
  sketch2.ino
  mylib.h (this is a symlink to sketch1/mylib.h)

```

**Option 3:** Avoid Arduino IDE entirely and build using avr-gcc. Example: http://thinkingonthinking.com/an-arduino-sketch-from-scratch/ and Will a .ino Arduino Sketch compile directly on GCC-AVR? This is much more complicated, but supports bigger projects using Makefiles.
> 1 votes

# Answer
Arduino ide has terrible project mgmt capabilities. So two solutions.

1. Switch to a real ide.
2. Use an extern atteibute.
> 0 votes

# Answer
You can make this easier by naming only the main sketch file '.ino', and naming all other code files as '.cpp'. The compiler has to know about 'a' before you use it, so declare 'a' in the .ino file as \`extern int a;' before its first use, to tell it what 'a' is. Not having that is the reason for the error message.
> 0 votes

---
Tags: programming, c++, ino
---


# Question
Title: Do I need a pull-up/down resistor for button LED circuit?
When reading up on how to make a circuit that turns an LED on when a button is held down, I keep finding people saying a pull up or down resistor must be involved, to avoid the flickering state of the LED seen with a floating pin. There's also code being implemented, where the state of a pin is read and monitored as the button is pressed down or left raised. What I don't understand, is why this is all necessary. Surely it isn't, considering the circuit below allows the button to be pressed with the LED turning on/off depending on the state of the button.

I made this circuit before drawing it online, and it works exactly as intended. No need for a pull up/down resistor or any code. I must be missing something here, can anyone please explain? It works perfectly with a buzzer as well.

Many thanks.

# Answer
> 6 votes
The circuit you have made is only using Arduino as a 5V power source. You aren't using any GPIO pins to read the state of the button or to control the LED by an output pin. You've just made a plain-old circuit with a button and LED in series with a power source.

Often for a button-controlling-LED sketch, you will have a button connected between GND and an I/O pin defined as an `INPUT_PULLUP`, which means the Arduino will be able to read the state of the pin as `HIGH` (5V) or `LOW` (0V). The `PULLUP` part indicates that when the button is not completing the circuit between GND and the pin, a weak voltage is applied to get it up to 5V. In this way it's not "floating" at an unspecified voltage, but is being actively driven to 5V. When you press the button, the input pin is shorted to GND.

A pull-up resistor causes an otherwise un-driven pin to go to logic `HIGH`. A pull-down resistor causes an otherwise un-driving pin to go to logic `LOW`.

In the case of a pull-up resistor, reading a logic `LOW` means the button is pressed, which is kind of the reverse of your circuit operation, so in your sketch code, you would look for `LOW` to turn on the LED.

# Answer
> 2 votes
No, you don't.

The thing to remember is that you don't put a pulldown (or pullup) resistor on the *button* \- you actually put it on the *input*.

And since you aren't using an input there is nowhere to put the resistor.

A pullup or pulldown resistor is used to set an input to a pre-defined state. The button or switch is then used to override that pre-defined state. With your circuit you are just controlling the flow of electrons around a simple loop, from power, through resistor, through LED and back to power. The button just completes that circuit. There is no "input" to place into a pre-defined state. Hence no pullup or pulldown resistor.

# Answer
> 0 votes
A series resistor is needed to prevent excess current thru the LED or thru the IO pin. 270 ohm to 1K ohm works well.

simulate this circuit – Schematic created using CircuitLab

The internal pullup in the Arduino processer is 30-50K ohm. The external resistor is a current limit resistor. (5V - Vf-led)/resistor = current. (5V - 2.2V)/270 ohm = 10.3mA. Vf of the LED will vary by color from say 2.2V for a Red to 3.5V for a blue or white. Insert values if known, or use a 270 to 1K resistor and measure Vf across the LED, then adjust resistor as needed for desired brightness (more current = brighter).

---
Tags: arduino-uno, led, button, pull-up
---