# Question
Title: LED Programme where it delays the amount written in the Serial Monitor
I have written a simple code to delay the blinking of LED 13, the delay time is set by us.I have incurred a problem when I enter a 2 digit value in the serial monitor.There is some problem with the ASCII. Is there a way to solve this problem without using `Serial.parseInt()`.

```
void setup()
{
  Serial.begin(9600);
  Serial.println("Programming is starting");
  pinMode(13,OUTPUT);
}

void loop()
{
  if(Serial.available())
  {
    int val=Serial.read();
    int val1=val-'0';
    Serial.println(val1);
    digitalWrite(13,HIGH);
    delay(val1*1000);
    digitalWrite(13,LOW);
  }
}

```

# Answer
Here you have.

No error checking. Anything not digit produce zero as output.

```
void setup()
{
    Serial.begin(9600);
    Serial.println("Programming is starting");
    pinMode(13,OUTPUT);
}

void loop()
{
    static int value = 0;

    while(Serial.available() > 0) {
        int c = Serial.read();

        if(isDigit(c)) {
            value = value * 10 + (c - '0');
        } else {
            Serial.println(value);
            digitalWrite(13,HIGH);
            delay(value*1000);
            digitalWrite(13,LOW);
            value = 0;
        }
    }

```

It convert chars to values as they are being readed, one by one. There are no size limit for the input string, other that final value must fit in an `int`

You write a value in the Serial Monitor and end it with return, space bar or whatever non digit key you want.
> 2 votes

---
Tags: code-optimization
---


# Question
Title: How to prevent optocoupler to activate when resetting the arduino?
From various example on how to use optocouplers ( eg 4N25) I gathered that they work in inverted way meaning that for the optocoupler to output a signal, the input LED must be OFF.

This is very easy to process by code as I just need to use digitalWrite LOW instead of digitalWrite HIGH to activate the output of the optocoupler.

My problem is that when I reboot the arduino, the optocupler LED goes OFF and thus activate the ouput of the optocoupler for a few seconds until the code is loaded on the arduino.

How can I prevent this behavior ? Should I connect the optocoupler in a non inverted way ? ( And if so how ? ). Should I use an inverter ?

# Answer
The Fairchild datasheet for 4N25 shows this diagram:

describing the (or 'an') operation of the device. If this is how yours is operating, and if the input side is connected between an output pin and ground, then yes, on reset, the LED will go out and the switched output will go high. If you connect the device's input between the pin and +5v, the LED will light on reset, taking the switched output low. Plus, the switched output will now have the same sense as the Arduino output pin: i.e., `digitalWrite(PIN, HIGH)` will turn the switched output on, and vice-versa.
> 0 votes

---
Tags: reset, opto-isolator
---


title: Connecting NodeMCU with OV7076 camera

text:
# Question
Title: Connecting NodeMCU with OV7076 camera
I am trying to connect an OV7076 camera with a NodeMCU, but there are no pin diagram available for it. As NodeMCU has 4 MB storage and 128 KB memory, is there any possibility to use it?

AI thinker esp8266mod

Omnivision OV7076

# Answer
> 2 votes
You cannot connect an OV7076 camera with NodeMCU because OV7076 got 4 analog pins (VGA) and on the other hand NodeMCU got only one analog pin.

---
Tags: esp8266, wifi, nodemcu
---


# Question
Title: Arduino IDE fails on Fedora with arduino-builder error "Parameter 'tools' is mandatory"
The `arduino-builder` app when invoked directly with parameter `--tools /usr/bin` works, but the IDE fails with the error in the title for any sketch (including the Blink example).

I've tried adding things to `preferences.txt` like

```
tools.path=/usr/bin

```

And variations, but I keep getting the same failure in the IDE. This is using a fresh distro package install on Fedora 27 (I did not have this problem previously using Fedora 25).

# Answer
I don't understand why this worked, but I found this comment in Redhat Bugzilla (it doesn't seem to be a bug report specifically about that...but anyway):

> > Parameter 'tools' is mandatory \[...\]
>
> However, if I create the packages directory in ~/.arduino15, compilation now works.
>
> ```
> mkdir ~/.arduino15/packages
>
> ```

Seemed like an easy thing to try, and voila -- after an hour of fuss.

I do not understand why this is so (nothing ends up in that directory, either) but I'm leaving this in hopes it may save someone else some time.
> 18 votes

# Answer
The problem occurs because arduino does not have permission to modify directory in /usr/share/arduino to create tools-builder

All you have to do is navigate to usr/share/arduino create 'tool-builder' directory **`sudo mkdir /usr/share/arduino/tools-builder`**
> 5 votes

---
Tags: arduino-ide, arduino-builder
---


title: rev id and read_rev_id() function

text:
# Question
Title: rev id and read_rev_id() function
What is a rev id? I have looked everywhere for a proper definition but I haven't found anything. I am trying to understand the code below. I don't understand why this read\_rev\_id function is necessary and yes, I tried to look in the user manual for the IMU I am using but it is practically none-existent. I am using the myAHRS IMU and the only manual I could find, on GitHub, didn't even show a register by this name.

```
void setup()
{
  //Initialization
  Wire.begin();
  Serial.begin(115200);
  who_am_i();
  read_rev_id();
  delay(1000); //Wait for 1second.
}

```

# Answer
You haven't provided enough information for anyone to easily help you. Assuming that you took your code from GitHub myAHRS\_plus\_i2c.ino you can look further down the file to find the definition of **read\_rev\_id()**. It simply reads the revision number from the AHRS chip and displays it on the console. Since this is all that it does you could leave out the call to read\_rev\_id(). But if you are going to use it then be aware that it contains an obvious bug. The second **read()** should be to I2C\_SLAVE\_REG\_REV\_ID\_MINOR.

```
//READ REVISION ID
int read_rev_id()
{
    uint8_t id_1 = 0;
    uint8_t id_2 = 0;
    read(I2C_SLAVE_REG_REV_ID_MAJOR, &id_1, 1);
    read(I2C_SLAVE_REG_REV_ID_MAJOR, &id_2, 1);
    Serial.print("READ REVISION ID= "); Serial.print(id_1); Serial.println(id_2);
}

```
> 1 votes

---
Tags: programming, imu
---


# Question
Title: Help understanding Print::write()--it calls write()--where is write() defined? Help reading code
I'm writing a new serial library (eRCaGuy\_Peer2Peer) to allow any 2 pins on an Arduino to be used for peer-to-peer type communication between Arduinos, withOUT interrupts or timers/counters.

Currently SPI, Serial, and I2C are pin-specific, and SoftwareSerial requires pin change interrupts. My implementation will solve these problems.

However, I first am trying to understand some things. As I study SoftwareSerial, I see it inherits from the Stream class, which inherits from the Print class.

I don't understand how Print's `write` is implemented. This is from Print.h:

```
virtual size_t write(uint8_t) = 0;
size_t write(const char *str) {
  if (str == NULL) return 0;
  return write((const uint8_t *)str, strlen(str));
}
virtual size_t write(const uint8_t *buffer, size_t size);
size_t write(const char *buffer, size_t size) {
  return write((const uint8_t *)buffer, size);
}

```

This is from Print.cpp:

```
/* default implementation: may be overridden */
size_t Print::write(const uint8_t *buffer, size_t size)
{
  size_t n = 0;
  while (size--) {
    if (write(*buffer++)) n++; //<--where is this write defined?
    else break;
  }
  return n;
}

```

**My Questions:**

1. What does this mean? I've never seen anything like this before: `virtual size_t write(uint8_t) = 0;` Why the `= 0`?
2. What does it mean/how does it work defining functions in .h files? I've never done this before: ex:
`size_t write(const char *str) {
 if (str == NULL) return 0;
 return write((const uint8_t *)str, strlen(str));
}`
3. Where is the `write` command I've marked above defined? Is Print::write() calling itself recursively?
4. Also, why does SoftwareSerial.h call `using Print::write;` (shown below) when it already re-implements the virtual `write` function just above that?

`virtual size_t write(uint8_t byte);
 virtual int read();
 virtual int available();
 virtual void flush();
 operator bool() { return true; }`

```
using Print::write;

```

# Answer
> 2 votes
`write` is implemented in the class that inherits the Print class - such as HardwareSerial.

There are a number of `write` functions, and they are *overloaded*, which means that they are all distinct functions identified using their parameters as well as their name (`write(uint8_t)` and `write(uint8_t *, size_t)` are different functions). The child class overrides the `write(uint8_t)` function that is *pure virtual1* in the main `Print` class, but the other `write` functions with other parameter lists aren't overridden and are just "used".

The `using Print::write` tells it "the write functions to which I am referring are from the Print class."

> Using-declaration introduces a member of a base class into the derived class definition, such as to expose a protected member of base as public member of derived. In this case, nested-name-specifier must name a base class of the one being defined. If the name is the name of an overloaded member function of the base class, all base class member functions with that name are introduced. If the derived class already has a member with the same name, parameter list, and qualifications, the derived class member hides or overrides (doesn't conflict with) the member that is introduced from the base class.

I'm not entirely sure why they feel they need to use it, since the `write` functon(s) in `Print` are public and thus exposed already.

> What does it mean/how does it work defining functions in .h files? I've never done this before

Exactly the same as if you had defined the function in a .cpp file, but with a few minor differences, the most important one of which is that the compiler finds it easier to *inline* the function (or if you're really lucky eradicate the function altogether). It's great for simple functions such as *setters* and *getters* that just set or return the value of a variable. In such cases *inlining* is desirable, and the compiler may even be able to replace the entire function with just direct access to the variable (if it's clever enough).

Another important thing to note with functions in .h files is that you can only really do it with *class member functions* or *static* functions. Otherwise you end up with compilation errors complaining about *multiple definitions* if you use the header file in more than one place.

---

 1: A *Pure Virtual* function (such as `virtual size_t write(uint8_t) = 0;`) is one which has to be implemented in the child class. Failure to implement it results in a compilation error. The pure virtual function defines part of the *interface* but doesn't implement the software for it - that is down to the child class to implement.

# Answer
> 2 votes
In the Print class the `virtual size_t write (uint8_t)=0` DEFINES and names a function that accepts a byte and returns a size. ANY "virtual" function in a base class CAN be over-ridden in a derived class; however, the `=0` declares that there is NO actual function in the base class -- the compiler sticks a null function pointer there. This is why pure virtual functions MUST be over-ridden in the derived (child) class.

The `using Print::write;` in the .h header file of your derived class tells the compiler that YOUR `size_t DerCl::write (uint8_t val) {}` should fill in that null pointer in the base class...this is why your `write` function must be declared exactly like the one in the base class. If it were not, then when the base class calls it, it would push too many values onto the stack, it would pop too many values off the stack, or it would mix up the parameters sent to the function, etc.

This "polymorphism" allows the base class (Print) to define an interface (for printing in this case) and simultaneously allows the derived class to determine where the resulting byte stream will be sent. *Serial* sends it to the USART's serial port. *SoftSerial* sends it to any two port pins (one Tx and one Rx). But you also can create classes to use SPI, TWI(i.e. CAN), a HDMC file, an LCD display, etc. And you can leverage the uniformity and the functionality of all of the `Write()`, `print()`, and `println()` functions that you're already familiar with by writing a single, simple `size_t write(uint8_t)` function for your derived class.

---
Tags: stream, print
---


# Question
Title: Unable to use Keyboard library with Arduino UNO even after changing the firmware
So I'm trying to use my UNO as an HID device. I followed this tutorial, flashed the firmware and got the UNO to be detected as an HID device.

However, I am still getting the error

> 'Keyboard' not found. Does your sketch include the line '#include '?

Here's the code -

```
/*
Copyright (c) 2014 NicoHood
 See the readme for credit to other people.

 Keyboard example
 Press a button to write some text to your pc.
 See official documentation for more infos
 */

// include HID library
#include <HID.h>

const int pinLed = 13;
const int pinButton = 8;

void setup() {
  pinMode(pinLed, OUTPUT);
  pinMode(pinButton, INPUT_PULLUP);

  // Starts Serial at baud 115200 otherwise HID wont work on Uno/Mega.
  // This is not needed for Leonado/(Pro)Micro but make sure to activate desired USB functions in HID.h
  Serial.begin(115200);

  // Sends a clean report to the host. This is important because
  // the 16u2 of the Uno/Mega is not turned off while programming
  // so you want to start with a clean report to avoid strange bugs after reset.
  Keyboard.begin();
}

void loop() {
  if (!digitalRead(pinButton)) {
    digitalWrite(pinLed, HIGH);

    // Same use as the official library, pretty much self explaining
    Keyboard.println("This message was sent with my Arduino.");
    Serial.println("Serial port is still working and not glitching out");

    // simple debounce
    delay(300);
    digitalWrite(pinLed, LOW);
  }
}

/*
Definitions:

 KEY_LEFT_CTRL
 KEY_LEFT_SHIFT
 KEY_LEFT_ALT
 KEY_LEFT_GUI
 KEY_RIGHT_CTRL
 KEY_RIGHT_SHIFT
 KEY_RIGHT_ALT
 KEY_RIGHT_GUI

 KEY_UP_ARROW
 KEY_DOWN_ARROW
 KEY_LEFT_ARROW
 KEY_RIGHT_ARROW
 KEY_BACKSPACE
 KEY_TAB
 KEY_RETURN
 KEY_ESC
 KEY_INSERT
 KEY_DELETE
 KEY_PAGE_UP
 KEY_PAGE_DOWN
 KEY_HOME
 KEY_END
 KEY_CAPS_LOCK
 KEY_F1
 KEY_F2
 KEY_F3
 KEY_F4
 KEY_F5
 KEY_F6
 KEY_F7
 KEY_F8
 KEY_F9
 KEY_F10
 KEY_F11
 KEY_F12

 KEY_PRINT
 KEY_SCROLL_LOCK
 KEY_PAUSE
 */

```

Can anyone point out what I'm doing wrong here?

# Answer
> 0 votes
Okay, so the problem was that the added HID library was conflicting with the core Keyboard/Mouse library. I replaced the core library with the new one and it worked without any problems.

Well one problem actually, it would ask for a platform.h. To solve this download the Arduino v1.5.7 BETA zip and find the platform.h file in it and paste it in your current Arduino directory.

# Answer
> 0 votes
If I open the rar library file, than I see a file called Keyboard.h. I'm sure you need to include Keyboard.h, than the class Keyboard is known and you can use it in your sketch.

---
Tags: arduino-uno, library, arduino-leonardo, sketch, core-libraries
---


# Question
Title: Arduino UNO - analogRead() returning mixed results
I have created a small circuit with a 220 Ohm resistor and a LED connected to PIN9 for power.

I want to measure the Voltage of the current flowing through the circuit. In order to do that I connected a bridge from between the resistor and the LED to the A3 PIN and used this code:

```
int ledPin=9;
int inPin=A3;
long int in=0;
float V_in=0;
int val;

void setup() {
  analogReference(DEFAULT);
  pinMode(ledPin, OUTPUT);
  pinMode(inPin, INPUT);
  Serial.begin(9600);
  }

  void loop() {
    if (Serial.available() > 0) {
      val = Serial.parseInt();

      if (val>=0 && val<=155) {
        analogWrite(ledPin, val);
        //Serial.println(val);

        for (int i=0; i<10; i++) {
          val+=5;
          analogWrite(ledPin, val);
          //Serial.println(val);

          delay(1000);
          in = analogRead(inPin);
          V_in=float(5.0)*(float(in)/float(1023));
          Serial.println(V_in);
          delay(1000);
          }

        }
        else {
          Serial.println("Dio è morto.");
          }
      }
    }

```

**The problem is that when I run it, with an Input of 55, I get what seams to be a random arrangement of 0s and 2.56s. While I expect a increasing sequence of numbers between 0 and 2.5.**

**What am I doing wrong?**

I measured the Voltage on the A3 Pin using a voltimeter, and it increases every step by 0.2, exactly as expected.

This is an output example:

# Answer
The `analogWrite` function, despite its name, outputs PWM (pulse width modulation) which is either fully on or fully off, with varying duty cycles. If you run that through a RC network (eg. 4.7k in series and 10 µF to ground), it will smooth out the pulses and you will actually get a varying voltage.

So in your case you are measuring on or off depending on the timing. However since you are measuring between the resistor and the LED, you won't get 5V because of the voltage drop over the resistor. An LED, depending on the colour, might have a voltage drop of around 2.2V, and thus you might expect 2.8V at that junction. This is approximately what you got.

---

> I want to measure the Voltage of the current ...

This doesn't make any sense electrically. You are either measuring the voltage (in volts) or the current (in amps). You don't measure the "voltage of the current". I suppose you mean "the voltage at that point".

---

### Reference

Arduino functions reference:

Reference \> Language \> Functions \> Analog io \> Analogwrite
> 4 votes

---
Tags: arduino-uno, analogread
---


title: ledkeypad shield not responsive

text:
# Question
Title: ledkeypad shield not responsive
I recently purchased several of the DFRobot ledkeypad shields: https://www.dfrobot.com/product-1407.html

I have Arduino Leonardo (which also had some problems in the beginning, being recognized as modems). My OS is Linux Mint, and I'm using the last Arduino IDE.

The library I use is the one recommended on the website of the vendor, LedKeypad.h, and works fine with the other shields of the same model from the same batch.

Some shields worked fine but I am now having trouble with one of them, which seems unresponsive. I can load for instance the blink program in the arduino, and it works, but the shield does not work. When it is plugged in, the fours dots are slightly red, and I cannot turn them off.

I tried displaying something on the serial monitor when the buttons are pushed, and only one of the 5 buttons works (the KEY\_DOWN one).

Is there anything I can attempt to fix the problem ? Or should I just give up on this shield ?

# Answer
> -1 votes
> ... and works fine with the other shields of the same model from the same batch.

So had you considered that the shield might be faulty? Have you contacted the manufacturer or vendor for support?

---
Tags: shields, hardware
---


# Question
Title: Arduino extended database library data type. Is char str[] in Arduino the equivalent of VARCHAR in SQL?
I am new to Arduino and I am currently working with an Arduino Uno and SD card module - SD/MMC for database storage using the Arduino database library from https://github.com/jwhiddon/EDB.

My question is, is the `char str[]` type the equivalent of `VARCHAR`?

Here is my arbitrary record definition for my table:

```
struct LogEvent {
  int logId;
  int unumber;
  char username[10];
  char fname[15];
  char lname[15];
  char role[6];
  char boxid[10];
  char userStatus[2];
} logEvent;

```

# Answer
If you mean, are these equivalent:

```
foo VARCHAR(100);

```

and:

```
char foo [100];

```

No, they are not equivalent, really. In the case of SQL you can put 100 characters into foo. In the case of C++ you would (generally speaking) put up to 99 characters into foo, with the final character being 0x00 which indicates the length of the string.

You could conceivably put 100 characters into `foo` but then you would have to store the size of `foo` in another variable.
> 2 votes

# Answer
If you're referring to the SQL type `VARCHAR`, then, vaguely. `char username[10];` for instance will define a char array of 10 bytes. A `char` being the equivalent of a byte. That's about it for the type. This is C++, so you're pretty close to the iron, and a char array is about as basic as it gets. No collation, no encoding (remember that a character is not always a single byte!), no indexing. Just a bunch of bytes put together.
> 1 votes

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


# Question
Title: Send and receive text between Arduino Mega 2560 and C# via ENC28J60
I'm working on an Arduino project that sends and receives text to/from a C# application via ENC28J60 in a LAN network. Whenever C# sends a request to Arduino (In text), Arduino responds to it by sending also a text. What is the best way to do this? I'm newbie in network programming (Or whatever it's called). Thanls in advance :)

# Answer
You can use TCP or UDP protocols.

https://www.arduino.cc/en/Tutorial/UDPSendReceiveString

https://www.arduino.cc/en/Tutorial/DhcpChatServer

You can use free UDP, TCP port listener sofwares for Windows, Linux etc.. for testing your setup.

For C# development:

https://stackoverflow.com/questions/20038943/simple-udp-example-to-send-and-receive-data-from-same-socket

and

https://stackoverflow.com/questions/10182751/server-client-send-receive-simple-text
> 1 votes

---
Tags: arduino-mega, c#
---


# Question
Title: Code that worked in Uno/Nano is not working in Mega - help me port the code to Mega
I used the code from this project... to build an oscilloscope-like project. It worked fine with Uno and Nano.

Later I tried to do the same with a Mega, but I don't know what's wrong. It's not working! Maybe due to some pin or port number mismatch (I think so...). Because it has some low level code like:

```
------------------------------------------------------
// set up 8 MHz timer on pin 9
pinMode (9, OUTPUT);
// set up Timer 1
TCCR1A = _BV (COM1A0);  // toggle OC1A on Compare Match
TCCR1B = _BV(WGM12) | _BV(CS10);   // CTC, no prescaling
OCR1A =  0;       // output every cycle
---------------------------------------------------------

```

And like:

```
Data.Values[i]=PINC;

```

I have very little knowledge about these registers.

Please help me port this code to Mega and make it work...

# Answer
> 2 votes
There is some concept you would have to learn before you can go from Arduino Uno to Mega.
Because your project is designed to operate on Arduino Uno R3, the registers operations like below are specific to the microcontroller in Arduino Uno - in this case ATmega328P-PU - datasheet here `TCCR1A = _BV (COM1A0); // toggle OC1A on Compare Match
 TCCR1B = _BV(WGM12) | _BV(CS10); // CTC, no prescaling
 OCR1A = 0;`
You can find description of registers in mentioned datasheet in chapter 19. TC0 - 8-bit Timer/Counter0 with PWM
Now, you grab another datasheet - one which describes ATmega2560 (yes, this is microcontroller which is sitting in Arduino Mega), find corresponding pin (like OC1 in Uno - check the drawing below):  and find proper pin and corresponding register from ATmega2560 datasheet. Take a look at the schematic picture first, select one of OCx pins and configure what is needed. Pins from Aruino Mega with OCR functionality:
and
You need to learn what registers are, and what they can do. Can be a little demanding task, but believe me - this will give you supernatural powers in microcontrollers world ;)

---
Tags: arduino-mega, programming
---


# Question
Title: EEPROM put and get not working on ESP8266 (NodeMCU)
The Arduino documentation provides two examples to store data in the EEPROM.

https://www.arduino.cc/en/Reference/EEPROMPut stores data in the EEPROM and the EEPROMGet example reads the data back and writes it out.

These examples work fine on my Arduino Uno, but on my ESP8266 (NodeMCU) the EEPROMGet example code is unable to retrieve the data EEPROMPut should have stored previously. Instead it's just returning some random bits and bytes.

Any ideas? I haven't found anything about known incompatibilities related to the ESP8266 boards...

# Answer
> 5 votes
The ESP8266 doesn't have any EEPROM. Instead it emulates it using Flash.

In order not to wear out your flash you have to "commit" changes to the flash once they have been queued for writing - otherwise they will be lost.

Instead of using the Arduino examples you should be using the ESP8266 specific examples included with the ESP8266 EEPROM emulation library (but also here).

# Answer
> 2 votes
**EEPROM for the ESP8266/NodeMCU**

This is a bit different from standard EEPROM class for Arduino. You need to call `EEPROM.begin(size)` before you start reading or writing, size being the number of bytes you want to use. Size can be anywhere between 4 and 4096 bytes.

`EEPROM.write` does not write to flash immediately, instead you must call `EEPROM.commit()` whenever you wish to save changes to flash. `EEPROM.end()` will also commit, and will release the RAM copy of EEPROM contents.

EEPROM library uses one sector of flash located just after the SPIFFS.

---
Tags: esp8266, nodemcu, eeprom
---


title: SSID was not declared in this scope

text:
# Question
Title: SSID was not declared in this scope
so I am new to arduino and coding in general, I am trying to use the arduino to remotely survey plants, I am using this guide: https://create.arduino.cc/projecthub/arduino/plant-communicator-7ea06f. The entire code is:

```
#include <WiFi101.h>
#include<WiFiSSLClient.h>
const char* ssid = SKY1C9D0;    //  your network SSID (name)
const char* password = SYDTSTQR;  // your network password
String httpsRequest = https://hooks.zapier.com/hooks/catch/2821422/84ehn1/;
// your Zapier URL
   const char* host = "hooks.zapier.com";
WiFiSSLClient client;
void setup() {
  Serial.begin(9600);
  while (!Serial);
  delay(2000);
  Serial.print("Connecting Wifi: ");
  Serial.println(ssid);
  while (WiFi.begin(ssid, password) != WL_CONNECTED) {
    Serial.print(".");
    delay(500);
  }
  Serial.println("");
  Serial.println("WiFi connected");
}
void loop() {
  float temperature = 22;
  int moisture = 150;
  int light = 40;
  String warning = "This is a warning message";
  warning.replace(" ", "%20");
  send_email(temperature, moistue, light, warning );
  delay(20000)
}
void send_email(float temperature, int moisture, int light, String warning)     {
  // convert values to String
  String _temperature = String(temperature);
  String _moisture = String(moisture);
  String _light = String(light);
  String _warning = warning;
  if (client.connect(host, 443)) {
    client.println("POST " + httpsRequest + "temperature=" + _temperature +                 "&moisture=" + _moisture + "&light=" + _light + "&warning=" + _warning + "     HTTP/1.1");
    client.println("Host: " + String(host));
    client.println("Connection: close");
    client.println();
    delay(1000);
    while (client.available()) { // Print on the console the answer of the server
      char c = client.read();
      Serial.write(c);
    }
    client.stop();  // Disconnect from the server
  }
  else {
    Serial.println("Failed to connect to client");
 }
}

```

The error is specifically highlighted here: `const char* ssid = SECRET_SSID; // your network SSID (name)`. The error is that the ssid has not been declared. I am unsure of what to do to fix this and any other possible errors that have gone unnoticed. I would highly appreciate any help or guidance. Thank you

# Answer
A problem in the include file on the line previous could cause the following line to be misinterpreted. To test that try moving the ssid after the password and see if the error changes. Obviously make sure all strings are properly quoted.

```
#include <WiFi101.h>
#include <WiFiSSLClient.h>

const char* password = "SYDTSTQR";  // your network password
const char* ssid = "SKY1C9D0";    //  your network SSID (name)
String httpsRequest = "https://hooks.zapier.com/hooks/catch/2821422/84ehn1/";

```
> 1 votes

# Answer
You need quotes around literal string values.

```
const char* ssid = "SKY1C9D0" ; // your network SSID (name)
const char* password = "SYDTSTQR" ;

```
> 0 votes

---
Tags: code-review, mkr1000, iot
---


title: ENC28J60 is not getting ping

text:
# Question
Title: ENC28J60 is not getting ping
I bought a new ENC28J60 module and I tried to communicate with the PC through Arduino Uno board.

When I tried to ping the address that I gave in the program it's not getting the ping. Give me some solution.

I used the web server example that is in the example section of Arduino. I even turned off my firewall setting.

The code that I used is:

```
/*
  Web Server

 A simple web server that shows the value of the analog input pins.
 using an Arduino Wiznet Ethernet shield.

 Circuit:
 * Ethernet shield attached to pins 10, 11, 12, 13
 * Analog inputs attached to pins A0 through A5 (optional)

 created 18 Dec 2009
 by David A. Mellis
 modified 9 Apr 2012
 by Tom Igoe
 modified 02 Sept 2015
 by Arturo Guadalupi

 */

#include <SPI.h>
#include <Ethernet.h>

// Enter a MAC address and IP address for your controller below.
// The IP address will be dependent on your local network:
byte mac[] = {
  0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED
};
IPAddress ip(192, 168, 1, 20);

// Initialize the Ethernet server library
// with the IP address and port you want to use
// (port 80 is default for HTTP):
EthernetServer server(80);

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

  // start the Ethernet connection and the server:
  Ethernet.begin(mac, ip);
  server.begin();
  Serial.print("server is at ");
  Serial.println(Ethernet.localIP());
}

void loop() {
  // listen for incoming clients
  EthernetClient client = server.available();
  if (client) {
    Serial.println("new client");
    // an http request ends with a blank line
    boolean currentLineIsBlank = true;
    while (client.connected()) {
      if (client.available()) {
        char c = client.read();
        Serial.write(c);
        // if you've gotten to the end of the line (received a newline
        // character) and the line is blank, the http request has ended,
        // so you can send a reply
        if (c == '\n' && currentLineIsBlank) {
          // send a standard http response header
          client.println("HTTP/1.1 200 OK");
          client.println("Content-Type: text/html");
          client.println("Connection: close");  // the connection will be closed after completion of the response
          client.println("Refresh: 5");  // refresh the page automatically every 5 sec
          client.println();
          client.println("<!DOCTYPE HTML>");
          client.println("<html>");
          // output the value of each analog input pin
          for (int analogChannel = 0; analogChannel < 6; analogChannel++) {
            int sensorReading = analogRead(analogChannel);
            client.print("analog input ");
            client.print(analogChannel);
            client.print(" is ");
            client.print(sensorReading);
            client.println("<br />");
          }
          client.println("</html>");
          break;
        }
        if (c == '\n') {
          // you're starting a new line
          currentLineIsBlank = true;
        } else if (c != '\r') {
          // you've gotten a character on the current line
          currentLineIsBlank = false;
        }
      }
    }
    // give the web browser time to receive the data
    delay(1);
    // close the connection:
    client.stop();
    Serial.println("client disconnected");
  }
}

```

# Answer
You have an ENC28J60 based module. Your code is for the Wiznet-based module. The two are not interchangeable.

See this: http://nathanhein.com/2013/02/getting-arduino-online-with-an-enc28j60/

Good luck.
> 2 votes

---
Tags: arduino-uno
---


title: EEPROM - Arduino

text:
# Question
Title: EEPROM - Arduino
In my recent project, I want to store values permanently. So for that, I want to use the EEPROM. I searched for it and read about it. Now, I have some questions.

Questions:

> 1. How many locations are there in the EEPROM? (For Arduino Uno & Mega)
> 2. I read that an EEPROM has a limit of 100,000 write cycles per single location. That means if one location is used 100,000 times then we can use another after that? Or overall the EEPROM has a limit of 100,000 write cycles?
> 3. So, what about reading the contents of the EEPROM? Does it have the same limit?
> 4. And what is the starting location (address) of the EEPROM? (For Arduino Uno & Mega)

EDIT:1

> 5. Suppose I store the HIGH value of LED in one location and the LOW value of LED in another one. Then now read the value from that locations. Now how many times I can read this value? So what about write cycle? It just uses for only one time maybe?

Any better option for storing data permanently?

# Answer
> (1) How many locations are there in EEPROM? (For ARDUINO UNO & MEGA)

Read the datasheet for the chip on the board. It tells you how many bytes or kilobytes the chip has for EEPROM. For instance the ATMega328P on the Uno has 1024 bytes (1k).

> (2) As I read out EEPROM has a limit of 100,000 write cycles per single location. That means If one location is used 100,000 times then we can use another after that? Or Overall EEPROM has a limit of 100,000 write cycle?

Each cell has at least a 100,000 write limit. Or more specifically a 100,000 *erase* limit (since a cell must be erased before writing).

> (3) So, what about reading the content from EEPROM? Has it maybe same limit?

No, no limit - the limit as I mentioned is on erasing: you don't erase when reading.

> (4) And what is starting location(address) of EEPROM? (For ARDUINO UNO & MEGA)

Zero. It's not really part of any address space, it uses special instructions and registers to get at it.
> 5 votes

---
Tags: arduino-uno, eeprom
---


title: Arduino HTTP Post request

text:
# Question
Title: Arduino HTTP Post request
I have a Arduino Mega with Wiznet 5100 Ethernet shield. Am trying to post some data onto localhost for started later on which will be accepted by a website. But when I try to post the data I get some error. When I try to send the same data via postman it gets accepted . But when it goes from arduino error occurs. The arduino Code is as follows:

```
client.println("POST /api/trackers/5a28eddaf57a6e2060e85601/solars/5a3bb2adf57a6e1a71ca135b/arduino_data HTTP/1.0");

client.println("Host: 192.168.6.16");

client.println("Accept: application/vnd.mirasol.v1");
Serial.println("After Accept application vnd");

client.println("User-Agent: Arduino/1.0");
Serial.println("After User Agent Arduino");

client.println("Accept: application/json");
Serial.println("After Accept application json");

client.println("Content-Length: ");
Serial.println("After content length");

client.println(postdata.length());

client.println("Content-Type: application/json");
Serial.println("After content type application json");

client.println("Connection: close");
Serial.println("After connection close");

client.println();
Serial.println("After client println");

client.println(postdata);
Serial.println("After post data");
Serial.println(postdata);

```

The output in the serial monitor is as follows:

```
    connecting...
connected
After Accept application vnd
After User Agent Arduino
After Accept application json
After content length
After content type application json
After connection close
After client println
After post data
{"current":10.50, "voltage":10.50}
H
disconnecting.

```

And the error shown in localhost is as follows:

```
2017-12-27 15:21:57 +0530: HTTP parse error, malformed request (): #<Puma::HttpParserError: Invalid HTTP format, parsing fails.>

```

I have the application in Ruby on Rails with Mongoid as the DB.

FYI: New to coding..

# Answer
Your problem most likely stems from this bit:

```
client.println("Content-Length: ");
Serial.println("After content length");

client.println(postdata.length());

```

You have an extraneous "ln" in there causing the post data length to be on a separate line from the Content-Length:

```
Content-Length:
23

```

You should change the first `println` to a `print`. Also the order could do with changing to keep things logically grouped:

```
client.print("Content-Length: ");
client.println(postdata.length());

Serial.println("After content length");

```

Which would result in:

```
Content-Length: 23

```
> 1 votes

---
Tags: arduino-mega, http, ethernet-shield
---


# Question
Title: How to read a timer's value once stopped?
I've downloaded the Timer1 library but unfortunately it seems that the read() method has been removed from it. I tried also SimpleTimer library from the arduino website but the program didn't compile because of undefined reference to \`SimpleTimer::SimpleTimer()' error. Anybody knows how to solve this error or just another timer library which has a read function?

To be more specific I need to start a timer as I press a button and to stop it as it is released.

# Answer
> 1 votes
Here, below is a code which is you looking for. When you pressed a button then a timer is started and when you released it then a timer is stopped. And you can also see that time also means how long button is pressed.

```
const uint8_t button_pin = 2;

void setup()
{
    pinMode(button_pin, INPUT_PULLUP);
    Serial.begin(9600);
}

void loop()
{
    static int last_button_state = HIGH;
    static unsigned int push_count;
    static unsigned long last_press_time;
    int button_state = digitalRead(button_pin);
    unsigned long now = millis();

    // Record when the button is pressed.
    if (last_button_state == HIGH && button_state == LOW) {
        push_count++;
        last_press_time = now;
    }

    // Report when the button is released.
    if (last_button_state == LOW && button_state == HIGH) {
        unsigned long push_duration = now - last_press_time;
        if (push_duration < 10) {  // discard bounce
            push_count--;
        }
        else {
            Serial.print(F("pushes: "));
            Serial.print(push_count);
            Serial.print(F(", duration: "));
            Serial.print(push_duration);
            Serial.println(F(" ms"));
        }
    }

    last_button_state = button_state;
}

```

---
Tags: arduino-uno, timers, button
---


# Question
Title: Detecting the presence of a specific smartphone
I would like you to give me some clues about a projet I have: I want to make sure that my little brother's smartphone stays in a shelf overnight and during school hours in order to monitor the time he spends with it.

In order to fulfill my needs, I thought of using an Arduino to detect that the smartphone stays in proximity at certain hours.

Since this is my first Arduino project, I'm not quite sure what I could do, and what is possible to do.

Hence I've got a lot of questions:

* Can I easily detect that a specific smartphone is in range?
* Can I use the smartphone's NFC (RFID) to do so?
* What kind of output could I possibly get from an Arduino? I would like to make statistics, so it must be stored somewhere, and I know Arduino doesn't have a lot of memory.
* Is it possible to write on a USB key?
* Which Arduino is best suited for my needs Should I consider buying an Arduino with Ethernet in order to send emails?

Thanks a lot!

# Answer
> Can I easily detect that a specific smartphone is in proximity ?

It can be done, yes. How "easily" depends on how much money and expertise you have to throw at it.

> Can I use the smartphone's NFC (RFID) to do so ?

It is possible to use that, yes - if you add the right hardware and software to the Arduino.

> How long can an Arduino run on battery using a 9V battery from the market ?

A couple of hours if you're lucky. They are useless batteries.

> What kind of output could I possibly get from an Arduino ? I would like to make statistics, so it must be stored somewhere, and I know Arduino has not a lot of memory.

Whatever you want. Again, it's SMOP / SMOH.

> Is it possible to write on an USB key ?

Sure, if you get the right hardware for that.

> Which Arduino is best suited for my needs ? Should I consider buying an Arduino with Ethernet in order so send email ?

The Arduino that provides the facilities your project requires - and that depends on how you are going to decide on how to do it. Remember: the Arduino is just the "brain" of the operation. You need to decide what "organs" the brain needs to control and in what way.

There's a million and one ways of achieving what you want. You could even do it 100% in the phone in software (there's probably an app for that...) without need of an Arduino...
> 1 votes

---
Tags: usb, rfid
---


title: Supervised inputs for alarm panel

text:
# Question
Title: Supervised inputs for alarm panel
I'm using an Arduino Mega 2560 to make a fire alarm control panel. The control panel takes 50 (inputs) supervised inputs. The normal way as mentioned in the link is to use the analog inputs, which I am short of. Is there any other way to monitor supervised inputs other than using analog inputs?

Thanks in advance for your time – if I’ve missed out anything, over- or under-emphasized a specific point let me know in the comments.

# Answer
> 2 votes
I can think of a number of ways of doing this:

1. **Multiplexing** -- Employ a (large) number of analog MUX chips to expand the number of analog inputs you have available. That would get messy *very* quickly.
2. **External ADC Chips** -- Add more real analog inputs over SPI or I2C. For 50 inputs that would be quite a lot of extra chips.
3. **Use Op-Amps** -- Each input can be converted into a pair of digital inputs using two op-amps to compare the voltage of the input against two thresholds, which would give you an "active" and a "fault" signal. That would be 100 digital inputs needed (and 100 op-amps, which could be done with 25 quad op-amp chips).
4. **Distributed processing** -- Don't try and do it all with one device. Split your system into zones with far less inputs then get the zones to communicate with each other.

Of course, you can combine any of those - you could have analog MUX chips fanning out a number of external ADC chips inputs. You could MUX the inputs to the op-amps. You could have external ADC chips on multiple zone systems. Etc.

Personally, on a system of this size, I would certainly consider distributing the inputs across multiple processors even if they are all in the same physical control unit. However, distributing nodes across the building (it sounds like it's quite a large building for 50 inputs) would reduce the amount of cable needed to implement those inputs, and some industry standard bus snaking its way around the building connecting all the nodes up to a master unit would, if implemented correctly, be robust. CAN is a popular protocol for interconnecting control systems (it's used in modern lifts, and those are life critical... you don't want a lift to fail...) so could be a good choice for this.

---
Tags: arduino-uno, arduino-mega, programming
---


# Question
Title: Arduino LED flashes with one button press
I want the LED to flash when I press the switch once, but it keeps flashing. I tried the idea of just lighting the LED and keeping it lit with just one button press, so I wrote:

```
int led=13,button=12;
void setup() {
pinMode(led,OUTPUT);
pinMode(button,INPUT);
}
void loop() {
if (digitalRead(button)==HIGH)
  digitalWrite(led,HIGH);
}

```

and this worked; it stayed on after I pressed the button once, so for the flashing LED I wrote:

```
int led=13,button=12;
void setup() {
pinMode(led,OUTPUT);
pinMode(button,INPUT);
}
void loop() {
if (digitalRead(button)==HIGH)
{
  digitalWrite(led,HIGH);
delay(1000);
 digitalWrite(led,LOW);
 delay(1000);

} }

```

but this didn't work. It stops flashing after I remove my hand from the switch. Why is this happening?

# Answer
> 2 votes
Because the digital writes only apply on `if (digitalRead(button)==HIGH)`. If you don't press the button, then the code goes:

```
void loop() {
}

```

Essentially doing nothing. Your code needs a bit more to keep track of the button press. Pseudo Code:

```
if button == pressed {
    int tracker=1;
}
if tracker == 1 {
    led on;
    wait;
    led off;
    wait;
}
loop

```

# Answer
> 0 votes
This is what you need. When you pressed the button then your LED turn ON. And it still ON until you pressed the button again.I hope it will help you.

```
const int kPinBtn = 2;
const int kPinLed = 13;

boolean kPress = false;

void setup()
{
  pinMode(kPinBtn, INPUT_PULLUP);
  pinMode(kPinLed, OUTPUT);
}

void loop()
{
  if(digitalRead(kPinBtn) == LOW && kPress == false)
  {
    digitalWrite(kPinLed, HIGH);
    kPress = true;
  }
  if(digitalRead(kPinBtn) == LOW && kPress == true)
  {
    digitalWrite(kPinLed, LOW);
    kPress = false;
  }
}

```

---
Tags: led, flash, arduino-uno
---


# Question
Title: Arduino uno PWM CTC mode - strange behaviour on interrupt
i have this simple code that i use for generating a square wave signal of 125 KHz on pin 9 using Timer1 in the "Clear Timer on Compare Match (CTC) Mode". I also use Timer1 Compare Match A interrupt for toggling pin 7 of PORTD.

```
void setup() {
pinMode(9, OUTPUT);
pinMode(7, OUTPUT);

TCNT1 = 0;
TCCR1A = 0;
TCCR1B = 0;

OCR1A = 7;
TIMSK1 = _BV(OCIE1A);
TCCR1A = _BV(COM1A0);
TCCR1B = _BV(CS11) | _BV(WGM12);
}

void loop() {
}

ISR(TIMER1_COMPA_vect)
{
  PORTD = PORTD ^ 128;
}

```

It happens that

* The 125KHz waveform on pin 7 is delayed by 1us with respect to the waveform of pin 9. I think that is related to the time that the microcontroller takes to "entering" the interrupt function and toggling the PORTD pin (1us are 16 clock cycle of the 16MHz master clock).
* Sometimes the waveform on pin 7 (the one generated inside the interrupt service routine) has some "gaps". For example, this is the waveform acquired with my scope:Why this strange behaviour happens?

Thank you

# Answer
> 2 votes
This isn't the only `ISR` in the Arduino, there is at least the one counting `millis`. Counter 0 overflow ISR is not as short as yours, so every `1024us` it'll cause some jitter (or as in your case, skipping the edge and basically inverting the phase). It'd be also several clock cycles delayed (against HW generated signal). Pushing and poping the registers into the stack are the deterministic delays, but the latency between setting the `ISR` flag and calling the `ISR` routine depends on currently executed instruction (some of them takes 2cycles, and there are also longer ones).

There is not much time to do anything else either. Your `ISR` might take less than `20` cycles, but you only have `64` cycles (`ISR` is called at `250kHz` rate so it generates `125kHz` signal). So if anything else prevents your `ISR` to be called (another `ISR`, disabled interrupts), you can miss them, as there is only one interrupt flag.

If you want the same waveform on pin 7, just use a wire and let the pin mode as `INPUT`.

BTW: You don't have to use `PORTB = PORTB ^ _BV(PB7);`, the `PINB = _BV(PB7)` toggles PB7 without read-modify-write access.

---
Tags: arduino-uno, programming, interrupt, pwm
---


title: How to loop a specific tone?

text:
# Question
Title: How to loop a specific tone?
I am building a security system, and found the following code

```
#define NOOT_B0  31
#define NOOT_C1  33
#define NOOT_D1  37
#define NOOT_E1  41
#define NOOT_F1  44
#define NOOT_G1  49
#define NOOT_A1  55
#define NOOT_B1  62
#define NOOT_C2  65
#define NOOT_D2  73
#define NOOT_E2  82
#define NOOT_F2  87
#define NOOT_G2  98
#define NOOT_A2  110
#define NOOT_B2  123
#define NOOT_C3  131
#define NOOT_D3  147
#define NOOT_E3  165
#define NOOT_F3  175
#define NOOT_G3  196
#define NOOT_A3  220
#define NOOT_B3  247
#define NOOT_C4  262
#define NOOT_D4  294
#define NOOT_E4  330
#define NOOT_F4  349
#define NOOT_G4  392
#define NOOT_A4  440
#define NOOT_B4  494
#define NOOT_C5  523
#define NOOT_D5  587
#define NOOT_E5  659
#define NOOT_F5  698
#define NOOT_G5  784
#define NOOT_A5  880
#define NOOT_B5  988
#define NOOT_C6  1047
#define NOOT_D6  1175
#define NOOT_E6  1319
#define NOOT_F6  1397
#define NOOT_G6  1568
#define NOOT_A6  1760
#define NOOT_B6  1976
#define NOOT_C7  2093
#define NOOT_D7  2349
#define NOOT_E7  2637
#define NOOT_F7  2794
#define NOOT_G7  3136
#define NOOT_A7  3520
#define NOOT_B7  3951
#define NOOT_C8  4186
#define NOOT_D8  4699

 int melody[] = {
// NOOT_C4, NOOT_G3, NOOT_G3, NOOT_A3, NOOT_G3, 0, NOOT_B3, NOOT_C4
NOOT_D8, NOOT_D8, NOOT_D8, NOOT_D8, NOOT_D8, NOOT_D8
};
int NOOTDurations[] = {
 4, 4, 4, 4, 4, 4, 4, 4
 };
 void setup() {
    // iterate over the NOOTs of the melody:
  for (int thisNOOT = 0; thisNOOT < 8; thisNOOT++) {

// to calculate the NOOT duration, take one second divided by the NOOT type.
//e.g. quarter NOOT = 1000 / 4, eighth NOOT = 1000/8, etc.
int NOOTDuration = 1000 / NOOTDurations[thisNOOT];
tone(8, melody[thisNOOT], NOOTDuration);

// to distinguish the NOOTs, set a minimum time between them.
// the NOOT's duration + 30% seems to work well:
int pauseBetweenNOOTs = NOOTDuration * 1.50;
delay(pauseBetweenNOOTs);
// stop the tone playing:
noTone(8);
  }
 }

void loop() {
int melody[] = {
 // NOOT_C4, NOOT_G3, NOOT_G3, NOOT_A3, NOOT_G3, 0, NOOT_B3, NOOT_C4
 NOOT_D8, NOOT_D8, NOOT_D8, NOOT_D8, NOOT_D8, NOOT_D8
  };
 int NOOTDurations[] = {
  4, 4, 4, 4, 4, 4, 4, 4
  };

  }

```

How can i let the specific tone loop? Right now it's not within the loop and i am struggling to make it work in the loop. Thanks in advance!

# Answer
> 1 votes
```
#include "Arduino.h"

const byte TONE_PIN = 4;
const int ALARM_BEEP_1 = 4186;
const int ALARM_BEEP_2 = 4699;

const int ALARM_TONE_LENGTH = 200;
const int ALARM_TONE_PAUSE = 800;
const int ALARM_TONE_REPEAT = 6;

boolean alarm = false;

void setup()
{
  alarm = true;
}

void loop()
{
  if (alarm) {
    alarmSound();
  }
}

void alarmSound() {
  static unsigned long next = millis();
  static byte count = 0;
  if (millis() > next) {
    next += ALARM_TONE_LENGTH;
    count++;
    if (count == ALARM_TONE_REPEAT) {
      next += ALARM_TONE_PAUSE;
      count = 0;
    }
    tone(TONE_PIN, (count % 2) ? ALARM_BEEP_1 : ALARM_BEEP_2, ALARM_TONE_LENGTH);
  }
}

```

---
Tags: arduino-uno, speaker
---


# Question
Title: Arduino Uno: Driving a small LED strip with 2N3904 NPN
I'd like to know why I cannot dim the small LED strip with my design. I can only turn them on and off. This is a problem for me as I wanted to have a fade effect. Here is my circuit:

The voltage from the power jack is 5 volts. My NPN transistor is a 2N3904 (from left to right: emitter, base, collector). For the Arduino I am only using the fade exemple sketch:

```
int led = A2; // the PWM pin the LED is attached to
int brightness = 0; // how bright the LED is
int fadeAmount = 5; // how many points to fade the LED by

// the setup routine runs once when you press reset:
void setup() {
   pinMode(led, OUTPUT);
 }

// the loop routine runs over and over again forever:
void loop() {
  // set the brightness of pin 9:
  analogWrite(led, brightness);

  // change the brightness for next time through the loop:
  brightness = brightness + fadeAmount;

  // reverse the direction of the fading at the ends of the fade:
  if (brightness <= 0 || brightness >= 255) {
     fadeAmount = -fadeAmount;
  }
  // wait for 30 milliseconds to see the dimming effect
  delay(30);
}

```

By the way, this is my first post so please tell me if something is wrong with it! Thank you for your help!

Have a nice day.

# Answer
> 2 votes
The `analogWrite` works only on `PWM` pins (in your scheme it's marked by ~). On the other pins it's possible to set only `LOW`/`HIGH` (values under `128` are translated to the `LOW`)

Not to mention weirdly used `NPN` with LEDs as negative feedback. But that's why it doesn't burned out yet. The usual way is connect the Emmiter to the ground and base is driven over current limiting resistor (about 1k). This is how we usualy use `PNP` transistor (again with 1k resistor and emitter to the `Vcc`, not the collector). But `PNP` won't work with `5V` logic and higher `Vin` than `5V` as there will be current flow from `0V` or `5V` to the `Vin`.

---
Tags: led, transistor
---


# Question
Title: How to store values from a sensor inside an empty array?
I need to store the value of the distance in the dist array, then calculate the maximun value and print the index associated with this value:

The problem is when starting the nested for inside another for, the servomotor stops working

```
// Includes the Servo library
#include <Servo.h>

// Array y valores para funcion valor maximo

int max=0;

int angle=0;

int distance=0;

// Defines Tirg and Echo pins of the Ultrasonic Sensor

const int trigPin = 10;

const int echoPin = 11;

// Variables for the duration and the distance

long duration;

//int distance[180];

Servo myServo1; // Creates a servo object for controlling the servo motor

void setup() {

  pinMode(trigPin, OUTPUT); // Sets the trigPin as an Output

  pinMode(echoPin, INPUT); // Sets the echoPin as an Input

  Serial.begin(9600);

  myServo1.attach(12); // Defines on which pin is the servo motor attached
  }

void loop() {

distance = calculateDistance();
  if (distance <= 15 && distance >=2)
  {

  // rotates the servo motor from 1 to 179 degrees and calculate the distance at each angle

  for(int j=90;j>=0;j--){

  myServo1.write(j);

  delay(30);}

  for(int j=0;j<=180;j++){

  myServo1.write(j);

  int i=0;

  int  dist [i] = {calculateDistance()};

      for (i=0;i=180;i++){           <--------------------------------------

       if (dist[i]>max){
      max=dist[i];
      angle=i;
      Serial.print(angle);
      delay(30);}

  }
      }

  // Repeats the previous lines from 179 to 90 degrees

for(int j=180;j>90;j--){

  myServo1.write(j);

  delay(30);

  }
}
}

// Function for calculating the distance measured by the Ultrasonic sensor
int calculateDistance(){

  digitalWrite(trigPin, LOW);

  delayMicroseconds(2);

  // Sets the trigPin on HIGH state for 10 micro seconds

  digitalWrite(trigPin, HIGH);

  delayMicroseconds(10);

  digitalWrite(trigPin, LOW);

  duration = pulseIn(echoPin, HIGH); // Reads the echoPin, returns the sound wave travel time in microseconds

  distance= duration*0.034/2;

  return distance;

}

```

# Answer
> 1 votes
```
  int i=0;
  int  dist [i] = {
    calculateDistance()      };

```

I'm not sure what you are thinking here, but you obviously cannot store data into a zero-length array. You also cannot put a function call to populate an array of variable length.

You need to decide how many elements you need in the array, in advance, and allocate an array of that size.

---

Maybe more like this:

```
 int  dist [180];

  for (i=0;i<180;i++){
    dist [i] = calculateDistance ();
    if (dist[i]>max){
      max=dist[i];
      angle=i;
      Serial.print(angle);
      delay(30);
    }

  }

```

---

Also, this is wrong in your code:

```
for (i=0;i=180;i++){

```

You need to test for \< 180 here. Your `for` loop will **assign** 180 to i and then check to see if it is non-zero, which will always be true.

---
Tags: c++, array
---


# Question
Title: Attempts with Sainsmart Motor Shield Not Working
I received the sainsmart motor controller a few days ago, and am now having trouble testing it. The Arduino I am using is an Arduino Mega 2560. I thought it was an I2C communication issue but that wasn't working. So here I am now asking for help. Here is my wiring.

Here is my code:

```
#include <AFMotor.h>

AF_DCMotor motor(2);

void setup() {
 Serial.begin(9600);           // set up Serial library at 9600 bps
 Serial.println("Motor test!");

 // turn on motor
 motor.setSpeed(200);

 motor.run(RELEASE);
}

void loop() {
 uint8_t i;

 Serial.print("tick");

 motor.run(FORWARD);
 for (i=0; i<255; i++) {
  motor.setSpeed(i);
  delay(10);
 }

 for (i=255; i!=0; i--) {
  motor.setSpeed(i);
  delay(10);
 }

Serial.print("tock");

motor.run(BACKWARD);

 for (i=0; i<255; i++) {
  motor.setSpeed(i);
  delay(10);
 }

for (i=255; i!=0; i--) {
  motor.setSpeed(i);
  delay(10);
 }

Serial.print("tech");
motor.run(RELEASE);
delay(1000);
 }

```

**I also tried this one:**

```
#include<AFMotor.h>
 AF_DCMotor motor2(2);
void setup() {
 // put your setup code here, to run once:
 motor2.setSpeed(255);
}

void loop() {
 // put your main code here, to run repeatedly:
 motor2.run(FORWARD);
  }

```

**None of the two worked. If someone could help me that would be great. Thank You!!!**

# Answer
I figured out the problem. One of the terminals was damaged during transportation. Now it's all good. Thanks for the help.
> 1 votes

---
Tags: arduino-motor-shield
---


title: how to wrap/scroll text with U8G2

text:
# Question
Title: how to wrap/scroll text with U8G2
Does anyone know how to wrap and or text using the U8G2 Libary? I know there are other libraries that do this for you, but I'd like to use U8G2.

Thank you!

my code's here for reference. It's not clean, but it works for now https://create.arduino.cc/editor/shaiss/0a2736f4-fb79-4e12-b9d7-fb15ff6757b7/preview

# Answer
You can do something like

```
void loop(void) {
    u8g2_uint_t x;

    u8g2.firstPage();
    do {

        // draw the scrolling text at current offset
        x = offset;
        u8g2.setFont(u8g2_font_inb30_mr);       // set the target font
        do {                                // repeated drawing of the scrolling text...
            u8g2.drawUTF8(x, 30, text);         // draw the scolling text
            x += width;                     // add the pixel width of the scrolling text
        } while( x < u8g2.getDisplayWidth() );      // draw again until the complete display is filled

        u8g2.setFont(u8g2_font_inb16_mr);       // draw the current pixel width
        u8g2.setCursor(0, 58);
        u8g2.print(width);                  // this value must be lesser than 128 unless U8G2_16BIT is set

    } while ( u8g2.nextPage() );

    offset-=1;                          // scroll by one pixel
    if ( (u8g2_uint_t)offset < (u8g2_uint_t)-width )
        offset = 0;                         // start over again

    delay(10);                          // do some small delay
}

```

this is taken from here.

It is an excellent lib, but it is can require big amount of memory, fit very well on ESP8266 (tried on nodeMCU) / ESP32.

Of course on ESP32 it is faster.

Used for small OLED 0.98" screen
> 1 votes

---
Tags: arduino-uno, u8glib
---


# Question
Title: Pass a char array to a function that uses File as parameter
I am in serious need for help here. I have a rather small function that get's the number of files from within a given directory. Now, the directory name (that is the path) is stored in a char array within my main loop.

My problem is, I have no idea how to pass this char array to my function.

This is my code (it's of course just a subset but it's the part that is obviously wrong) and you can also see the complete program at the end:

In the setup() routine I define my current working directory:

```
char plrCurrentFolder[9];

```

In the main loop I want to get the number of files of a given directory (in the final program this directory name will come from an NFC tag):

```
String temp = "findorie";
temp.toCharArray(plrCurrentFolder, 9);
unsigned int numberOfFiles = countFiles(plrCurrentFolder);

```

This is the function to return the number of files:

```
unsigned int countFiles(File dir){
  unsigned int counter = 0;
  while (true){
    File entry = dir.openNextFile();
    if (!entry){
      // no more files
      break;
    }
    counter++;
    entry.close();
  }
  dir.close();
  return counter;
}

```

To be honest I have two issues with this. First, I don't really like to create a temp String variable to create the char array here as I would rather stick with the char array in itself to safe on memory and maybe this would also aid in performance (although I'm not sure about that).

**Second, The way this whole thing is structured right now, it simply doesn't work. When building, the compiler correctly complains:**

```
exit status 1
could not convert '(char*)(& plrCurrentFolder)' from 'char*' to 'SDLib::File'

```

Can anyone help me out and give me a code snippet how to make this work???

Kind regards to all,

Christian

--- below you may find the complete code as of now ---

```
/*
 * Fairytale Main program
 *
 * This programm will read an nfc tag. It will check for a directory name and optional a filename
 * and start playing this on the music maker shield.
 *
 * Restrictions:
 * 1. All filenames mus be in the format  trackXXX.mp3  - where XXX is a numbering from 001 to 999
 * 2. All directory names must be exactly 8 chars long
 *
 */

// make sure to change this to 0 before uploading in production as it turns on lots and lots of serial messages
#define DEBUG 1
// we only show light effects, in case this is set to 1
#define LIGHTEFFECTS 0
// we only use the nfc reader if this is set to 1
#define NFCREADER 0

//
// setup SPI, MP3 and SD libraries
//
#include <SPI.h>
#include <Adafruit_VS1053.h>
#include <SD.h>
// These are the pins used for the music maker shield
#define SHIELD_RESET  -1     // VS1053 reset pin (unused!)
#define SHIELD_CS     7      // VS1053 chip select pin (output)
#define SHIELD_DCS    6      // VS1053 Data/command select pin (output)
#define CLK 13 // SPI Clock, shared with SD card
#define MISO 12 // Input data, from VS1053/SD card
#define MOSI 11 // Output data, to VS1053/SD card

// These are common pins between breakout and shield
#define CARDCS 4     // Card chip select pin
// DREQ should be an Int pin, see http://arduino.cc/en/Reference/attachInterrupt
#define DREQ 3       // VS1053 Data request, ideally an Interrupt pin

Adafruit_VS1053_FilePlayer musicPlayer =
  // create shield-example object!
  Adafruit_VS1053_FilePlayer(SHIELD_RESET, SHIELD_CS, SHIELD_DCS, DREQ, CARDCS);

//
// setup NFC Adapter
//
#ifdef NFCREADER
/*
  #include <PN532_SPI.h>
  #include <PN532.h>
  #include <NfcAdapter.h>

  #define PN532_SCK (13) //changed from pin 2
  #define PN532_MISO (12) //changed from pin 5
  #define PN532_MOSI (11) //changed from pin 3
  #define PN532_SS (10) //changed from 4

  PN532_SPI pn532spi(SPI, PN532_SS);
  NfcAdapter nfc = NfcAdapter(pn532spi);
*/
#endif

// these variables are used for the light effects
int lightValue1, lightValue2, lightValue3;
const int redPin = 7;
const int greenPin = 8;
const int bluePin = 9;

// these are timing counters for the light effects
long time=0;
int periode = 20000;
int displace = 500;

// uptime counters
unsigned int runCounter = 0;
unsigned long startUpTime = 0;
const unsigned long maxUpTime = 120000; // 1800000L;  // 30 Minutes

// these are variables for the nfc card
boolean cardScanned = false;    // did we already scan the card?? using this to suppress reading in the card data while it is on the reader
char cardId[16];                // the uid of the card as read in through the nfc reader

// mp3 player variables
boolean plrIsPlaying = false;                         // is the mp3 player already playing?
char plrCurrentFile[13];                              // which track is the player playing?
char plrNextFile[13];                                 // which track is the player playing?
char plrPrevFile[13];                                 // which track is the player playing?
char plrCurrentFolder[9];                             // which directory is the player playing?
uint8_t plrCurrentPosition = 0;                       // on which position in seconds are we in the current track?
char currentTrackFileName[] = "/system/current.txt";  // a file we might use to store the last played track

// volume control variables for the analog poti
int volumePotPin = A0;        // the analog input pin that we use for the potentiometer
int sensorDrift = 7;          // difference to last received sensor value that must be exceeded to activate a change in the volume
int compareValue = 0;         // just a convenience variable to make comparison easier
int sensorValue = 0;          // read the value from the potentiometer
int lastSensorValue = 0;      // keeps the last read sensor value
uint8_t soundVolume = 0;      // the sound volume is derived via a map function from the sensor value

// other button settings
int btnLinePin = A1;         // pin on which the button line (4 buttons) is connected
int btnVal = 0;

// these are the prototypes for the nfc card reader
void getNfcCardData();

// these are the prototypes for the mp3 player controller
uint8_t getVolume(void);        // function that returns the volume setting based on the analog read
char plrNext(void);             // play next file in album
char plrPrev(void);             // play previous file in album
void plrPlayTrack(char, char);  // play a single track
void setupSound(void);          // initializes the sound system and plays the startup sound

// these are the prototypes to work on files
void printDirectory(File, int);   // print out the content of specified directory on serial console
unsigned int countFiles(File);    // return the number of files in a directory passed as a File descriptor
//unsigned int countFiles(char[]);    // return the number of files in a directory passed as a File descriptor

// these are the prototypes for the light effects
void fader(void);
void startuplight(void);
void highlight(int);
void flash(int);
void pulse(int);

void setup() {
  #ifdef DEBUG
    Serial.begin(115200);
  #endif

  plrCurrentFile[0] = 0; // we initialize the fiirst element of the array to 0 to later check if a current file was given.

  // initialise the music player
  if (! musicPlayer.begin()) { // initialise the music player
    #ifdef DEBUG
      Serial.println(F("Couldn't find VS1053, do you have the right pins defined?"));
    #endif
    while (1);
  }
  #ifdef DEBUG
    Serial.println(F("Music Maker Shield VS1053 found"));
  #endif

  //musicPlayer.sineTest(0x44, 500);    // Make a tone to indicate VS1053 is working

  if (!SD.begin(CARDCS)) {
    #ifdef DEBUG
      Serial.println(F("failed to detect the SD-Card"));
    #endif
    while (1);  // don't do anything more
  }
  #ifdef DEBUG
    Serial.println("SD found and operational");
  #endif

  // set the buttons as input
  pinMode(volumePotPin, INPUT);
  pinMode(btnLinePin, INPUT);

  // setup music maker shield and start playing startup file
  setupSound();

  #ifdef DEBUG
    // list files
    printDirectory(SD.open("/"), 0);
  #endif

/*
  // now as the last thing, start the nfc reader
  #ifdef DEBUG
    Serial.print("initializing NFC TAG reader ... ");
  #endif
  nfc.begin();
  delay(1000); // wait some time for
*/

  // check our current time, so we know when to stop
  startUpTime = millis();
  #ifdef DEBUG
    Serial.println("we are up and running and ready to play audio");
  #endif
}

//
//      LL       OOOOOO    OOOOOO   PPPPPPP
//      LL      OO    OO  OO    OO  PP    PP
//      LL      OO    OO  OO    OO  PP    PP
//      LL      OO    OO  OO    OO  PPPPPP
//      LLLLLL   OOOOOO    OOOOOO   PP
void loop() {
  #ifdef LIGHTEFFECTS
    // turn off all the lights. we only want to have fading lights, while the playr is active
    //analogWrite(redPin, 0);
    //analogWrite(greenPin, 0);
    //analogWrite(bluePin, 0);
  #endif

  // NFC Tag reader functions
  // now we only do this, when an nfc tag is present
/*
  if (nfc.tagPresent()){
    Serial.println("NFC tag Found!\n");
    NfcTag tag = nfc.read();
    Serial.print("Tag Type: ");
    Serial.println(tag.getTagType());
    Serial.print("UID: ");
    Serial.println(tag.getUidString());

    getNfcCardData();
*/

    String temp = "findorie";
    temp.toCharArray(plrCurrentFolder, 9);

    // now let's get the number of files in the album directory
    //unsigned int numberOfFiles = 0;
    unsigned int numberOfFiles = countFiles(plrCurrentFolder);
    #ifdef DEBUG
      Serial.print("Directory ");Serial.print(plrCurrentFolder);Serial.print(" contains ");Serial.print(numberOfFiles);Serial.println(" files");
    #endif

    // if we did not get the current file from the tag, we are hardcoding it to track001.mp3
    if ((plrCurrentFile[0] == 0)) {
      temp = "track001.mp3";
      temp.toCharArray(plrCurrentFile, 13);
    }

    #ifdef DEBUG
      Serial.print("currentFolder holds: ");Serial.print(plrCurrentFolder);Serial.print(" / currentFile contains: ");Serial.print(plrCurrentFile);
    #endif

    temp = "/";
    temp.concat(plrCurrentFolder);
    temp.concat("/");
    temp.concat(plrCurrentFile);
    char filename[temp.length() + 1];
    temp.toCharArray(filename, sizeof(filename));
    Serial.print(" / filename contains: ");Serial.println(filename);

    if (SD.exists(filename)) {
      Serial.print(filename);Serial.println(" exists.");

      // mp3 player functions playback
      // Start playing a file, then we can do stuff while waiting for it to finish
      if (! musicPlayer.startPlayingFile(filename)) {
        #ifdef DEBUG
          Serial.print("Could not open file ");Serial.println(filename);
        #endif
        while (1);
      }
      #ifdef DEBUG
        Serial.print(F("Start playing "));Serial.println(filename);
      #endif

      while (musicPlayer.playingMusic) {
        // file is now playing in the 'background' so now's a good time
        // to do something else like handling LEDs or buttons :)

        // play some nice light effects, if wanted
        #ifdef LIGHTEFFECTS
          //fader();
        #endif

        // volume control functions
        // read the input on analog pin 0 and check if we have a change in volume.
        sensorValue = analogRead(volumePotPin);
        if (lastSensorValue > sensorValue) {compareValue = lastSensorValue - sensorValue;} else {compareValue = sensorValue - lastSensorValue;}
        // If we have a high enough difference in the sensor reading, calculate it so we may set it on the player
        if (compareValue > sensorDrift){
          #ifdef DEBUG
            Serial.print("changing volume: ");
          #endif
          soundVolume = getVolume();
          musicPlayer.setVolume(soundVolume,soundVolume);
        }
      }
      #ifdef DEBUG
        Serial.println("Done playing ");Serial.println(filename);
      #endif
      #ifdef LIGHTEFFECTS
        //startuplight();
      #endif
    } else {
      Serial.print(filename);Serial.println(" does not exist.");
    } // end of file does not exist

  //} // end of tag found
} // end of loop

//
//        NN    NN  FFFFFF   CCCCCC
//        NNNN  NN  FF      CC
//        NN  N NN  FFFF    CC
//        NN  NNNN  FF      CC
//        NN    NN  FF       CCCCCC
//  BELOW THIS LINE THE NFC CONTROL IS DEFINED
//
void getNfcCardData(){
/*
  NfcTag tag = nfc.read();
  boolean usableContent = false;
  if (tag.hasNdefMessage()){
    NdefMessage message = tag.getNdefMessage();

    // If you have more than 1 Message then it wil cycle through them
    int recordCount = message.getRecordCount();
    for (int i = 0; i < recordCount; i++) {
      NdefRecord record = message.getRecord(i);

      int payloadLength = record.getPayloadLength();
      byte payload[payloadLength];
      record.getPayload(payload);

      String payloadAsString = ""; // Processes the message as a string vs as a HEX value
      for (int c = 0; c < payloadLength; c++) {
        payloadAsString += (char)payload[c];
      }

      String cleanString = payloadAsString;
      cleanString.remove(0,3);
      #ifdef DEBUG
        Serial.print("content element "); Serial.print(i); Serial.print(": "); Serial.println(cleanString);
      #endif

      // now populate the vars for the player
      int spacePosition = cleanString.indexOf(':');
      if (cleanString.charAt(spacePosition - 1) == 'A') {
        String contentString = cleanString.substring(3);
        #ifdef DEBUG
          Serial.print("Album info: ");Serial.println(contentString);
        #endif
      }
      if (cleanString.charAt(spacePosition - 1) == 'D') {
        usableContent = true;
        String contentString = cleanString.substring(3);
        plrCurrentFolder = contentString;
        #ifdef DEBUG
          Serial.print("Directory: ");Serial.println(contentString);
        #endif
      }
      if (cleanString.charAt(spacePosition - 1) == 'T') {
        String contentString = cleanString.substring(3);
        plrCurrentFile = contentString;
        #ifdef DEBUG
          Serial.print("Track: ");Serial.println(contentString);
        #endif
      }
      if (cleanString.charAt(spacePosition - 1) == 'P') {
        String contentString = cleanString.substring(3);
        plrCurrentPosition = contentString.toInt();
        #ifdef DEBUG
          Serial.print("Position: ");Serial.println(contentString);
        #endif
      }

      String uid = record.getId();
      if (uid != "") {
        #ifdef DEBUG
          Serial.print("  ID: ");
          Serial.println(uid);
        #endif
      }
    }
    if (!usableContent){
      #ifdef DEBUG
        Serial.println("THIS CARD DOES NOT HAVE THE NECESSARY MESSAGES FOR THE MP3 PLAYER");
      #endif
    }
  } else { // does the card have NDEF messages?
    #ifdef DEBUG
      Serial.println("THIS CARD DOES NOT HAVE MESSAGES AT ALL - NOT USABLE FOR THE MP3 PLAYER");
    #endif
  }
*/
}

//
//        MM      MM   PPPPPP   33333
//        MMMM  MMMM  PP    PP      33
//        MM  MM  MM  PP    PP    3333
//        MM      MM  PPPPPP        33
//        MM      MM  PP        33333
//  BELOW THIS LINE THE MP3 PLAYER CONTROL IS DEFINED
//
uint8_t getVolume(){
  soundVolume = map(sensorValue, 0, 1023, 0, 100); // map the sensor value to a sound volume

  #ifdef DEBUG
    Serial.print("last sensor value (if any) was ");Serial.print(lastSensorValue);Serial.print(" / new sensor value is ");Serial.print(sensorValue);Serial.print(" which is a volume of ");Serial.println(soundVolume);
  #endif
  lastSensorValue = sensorValue;
  return (soundVolume);
}

void plrPlayTrack(char dir, char file) {
  String temp = "/";
  temp.concat(dir);
  temp.concat("/");
  temp.concat(file);
  char myFile[temp.length() + 1];
  temp.toCharArray(myFile, sizeof(myFile));

  // mp3 player functions playback
  // Start playing a file, then we can do stuff while waiting for it to finish
  if (! musicPlayer.startPlayingFile(myFile)) {
    #ifdef DEBUG
      Serial.print("Could not open file ");Serial.println(myFile);
    #endif
    while (1);
  }
  #ifdef DEBUG
    Serial.print(F("Start playing "));Serial.println(myFile);
  #endif

  while (musicPlayer.playingMusic) {
    // file is now playing in the 'background' so now's a good time
    // to do something else like handling LEDs or buttons :)
    #ifdef DEBUG
      Serial.print(".");
    #endif
    #ifdef LIGHTEFFECTS
      //fader();
    #endif

  }
  #ifdef DEBUG
    Serial.println("Done playing ");Serial.println(myFile);
  #endif
}

char plrNext(void){
  char track[12] = "track003.mp3";
  #ifdef DEBUG
    Serial.println("plrNext toggled");
  #endif
  #ifdef LIGHTEFFECTS
    //pulse(bluePin);
  #endif

  return track;
}
char plrPrev(void){
  char track[12] = "track001.mp3";
  #ifdef DEBUG
    Serial.println("plrPrevious toggled");
  #endif
  #ifdef LIGHTEFFECTS
    //pulse(greenPin);
  #endif

  return track;
}

void setupSound(){
  // This option uses a pin interrupt. No timers required! But DREQ
  // must be on an interrupt pin. For Uno/Duemilanove/Diecimilla
  // that's Digital #2 or #3
  // See http://arduino.cc/en/Reference/attachInterrupt for other pins
  // *** This method is preferred
  if (! musicPlayer.useInterrupt(VS1053_FILEPLAYER_PIN_INT)) {
    #ifdef DEBUG
      Serial.println(F("DREQ pin is not an interrupt pin"));
    #endif
    while (1);
  }

  // Start playing a file, then we can do stuff while waiting for it to finish
  if (! musicPlayer.startPlayingFile("hello.mp3")) {
    #ifdef DEBUG
      Serial.println("Could not open file hello.mp3");
    #endif
  } else {
    #ifdef DEBUG
      Serial.print("playing welcome file hello.mp3 ");
    #endif
  }

  // now we play the welcome sound
  startUpTime = millis();
  while (musicPlayer.playingMusic) {
    if (millis() - startUpTime > 500) {
      #ifdef DEBUG
        Serial.print(".");
      #endif
      startUpTime = millis();
    }
    // file is now playing in the 'background' so now's a good time
    // to do something else like handling LEDs or buttons :)
    #ifdef LIGHTEFFECTS
      //startuplight();
    #endif
  }
  #ifdef DEBUG
    Serial.println(" done");
  #endif
  getVolume();
  musicPlayer.setVolume(soundVolume,soundVolume);
}

//
//        FFFFFF  II  LL      EEEEEE
//        FF      II  LL      EE
//        FFFF    II  LL      EEEE
//        FF      II  LL      EE
//        FF      II  LLLLLL  EEEEEE
// BELOW THIS LINE THE FILE HELPER FUNCTIONS CAN BE FOUND
//
// counts the number of files in directory
//unsigned int countFiles(char dir[]){

unsigned int countFiles(File dir){
  unsigned int counter = 0;
  while (true){
    File entry = dir.openNextFile();
    if (!entry){
      // no more files
      break;
    }
    counter++;
    entry.close();
  }
  dir.close();
  return counter;
}

// store last played track
void rememberCurrentTrack(){

}

// read last played track
void getLastPlayedTrack(){

}

// File listing helper
void printDirectory(File dir, int numTabs) {
   while(true) {
     File entry =  dir.openNextFile();
     if (! entry) {
       // no more files
       //Serial.println("**nomorefiles**");
       break;
     }
     for (uint8_t i=0; i<numTabs; i++) {
       Serial.print('\t');
     }
     Serial.print(entry.name());
     if (entry.isDirectory()) {
       Serial.println("/");
       printDirectory(entry, numTabs+1);
     } else {
       // files have sizes, directories do not
       Serial.print("\t\t");
       Serial.println(entry.size(), DEC);
     }
     entry.close();
   }
}

//
//        LL      EEEEEE  DDDDDD
//        LL      EE      DD    DD
//        LL      EEEE    DD    DD
//        LL      EE      DD    DD
//        LLLLLL  EEEEEE  DDDDDD
//  BELOW THIS LINE THE LIGHT EFFECTS ARE DEFINED
//
// fading organically
void fader(){
  time = millis();
  lightValue1 = 128+127*cos(2*PI/periode*time);
  lightValue2 = 128+127*cos(2*PI/periode*(displace-time));
  lightValue3 = 128+127*cos(2*PI/periode*(2*displace-time));
  analogWrite(redPin, lightValue1);           // sets the value (range from 0 to 255)
  analogWrite(greenPin, lightValue2);        // sets the value (range from 0 to 255)
  analogWrite(bluePin, lightValue3);         // sets the value (range from 0 to 255)
}
// illuminate the 3 led with some fancy lightning during startup
void startuplight(){
  for (int i = 0; i<150; i++) {
    analogWrite(redPin, i);
    analogWrite(greenPin, i);
    analogWrite(bluePin, i);
    delay(10);
  }
  for (int i = 150; i>0; i--) {
    analogWrite(redPin, i);
    analogWrite(greenPin, i);
    analogWrite(bluePin, i);
    delay(10);
  }
  analogWrite(redPin, 0);
  analogWrite(greenPin, 0);
  analogWrite(bluePin, 0);
}
//turn on the desired pin for 5000 milliseconds
void highlight(int pin){
  time = millis();
  while (millis()<time+5000){
    analogWrite(pin, 255);
  }
  analogWrite(pin, 0);
}
//turn on the desired pin for 5000 milliseconds
void flash(int pin){
  time = millis();
  while (millis()<time+1000){
    analogWrite(pin, 255);
  }
  analogWrite(pin, 0);
}
//turn on the desired pin for 5000 milliseconds
void pulse(int pin){
  for (int i=0;i<3;i++){
    time = millis();
    while (millis()<time+2500){
      analogWrite(pin, 255);
    }
    analogWrite(pin, 0);
  }
}

```

# Answer
> 1 votes
OMG. I'm so sorry for posting such a stupid question. And I'm also sorry for not seeing the obvious even after Majenko pointed me to it.

Of course I need to call the function like this:

```
numberOfFiles = countFiles(SD.open(plrCurrentFolder));

```

That way, the directory get's opened and my function can operate on it.

I see I still have to learn a lot :-)

---
Tags: arduino-uno, sd-card, array, compiler
---


title: WEMOS: How to install it?

text:
# Question
Title: WEMOS: How to install it?
I have been using an Arduino Uno for a year now, and I bought a WEMOS D1 Mini and a NodeMCU. I want to select WEMOS or NodeMCU from the Arduino Web Editor but it doesn't appear on the list:

I think I need to install a driver but it's only for the Arduino desktop editor (not for the web editor).

# Answer
> 1 votes
I just read that it can't. It's a shame:

https://forum.arduino.cc/index.php?topic=441328.0

---
Tags: nodemcu
---


title: Custom ISR triggering function/value

text:
# Question
Title: Custom ISR triggering function/value
Is there a way to write a custom function which would be the mode/reason to trigger an interrupt. I have an analog joystick connected to my arduino analog pin. It reads a value of 689 on one end and 0 on the other and around 480 in the center. I would like to trigger an interrupt based on these value changes i.e an interrupt when it more then 600 and another when less then 10. None of the pre-defined modes RISING,HIGH,LOW,FALLING,CHANGE are working satisfactorily.

# Answer
> 1 votes
No. Interrupts are hardware. You cannot "create" interrupts in software.

The closes there is to what you are after is the Analog Comparator (see section 27 of the datasheet).

The analog comparator allows you to trigger an interrupt if a voltage is above (or below) a reference voltage which is up to you to provide.

For anything more complex you would need to use external comparators to trigger on different voltage levels which then trigger external INT pins on the ATMega.

# Answer
> 1 votes
Of course, you can make software interrupts on Arduino; it just costs a hardware pin. The following is a quote from the Atmel ATmega48A/PA/88A/PA/168A/PA/328/P datasheet:

"13. External Interrupts The External Interrupts are triggered by the INT0 and INT1 pins or any of the PCINT23...0 pins. Observe that, if enabled, the interrupts will trigger even if the INT0 and INT1 or PCINT23...0 pins are configured as outputs. This feature provides a way of generating a software interrupt."

You set up an interrupt on the pin you select for the purpose, you set the pin as output, and then you trig your "software interrupt" by writing a value to the pin.

# Answer
> 0 votes
As Majenko already said, you cannot do that. But you can look for alternative ways of achieving a similar end result. The real question is: what are you trying to achieve? Interrupts may not be the best answer.

I assume what you have in mind is a program roughly along these lines:

```
// Interrut handler called when input > 600.
void handleHigh()
{
    // ...
}

// Interrut handler called when input < 10.
void handleLow()
{
    // ...
}

void setup()
{
    // Register the interrupt handlers.
    attachInterrupt(ANALOG0, handleHigh, MORE_THAN_600);
    attachInterrupt(ANALOG0, handleLow, LESS_THAN_10);
}

void loop()
{
    doSomeStuff();
}

```

Of course, that syntax for calling `attachInterrupt()` does not work, I just made it up.

The most obvious alternative is to read the value through an analog input in `loop()` and act accordingly:

```
void loop()
{
    // Check the analog input.
    int sample = analogRead(A0);
    if (sample > 600) handleHigh();
    if (sample < 10) handleLow();

    // Do the rest of the job.
    doSomeStuff();
}

```

No need to use interrupts. The only drawback is that the latency of your response to a change in the joystick position can be as long as the time your program takes to run through `loop()`. This should normally not be a problem: the joystick is a very slow mechanical device, and your loop should take no more than a few milliseconds. If the loop if really too slow, you are probably doing something wrong, like using `delay()`. You should then *fix* that problem rather than trying to work around it with interrupts.

Just for completeness, there *is* an interrupt-based solution. Assuming you have no other analog input to read, you could configure the ADC to *continously* read the same input (say, A0) in the so called “free running mode”, and trigger an interrupt on each reading. In the ISR, you can then call one of your interrupt handlers if needed (if the sample you get is outside \[10, 600\]). Here is how you can do it on an Arduino Uno:

```
void setup()
{
    // Configure the ADC in "free running mode".
    ADMUX  = _BV(REFS0)  // ref = AVCC
           | 0;          // input channel = A0
    ADCSRB = 0;          // free running mode
    ADCSRA = _BV(ADEN)   // enable
           | _BV(ADSC)   // start conversion
           | _BV(ADATE)  // auto trigger enable
           | _BV(ADIF)   // clear interrupt flag
           | _BV(ADIE)   // interrupt enable
           | 7;          // prescaler = 128
}

// ADC interrupt service routine.
// Called each time a conversion result is available.
ISR(ADC_vect)
{
    // Read the ADC.
    int sample = ADC;

    // Call the handlers if needed.
    if (sample > 600) handleHigh();
    if (sample < 10) handleLow();
}

```

**Edit**: With the code above, the ISR runs every 104 µs. Then you should make sure that your handlers take significantly less than that time to complete. Otherwise they will consume 100% of the CPU power whenever the joystick is in the range to trigger one of them. As a small optimization, you could declare the handlers `static inline` in order to avoid the overhead of a function call.

---
Tags: arduino-uno, interrupt, analogread, isr
---


# Question
Title: RF receiver for integer only, how to cast uint8_t to int?
I'm using the RadioHead library with ASK Driver to transmit/receive data with generic RF modules. It works fine, but I'm lacking some knowledge in programming the code to use the data received. Most examples I could find show how to send a string, but I only need to send and receive an integer.

I'm sending the decimal value '1' through the **transmitter**:

```
    uint8_t *data;
    uint8_t value;

    void loop() {
    value = 1;
    data = &value;
    driver.send(data, sizeof(value));
    driver.waitPacketSent();
    delay(200);
    }

```

And I have in the **receiver**:

```
void loop() {
  uint8_t buf[RH_ASK_MAX_MESSAGE_LEN];
  uint8_t buflen = sizeof(buf);
  int value;

  if (driver.recv(buf, &buflen)) {
    driver.printBuffer("Received:", buf, buflen); //prints 1.
    value = (int) buf; //my attempt to cast
    Serial.println(value); // the output is 2233, so this is wrong.
  }
  if (value == 1){ //example
  Serial.println("good");
  }
}

```

So what I think it is, I'm receiving bytes from the transmitter, which the library function 'driver.printBuffer' reinterprets as decimals and prints the value '1'. But how do I interpret (or cast) this as an integer so I can use it for other things like in the example (If condition) at the end? Any help is very much appreciated. Thanks.

# Answer
`buf` is a pointer to the received bytes. Try `value = buf[0];` instead.
> 1 votes

---
Tags: programming, c++, rf, data-type
---


# Question
Title: Can I power up my Arduino and MotorShield with four AA batteries?
can I power up my Arduino UNO with four AA batteries? It's about 6V, will my arduino burn? And, if I power my Arduino, I have to power my Motor Shield too or not?

I want to make line follower. I have to know what I have to power up. I dont know, how many battery holders I need. I have: Arduino UNO, motor shield, two 6V DC motors

# Answer
You won't damage the Arduino if you remove the power to the motors as even though you're using the same power supply to power the motots and Arduino (4 x 1.5 - 6V batteries) you're not powering it from the Arduino pins itself.

What exactly are you trying to accomplish here? Post some more info.
> 1 votes

# Answer
> can I power up my Arduino UNO with four AA batteries?

6v is about the max if it is directly applied to the chip;

6v is just shy of the minimum if it is applied to a regulator and then to the chip.
> 0 votes

# Answer
It won't cause damage to connect 4xAA to the input of the Arduino's regulator, however it also won't result in specified operation, as even with fairly new cells the voltage will below that which the typically used 5v regulators require to deliver 5v at the output.

Additionally, the common L293D and L298 based bipolar motor shields are horribly lossy. Feed them about 6v input, and you'll get just over 4v to your motor, which is likely to be disappointing.

To build an Arduino-based battery-powered motor project, you typically need to do one of two things

* Use 6, 7, 8 or more cells, and higher-voltage, lower current motors
* Use a 3.3v Arduino and a more efficient FET-based H-bridge motor driver/shield, for example the TB6612FNG. This supports 4 cell operation quite well, and may to a more limited degree work on 3 *alkaline* cells.
> 0 votes

---
Tags: arduino-uno
---


# Question
Title: A function-definition is not allowed here before '{' token
I'm trying to light up 81 on a 4-digit 7-segment display, but when I try to upload the code to my Uno R3 it gives me this error: "a function-definition is not allowed here before '{' token". I'm new to Arduino and this is my second day using it, so I would like to get help and know how to fix this problem. Here is my code:

```
int isej1 = 2;
int isej2 = 3;
int vienetas[] = { 12, 11 };
int astuonetas[] = { 13, 12, 11, 10, 9, 8, 7 };

void setup() {
  pinMode (vienetas[2], OUTPUT);
  pinMode (astuonetas[8], OUTPUT);
  pinMode (isej1, OUTPUT);
  pinMode (isej2, OUTPUT);
}

void uz_vien() {
  digitalWrite (vienetas[0], HIGH);
  digitalWrite (vienetas[1], HIGH);
}

void uz_astuon() {
  digitalWrite (astuonetas[0], HIGH);
  digitalWrite (astuonetas[1], HIGH);
  digitalWrite (astuonetas[2], HIGH);
  digitalWrite (astuonetas[3], HIGH);
  digitalWrite (astuonetas[4], HIGH);
  digitalWrite (astuonetas[5], HIGH);
  digitalWrite (astuonetas[6], HIGH);
}

void is_vien() {
  digitalWrite (vienetas[0], LOW);
  digitalWrite (vienetas[1], LOW);
}

void is_astuon() {
  digitalWrite (astuonetas[0], LOW);
  digitalWrite (astuonetas[1], LOW);
  digitalWrite (astuonetas[2], LOW);
  digitalWrite (astuonetas[3], LOW);
  digitalWrite (astuonetas[4], LOW);
  digitalWrite (astuonetas[5], LOW);
  digitalWrite (astuonetas[6], LOW);

void loop() {
  digitalWrite (isej1, LOW);
  digitalWrite (isej2, HIGH);
  void uz_vien();
  delay(5);
  void is_vien();
  digitalWrite (isej1, HIGH);
  digitalWrite (isej2, LOW);
  void uz_astuon();
  delay(5);
  void is_astuon();
}

```

# Answer
You are missing a "}" just before `loop`

```
  void is_astuon() {
    digitalWrite (astuonetas[0], LOW);
    digitalWrite (astuonetas[1], LOW);
    digitalWrite (astuonetas[2], LOW);
    digitalWrite (astuonetas[3], LOW);
    digitalWrite (astuonetas[4], LOW);
    digitalWrite (astuonetas[5], LOW);
    digitalWrite (astuonetas[6], LOW);
   } // <- missing here.
  void loop() {

```
> 3 votes

# Answer
The importance of proper indentation is clear here...

I thought you were missing a closing curly braces. When you type code, press regularly cmd/ctrl-T to ident your code -- it helps catching mistakes. You are indeed missing one, for `is_astuon()`.

Moreover these lines are wrong too:

```
**void** uz_vien();
delay(5);
**void** is_vien();
digitalWrite (isej1, HIGH);
digitalWrite (isej2, LOW);
**void** uz_astuon();

```

The `void` part is not needed and creates the error.
> 2 votes

---
Tags: 7-segment
---


# Question
Title: Uno r3 - Can't get USB Keyboards to work with an USB Host Shield
I'm a day 1 beginner to Arduino, and I am trying to obtain input from a USB keyboard. I've connected the USB keyboard to an Arduino USB host shield attached to an Arduino Uno r3, and I am using the example HID sketch (USBHIDBootKeyboard.ino) provided with the USB Host Shield libraries : https://github.com/felis/USB\_Host\_Shield\_2.0/blob/master/examples/HID/USBHIDBootKbd/USBHIDBootKbd.ino

I am powering the Arduino Uno r3 + USB Host Shield via USB. Upon init, only Start is written to the Serial Monitor. Tests show that SetReportParser exits with 0. Yet the keyboards are silent. I've tried three keyboards, all of which work properly when connected to the computer.

When using USBHidBootMouse.ino with a mouse, movements & buttons are perceived and print messages as intended.

https://www.circuitsathome.com/mcu/hid-support-for-usb-host-shield-library-2-0-released/ states that

> Also, it is recommended to use external power supply while working with HID devices – I’ve seen many devices which would refuse to function when Arduino receives power from its USB port only.

EDIT : I tried to test if the power was the issue, so I used a 5V generator with intensity measurement. The results are : the Arduino Uno r3 uses 60mA, the keyboard uses 60 mA, connecting to the serial port uses 40 mA (much to my surprise).

This means the keyboard's power requirements shouldn't be the problem.

Then what would the problem be ? I'm helpless here. If the library linked on the official Arduino site doesn't work, then it should mean i'm using it wrong.

# Answer
see last paragraph of this page https://github.com/felis/USB\_Host\_Shield\_2.0

it says this:

> FAQ
>
> When I plug my device into the USB connector nothing happens?
>
> Try to connect a external power supply to the Arduino - this solves the problem in most cases.
>
> You can also use a powered hub between the device and the USB Host Shield.
>
> You should then include the USB hub library: `#include <usbhub.h>`
>
> and create the instance like so: `USBHub Hub1(&Usb);`.

your keyboard may be multiple HID devices with a USB hub to connect them
> 0 votes

# Answer
I looked for the difference between USBHIDBootMouse & USBHIDBootKbd, and noticed line 100,

> USBHub Hub(&Usb);

was commented in the BootKbd side. Uncommenting it got the code to work.

I'm quite unsure how what interpretation to have from this. There should be a reason this line is commented in the library github.

Or maybe it is simply an error. In any case, uncommenting it got the code to work here.
> 0 votes

---
Tags: arduino-uno, usb, shields, keyboard
---


# Question
Title: Arduino Uno versus Arduino Nano power consumption
I have both an Arduino Uno and an Arduino Nano but I can't decide which one to use for my project. My aim is to maximize battery lifetime. I have also implemented an 8-second watchdog timer to periodically sleep and wake up the ATMega328P.

* Option 1: Arduino Uno R3 + DHT11 sensor: The board is powered on by 4 * 1.25V (2700 mAh) Nickel Metal Hydride batteries and the 3.3V output voltage of the Arduino is supplied to VCC of DHT11. (**Arduino Uno specification** DC Current per I/O Pin 40 mA, DC Current for 3.3V Pin 50 mA).
* Option 2: Arduino Nano + DHT11 sensor. The board is powered on by 4 * 1.25V (2700 mAh) Nickel Metal Hydride batteries and the 3.3V output voltage of the Arduino is supplied to VCC of DHT11. (**Arduino Nano specification**: DC Current per I/O Pin: 40 mA but **NO** information for DC current for 3.3V or 5V).

I would like to know which one will be more power-efficient.

# Answer
> 12 votes
A Uno which isn't doing anything useful except being turned on will use about 50 mA of current from the power jack at 9V.

If you use 3 x alkaline AA batteries (giving a nominal voltage of 4.5V) directly into the 5V pin of the Arduino then you might get 2500 mAh which would be 50 hours at 50 mA per hour.

You can save a considerable amount of power by using sleep modes as I describe on my page about power. It also helps to use a bare processor (no voltage regulator, no LEDs).

I made a temperature and humidity sensor which runs from 3 x AA batteries. Using sleep mode, plus various other techniques, that is running for **over a year** without needing new batteries.

---

> I would like to know which one will be power efficient?

Both the Uno and the Nano use the same Atmega328P processor. Thus the technical considerations would be the same. Both have a voltage regulator and a "power on" LED which alone would use a lot of current, compared to everything else.

---

It's *not that hard* to make a minimal board. I have a page about doing that. Example of all you need:

---

If you use a deep sleep mode, combined with using the watchdog timer to wake every 8 seconds (and check the time, say every 10 times it wakes) you can reduce power consumption right down.

My temperature sensor uses an average of 42 µA which is a **lot** less than 50 mA. (A thousand times less). Thus your 50 hours run time becomes 50,000 hours which is 2083 days. Your batteries will probably self-discharge sooner. :)

# Answer
> 1 votes
Don't use either use something with no USB, regulator - e.g. Pro Mini (run from 3.3V)

Just running the Arduino (or indeed most digital circuitry) from a lower voltage will already reduce power consumption - admittedly at a slight cost in processor speed. The Atmega328P will run at 12MHz on 3.3V, although the Pro Mini uses the more conservative 8MHz.

---
Tags: power, arduino-nano
---