# Question
Title: DF Robot W5200 Ethernet Shield for an Arduino Uno not working?
I've been working on using an ethernet shield for my Arduino Uno for a couple weeks now. I've been going through the problems one by one and now realise that there seems to be nothing transmitting. Running code similar to DHCPAddressPrinter results in nothing, and any web server I set up does not work at all. Can anyone please help? Running the code below results in an output of "Baud rate set!" and nothing else. One thing to note is that the MAC address I am using is from going into the command prompt and using the MAC address listed from ipconfig /all, as there is no sticker on the ethernet shield itself.

```
    /*
    DHCP-based IP printer

     This sketch uses the DHCP extensions to the Ethernet library
     to get an IP address via DHCP and print the address obtained.
     using an Arduino Wiznet Ethernet shield.

     Circuit:
     * Ethernet shield attached to pins 10, 11, 12, 13

     created 12 April 2011
     modified 9 Apr 2012
     by Tom Igoe

     */

    #include <SPI.h>
    #include <EthernetV2_0.h>

    // Enter a MAC address for your controller below.
    // Newer Ethernet shields have a MAC address printed on a sticker on         the shield
    byte mac[] = {
      /*MAC Address here*/ };

    // Initialize the Ethernet client library
    // with the IP address and port of the server
    // that you want to connect to (port 80 is default for HTTP):
    EthernetClient client;

    void setup() {
     // Open serial communications and wait for port to open:
      Serial.begin(9600);
      Serial.println("Baud rate set!");

      // start the Ethernet connection:
      if (Ethernet.begin(mac) == 0) {
        Serial.println("Failed to configure Ethernet using DHCP");
        // no point in carrying on, so do nothing forevermore:
        for(;;)
        Serial.println("FAIL");
          ;
      }
      // print your local IP address:
      Serial.print("My IP address: ");
      for (byte thisByte = 0; thisByte < 4; thisByte++) {
        // print the value of each byte of the IP address:
        Serial.print(Ethernet.localIP()[thisByte], DEC);
        Serial.print(".");
      }
      Serial.println();
      Serial.println("Loop");
    }

    void loop() {

    }

```

# Answer
> 1 votes
Don't use the MAC address of your computer read from ipconfig output. It creates a conflict on LAN. Use the MAC address from examples.

To troubleshoot Ethernet shield, use the Ethernet library newest version 2.00. It supports W5100, W5200 and W5500 and has better diagnostic in examples.

And to troubleshoot, always connect the LAN cable to router or switch, not to computer, because direct connection to computer requires manual setup of addresses (no DHCP).

---
Tags: arduino-uno, ethernet, ethernet-shield
---


title: Nano V3 values "overwritten" randomly

text:
# Question
Title: Nano V3 values "overwritten" randomly
When I assign a global var to a certain value inside an if-block it has been changed to another value in the next statement. Somehow the address of the var is overwritten by some other process. It also does not stop at 1 value, this happens to the next vars that are assigned another value too. The vars are not defined in a row but should be close. I already installed a newer version of Arduino IDE, no change. Example:

```
menuActive=1;
Serial.print(menuActive);

```

gives results in the range 40 to 57 as far as I have seen till now. Further actions assign always the SAME value to next vars I assign after this. Anyone some idea what could cause this? Am I low on memory for local vars? This is compile message:

```
Sketch uses 21790 bytes (70%) of program storage space. Maximum is 30720 bytes.
Global variables use 1454 bytes (70%) of dynamic memory, leaving 594 bytes for local variables. Maximum is 2048 bytes.

```

edit:

As I already said, it is 21k of code. But I show you the part of the code that mishaves:

```
while ((digitalRead(rotSwPin) == 0) && lpress <= 200) {
    delay(10);
    lpress++;
    if (lpress > 200) {
        menuActive++;
        menuLvl=0;
        menuPos=0;
        subPos=0;
    }
}

```

Normally I use menuActive=1. Within the braces, it is still 1, out of that it changes. Maybe change from byte to bool.

# Answer
> 1 votes
I found the problem. I could see that the false value is the character code of the minute I am displaying. I display hours and minutes and there was a declaration that was 3 characters short for the string I got as a result for hours added to minutes. Yes, it was memory corruption. So be very careful to dimension enough places for your C-strings including 1 extra for 0. If you are not so short on RAM then a few more characters will do no harm, the end of the string will be the character before the 0 in memory. When strange things happen start looking at this matter!

---
Tags: arduino-ide, arduino-nano
---


# Question
Title: ArduinoJSON: Using a reference to a reference when parsing array of arrays
I started to play around with the ArduinoJson library to parse data I got from one of my APIs (the format of the JSON data I get from my API can be improved for sure, but the software I had to implement the API with is rather limited in formatting JSON strings). The data is formatted as an array of arrays like this:

```
[["P101","1.2345","bar(a)"],["P102","1234.567","mbar"],["P103","2345.678","mbar"],["P104","2.3456","bar(a)"]]

```

In order to get a first impression about how much memory is needed I used ArduinoJSON's Assistant to analyse my dataset, calculate memory requirements and get a very basic code snippet for parsing the data. Code snippet generated by the assistant is as follows:

```
const size_t bufferSize = 4*JSON_ARRAY_SIZE(3) + JSON_ARRAY_SIZE(4) + 90;
DynamicJsonBuffer jsonBuffer(bufferSize);

const char* json = "[[\"P101\",\"1.2345\",\"bar(a)\"],[\"P102\",\"1234.567\",\"mbar\"],[\"P103\",\"2345.678\",\"mbar\"],[\"P104\",\"2.3456\",\"bar(a)\"]]";

JsonArray& root = jsonBuffer.parseArray(json);

JsonArray& root_ = root;

JsonArray& root_0 = root_[0];
const char* root_00 = root_0[0]; // "P101"
const char* root_01 = root_0[1]; // "1.2345"
const char* root_02 = root_0[2]; // "bar(a)"

JsonArray& root_1 = root_[1];
const char* root_10 = root_1[0]; // "P102"
const char* root_11 = root_1[1]; // "1234.567"
const char* root_12 = root_1[2]; // "mbar"

JsonArray& root_2 = root_[2];
const char* root_20 = root_2[0]; // "P103"
const char* root_21 = root_2[1]; // "2345.678"
const char* root_22 = root_2[2]; // "mbar"

JsonArray& root_3 = root_[3];
const char* root_30 = root_3[0]; // "P104"
const char* root_31 = root_3[1]; // "2.3456"
const char* root_32 = root_3[2]; // "bar(a)"

```

I did not test this, yet but had a look at the produced snippet and stumbled upon these lines:

```
JsonArray& root = jsonBuffer.parseArray(json);

JsonArray& root_ = root;

```

What is the exact advantage of using address-references `root`, `root_` and e.g. `root_1` here? Those should, as far as I understood the code, reference to the same data at the end. Is it for better readability only?

# Answer
The advantage of reference above pointers:

* References cannot be NULL, so it's much safer to use them
* Address of a reference cannot be acquired, this means a calling function cannot mess up anything outside the type (value) being passed.

For passing a reference to an address the same advantages applies (cannot be NULL, address cannot be changed).

Also, address arithmetic (address + xxx or address - xxx) cannot be used, which prevents tricky programming errors where values outside a variable's memory space can be changed.
> 1 votes

# Answer
It is not a reference to reference. It is a copy of the reference.

The generator must handle more difficult JSON inputs then yours and to make output readable it has a strategy, which in simple case can look as unnecessary. Yes, it could use `root[n][m]`.
> 0 votes

---
Tags: string, array, json
---


# Question
Title: max7219 chained display showing mirrored text
I'm using a max7219 like this one max7219. When I first tested my circuit, I used an 8x8 display and the code worked just fine. Now, after I modified the code with the one that can be found online at arduino code and changed the display with the chained one, the text appears to be mirrored on the matrix display.

.

Below, I'll attach part of the code. Please help me find the problem.

```
#include <MD_Parola.h>
#include <MD_MAX72xx.h>
#include <SPI.h>

// Define the number of devices we have in the chain and the hardware interface

#define MAX_DEVICES 4
#define CLK_PIN     13
#define DATA_PIN    11
#define CS_PIN      10

// Hardware SPI connection
MD_Parola P = MD_Parola(CS_PIN, MAX_DEVICES);
// Arbitrary output pins
// MD_Parola P = MD_Parola(DATA_PIN, CLK_PIN, CS_PIN, MAX_DEVICES);

void setup(void)
{
  P.begin();
  P.displayText("Hello", PA_CENTER, 0, 0, PA_PRINT, PA_NO_EFFECT);
}

void loop(void)
{
  P.displayAnimate();
}

```

# Answer
Since version 3.0 `MD_MAX72xx.h` no longer supports that definition. Now the hardware type is defined as a parameter on creation (in the "Example" file you are using - not in `MD_MAX72xx.h`)

```
#define HARDWARE_TYPE MD_MAX72XX::FC16_HW
...
MD_Parola P = MD_Parola(HARDWARE_TYPE, CS_PIN, MAX_DEVICES);

```

Note that I've changed the hardware type from `PAROLA_HW` to `FC_16`.
> 6 votes

# Answer
Check the configuration in MD\_MAX72xx.h file and ensure you have the right module selected.

For example there is a define

```
#define USE_PAROLA_HW   0

```

if your hardware is this item then turn off the other hardware settings and turn this one on so it reads as follows:

```
#define USE_PAROLA_HW   1

```

there many other settings if it is not there then you will have to experiment until you find the correct one.
> 2 votes

# Answer
In library, change `#define USE_GENERIC_HW 0` to `#define USE_GENERIC_HW 1` is the solution.
> 0 votes

# Answer
In latest version of `#include <MD_Parola.h>`, `#include <MD_MAX72xx.h>` you have to define the following and characters will display correctly.

```
#define HARDWARE_TYPE MD_MAX72XX::FC16_HW

```
> 0 votes

---
Tags: arduino-uno, c, max7219
---


title: How to regulate a led on-board?

text:
# Question
Title: How to regulate a led on-board?
There is **blink project** consisting 3 sections:

***1 - regulation of the led brightness using a potentiometer***

***2 - whenever: the button is pressed - the led is on***

***\- the button is released - the led is off***

***3 - change state of a led statically***

The question is that:

May I make this project on-board? I am curious that, if I will try making this project on-board (Arduino UNO) will the Arduino damaged?

# Answer
Pin 13, which is the on-board LED, is not a pwm pin. So you cannot Control the brightness of that LED on-board. You will have to use another LED and a PWM pin.
> 3 votes

---
Tags: arduino-uno, led, button, potentiometer, project
---


title: Help with AlphaNumeric array

text:
# Question
Title: Help with AlphaNumeric array
I have a Leonardo board and I want to set up my pins to input in one shot using a for loop but the problem is with the analog pins I can't see how to set up a mixed alphanumeric array it gives me some errors.

Code:

```
// including keyboard.h library for the keyboard functions
#include <Keyboard.h>

// setting Arrays for looping later
   int myIntPins[12] = {2,3,4,5,6,7,8,9,10,11,12,13};
   int myChar[12] = {97, 98, 99, 100, 101,102,103,104,105,106,107,108};
  int myChar2[6] = {109,110,111,112,113,114};
 myCharPins[6] = {"A0","A1","A2","A3","A4","A5"};
  int a;
  int x;
  int i;

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

 //Setting up Digital Pins
for (int i=0; i <= 11; i=i+a){
  pinMode(myIntPins[i],INPUT);
  }

//pinMode(2, INPUT);
//pinMode(3, INPUT);
//pinMode(4, INPUT);
//pinMode(5, INPUT);
//pinMode(6, INPUT);
//pinMode(7, INPUT);
//pinMode(8, INPUT);
//pinMode(9, INPUT);
//pinMode(10, INPUT);
//pinMode(11, INPUT);
//pinMode(12, INPUT);
//pinMode(13, INPUT);

//------------------------------------------------------------------------------
//------------------------------------------------------------------------------

// setting up Analog Pins to Digital
for (int x=0; x <= 5; x=x+a){
  pinMode(myCharPins[x],INPUT);
  }
//pinMode(A0,INPUT);
//pinMode(A1,INPUT);
//pinMode(A2,INPUT);
//pinMode(A3,INPUT);
//pinMode(A4,INPUT);
//pinMode(A5,INPUT);

// starting keyboard
Keyboard.begin();

}

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

  //if pin 2 is pressed then send the a key/char
 // if (digitalRead(2) == LOW) {Keyboard.write(97);}

// instead of doing an if one by one doing a loop all in one shot
// this loop for regular digital pins
a=1;
  for (int i=0; i <= 11; i=i+a){
    if (digitalRead(myIntPins[i]) == LOW){
      Keyboard.write(myChar[i]);
      }
      }
a=1;
  // this loop for the analog pins now working as digital pins
  for (int x=0; x <= 5; x=x+a){
    if (digitalRead(myCharPins[x]) == LOW){
      Keyboard.write(myChar2[x]);
      }
      }

  delay(10);

  }

```

Error:

```
    Arduino: 1.8.7 (Windows 10), Board: "Arduino Leonardo"

Mandar_Keyboard_Key_1:10:2: error: 'myCharPins' does not name a type

  myCharPins[6] = {"A0","A1","A2","A3","A4","A5"};

  ^

C:\Users\manue\OneDrive\Documents\Arduino\Mandar_Keyboard_Key_1\Mandar_Keyboard_Key_1.ino: In function 'void setup()':

Mandar_Keyboard_Key_1:45:11: error: 'myCharPins' was not declared in this scope

   pinMode(myCharPins[x],INPUT);

           ^

C:\Users\manue\OneDrive\Documents\Arduino\Mandar_Keyboard_Key_1\Mandar_Keyboard_Key_1.ino: In function 'void loop()':

Mandar_Keyboard_Key_1:77:21: error: 'myCharPins' was not declared in this scope

     if (digitalRead(myCharPins[x]) == LOW){

                     ^

exit status 1
'myCharPins' does not name a type

This report would have more information with
"Show verbose output during compilation"
option enabled in File -> Preferences.

```

If I change my code I to this, I get a different error.

Code:

```
// including keyboard.h library for the keyboard functions
#include <Keyboard.h>

// setting Arrays for looping later
   int myIntPins[12] = {2,3,4,5,6,7,8,9,10,11,12,13};
   int myChar[12] = {97, 98, 99, 100, 101,102,103,104,105,106,107,108};
  int myChar2[6] = {109,110,111,112,113,114};
  char myCharPins[6] = {"A0","A1","A2","A3","A4","A5"};
  int a;
  int x;
  int i;

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

 //Setting up Digital Pins
 a=1;
for (i=0; i <= 11; i+=a){pinMode(myIntPins[i],INPUT);}

//pinMode(2, INPUT);
//pinMode(3, INPUT);
//pinMode(4, INPUT);
//pinMode(5, INPUT);
//pinMode(6, INPUT);
//pinMode(7, INPUT);
//pinMode(8, INPUT);
//pinMode(9, INPUT);
//pinMode(10, INPUT);
//pinMode(11, INPUT);
//pinMode(12, INPUT);
//pinMode(13, INPUT);

//------------------------------------------------------------------------------
//------------------------------------------------------------------------------

// setting up Analog Pins to Digital
for (x=0; x <= 5; x+=a){pinMode(myCharPins[x],INPUT);}
//pinMode(A0,INPUT);
//pinMode(A1,INPUT);
//pinMode(A2,INPUT);
//pinMode(A3,INPUT);
//pinMode(A4,INPUT);
//pinMode(A5,INPUT);

// starting keyboard
Keyboard.begin();

}

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

  //if pin 2 is pressed then send the a key/char
 // if (digitalRead(2) == LOW) {Keyboard.write(97);}

// instead of doing an if one by one doing a loop all in one shot
// this loop for regular digital pins
for (i=0; i <= 11; i+=a){if (digitalRead(myIntPins[i]) == LOW){Keyboard.write(myChar[i]);}}

  // this loop for the analog pins now working as digital pins
  for (x=0; x <= 5; x+=a){if (digitalRead(myCharPins[x]) == LOW){Keyboard.write(myChar2[x]);}}

  delay(10);

  }

```

Error:

```
    Arduino: 1.8.7 (Windows 10), Board: "Arduino Leonardo"

Mandar_Keyboard_Key_1:10:54: error: too many initializers for 'char [6]'

   char myCharPins[6] = {"A0","A1","A2","A3","A4","A5"};

                                                      ^

exit status 1
too many initializers for 'char [6]'

This report would have more information with
"Show verbose output during compilation"
option enabled in File -> Preferences.

```

# Answer
All of those "A1" "A2" pins have other numbers that go with them. The A1 or A2 is #defined in the core to be some number. You can just use A1 or A2 and it will work.

For example, try this line and see what it prints:

```
Serial.println(A0);

```

And for your pins, just put A0, A1, etc. in your int array and leave the quotes off. Those symbols are being replaced by numbers because they're defined constants.

```
int myIntPins[12] = {2,3,4,5,6,7,8,9,10,11,12,13, A0, A1, A2};

```
> 5 votes

---
Tags: arduino-leonardo, array
---


title: Keypad giving random inputs

text:
# Question
Title: Keypad giving random inputs
I have a keypad like this:

here is another, closer look at the bottom part.

Basically, I want the LED to power the amount that I pressed.

this is my code:

```
int LED = 1;
int inputs[4] {
  6,
  4,
  2,
  0
};
int outputs[4] {
  13,
  12,
  10,
  8
};
void outputAllBut(short int);
int numberInputCheck();
int inputCheck();

void setup() {
  for (int i = 0; i < 4; i++) {
    pinMode(outputs[i], OUTPUT);
    pinMode(inputs[i], INPUT_PULLUP);
  }
  pinMode(LED, OUTPUT);
}

void loop() {
  while (true) {
    int x = numberInputCheck();

    if (x == 500) {
      break;
    }

    delay(500);

    for (int i = 0; i < x; i++) {
      digitalWrite(LED, HIGH);
      delay(500);
      digitalWrite(LED, LOW);
      delay(300);
    }
  }
}

int numberInputCheck() {
  while (true) {
    for (int i = 0; i < 4; i++) {
      outputAllBut(i);
      for (int m = 0; m < 4; m++) {
        if (digitalRead(inputs[m]) == LOW) {
          switch (i) {
          case 0:
            if (m == 3) {
              return 500;
            } else {
              return m + 7;
            }
          case 1:
            if (m == 3) {
              return 500;
            } else {
              return m + 4;
            }
          case 2:
            if (m == 3) {
              return 500;
            } else {
              return m + 1;
            }
          case 3:
            return 500;
          }
        }
      }
    }
  }
}

void outputAllBut(short int b) {
  for (int i = 0; i < 4; i++) {
    if (i != b) {
      digitalWrite(outputs[i], HIGH);
    }
  }
}

int inputCheck() {
  for (int i = 0; i < 4; i++) {
    if (digitalRead(inputs[i]) == LOW) {
      return i;
    }
  }
  return 5;
}

```

for reference, the `numberInputCheck` function is the one that might go wrong here, I want it to wait for an input and return the number that I pressed. `i` is the rows and `m` is the columns. My problem is that whenever I press the keypad at one of the numbers, it will give me a random amount of times that the LED turns on, there doesn't seem to be any pattern.

`m+1`, `m+4` & `m+7` is because `m` is my columns so if I press 0 and the row is 0 then I add 1, same goes with everything else. Can anyone help me?

# Answer
> 1 votes
Your `outputAllBut` function is wrong. It turns all but the specified output high, but it doesn't turn the specified output low. As a result, after calling it multiple times, you end up with all of the outputs high forever (since you don't have code anywhere else that would turn them off), so it's just a question of timing which one it considered "on" any time you press a button.

Side note: toggling the outputs between low and high to do the matrix read is dangerous, as pressing multiple buttons at a time can cause a short circuit that way. You should instead always keep all of them low, and control which one is active by setting it to output mode and the rest to input mode.

---
Tags: arduino-uno
---


# Question
Title: Controlling a servo motor with a touch sensor
I want to modify my code to move a servo motor only for the duration of time that the sensor is touched and stop moving immediately when the sensor is no longer touched. The code I have moves the sensor from 0 to 90 and back. That motion is completed even when you remove your finger. I want it to be such that if you remove your finger before the servo reaches 90 degrees the servo stops. And the servo starts up again toward 90 when touch resumes. This is the code I currently have:

```
//when signal output is high the sensor is being pressed

#include <Servo.h>

Servo myservo;  // create servo object to control a servo
int pos = 0;    // variable to store the servo position
int sensor=11; //initialises component to arduino digital pins
led=13;

void setup() {
        myservo.attach(9);
        pinMode(led,OUTPUT);
        pinMode(sensor,INPUT);
        Serial.begin(9600);
}

void loop() {

        int value=digitalRead(sensor);
        if(value == HIGH){
                digitalWrite(led, HIGH);
                for (pos = 0; pos <= 90; pos += 1) {
                        myservo.write(pos);              // tell servo to go to position in
                        variable 'pos'
                                delay(15);                       // waits 15ms for the servo to reach the
                        position
                }
                for (pos = 90; pos >= 0; pos -= 1) { // goes from 90 degrees to 0 degrees
                        myservo.write(pos);              // tell servo to go to position in
                        variable 'pos'
                                delay(15);
                }
                Serial.println("TOUCHED ");
        }else{
                digitalWrite(led, LOW);

                Serial.println("NOT TOUCHED ");
                delay(500);
        }
}

```

# Answer
> 1 votes
To solve your problem, you need to take a tiny step into real time programming. Most Arduino programs deal with one issue or action at a time. Your simple twist to interrupt and action "i want it to be such that if you remove your finger before the servo reaches 90 degrees that's where the servo stops" requires you to continuously monitor your input (touch switch) while changing your output (next servo position).

You can go about this 2 ways. You can use interrupts to inform you when the state of the touch switch changes. This is challenging. Many find it difficult to conceive of what might happen if their program were to be interrupted at any and all possible points in its execution. A mistake here can lead to unexpected results.

Or you could take turns polling the state of the touch switch then making a small adjustment in the position of the servo. When the state of the touch switch changes from active to not-active, exit the loop you are using to change the servo position.

---
Tags: sensors, motor, servo
---


# Question
Title: Is it possible to use AWS and Arduino Uno to upload data from Arduino to a website running on my localhost?
I was wondering if it's possible to send data from my Arduino Uno (e.g. from the temperature sensor) to the Amazon Web Service RDS or anything there, which will then upload the data to a website on my localhost?

If yes, could someone give me guidance please?

I've been messing with this for a few weeks now, but I am just getting lost with linking it all up together.

Thanks.

# Answer
> 2 votes
No, it is not (easily) possible.

AWS has no access to your localhost - you are (most likely) behind a NAT router.

You could *possibly* open up port forwarding on your router and then ensure that AWS knows always what the IP address of your router is so it can connect (using some dynamic DNS service maybe).

However, that is not secure, and dynamic IP address assignments makes it a real pain. It opens up your computer to hacking from the internet. A more secure method is to use AWS as the "central point" and have your computer go and fetch data from there rather than having it send data to your computer.

# Answer
> 2 votes
I realize that this probably two years too late for the OP; however, I'd like to provide insight to anyone else who might be interested.

It is possible to do what you're asking. What you are looking for my friend is AWS IoT Core and the related IoT Services (e.g. IoT Device Management).

There are several steps that you're going to need to perform prior to being able to send telemetry to AWS:

1. Ensure that your device has the necessary components to connect to the Internet (e.g. a network shield).
2. Once you are Internet-capable, locate here the AWS IoT SDK that will work well with your device.
3. Read the documentation (I'll let you look that part up ;-)...probably within the sub-links on the page from #2) on how to connect your device to an MQTT-based Web Sockets connection to AWS IoT Core.
4. Once you've figured out how (using the SDK from your device) to connect to AWS using MQTT, read about AWS Lambda and how you can setup various triggers off of IoT Core, which can then propagate data down to your RDS DB or the like.
5. Once you have your data in AWS, you can then connect your "localhost" website to RDS, using the appropriate connection string, and pull the data from there.

Good luck and happy IoTing.

---
Tags: arduino-uno, web-server
---


title: Arduino DC motor with 2 buttons

text:
# Question
Title: Arduino DC motor with 2 buttons
I have a problem with my Arduino project and I tried everything to fix it but nothing helps.

I am trying to rotate my DC motor with two buttons:

* one button is to stop/start rotating on left side, and;
* the second one is for stop/start rotating on the right side.

I can't switch the states and if the motor is rotating I can't stop it. The speed is controlled by the potentiometer and works fine, just the buttons are the problem. I hope somebody can help me.

```
int enablePin = 11;
int in1Pin = 10;
int in2Pin = 9;
int switchPin = 7;
int switchPin1 = 6;
int potPin = 0;
int statusPin= 13;
boolean status;

void setup()
{
  pinMode(in1Pin, OUTPUT);
  pinMode(in2Pin, OUTPUT);
  pinMode(enablePin, OUTPUT);

  pinMode(switchPin, INPUT_PULLUP);
  pinMode(switchPin1, INPUT_PULLUP);

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

void loop()
{
  digitalWrite(13,HIGH);

  int speed = analogRead(potPin) / 4;

  boolean reverse = digitalRead(switchPin);
  boolean reverse1 = digitalRead(switchPin1);

  if(reverse == false){
    status = true;
  }
  if(reverse1 == false){
    status == false;
  }

  setMotor(speed, status);
}

void setMotor(int speed, boolean reverse)
{
  analogWrite(enablePin, speed);

  digitalWrite(in1Pin, ! reverse);
  digitalWrite(in2Pin, reverse);
}

```

I just added the second button with paint, so don't get confused.

# Answer
In your code the buttons only control the direction, but are not turning the motor on or off. This is only be done with the potentiometer, which can be set to zero speed.

To really enable the motor with the buttons, you have add some logic for the enable pin. For example change the `setMotor()` function and give it also a boolean as parameter, which indicates the enabling of the motor:

```
void setMotor(int speed, boolean enabled, boolean reverse)
{
    if(enabled) analogWrite(enablePin, speed);
    else        analogWrite(enablePin, 0);
    digitalWrite(in1Pin, ! reverse);
    digitalWrite(in2Pin, reverse);
}

```

You can set a corresponding boolean variable in the `loop()` function like you did with the `status` variable. Set this new variable to `true` in both if-statement of the buttons. Alternatively you can do this inline with the `setMotor()` call by writing:

```
setMotor(speed, reverse || reverse1, status);

```

The `||` is a logical OR operation. It returns `true` if any of both operands are true. In a similar way you can ditch the other if-statement with the `status` variable:

```
setMotor(speed, reverse || reverse1, !reverse && reverse1);

```

`!` negates the value of `reverse` and `&&` does a logical AND. You can decide yourself, if you want to use if-statements (which are a bit easier to read or these logical statements (which are more compact).

---

Also you should use better variable names. `reverse` and `reverse1` are not really good to distinguish. Better would be `reverse` and `forward`.
> 1 votes

---
Tags: motor, button, switch
---


# Question
Title: Why is 'n' parameter of snprintf ignored?
I have found that the `n` parameter of `snprintf()` seems to be ignored in my code.

```
char asdf[10];
Serial1.println(snprintf(asdf, 2, "hello"));

```

This prints 5 when I would expect it to print 2. What is happening?

# Answer
> 7 votes
snprintf() will not write more than \<size\> (snprintf's 2d argument) characters to your buffer, but it does count (and discard the extra) characters it would have written, had there been space enough, and that is the number it returns. Yeah, it can be confusing!

See this snprintf() reference.

# Answer
> 2 votes
A test sketch for the Arduino Uno:

```
char buffer[10];

void setup() {
  Serial.begin(9600);
  int n = snprintf(buffer, 2, "hello");
  Serial.println(n);
  Serial.println(buffer);
}

void loop() {
}

```

As @JRobert wrote, the "would have" is the key. As far as I know only the snprintf and the vsnprintf return a "would have" number.

I think the reason is to be able to tell if the string was truncated. Suppose the 'size' parameter is 25 and the format string is very long, then the return value can be tested against 25. If the return value was 26 (the "would have" number of bytes), then the string was truncated.
This information was not possible to retrieve when the "would have" number was not available.

# Answer
> 2 votes
For completion, the man page for `fprintf` states:

> The snprintf() function shall be equivalent to sprintf(), with the addition of the n argument which states the size of the buffer referred to by s. If n is zero, nothing shall be written and s may be a null pointer. Otherwise, output bytes beyond the n‐1st shall be discarded instead of being written to the array, and a null byte is written at the end of the bytes actually written into the array.

and, more relevant:

> Upon successful completion, the snprintf() function shall return the number of bytes that would be written to s had n been sufficiently large excluding the terminating null byte.

---
Tags: string
---


title: Linked List based question

text:
# Question
Title: Linked List based question
I am making a Smart Cart using RFID. The user will have a RFID card. As soon as he swipes the card on the RFID Reader it will identify the user and will create a linked list for that particular user. The linked list will contain the unique Rfid based Ids of the items purchased by the user. In my code the problem is that after the detection of the user it is not creating any linked list for the items/it is not detecting the items bought by the user. Both the user and items are identified by their unique ids (ie RFID tags).It is detecting the user but once the user is being detected it is not mapping the items bought with that user.

the code for the same is :

```
int count = 0; // count = 0
int i;
char input[12];                                   // character array of size 12
boolean flag = 0;
// flag =0

boolean comparetag(char x[12], char bb[12]) {
  boolean ff = false;
  int fg = 0;
  for (int cc = 0; cc < 12; cc++) {
    if (x[cc] == bb[cc]) {
      fg++;
    }
  }
  if (fg == 12) {
    ff = true;
  }
  return ff;
}

struct Node {
  char x[12];
  struct Node *next;
};

struct Node* X;
struct Node* point;

void printList(struct Node *n) {
  while (n != NULL) {
    Serial.print(n->x);
    n = n->next;
  }
}

struct Node* Shopping(char[]) {

  Serial.print(input);
  // Print RFID tag number
  Serial.print("Welcome User");
  Serial.println();

  Serial.print("Start Shopping ");

  struct Node* head = NULL;
  head = (struct Node*) malloc(sizeof(struct Node));

  return head;

}

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

void loop() {

  if (flag == 0) {
    if (Serial.available()) {
      count = 0;
      while (Serial.available() && count < 12) // Read 12 characters and store them in input array
      {
        input[count] = Serial.read();
        count++;
        delay(5);
      }

      if (comparetag(input, "1B006AFA9F14")) {
        flag = 1;

        point, X = Shopping(input);
      } else {
        Serial.println("not Registered User");
      }
    }
  } else {
    int c = 0;
    if (Serial.available()) {
      while (Serial.available() && c < 12) // Read 12 characters and store them in input array
      {
        Serial.print("Taking Input");
        X->x[c] = Serial.read();
        c++;
        delay(5);
      }
      struct Node* second = NULL;
      second = (struct Node*) malloc(sizeof(struct Node));
      second = NULL;

      X->next = second;
      X = second;

    }
  }
  printList(point);
}

```

# Answer
I don't see any code for making new nodes or linking them into a list. A linked-list needs a root (a known variable that points to the first member of the list); a way to make or acquire new nodes and link them onto the list as the number of items grows; and a way to unlink a node and "discard" it - return its memory - once it is no longer useful.

I'll offer a couple of suggestions for linked-lists, especially in processors like the Uno with limited memory:

1. Don't be tempted to use `malloc()` and `free()` or `new` and `delete` for a system that must run continuously. Allocating and deallocating small pieces of memory, especially when interspersed with other allocation & deallocations, will lead to fragmentation of the heap (that portion of memory used for allocating memory at run-time). The result is that the heap will end up with lots of separate pieces of memory that are free but too small for other allocation requests, so the heap has to acquire more memory to satisfy the larger allocations. It does this by reducing the stack space! Eventually the stack will grow into the heap space, and the program will fail.
My solution is to define a global array of node structs; enough of them for the program's greatest conceivable need, plus a few more for safety; link them into a list of free nodes; and give new nodes to the application by deallocating one from the free list. A You need link() and unlink() functions for a linked-list anyway, so it takes very little more code to do this.
2. Because we're talking about memory limited processors, If I don't need more than 255 nodes, I link with array indices instead of pointers, saving one byte per node. This costs a little bit more code to index into an array than to de-reference a pointer but compilers have gotten pretty smart about minimizing even that overhead.
> 2 votes

---
Tags: rfid
---


# Question
Title: Can an IC be programmed by an Arduino and then be removed, to be used in an external breadboard?
I wanted to find out if is possible to write programs into a micro controller using the Arduino and use the micro controller independent of the Arduino board?

# Answer
> 1 votes
Yes. The compiles code will is burned in the Arduino ROM. You can then take the Atmel chip (the Arduino microprocessor) and use it. You only need a few extra component for a chip like the 328p (Arduino Uno).

# Answer
> 0 votes
For another example, using another method, an Uno can program another MCU without the target needing any bootloader, thus enabling your code to occupy the entire Flash memory of the target devices. Here is a link describing how to program an Attiny using an Uno and the ArduinoISP example program. An Attiny85, for example, has 8K of flash, all of which is usable by your application, using this technique. For comparison, a bootloader in an Attiny85 takes about 2.5K, or 30% of the Flash space! And it only gets worse with the smaller Attinys.

---
Tags: arduino-ide
---


title: Serial Moniter is repeating output

text:
# Question
Title: Serial Moniter is repeating output
I do apologize for the constant posts on here. However I ran into an issue and I cannot seem to find any solution to it. The goal is to enter a username, through the Serial.read function, and if the username matches it simply responds "Welcome Steven", and lights a green LED, when the wrong username is submitted it responds "Access Denied" and lights a red LED. So far the code works in response to access granted, and access denied, while also lighting the appropriate LEDs. However the Serial Monitor does not wait until there is a user input, it automatically starts repetitively "access denied" and lights the red LED. When the username is entered the red LED turns off, the green LED turns on, and Serial Monitor repetitively responds "Welcome Steven". I can do this multiple times, and each time it will change state. I have looked at many tutorials and read many posts on here concerning issues, but so far nothing has worked out. Even tried making changes NickGammon suggested in another post. Would like to get rid of the repetitive issue, and wait for user input before access denied or granted appears.

```
int led1 = 9;
int led2 = 10;
String user_name;

void setup()
{
  Serial.begin(9600);
  pinMode(led1, OUTPUT);
  pinMode(led2, OUTPUT);
  Serial.println("Enter Username");
}

void loop()
{
 if(Serial.available())
   user_name = Serial.readStringUntil('\n');
{

if(user_name == "Grantham1")
{
  Serial.println("Welcome Steven");
  digitalWrite(led1, HIGH);
  digitalWrite(led2, LOW);
}
else if(user_name != "Grantham1")
{
  Serial.println("Invalid Input");
  digitalWrite(led1, LOW);
  digitalWrite(led2, HIGH);
}
else
{
  Serial.println("Waiting Pateintly");
  digitalWrite(led1, LOW);
  digitalWrite(led2, LOW);
}
}
}

```

# Answer
Change

```
if(Serial.available())
    user_name = Serial.readStringUntil('\n');
{

```

to

```
if(Serial.available()) {
    user_name = Serial.readStringUntil('\n');

```

Edit: The reason why it didn't work properly was because all subsequent `if`s were evaluated repeatedly regardless of whether there was anything new in the serial buffer or not. The modification fixes that problem.
> 2 votes

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


title: Increase and Decrease Motor Speed

text:
# Question
Title: Increase and Decrease Motor Speed
I'm a newbie on Arduino and I'm doing an exercise about the Motor controller "Increase the motor speed from zero to maxium (255) and then decrease slowly from the maximum to the minium." Here's my code. I don't know whether it's true or not. So, can anyone help me to check it and give me some advice how to do better on Arduino ?

```
int i;
void setup()
{
   pinMode(motor, OUTPUT);
}

void loop()
{
   for (i=0; i<=255; i++)
   {
   analogWrite(motor, i);
   }

   for (i=255; i>=0; i--)
   {
   analogWrite(motor, i);
   }
}

```

I also have one other problem :D that I don't know what will happen if I set the analogWrite value to 300.

Thank you so much.

# Answer
It won't work, as you don't give it any time to do anything. The PWM works about 1kHz and motor needs much more time to start rotating. And you are sending values as fast as possible (it means microseconds for every analogWrite)

And `analogWrite(300)` without changing the Arduino default settings means it overflows to value `300 % 256 = 44`. All Timers are set near to 1kHz and 8bit resolution by Arduino core.
> 2 votes

---
Tags: motor, speed
---


title: Solenoid "vibrates" instead of pushing

text:
# Question
Title: Solenoid "vibrates" instead of pushing
I'm using my Arduino Uno to control a 5V 1A solenoid.

I'm using an N-Channel MOSFET linked to the Uno's 0 pin to switch the solenoid on and off. It is protected by a Schottky diode. Initially, I tested the circuit with the blink example sketch (just set to blink Pin 0 instead of Pin 13). I used the Uno's built in 5V 500mA output and the solenoid "blinked" on/off perfectly at whatever interval I wanted:

I plan on controlling multiple solenoids in a future version, which will draw more current than the Arduino output can supply, so I bought a 5V 12A power supply. I proceeded to test it with my single-solenoid set up using the same blink example sketch:

When I power the solenoid with my 5V 10A my power supply, the solenoid doesn't push on command. It merely "vibrates," travelling only about .5mm at several hundred Hz. The solenoid vibrates constantly the moment I plug in the power supply, and does so completely independently of whatever interval I have set it to "blink."

Any ideas as to what may be causing this to work with the Arduino's built in power supply, but not with an external power supply? I've tested the voltage on my power supply, and it reads 5V as advertised. I'm somewhat new this, and feel like I may be missing something obvious.

Thanks,

Max

# Answer
> 4 votes
From your schematics it looks like:

* you connected the power supply backwards (on both schematics actually, I wonder how come you did not fry your Arduino)
* the external supply and the Arduino do not share a common ground as they should.

**Edit**: about the orientation of the power supply:

* the (−) side of the supply (and GND of the Arduino) should be connected to the source of the N-MOSFET
* the (+) side of the supply should be connected to the cathode of diode (the side identified by the small white bar)

---
Tags: arduino-uno, power, transistor, mosfet
---


# Question
Title: Arduino Uno keeps looping on setup() everytime I press a specific button on the remote
I'm trying to decode my Panasonic television remote using the IR\_RECEIVE sketch below.

When I press the remote's buttons it works fine and Iget the values, except from when I press the power button - the setup() function executes.

This is the code:

```
/* Raw IR decoder sketch!

This sketch/program uses the Arduno and a PNA4602 to
decode IR received. This can be used to make a IR receiver
(by looking for a particular code)
or transmitter (by pulsing an IR LED at ~38KHz for the
durations detected

Code is public domain, check out www.ladyada.net and adafruit.com
for more tutorials!
*/

#define IRpin_PIN      PIND
#define IRpin          2
#define MAXPULSE 65000
#define RESOLUTION 20

uint16_t pulses[100][2];  // pair is high and low pulse
uint8_t currentpulse = 0; // index for pulses we're storing

void setup(void) {
    Serial.begin(9600);
    Serial.println("Ready to decode IR!");
}

void loop(void) {
    uint16_t highpulse, lowpulse;  // temporary storage timing
    highpulse = lowpulse = 0; // start out with no pulse length

    while (IRpin_PIN & (1 << IRpin)) {
        highpulse++;
        delayMicroseconds(RESOLUTION);

        if ((highpulse >= MAXPULSE) && (currentpulse != 0)) {
            printpulses();
            currentpulse = 0;
            return;
        }
    }
    pulses[currentpulse][0] = highpulse;

    while (!(IRpin_PIN & _BV(IRpin))) {
        lowpulse++;
        delayMicroseconds(RESOLUTION);
        if ((lowpulse >= MAXPULSE) && (currentpulse != 0)) {
            printpulses();
            currentpulse = 0;
            return;
        }
    }
    pulses[currentpulse][1] = lowpulse;

    currentpulse++;
}

void printpulses(void) {
    Serial.println("\n\r\n\rReceived: \n\rOFF \tON");
    for (uint8_t i = 0; i < currentpulse; i++) {
        Serial.print("delayMicroseconds(");
        Serial.print(pulses[i][0] * RESOLUTION, DEC);
        Serial.println(");");

        Serial.print("pulseIR(");
        Serial.print(pulses[i][1] * RESOLUTION, DEC);
        Serial.println(");");
    }
}

```

This is the output:

> Ready to decode IR!
>
> Received:
>
> OFF ON
> delayMicroseconds(34724);
> pulseIR(3600);
> delayMicroseconds(1800);
> ......
> delayMicroseconds(1340);
> pulseIR(460);
> delayMicroseconds(1360);
> pulseIR(460);
> Ready to decode IR!
> Ready to decode IR!

The last 2 rows appeared when I pressed the power button (twice). The rows above appears when I press any other button.

I played around with the Arduino and the remote, I might have done something to cause this. The first time I tried it - it worked fine.

I tried resetting and re-uploading.

Sorry if the post is too long or not informative enough - I'm new to this and not really sure what kind of information to provide.

# Answer
> 1 votes
How high can `currentpulse` get before it is reset to zero? It is used an array index and if it gets larger than the (number of array elements-1), your code will write outside of the array.

Can the array be so far over-written that it grows into the stack area? That could definitely cause a reset, or reset-like behavior.

---
Tags: arduino-uno, ir, remote-control
---


# Question
Title: How to change speed of multiple servos acting at the same time with PCA9685 module?
I'm using the PCA9685 module with its Adafruit library. In my code I have one object of the servodriver class that has 14 channels (controlling 14 servos basically).

```
void Positioning(){
  ServoDriver.setPWM(right_foot, 0, MapRotation(rotations[0],"1"));
  ServoDriver.setPWM(left_foot, 0, MapRotation(rotations[1],"2"));
  ServoDriver.setPWM(right_calf, 0, MapRotation(rotations[2],"1"));
  ServoDriver.setPWM(left_calf, 0, MapRotation(rotations[3],"2"));
  ServoDriver.setPWM(right_thigh, 0, MapRotation(rotations[4],"1"));
  ServoDriver.setPWM(left_thigh, 0, MapRotation(rotations[5],"2"));
  ServoDriver.setPWM(right_pelvis, 0, MapRotation(rotations[6],"1"));
  ServoDriver.setPWM(left_pelvis, 0, MapRotation(rotations[7],"2"));
  ServoDriver.setPWM(torso, 0, MapRotation(rotations[8], "1"));
  ServoDriver.setPWM(right_shoulder, 0, MapRotation(rotations[9], "1"));
  ServoDriver.setPWM(left_shoulder, 0, MapRotation(rotations[10], "2"));
  ServoDriver.setPWM(right_arm, 0, MapRotation(rotations[11], "1"));
  ServoDriver.setPWM(left_arm, 0, MapRotation(rotations[12], "2"));
  ServoDriver.setPWM(right_hand, 0, MapRotation(rotations[13], "1"));
  ServoDriver.setPWM(left_hand, 0, MapRotation(rotations[14], "2"));
}

```

All the function positioning does is just set all the servos to a certain position (they're in a humanoid robot and so this position is for standing). The array `rotations[]` just contains the servo positions from 0 to 180 which is set elsewhere in the code for each servo respectively. The second argument for map rotation just maps it between the servos pulse min and max values (115 and 560) in normal order or reverse depending on number.

My question is how do I change the speed of the servos? I cannot use `delay()` or loops because wouldn't that cause all the servos to turn sequentially instead of all at once. a change in any `rotations[]` value indicates the robot is moving and so how do I make the servos slower instead of turning at their fastest to the new `rotations[]` positions whenever they are changed (as `positioning()` is called in the `loop()` function)?

# Answer
You cannot simply change the speed of a servo. You can only move step my step to the desired position, waiting inbetween. So for example instead of directly moving from 0° to 90°, you can first move to 5°, wait a bit, move to 10°, wait a bit, move to 15°, wait a bit,... until you reached 90°. You can also go in 1° steps to make it smoother.

You can solve this with delays, but if you want to move the servos at different speeds, you will need a non-blocking coding style like in the `BlinkWithoutDelay` example of the Arduino IDE (it was described countless times at this site and on the web).

Also, when building a humanoid robot, at some point you will have to consider not only the pose, that you want the robot to reach, but also the way to get there. This can be very important and it can be a complex task. Basically you need formulas for the movements, which return you the exact position for Dach servo at any given time in a movement. Then you can set the servos to this value for the current time.
> 0 votes

---
Tags: i2c, servo, pwm, adafruit, robotics
---


# Question
Title: Does a normal Ultra-Sonic sensor (HC SR04) sense through a Football Net like obstacle?
I am planning to to use ultrasonic sensors mounted on a drone for obstacle avoidance. I am not sure if the sensors would be capable of detecting a Net Like obstacle in its path.

# Answer
There is always a chance of picking up the net for a split second, but most likely, you will never accurately detect the net with this type of sensor. There is too little to detect.
> 2 votes

---
Tags: sensors, drone
---


# Question
Title: How to get the encoder position while the rotary motor is moving
I have a question with encoder and the rotary motor. When the motor is moving, I can't access the position of the motor. I have run the code separately, it is perfectly fine. But when I combine, these two codes, the motor is able to move but there was no position data.

Any suggestion on how can I get the motor moving and get the encoder position at the same time.

The combined code I have drafted is there:

```
  #include <Stepper.h>

    const int stepsPerRevolution = 4000;  // 4000 steps for one circle with 10mm increment.
    const int motorPitchPerCircle = 10;     // 10mm per circle for the linear ball screw guide for motor.

    int val;
    int encoder0PinA = 3; // Pin 15 of the cable.
    int encoder0PinB = 4; // Pin 13 of the cable.
    int encoder0Pos = 0;
    int encoder0PinALast = LOW;
    int n = LOW;

    // initialize the stepper library on pins 8 through 11:
    Stepper myStepper(stepsPerRevolution, 9, 8, A3, A5);

    void setup() {
      // set the speed at 60 rpm:
      myStepper.setSpeed(100);
      // initialize the serial port:
      Serial.begin(9600);

      pinMode (encoder0PinA, INPUT);
      pinMode (encoder0PinB, INPUT);
      Serial.begin (9600);
    }

    void loop() {
      // step one revolution  in one direction:
      myStepper.step(6*stepsPerRevolution);
      delay(2000);

       n = digitalRead(encoder0PinA);
      if ((encoder0PinALast == LOW) && (n == HIGH)) {
        if (digitalRead(encoder0PinB) == LOW) {
          encoder0Pos--;
        } else {
          encoder0Pos++;
        }
        Serial.print (encoder0Pos);
        Serial.print ("/");
      }
      encoder0PinALast = n;

    }

```

# Answer
> 1 votes
While your `delay()` function is running, you won't be able to read any data. Suggestion is to use interrupts, which basically guarantee that whenever your pin state changes (low edge, high edge, or any change, feel free to select it), some action will be performed. This action can be reading your encoder position.

Read about it here https://www.arduino.cc/reference/en/language/functions/external-interrupts/attachinterrupt/

I am sure it will answer all your questions, it is quite well documented

---
Tags: rotary-encoder
---


title: Adafruit Trinket M0 persistent storage?

text:
# Question
Title: Adafruit Trinket M0 persistent storage?
I am using an Adafruit Trinket M0 to program a small game and would like to save the game state every so often. I am programming it through the Arduino IDE as the chip does not have enough space to run my game with circuitpython (too many libraries). Does the Trinket M0 have any form of persistent storage that I can use, or will I need to use a different device?

I couldn't find EEPROM in the documentation, but I wasn't able to find a definitive answer whether or not it has any form of long term storage. Knowing the board is based on the Attiny85 I would expect it to have 512 bytes or so, but the arduino library is giving me problems when I try to use it as well, so there is no way for me to trial and error this.

# Answer
The M0 boards use a SAMD chip. It has no EEPROM. To store data without additional hardware like external EEPROM or SD card, you can use the flash memory of the SAMD. But it has a drawback of limited count of writes to flash memory.

An EEPROM emulation library exits. It uses the flash memory, so the drawback of limited writes, applies. I used it, it works. The library is almost official. The author is Arduino's coworker.
> 1 votes

---
Tags: attiny, adafruit, eeprom
---


# Question
Title: LDC paired with Arduino locks up and freezes. Out of SPRAM?
I am making an alarm clock using a 4x20 lcd display, rtc, and Arduino Pro Mini 3.3v. I have implemented a menu system for setting the time/date that blinks the text on the lcd display to indicate that I have it selected, but the blinking randomly stops and the Arduino stops printing to the serial after about ten seconds.

After much head scratching and Googling I came to the conclusion that all my lcd.print() lines were using up all my ram. I tried to create PROGMEM variables to use in the print commands, but I couldn't get it to work so I ended up just adding the F() macro to every print statement (there's a lot). This now prints everything as expected, but the Arduino still freezes up after the same amount of time. Am I using F() wrong or is the problem something else like power???

Visual Studio code says I am using 643/2048 bytes of data/ram and 14960/30720 bytes of flash when I upload the code. (that is with the F() macro implemented)

--------------EDIT----------------

So I've created a small test sketch to use with the same circut, and now I'm really confused. I've been running it for about an hour now and it is still not freezing. The script blinks a full screen of number signs every 200ms. The backlight is on and everything is still powered the same way. This, in theory, rules out both running out of ram and not providing enough power. Any other ideas?

```
#include <Arduino.h>
#include <Wire.h>
#include <LiquidCrystal_I2C.h>
#include <RTClibExtended.h>

LiquidCrystal_I2C lcd(0x27,20,4);
RTC_DS3231 clock;

void setup() {
    Serial.begin (9600);
    lcd.init();
    clock.begin();
    clock.adjust (DateTime (__DATE__, __TIME__));
    lcd.backlight();
}

bool on = true;

void loop() {
    lcd.setCursor (0, 0);

    if (on) {
        for (int i = 0; i < 4; i++) {
            lcd.setCursor (0, i);
            for (int j = 0; j < 20; j++) {
                lcd.print ("#");
            }
        }
    }
    else {
        for (int i = 0; i < 4; i++) {
            lcd.setCursor (0, i);
            for (int j = 0; j < 20; j++) {
                lcd.print (" ");
            }
        }
    }

    on = !on;
    delay (200);
}

```

# Answer
I found the problem! it was specific to my code and didn't turn out to have anything to do with ram or power. The problem was I hadn't detached the interrupt from the rtc when I woke it up with a button. It would freeze seemingly randomly because the rtc would fire an interrupt signal when the next minute ticked, while the arduino was awake. I guess it causes problems when you try to interrupt arduino's sleep and it's not actually sleeping. All I had to do was detach both interrupts when the button is clicked. Thank you all for your help :)
> 0 votes

---
Tags: serial, lcd, arduino-pro-mini, sram, progmem
---


# Question
Title: Can you help me combining these sensor sketches as one in Arduino
I want to combine these three sketches into one.

RAIN SENSOR:

```
int rainPin = A0;
int greenLED = 6;
int redLED = 7;
// you can adjust the threshold value
int thresholdValue = 500;

void setup(){
  pinMode(rainPin, INPUT);
  pinMode(greenLED, OUTPUT);
  pinMode(redLED, OUTPUT);
  digitalWrite(greenLED, LOW);
  digitalWrite(redLED, LOW);
  Serial.begin(9600);
}

void loop() {
  // read the input on analog pin 0:
  int sensorValue = analogRead(rainPin);
  Serial.print(sensorValue);

  if(sensorValue < thresholdValue){
    Serial.println(" - It's wet");
    digitalWrite(greenLED, LOW);
    digitalWrite(redLED, HIGH);
  }
  else {
    Serial.println(" - It's dry");
    digitalWrite(greenLED, HIGH);
    digitalWrite(redLED, LOW);
  }
  delay(500);
}

```

LIGHT SENSOR:

```
int ldrPin = A0;
int greenLED = 6;
int redLED = 7;
// you can adjust the threshold value
int thresholdValue = 500;

void setup(){
  pinMode(ldrPin, INPUT);
  pinMode(greenLED, OUTPUT);
  pinMode(redLED, OUTPUT);
  digitalWrite(greenLED, LOW);
  digitalWrite(redLED, LOW);
  Serial.begin(9600);
}

void loop() {
  // read the input on analog pin 0:
  int sensorValue = analogRead(ldrPin);
  Serial.print(sensorValue);

  if(sensorValue < thresholdValue){
    Serial.println(" - light");
    digitalWrite(greenLED, LOW);
    digitalWrite(redLED, HIGH);
  }
  else {
    Serial.println(" - dark");
    digitalWrite(greenLED, HIGH);
    digitalWrite(redLED, LOW);
  }
  delay(500);
}

```

SMOKE SENSOR:

```
int smokeD0 = A5;
int greenLed = 11;
int redLed = 12;
// Your threshold value
int sensorThres = 300;

void setup() {
  pinMode(smokeD0, INPUT);
  pinMode(greenLed, OUTPUT);
  pinMode(redLed, OUTPUT);
  digitalWrite(greenLed, LOW);
  digitalWrite(redLed, LOW);
  Serial.begin(9600);
}

void loop() {
  int analogSensor = analogRead(smokeD0);
  Serial.println(analogSensor);

  // Checks if it has reached the threshold value
  if (analogSensor < sensorThres)
  {
    Serial.println(" - Smoke");
    digitalWrite(redLed, LOW);
    digitalWrite(greenLed, HIGH);
  }
  else
  {
    Serial.println(" - No Smoke");
    digitalWrite(redLed, HIGH);
    digitalWrite(greenLed, LOW);
  }
  delay(100);
}

```

I want to combine those codes as one with only two outputs:

* the `greenLED` and;
* the `redLED`.

# Answer
> 0 votes
### Variable renaming

1. Rename `thresholdValue` in the first two sketches to `rainSensorThreshold`, and `lightSensorThreshold` respectively, and `sensorThres` to `smokeSensorThreshold` in the third sketch.
2. Rename `sensorValue` in the first two sketches to `rainSensorValue`, and `lightSensorValue` respectively, and `analogSensor` to `smokeSensorValue` in the third sketch.

### Change the Analog pin

Use `A1` (or some other analog input other than `A0` or `A5`) for `ldrPin` in the second sketch, for example:

```
int ldrPin = A0;

```

### Consistant LED pins

Use the same pins in the third sketch, as are used in the first two sketches, for the two LEDs *and* note the change in case:

```
int greenLed = 11;
int redLed = 12;

```

to

```
int greenLED = 6;
int redLED = 7;

```

### Recompile each sketch

To check that the each sketch still works, recompile each one separately.

### Combine the code

Finally... Splice the code together appropriately, keeping the three parts separate:

* Global variables
* `setup()`
* `loop()`

---
Tags: arduino-uno, sensors
---


# Question
Title: Why is there no hex file generated when I "build binary output" from the Arduino IDE?
I want to obtain the `.hex` file from my Arduino sketch. I have followed various guides but there is no `.hex` file in my output folder.

How can I obtain my hex file?

Here are my preferences:

>

This is the contents of my output folder

>

# Answer
> 1 votes
Based on your setting with the URL for esp8266 package and bin file name with "...generic" I assume you want it for esp8266.

esp8266 doesn't use hex format and "Export compiled binary" creates bin. You can upload it with esptool.

For AVR boards "Export compiled binary" generates hex. You can upload it with avrdude.

# Answer
> 0 votes
## Current versions of Arduino IDE

Use the menu option in the Arduino IDE:

**Sketch****Export Compiled Binary**

See post #6 from the thread How to get hex file from arduino files ?:

> Well, since it was bumped it's worth mentioning there is a new way to do this added in Arduino IDE 1.6.5:
>
> * Sketch \> Export Compiled Binary
> * If you are doing this with an example then you will be prompted to save the sketch in another location.
> * Wait until the sketch has finished compiling.
> * Sketch \> Show Sketch Folder
> * The .hex file will be in the sketch folder

Here is a screenshot for OS X:

>

There is no need to fully compile, a simple verify will suffice. From post #10:

> Reopen Arduino, and open a sketch of your choice (use the Examples-\>Digital-\>Blink if you have no other sketches). Hit the Verify button to compile the sketch. Now, navigate to the build.path folder. You should see a bunch of files including one with a .hex extension.

---

## Older versions of Arduino IDE

If using an older version of the Arduino IDE, from post #12:

> Try this if using an older version of Arduino
>
> Taking out HEX file from Arduino in 3 simple steps

1. Open Arduino IDE
2. **File****Preferences** menu

>

3. Find "Show verbose output during " and check the "compilation" box
4. Locate the `preferences.txt` file and open it
5. Add the following line (this is the path to the directory where the hexfile will be stored):

```
build.path=C:\Users\<username>\Desktop\hexfile

```
6. Change the following line

```
export.delete_target_folder=true

```

to

```
export.delete_target_folder=false

```
7. Quit the Arduino IDE and restart it.
8. Now when you compile, the directory specified in `build.path` will contain the `.hex` file (along with other files which can be ignored)

---
Tags: arduino-ide
---


# Question
Title: Arduino UNO + ESP8266 WiFi Relay by LC Technology
I have Arduino Uno, and recently obtained ESP8266 WiFi Relay by LC Technology. I tried to look up some information about that on the net, but all the answers / suggested solution didn't work for me. Let me briefly explain the problem.

I have connected this module to arduino in a very simple way:

* TX -\> pin 7
* RX -\> pin 6
* 5V -\> IN +
* GND -\> IN -

Simple code:

```
#include "Arduino.h"
#include <SoftwareSerial.h>

#define TxPin 7
#define RxPin 6

SoftwareSerial ESPrelay(RxPin, TxPin);

void setup() {
    Serial.begin(9600);
    ESPrelay.begin(9600);

    readRx();

    ESPrelay.println("AT");
    readRx();
}

void loop() {
    Serial.println(ESPrelay.read());
    // this above is constant -1
}

void readRx() {
    String msg = "";
    while (ESPrelay.available()) {
        char rxByte = ESPrelay.read();
        msg += rxByte;
    }
    Serial.println(msg);
    delay(500);
}

```

I can see WiFi AP created by the module - so I think module itself works fine - communication between Arduino and module is somewhat broken.

I tried all different AT commands, but none of them seems to take an effect (tried switching modes and connecting to home WiFI, but no luck) also, no response is returned. Could someone try and help me debug this issue?

I tried changing 9600 to 115200 when communicating, but no luck with this either.

# Answer
Serial connection requires connecting transmit TX pin to receive RX pin. Your SoftwareSerial pins ar pin 6 RX and pin 7 TX. So your wiring should be esp8266 TX to Uno pin 6 and esp8266 RX to Uno pin 7.

Connect 5 V and ground to the pins header, not to screw terminals. The IN terminals are for powering the relay coil.

Call read readRx() in the loop(). Add delay before sending "AT" in setup to let the esp8266 time to boot.
> 0 votes

---
Tags: esp8266, relay
---


title: Playing MP3 Shield tracks

text:
# Question
Title: Playing MP3 Shield tracks
I have an MP3 shield on a Arduino Uno. When using "File Player" I can get the tracks to play by keyboard entry with three digits (001-009).

The problem is that I want to use (SFEMP3Shield \> examples \> MP3ButtonPlayer2) that is looking for files 1-9. Any file numbers other than 1,2,3,4,5,6,7,8,9 doesn’t work. Any suggestions?

# Answer
The `playTrack` function used in MP3ButtonPlayer2 example plays file with name created with printf format "track%03d.mp3". %03d creates a number prefixed with zeros to lenght 3. For example track005.mp3 or track042.mp3 or track999.mp3.

implementation of the playTrack function:

```
uint8_t SFEMP3Shield::playTrack(uint8_t trackNo){

  //a storage place for track names
  char trackName[] = "track001.mp3";
  uint8_t trackNumber = 1;

  //tack the number onto the rest of the filename
  sprintf(trackName, "track%03d.mp3", trackNo);

  //play the file
  return playMP3(trackName);
}

```

change it to:

```
uint8_t SFEMP3Shield::playTrack(uint8_t trackNo){

  //a storage place for track names
  char trackName[13];
  int trackNumber = trackNo;

  //tack the number onto the rest of the filename
  sprintf(trackName, "track%03d.mp3", trackNumber);

  //play the file
  return playMP3(trackName);
}

```
> 1 votes

---
Tags: shields
---


title: RGB LED strip 100m

text:
# Question
Title: RGB LED strip 100m
Hello all, I'm working on RGB LED strip SMD 5050 5m This all setup is working on 12v 2A with about diagram. I want to use same connection with 100m of LED strip using Arduino. Please support regarding this topic. H/W details : Arduino uno Hc-05 bt module 12v 1.2 amp supply Td140 pnp transistor SMD 5050 LED strip 60 LED/m

# Answer
100 Meters of 5050 SMD strip LEDs will require roughly 120-200 amps. However, you cannot drive a 100 meter strip from a single power supply. The thin copper traces in the LED strip can only handle so many amps before they become too hot (your LED strip would melt like ice cream on a hot summer day). This is why led strips are usually limited to 5 meters (~5A). You would need separated strips and power supplies for the 100 meters worth.

You have the correct idea with your circuit for turning the leds on/off (in fact the wiring is correct) but the transistors you plan on using are the wrong type. To switch the LEDs to ground you would need a low side switch, which would be a NPN transistor. Be careful however, transistors typically switch currents less than 1 amp. For higher power applications I would suggest using a N-channel Mosfet. A quick search on Sparkfun turns up the FQP30N06L, which is capable of handling 30A (with a heatsink, probably less than half without), and is also logic-level, meaning it can be driven with a 5 volt source (Arduino I/O pin).

Keep in mind, whatever current your LED strip draws, the ground switch (NPN transistor, N-Channel MOSFET, relay) must be able to handle the same current.

Good luck with your circuit!
> 4 votes

---
Tags: arduino-uno, power, rgb-led, led-strip, arduino-uno-smd
---


# Question
Title: Are there any Wi-Fi modules for the Arduino Uno that may connect to an external Wi-Fi Antenna?
I have an Arduino Uno I need to connect to Wi-Fi to make HTTP POST Requests to a Raspberry Pi Web Server.

The Arduino is located only about 30 feet from the AP, but there is a brick wall in the line of sight, and it is in a metal outdoor enclosure. For that reason, I wanted to attach an external Wi-Fi Antenna which would stick out a sealed hole in the enclosure.

I was contemplating using an ESP8266 Wi-Fi module, but it does not look like there is an easy way to attach the antenna.

What would be the best Wi-Fi module to which I could attach an external antenna for an Arduino Uno?

# Answer
There are variants of ESP8266-based modules which include a connection for an external antenna. The ESP-02, ESP-05 and ESP-07 modules all feature a U.FL socket.

Effectively, they are an ESP8266 mounted on a carrier board with a U.FL socket.

If you already have some code to suit an ESP8266-based module, this will avoid having to rewrite for a different unit.
> 2 votes

---
Tags: arduino-uno, esp8266, wifi, shields, web-server
---


# Question
Title: Changing PWM on Arduino Mega, pins 9 & 10 to 20 to 25 KHz
I'm trying to run a Nema 17 motor with a l298N motor Driver for a school project. The issue is that I am running the motor with PWM to avoid overheating of the driver, however the resulting noise at the default frequency is extremely aggravating.

How can I change the frequency for pins 9 & 10 to 20-25 KHz? Any tips tricks and code examples would be highly appreciated (***emphasis on code examples***).

# Answer
Fortunately, the timer for PWM on both pins 9 and 10 on the Arduino Mega (but not necessarily other boards) is timer 2, so changing the PWM frequency of one will change the PWM frequency of the other.

You should also check that changing the the timer frequency does not effect any other libraries (eg Servo, from memory typically uses timer 2).

The frequency for the timer is set by the TCCR2B register (bits CS22, CS21 and CS20) see p 185 of the datasheet for the Mega2560 IC http://ww1.microchip.com/downloads/en/devicedoc/atmel-2549-8-bit-avr-microcontroller-atmega640-1280-1281-2560-2561\_datasheet.pdf

As far as code goes, try the following (just tested with a small speaker, appears to change to pitch as expected, but I don't have a motor to try it on:

Each line sets the frequency for timer2 (PWM 9 and 10), should be ok to do during setup, and settings will remain. Note that the first line is equivalent to normal default values:

```
  TCCR2B=(TCCR2B&248)|4;    //prescaler=64, f=977Hz

  TCCR2B=(TCCR2B&248)|3;    //prescaler=32, 1953Hz

  TCCR2B=(TCCR2B&248)|2;    //prescaler=8, 7812Hz

  TCCR2B=(TCCR2B&248)|1;    //prescaler=1 62500Hz

```

Also check that your motor driver can handle the frequency.
> 1 votes

---
Tags: arduino-mega, pwm, frequency, stepper-motor
---


# Question
Title: USBasp problem: could not upload sketches to Arduino clone with PL2303 USB-to-UART chip
I'm trying to upload sketch to a Gizduino board (these boards have PL2303 chip for USB-to-Serial communication; other than that they are entirely similar with Arduino Uno).

I have installed the driver for it and can verify that the board associates to a COM Port whenever the board is connected to my PC (Win10) via USB. But everytime I try to upload a sketch, IDE (tried with 1.8.2 and 1.6.9) throws the error below, with or without the PL2303 driver installed on my PC.

```
avrdude: error: could not find USB device with vid=0x16c0 pid=0x5dc vendor='www.fischl.de' product='USBasp'

```

I'm certain that I have selected the right board from the Boards List.

So my intuition was that the PL2303 driver is not working the way it should be. I've been trying to get more information about avrdude and USBasp but so far was not able to find anything remotely similar to my case.

**UPDATE:** Realized that all I needed to do is install the driver for USBasp (whihch I'm having trouble doing); this post could be off-topic. But I'm urged to raise another question: Which programmer should I select from the programmer list? Currently its "AVRISP mkII". In fact it doesn't matter which one I use. Same error about USBasp occurs with any of them selected.

# Answer
Do you have a USBasp plugged into the computer? if yes then you need to install USBasp driver else why don't you just use the bootloader option from the arduino IDE.
> 1 votes

---
Tags: arduino-uno, usb, avrdude
---


# Question
Title: How to connect a MPU-6050 to an Arduino that already has a CNC Shield V3 on top of it?
I have a **CNC Shield** on top of an **Arduino Uno** (GRBL pinout) that controls 2 stepper motors through a4988 drivers and it is working like a charm.

Now I want to add an accelerometer to it. From my humble research, the **MPU-6050** seems a good pick.

If I purchase *stacking headers* to lift the CNC shield, can I connect the accelerometer to the *unused/reserved* **A4** and **A5** from the Arduino, but power it using CNC's **Ground** and **5V** pins?

I'm open to other approaches if I'm not doing it the proper way.

# Answer
MPU6050 can use only I2C. Those are pins A4 and A5 on an Uno. 5V and ground are 5v and ground, no matter from which pin
> 1 votes

# Answer
This may be a bit harder to implement than it might seem. The grbl code uses all but one pin, so you would have to change that in the library. So I checked out the the code for the shield, and under the cpu\_map tab it defines the pins. I would first try setting the unused pins to arbitrary values to enable the pins previously used by the code. For instance, if you are not using the Zed axis, try changing
`#define Z_STEP_BIT 4 // Uno Digital Pin 4`

to something like

```
`#define Z_STEP_BIT      0`.

```

This should clear up pin 4 to be setup as a input/output in your main sketch. Another pin definition associated with the Zed axis is

```
`#define Z_DIRECTION_BIT   7  // Uno Digital Pin 7`

```

Clear that one out, and you should be able to use pin 7 as an I/O.

I haven't personally tested the code so give it a try. Also just a heads up will probably run into errors while trying to use the MPU6050 library as well as grbl library, the grbl library is a LOT of code (I didn't spend enough time trying to compile so I don't know how much space it's actually using, but it's a lot). You might also run into timer errors as both libraries most likely reconfigure timers to work with each.

I hope this was a bit helpful!

EDIT:

I realized I didn't specify how to exactly free up A5. It has been assigned to the probe in the cpu\_map.
> 0 votes

---
Tags: arduino-uno, mpu6050, a4988
---


# Question
Title: How to convert this sketch to keep only one if-else statement?
```
int ldrPin = A0;
int rainPin = A1;
int smokePin = A2;
int greenLED = 6;
int redLED = 7;

// you can adjust the threshold value
int thresholdValue = 500;
int LightSensorThreshold = 500;
int RainSensorThreshold = 500;

void setup() {
  pinMode(ldrPin, INPUT);
  pinMode(greenLED, OUTPUT);
  pinMode(redLED, OUTPUT);
  digitalWrite(greenLED, LOW);
  digitalWrite(redLED, LOW);
  Serial.begin(9600);

  pinMode(rainPin, INPUT);
  pinMode(greenLED, OUTPUT);
  pinMode(redLED, OUTPUT);
  digitalWrite(greenLED, LOW);
  digitalWrite(redLED, LOW);
  Serial.begin(9600);

  pinMode(smokePin, INPUT);
  pinMode(greenLED, OUTPUT);
  pinMode(redLED, OUTPUT);
  digitalWrite(greenLED, LOW);
  digitalWrite(redLED, LOW);
  Serial.begin(9600);
}

void loop() {
  int lightSensorValue = analogRead(ldrPin);
  Serial.print(lightSensorValue);

  if(lightSensorValue < LightSensorThreshold){
    Serial.println(" - light");
    digitalWrite(greenLED, LOW);
    digitalWrite(redLED, HIGH);
  }
  else {
    Serial.println(" - dark");
    digitalWrite(greenLED, HIGH);
    digitalWrite(redLED, LOW);
  }
  delay(500);

  int rainSensorValue = analogRead(rainPin);
  Serial.print(rainSensorValue);

  if(rainSensorValue < RainSensorThreshold){
    Serial.println(" - It's wet");
    digitalWrite(greenLED, LOW);
    digitalWrite(redLED, HIGH);
  }
  else {
    Serial.println(" - It's dry");
    digitalWrite(greenLED, HIGH);
    digitalWrite(redLED, LOW);
  }
  delay(500);

  int smokeSensorValue = analogRead(smokePin);
  Serial.print(smokeSensorValue);

  if (smokeSensorValue < thresholdValue) {
    Serial.println(" - Smoke");
    digitalWrite(redLED, LOW);
    digitalWrite(greenLED, HIGH);
  }
  else
  {
    Serial.println(" - No Smoke");
    digitalWrite(redLED, HIGH);
    digitalWrite(greenLED, LOW);
  }
  delay(100);

}

```

# Answer
Sure:

Change these int's to byte, none have values more than 255:

```
int ldrPin = A0;
int rainPin = A1;
int smokePin = A2;
int greenLED = 6;
int redLED = 7;

```

Take these out of setup(), analog input pins don't need this:

```
pinMode(ldrPin, INPUT);
pinMode(rainPin, INPUT);
pinMode(smokePin, INPUT);

```

Take out the duplicates of these lines, pinMode() and turning them off (if LOW is off) only needs to be called once for each

```
pinMode(greenLED, OUTPUT);
pinMode(redLED, OUTPUT);
digitalWrite(greenLED, LOW);
digitalWrite(redLED, LOW);

```

Get rid of two the Serial.begin(9600) lines, calling it once is enough.

Within loop(), get rid of the int's. Those variables were already globally declared, you don't need to re-declare them as type int.
> -1 votes

# Answer
First find the duplicated code.

E.g. the fragment

```
  int lightSensorValue = analogRead(ldrPin);
  Serial.print(lightSensorValue);

  if(lightSensorValue < LightSensorThreshold){
    Serial.println(" - light");
    digitalWrite(greenLED, LOW);
    digitalWrite(redLED, HIGH);
  }
  else {
    Serial.println(" - dark");
    digitalWrite(greenLED, HIGH);
    digitalWrite(redLED, LOW);
  }
  delay(500);

```

is repeated three times.

Then find *within* the duplicate code fragments, the differences, which are:

* the pin number
* the value to check against.
* the two texts

Then make a new function containing one duplicated code fragment, and replace the differences, by variables which you pass in the function as arguments:

```
void checkSensor(int pin, int sensorLimitValue, char* okText, char* warningText)
{
  int sensorValue = analogRead(pin);
  Serial.print(sensorValue);

  if(sensorValue < sensorLimitValue) {
    Serial.println(okText);
    digitalWrite(greenLED, HIGH);
    digitalWrite(redLED, LOW);
  }
  else {
    Serial.println(warningText);
    digitalWrite(greenLED, LOW);
    digitalWrite(redLED, HIGH);
  }
  delay(500);
}

```

And call respectively:

```
checkSensor(ldrPin       , LightSensorThreshold, " - light"   , " - dark");
checkSensor(rainSensorPin, RainSensorThreshold , " - it's wet", " - it's dry");
checkSensor(smokePin     , thresholdValue      , " - Smoke"   , " - No Smoke");

```

I switched the green/red values, because I assume when the value is lower than the limit, the green LED should be on, and otherwise the red LED.

Btw, why not use `smokeSensorThreshold` instead of `thresholdValue` to keep it consistent with the other duplicated code fragments?
> 2 votes

---
Tags: arduino-uno, sensors, c++
---


# Question
Title: How do I know if my Arduino is connected to my LEDs?
I have an Arduino Uno and a string of WS2811 LEDs. I am still trying to get started on this project, which is creating a Stranger Things wall. I've installed FastLED and uploaded the sample program "Blink" to the Arduino, which appears to upload correctly. However, the lights don't blink.

Notes: \- When I plug the string of lights into a power source (when disconnected from the Arduino), they briefly light up red and then turn off. I don't know if this means there's something wrong with the power setup. (I don't know if they are supposed to stay on.) \- Here's a photo of my connection from the Arduino to the LEDs

* Here's the setup I'm trying to follow.

Thanks in advance for any help!

# Answer
> 2 votes
The sample code sets the data pin to 3, but I was using 6. Noob mistake.

---
Tags: led
---


# Question
Title: Can I measure velocity from an accelerometer? How accurately?
I've bought this module

Kootek GY-521 MPU-6050 MPU6050 Module 3 Axis analog gyro sensors+ 3 Axis Accelerometer Module

My project will involve affixing this to a moving object, moving at velocities varying from 0.1 to 1.0 meters per second.

From what I understand, this module will allow me to infer rotation and acceleration, will I be able to derive velocity?

How much accuracy can I expect?

# Answer
> 6 votes
The sensor in itself can't provide you the velocity. I have used it accelerometers in a couple of projects the easiest way to get the velocity is to constantly monitor acceleration changes and calculate velocity instantaneaously.

In order to do so follow these instruction. Pleas note that this is only 1 axis reading in actual case you will have to perform this for all three axis i.e. x,y and z.

I hope you are aware of the equation of motion (V = Vo + at)... The sensor will provide you value of acceleration at any given time. But acceleration can vary quite significantly during a huge time intervals so keep the time intervals 't' small. Lets say t = 10ms (depends on you). So calculate V after every 10ms intervale and this will give you current velocity at any given time. But what about Vo? As you know it is refered to as initial velocity so in the beginning it will be 0. Immediately after first reading when you are about to take second reading the Vo will change to the previous V calculated and hence forth.

This means Vo at any given interval is actually the V calculated in the previous interval.

I tried this method in my project when using accelerometer. hope it helps you as well.

# Answer
> 4 votes
I work with Arduino-based autopilot modules, which usually use similar sensors in addition to GPS data to maintain a reasonable estimate of its position/velocity/acceleration. If you were to add other sensors (i.e. a GPS) to your project, it might be worth looking into Extended Kalman Filters (https://github.com/simondlevy/TinyEKF), which are usually able to provide fairly accurate results.

If you're only using an accelerometer, EKF would probably be overkill, so you could look into other noise-reduction techniques. For example, using a weighted average of the last two readings:

```
// alpha is value between 0 and 1
acceleration = alpha * readAccelerationSensor() + (1 - alpha) * lastSensorReading

```

Another strategy to filter out noise would be to take multiple sensor readings at each time step and use the median value to integrate for velocity.

# Answer
> 1 votes
I don't think that will be possible. If my understanding of accelerometers is correct, they measure acceleration. Then you have a situation when the speed is constant. Acceleration = 0, according to Newton's laws.

You would have to keep track of changes in acceleration then perform math to maintain the state. As @Chris Stratton suggest, that will lead to keep integrating the error to the very likely situation of getting a meaningless value.

However, I have never worked with an accelerometer before, so it can be possible at a certain extent.

It would be great to hear from someone who actually tried this.

# Answer
> 0 votes
I think that calculating the instantaneous velocity as described by Usama is the correct method so long as you can deal with the cumulative error. I would also suggest that you provide regular recalibration to deal with that (like a return to home).

However, if you are trying to calculate velocity the best method would be to use a gyroscope, not an accelerometer.

Gyroscopes were (are?) how submarines navigate underwater. To measure acceleration with gyro sensors it is of course the rate of change of the velocity. V = Vo + at and d = Vo.t + (a.t^2)/2 are your two most important formulas.

Which you choose depends upon your application. I would chose either based on whether my application is more likely to have constant velocity or frequently accelerating and decelerating. Maybe even have both...

I have not experimented with digital gyro sensors but note that there are a couple of Arduino shields available.

# Answer
> -1 votes
Use to compass + accelerometer Use compass to eliminate g from the readings

---
Tags: arduino-uno, bluetooth, accelerometer
---


# Question
Title: How to build a robot that can stop at a certain point using an altimeter
I am thinking about creating a robot that climbs vertically and stops at a certain point. I thought about using an altimiter in order to measure the distance, however, I dont know how to create a code for it. Where would you start with it, can it be done with MATLAB?

Thanks for everything :)

# Answer
> 2 votes
have fun playing with the Arduino and some sensors! It is a great platform to learn. For your task, look into the Bosch sensor modules BME280 (pressure with temperature and humidity) or BMP280 (just pressure). You can expect maybe +-1 meter of accuracy. Or check the precision version BME388 that could give you +-50cm. Go to the adafruit shop and try a few of the breakout boards. They provide great library and documentation support.

In order to get absolute altitudes, you need to factor in ambient air pressure. A good source for that are METAR reports issued for aircraft. There are many online sources where you can get the so called *altimeter setting* for an airport close to you. Airplane altimeters actually just show the altitude above a standard pressure plane, so you need to compensate for whatever pressure the current weather gives you.

For higher precision, you pretty soon have to integrate barometric pressure, GPS altitude, and maybe other sensors, with some serious math. This is where MATLAB fits in.

---
Tags: arduino-uno
---


# Question
Title: Where does the sound come from this board?
As the question says, i can't figure out where the sound comes from on this board that i bought, nothing on the manuals and can't see any speaker on the board... It is a "RFID Proximity Entry Door Secure Lock Access Control System"

Thanks.

# Answer
this is a PCB mountable piezo buzzer. it makes sound in your "RFID Proximity Entry Door Secure Lock Access Control System"
> 0 votes

# Answer
That looks like a piezo buzzer, the component that had the sticker on it. It's likely louder now, with the sticker removed.
> 1 votes

---
Tags: sound
---


# Question
Title: UART connection between Arduino Nano and NodeMCU
I'm trying to create an UART connection between a Nano and an NodeMCU, running MicroPython.

Code for trying is meaningless - Arduino says "HI", and ESP8266 should receive and print msg value.

Connections :

Nano Rx --\> ESP Tx

Nano Tx --\> ESP Rx

Nano USB -- \> Mac running `repl`

ESP USB --\> Linux running `Arduino IDE`

BUT- when I physically connect as described the ESP BOARD freezes, in a way I can't even connect it using `repl`. Only after disconnecting wires (not only powering off the Nano), ESP unfreezes.

Appreciate any help.

# Answer
You can't connect the same Serial to a computer over USB and to a Nano at the same time. Not only because the Nano is on 5 V which disturbs the 3.3 V side of the USB converter.

Disconnect the NodeMCU from computer, try to power it from Nano's 3.3 V pin (not for WiFI) and don't forget to connect ground between the MCUs.

Nano has one Serial, which is connected over USB to computer too. So there too you can't use the USB and RX TX pins at the same time. You could use SoftwareSerial to connect to NodeMCU.

The Nano TX to esp8266 RX should have logic level conversion to not to send 5V to esp8266 3.3V pin.
> 1 votes

---
Tags: esp8266, uart
---


# Question
Title: Mac shortcut for next window - IDE 1.8.7 problem
How do I use the keyboard to cycle through Arduino windows on a mac?

In my System preferences, I have (default):

`Keyboard` -\> `Shortcuts` -\> `Move focus to next window` =  `Cmd ⌘`   ```

It works perfectly in all other programs, but in the Arduino IDE, it only swaps between the last two windows. If I have three(or more) windows open, it is a real pain to find the one in the background.

I am using fully updated MacOS 10.14 and Arduino IDE 1.8.7

# Answer
In MacOS 10.14 and Arduino IDE 1.6.12, `cmd```` cycles through 5+ IDE windows properly, for me.

Update:

> When you upgrade to Arduino 1.8.7,

I won't be. I've tried a couple of its point releases and have given up on it because its launch performance is so p...-poor. Maybe 1.9 will finally fix it.

Sloeber/Eclipse is my serious code-crunching IDE. I keep the A-IDE around for reference and for quick knock-off experiments because it's quick to launch.

Update 2:

The OP asked me to note that he

> found that  `Cmd ⌘`   `Shift`   ```  cycles through *all* windows (maybe in reverse).

Update 3:

> In older IDE the reverse cycling with Shift doesn't work?

It works in both directions for me (shifted/unshifted).
> 4 votes

# Answer
Just by trying, I found that  `Cmd ⌘`   `Shift`   ```  cycles through *all* windows (maybe in reverse).
> 3 votes

---
Tags: arduino-ide, mac-os
---


# Question
Title: Is there a board that can act as both a USB host and client for HID devices?
Trying to build an arduino-based Mouse/Keyboard enhancer. This will let me do things like press certain keyboard or mouse shortcuts on the input side, then do something custom on the output side. For instance, this would let me add keyboard shortcuts at the hardware level instead of having to do them at the OS level.

As such, I'm looking for a board which can act both as a USB host (i.e. it can have a keyboard and mouse plugged into it) as well as one that can show up as a USB HID device to the computer it's plugged into.

The boards that I'm aware of which have something close to this are the Leonardo and chip-similar, which work to emulate a keyboard/mouse to the computer they're attached to, but which don't let you connect a keyboard/mouse to them.

So is there such a board?

# Answer
> 1 votes
The TMK USB to USB converter is a thumb drive sized board with ATMega32u4 and max3421e with pass through/remapper software. It has the same functionality as a Leonardo with USB host shield.

https://geekhack.org/index.php?topic=69169.0

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


title: Is there a key switch for Arduino?

text:
# Question
Title: Is there a key switch for Arduino?
I am trying to make a launch controller, which will turn on with a key. Like the one in this photo below:

# Answer
Check for example here for a key switch (see picture below).

As you can see it has two pins. If the pins are connected the switch is closed (same like a normal switch). So you can just connect one wire to VCC / 5V and the other via a high value resistor to a GPIO pin and check for LOW or HIGH.

(note: in practice it's possible to use almost any (electric/mechanical) component as long as the number of pins is not too high to be reasonably used by an Arduino).
> 1 votes

# Answer
A key switch is just a normal switch. What you do with it depends on how you wire it and code for it.
> 1 votes

---
Tags: arduino-uno, switch
---


# Question
Title: Bridging the wifi networks on nodemcu: how to set the esp8266 as wifi extender, simplest case
It seems to me that humidity is getting high in one room in the basement in my house. To monitor the situation temporarily, I would like to build a very small wifi-mesh network to exchange these humidity data to a locally installed raspberry pie server. Most of the time the networking would be in idle state, every some 5 minutes sending the humidity sensor data over mqtt to the server.

What is the simplest code that sets up an esp8266 to connect to an existing wifi network and act as an access point and wifi extender a couple of yards further?

I tried this code:

```
#include <ESP8266WiFi.h>
#include <ESP8266WebServer.h>

const char* ssid = "SSID_Internet";
const char* password = "qaz12345";

const char* newssid = "SSID_Extender";
const char* newpassword = "qaz12345";

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

  // set both access point and station
  WiFi.mode(WIFI_AP_STA);
  WiFi.softAP(newssid, newpassword);

  Serial.print(newssid);
  Serial.print(" server ip: ");
  Serial.println(WiFi.softAPIP());

  WiFi.begin(ssid, password);
  int wifi_it = 0;
  int wifi_status;
  while ((wifi_status = WiFi.status()) != WL_CONNECTED) {
    Serial.println("Trying to connect to wifi");

    wifi_it++;
    delay(500);
  }

  Serial.println("");
  Serial.println("WiFi connected");
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());

  long rssi = WiFi.RSSI();
  Serial.print("Signal strength: ");
  Serial.print(rssi);
  Serial.println("dBm");
}

void loop(void){

}

```

It successfully registers the esp8266 to the wifi, sets up an AP, but if I connect to SID\_Extender with my mobile phone, the internet traffic is not forwarded further.

There are projects that allows to configure multiple esps in user friendly manner, but I am wondering how to setup such an esp myself.

# Answer
> 1 votes
The esp8266 will not bridge the networks. You can perhaps bridge the communication from your other ep8266 on the TCP level with WiFiServer and WiFiClient. Send the sensor value to middle esp8266 running AP and it sends the value to Raspberry.

With MQTT you could create some MQTT proxy. Receive the data with WiFiServer and forward it with WiFiClient. without parsing or anything, only copying the chars between servers client and local client in booth directions

something like this (not tested):

```
void loop() {

  if (!serverClient || !serverClient.connected()) {
    serverClient = server.available();
  }
  if (!serverClient || !serverClient.connected()) {
    if (client.connected()) {
      client.stop();
    }
    return;
  }

  if (!client || !client.connected()) {
    if (!client.connect(raspiIP, MQTT_PORT)) {
      Serial.println("Can't connect to MQTT");
      delay(1000);
      return;
    }
  }

  while (serverClient.available() > 0) {
    client.write(serverClient.read());
  }
  while (client.available() > 0) {
    serverClient.write(client.read());
  }
}

```

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


# Question
Title: Memory leakage caused by String Concatenation
In this link, section "Memory, memory, memory" it's been told that doing many String concatenations in sequence, e.g.: using operator+() multiple times, will cause memory fragmentation, which may lead to the fact that total heap not being totally used.

An alternative I'm suggesting is using strcat() with char buffers and not using Strings at all, and then convert from resultant char buffer to String if a String is needed at the end? Would that be an escape from fragmentation of the heap?

Clarification: I will specify the upper bound of the char buffer beforehand, as if I know the maximum needed/to-be-used size.

# Answer
If you size the buffer to be able to hold your final string, then yes, that method will avoid the fragmentation caused by the `String` concatenation function.

Note that `String` holds the string as a C-style char array internally; it is the concatenation procedure which dynamically allocates and deallocates memory, causing the fragmentation.
> 2 votes

# Answer
Your method would *reduce* the fragmentation. But will your application need do this once? A few times? Must it run forever? If your application uses malloc()/free() or new/delete pairs often, it will fragment the heap, causing it to grow, and eventually cause a stack collision. This is not so much about the Arduino being a resource-limited device; it will eventually happen in any continuously running device with a fixed amount of memory.

If you can set an upper bound to the buffer requirements, then pre-allocating a buffer-pool globally, locally as a file-level- or local-static, or on the heap (using malloc() \[1\]) - an array of "big-enough" buffers and enough of them for your application. Then always allocate/de-allocate one of these and you will avoid fragmentation. Your application (or buffer-handler library) will have to keep track of which buffers are free and which are in use, just as the system allocators do. But in exchange for writing this way, you get to allocate and deallocate memory, forever, fragmentation-free. Every request, and every return is the same size, so any free piece can fill a request with no need to grow the pool.

My personal preference is a static allocation (file-level or globally visible) because 1) it comes from lower memory which has the same effect as allocating it on the heap, and 2) it is declared as an array of arrays so array-indexing syntax works without manually having to write around it as you might if you malloc()ed on big chunk.

Note\[1\]: Though I have cautioned against using malloc() and free() calls, here and elsewhere on the site, the cause of fragmentation is repeated allocation and de-allocation from/to the heap. In this case, though, I'm suggesting using malloc() to allocate memory which will be kept for the rest of the program run.
> 1 votes

---
Tags: esp8266, c++, string
---


title: how to increase the range of KY-005?

text:
# Question
Title: how to increase the range of KY-005?
I am using a KY-005 with an Arduino Uno. I have the knowledge that Arduino can provide a forward current of 40 mA. How can I make it to 55 mA or above upto 60 mA to unlock its full potential, so as to get efficient IR communication without data being distorted at the KY-022 IR receiver?

# Answer
First, I think 40 mA to output from a GPIO is not a wise idea, because those are Arduino Pin Current Limitations.

What you can do is:

* The VCC pin can handle 200 mA. So you can use this pin to power your KY-005 and use a transistor to switch it via a GPIO (much less than 40 mA is needed for that).
* Or (high likely not needed): use an external power source and use a transistor in the same way.

For knowing all details about using a transistor this way, google for "transistor as switch".
> 1 votes

---
Tags: arduino-uno, remote-control, infrared
---