title: Changing Baud Rate not working

text:
# Question
Title: Changing Baud Rate not working
I have copied this code from Github :

```
 #include <Wire.h>
 #include <MPU6050.h>

MPU6050 mpu;

// Timers
unsigned long timer = 0;
float timeStep = 0.01;

// Pitch, Roll and Yaw values
float pitch = 0;
float roll = 0;
float yaw = 0;

void setup()
{
    Serial.begin(115200);
    //Serial.begin(9600);

    // Initialize MPU6050
    while(!mpu.begin(MPU6050_SCALE_2000DPS, MPU6050_RANGE_2G))
    {
         //Serial.println("Could not find a valid MPU6050 sensor, check
               wiring!");
     }

     // Calibrate gyroscope. The calibration must be at rest.
     // If you don't want calibrate, comment this line.
    //mpu.calibrateGyro();

     // Set threshold sensivty. Default 3.
     // If you don't want use threshold, comment this line or set 0.
      mpu.setThreshold(1);
   }

   void loop()
      {
       timer = millis();

      // Read normalized values
     Vector norm = mpu.readNormalizeGyro();

     // Calculate Pitch, Roll and Yaw
      pitch = pitch + norm.YAxis * timeStep;
       roll = roll + norm.XAxis * timeStep;
       yaw = yaw + norm.ZAxis * timeStep;

         // Output raw
      //Serial.print(" Pitch = ");
         Serial.print(pitch);
           Serial.print(":");
        //Serial.print(" Roll = ");
     Serial.print(roll);
        Serial.print(":");
       //Serial.print(" Yaw = ");
        Serial.println(yaw);

           // Wait to full timeStep period
      delay((timeStep*1000) - (millis() - timer));
     }

```

**Now the question is, whenever I try to change the baud rate Serial Monitor becomes empty.**

*How can this be resolved?*

Some screen-shots :

Stuck!!!

# Answer
You are not very much clear but these are the possible reasons for your problem.

1. You are using a while loop in your setup() function in your code. Your code might get stuck in there that's why you are not able to see pitch and roll. Try removing comment from the Serial.begin function over there.
2. After Changing baudrate in your code please make sure you are changing it on your serial monitor as well.
> 1 votes

---
Tags: arduino-uno, accelerometer, mpu6050, gyroscope, baud-rate
---


title: How to Simulate and Tune a PID

text:
# Question
Title: How to Simulate and Tune a PID
I've been trying to simulate a PID using Brett Beauregard's PID library in order to understand it better. Here is my code.

```
#include <PID_v1.h>

const unsigned int numReadings = 500;
double analogVals[numReadings];
unsigned int i = 0;
int angle = 0;
//Define Variables we'll be connecting to
double Setpoint, Input, Output;
//Specify the links and initial tuning parameters
PID myPID(&Input, &Output, &Setpoint,2,5,1, DIRECT);
void setup()

{
  //turn the PID on
  myPID.SetMode(AUTOMATIC);
  Serial.begin(115200);
  Setpoint = 300;
  myPID.SetOutputLimits(-2,2);
  myPID.SetSampleTime(100);
  Input = random(292, 302) ;
}

void loop()
{
  if (i % 2 == 0) {
  Input += random(-2,3);
  }
  angle += 1 % 360;
  Input += sin(angle*355/(113*180));
  myPID.Compute();
  Input += Output;
    analogVals[i] = Input;
    i++;
    if (i>= numReadings)
    {
      for (int j = 0; j < i; j++) {
      Serial.println(analogVals[j]);
      }

      i = 0; //reset to beginning of array, so you don't try to save readings outside of the bounds of the array
    }
}

```

Even if I restrict the output of the PID to a very small value, I get huge nonsense results of this code. It oscillates like -1000 to 1000. I've read this https://robotics.stackexchange.com/questions/167/what-are-good-strategies-for-tuning-pid-loops and tried to adjust my parameters, but they're just shots in the dark really, I can't even damp these massive oscillations. How would I tune a PID to cancel out a sin error ?

Thanks in advance

# Answer
> 1 votes
I do not have your PID\_v1.h, but I made a simple experiment trying to control your example with a simple P-Controller instead of the PID lib. I made the following changes to your code:

```
...
double K_P = 1;
...
//myPID.Compute();
  Output = K_P*(Setpoint - Input);
  Input += Output;

```

This is working for very small amounts of `K_P`, but as soon as `K_P` gets higher than 2.0 it gets instable very fast. I guess this is what you are observing. The reason for me is, that you have implemented a ideal control path. In real control tasks you will always have some transfer behavior

Therefore I added a simple PT1 element (first-order lag element) to your code, now your system is much more stable and you can experiment with the K, I and D factors. Here it works with K\_P even higher than 400:

```
// #include <PID_v1.h>

const unsigned int numReadings = 500;
double analogVals[numReadings];
unsigned int i = 0;
int angle = 0;
//Define Variables we'll be connecting to
double Setpoint, Input, Output;
double Input_PT1;
double K_P = 20;
//Specify the links and initial tuning parameters
//PID myPID(&Input, &Output, &Setpoint,2,5,1, DIRECT);
void setup()

{
  //turn the PID on
  // myPID.SetMode(AUTOMATIC);
  Serial.begin(115200);
  Setpoint = 300;
  // myPID.SetOutputLimits(-2,2);
  //myPID.SetSampleTime(100);
  Input = random(292, 302) ;
}

void loop()
{
  if (i % 2 == 0) {
    Input += random(-2, 3);
  }
  angle += 1 % 360;
  Input += sin(angle * 355 / (113 * 180));
  //myPID.Compute();
  Output = K_P * (Setpoint - Input_PT1);
  Input += Output;
  // start PT1
  Input_PT1 -= Input_PT1 / 25;
  Input_PT1 += Input / 25;
  // end PT1
  analogVals[i] = Input_PT1;
  i++;
  if (i >= numReadings)
  {
    for (int j = 0; j < i; j++) {
      Serial.println(analogVals[j]);
    }

    i = 0; //reset to beginning of array, so you don't try to save readings outside of the bounds of the array
  }
}

```

Some hint:

* The sketch above does not initialize `Input_PT1`, so it takes some secondes until you reach a steady value of 300, if you do not want to wait, just initialize `Input_PT1` with 300. But this is exactly where you can start increasing first I, then D factors to try to increase speed for reaching a steady value of 300 and experiencing what influence I and D part will have.
* `Input_PT1` is not a good naming, since this is the output of the PT1 element, but since you are using it as the PID Input, I did not change.

Here a drawing of what I implemented in contrast to your sketch (at least I hope so ;-))

---
Tags: code-review, pid
---


title: UART ESP and MEGA2560

text:
# Question
Title: UART ESP and MEGA2560
Could someone help me with some suggestions please? Using ESP8266 and MEGA2560 on UART interface i want to display the message received on the mega serial to the LCD connected to it on i2c. The problem is that the LCD shows some strange unknown character and the serial monitor corresponding to mega shows this :

```
LED on LED OFF LED on LED OFF LED on LED OFF LED on LED OFF LED on LED OFF LED on LED OFF LED on LED OFF LED on LED OFF LED on LED OFF LED on

```

when it should display this:

```
LED on
LED OFF
LED on
LED OFF
LED on
LED OFF
LED on
LED OFF
LED on
LED OFF
LED on
LED OFF
LED on
LED OFF
LED on
LED OFF
LED on
LED OFF

```

the code for ESP is this:

```
int pinLed = 16;
void setup()
{

 Serial.begin(115200);
 Serial.begin(115200);
 pinMode(16,OUTPUT);
 delay(500);
}

void loop()
{

digitalWrite(16,HIGH);
Serial.print("LED on\n");
delay(5000);

digitalWrite(16,LOW);
Serial.print("LED OFF\n");
delay(5000);

}

```

the code for mega is this:

```
#include <Wire.h>
#include <LiquidCrystal_I2C.h>
#include<SoftwareSerial.h>
LiquidCrystal_I2C lcd(0x3F,20,4);

void setup()
{

  Serial.begin(115200);
  lcd.init();
  lcd.backlight();
  while (!Serial)
  {

    Serial.print("Attempting to connect! ");
    Serial.print("Trying again...");
  }
}

  void loop()
{

  if (Serial.available()>0)

  {
    char c = Serial.write(Serial.read());
    Serial.print(c);
    lcd.print(c);
  }
}

```

# Answer
> 2 votes
Solution to your problems.

1. Use println instead of print.
2. Change `char c = Serial.write(Serial.read());` to `char c = Serial.read();`

# Answer
> -1 votes
Use:

```
println *emphasized text*

```

instead of

```
print *emphasized text*

```

---
Tags: serial
---


title: Fading led with push button

text:
# Question
Title: Fading led with push button
I need to make for school a project. That when i hold a button it fades. But when you let go the button it needs to stop immediately. But when i you hold the button again it needs to start again with fading but the brightness needs to start from 0. I have a program but when i press again it just starts from the previous brightness. Pls help. This is my code:

```
int led = 9;
int brightness = 5;
int fadeAmount = 5;

void setup() {
   Serial.begin(9600);
    pinMode(led, OUTPUT);
}
void loop() {
  int val = digitalRead(2);
  Serial.println(val);
if (val==HIGH){
  analogWrite(led, brightness);
  brightness = brightness + fadeAmount;
  if (brightness <= 0 || brightness >= 255) {
    fadeAmount = -fadeAmount; }
  delay(100);
}
else{

  digitalWrite(9, LOW);
}
}

```

# Answer
The main problem is you have to reset brightness to 0 when the switch is LOW. Btw, I did not test the sketch, only compiled it.

```
int led = 9;
int brightness = 5;
int fadeAmount = 5;

void setup() {
   Serial.begin(9600);
    pinMode(led, OUTPUT);
}
void loop() {
  int val = digitalRead(2);
  Serial.println(val);
if (val==HIGH){
  analogWrite(led, brightness);
  brightness = brightness + fadeAmount;
  if (brightness <= 0 || brightness >= 255) {
    fadeAmount = -fadeAmount; }
  delay(100);
}
else{

  digitalWrite(9, LOW);
  brightness = 0;    // Restart with brightness 0
}
}

```

Some other improvements result in:

```
#define LED_PIN      9
#define DELAY_TIME 100
int brightness = 5;
int fadeAmount = 5;

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

void loop() {
  int switchButton = digitalRead(2);
  Serial.println(switchButton);

  if (switchButton == HIGH) {
    analogWrite(LED_PIN, brightness);
    brightness += fadeAmount;
    if ((brightness <= 0) || (brightness >= 255)) {
      fadeAmount = -fadeAmount;
    }
    delay(DELAY_TIME );
  }
  else {
    digitalWrite(LED_PIN, LOW);
    brightness = 0;    // Restart with brightness 0
  }
}

```

Explanation

1. Always indent your code (so that { and } are clear, notice each new { increases the indentation by two spaces, each } decreases the indentation by two spaces.
2. For values that do not change use a #define. This prevents (in this case) a few bytes not be stored in valuable memory space. Especially if you would use arrays this is important.
3. You used 9 in `digitalWrite(9, LOW);` which was probably a mistake, always use defines wherever possible. I also would use `#define DELAY_TIME 100` instead of the hardcoded 100 value.
4. I addes some spaces before/after values (like `switchButton == HIGH`). It doesn't matter if you do or not, but be consequent.
5. Use good variable names (`switchButton` is more clear than `val`.
6. Use `brightness += fadeAmount;` instead of `brightness = brightness + fadeAmount;`; this is the normal way of increasing (or decreasing/multiplying/whatever) the value of a variable.
7. Use ( and ) in non trivial if statements like `if ((brightness <= 0) || (brightness >= 255))`, this could save you hours of searching in case you ever make a mistake (in this case there is no functional change).

Good luck with your project.
> 1 votes

---
Tags: arduino-uno
---


title: MAX7219 and Arduino

text:
# Question
Title: MAX7219 and Arduino
I am getting started in running this 8x8 led on an Arduino. Regardless of which tutorial sketch I attempted, I never got a scrolling text that I expect. What happens seems to be only a single (out of four) led module being addressed at a time, resulting in, for example, the message being scrolled on one module at a time, but all four in succession. Could it be a module problem?

# Answer
Got it somewhat working by changing:

```
#define HARDWARE_TYPE MD_MAX72XX::FC16_HW
to:
#define HARDWARE_TYPE MD_MAX72XX::ICSTATION_HW
But still a little problem with the last character in a message not showing all leds lit until it starts to scroll after the initial program delay. Then all is fine.
Anyone want to address that issue? My sketch follows:

{    // Use the Parola library to scroll text on the display
//
// Demonstrates the use of the scrolling function to display text received
// from the serial interface
//
// User can enter text on the serial monitor and this will display as a
// scrolling message on the display.
// Speed for the display is controlled by a pot on SPEED_IN analog in.
// Scrolling direction is controlled by a switch on DIRECTION_SET digital in.
// Invert ON/OFF is set by a switch on INVERT_SET digital in.
//
// UISwitch library can be found at https://github.com/MajicDesigns/MD_UISwitch
// MD_MAX72XX library can be found at https://github.com/MajicDesigns/MD_MAX72XX
//

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

// set to 1 if we are implementing the user interface pot, switch, etc
#define USE_UI_CONTROL 0

#if USE_UI_CONTROL
#include <MD_UISwitch.h>
#endif

// Turn on debug statements to the serial output
#define DEBUG 0

#if DEBUG
#define PRINT(s, x) { Serial.print(F(s)); Serial.print(x); }
#define PRINTS(x) Serial.print(F(x))
#define PRINTX(x) Serial.println(x, HEX)
#else
#define PRINT(s, x)
#define PRINTS(x)
#define PRINTX(x)
#endif

// Define the number of devices we have in the chain and the hardware interface
// NOTE: These pin numbers will probably not work with your hardware and may
// need to be adapted
//#define HARDWARE_TYPE MD_MAX72XX::FC16_HW
//#define HARDWARE_TYPE MD_MAX72XX::GENERIC_HW
#define HARDWARE_TYPE MD_MAX72XX::ICSTATION_HW
#define MAX_DEVICES 4
#define CLK_PIN   13
#define DATA_PIN  11
#define CS_PIN    10

// HARDWARE SPI
MD_Parola P = MD_Parola(HARDWARE_TYPE, CS_PIN, MAX_DEVICES);
// SOFTWARE SPI
//MD_Parola P = MD_Parola(HARDWARE_TYPE, DATA_PIN, CLK_PIN, CS_PIN, MAX_DEVICES);

// Scrolling parameters
#if USE_UI_CONTROL
const uint8_t SPEED_IN = A5;
const uint8_t DIRECTION_SET = 8;  // change the effect
const uint8_t INVERT_SET = 9;     // change the invert

const uint8_t SPEED_DEADBAND = 5;
#endif // USE_UI_CONTROL

uint8_t scrollSpeed = 25;    // default frame delay value
textEffect_t scrollEffect = PA_SCROLL_LEFT;
textPosition_t scrollAlign = PA_LEFT;
uint16_t scrollPause = 2000; // in milliseconds

// Global message buffers shared by Serial and Scrolling functions
#define BUF_SIZE    75
char curMessage[BUF_SIZE] = { "" };
char newMessage[BUF_SIZE] = { "Got Signals?" };//{ "Hello! Enter new message?" };
bool newMessageAvailable = true;

#if USE_UI_CONTROL

MD_UISwitch_Digital uiDirection(DIRECTION_SET);
MD_UISwitch_Digital uiInvert(INVERT_SET);

void doUI(void)
{
  // set the speed if it has changed
  {
    int16_t speed = map(analogRead(SPEED_IN), 0, 1023, 10, 150);

    if ((speed >= ((int16_t)P.getSpeed() + SPEED_DEADBAND)) ||
      (speed <= ((int16_t)P.getSpeed() - SPEED_DEADBAND)))
    {
      P.setSpeed(speed);
      scrollSpeed = speed;
      PRINT("\nChanged speed to ", P.getSpeed());
    }
  }

  if (uiDirection.read() == MD_UISwitch::KEY_PRESS) // SCROLL DIRECTION
  {
    PRINTS("\nChanging scroll direction");
    scrollEffect = (scrollEffect == PA_SCROLL_LEFT ? PA_SCROLL_RIGHT : PA_SCROLL_LEFT);
    P.setTextEffect(scrollEffect, scrollEffect);
    P.displayClear();
    P.displayReset();
  }

  if (uiInvert.read() == MD_UISwitch::KEY_PRESS)  // INVERT MODE
  {
    PRINTS("\nChanging invert mode");
    P.setInvert(!P.getInvert());
  }
}
#endif // USE_UI_CONTROL

void readSerial(void)
{
  static char *cp = newMessage;

  while (Serial.available())
  {
    *cp = (char)Serial.read();
    if ((*cp == '\n') || (cp - newMessage >= BUF_SIZE-2)) // end of message character or full buffer
    {
      *cp = '\0'; // end the string
      // restart the index for next filling spree and flag we have a message waiting
      cp = newMessage;
      newMessageAvailable = true;
    }
    else  // move char pointer to next position
      cp++;
  }
}

void setup()
{
  Serial.begin(57600);
  Serial.print("\n[Parola Scrolling Display]\nType a message for the scrolling display\nEnd message line with a newline");

#if USE_UI_CONTROL
  uiDirection.begin();
  uiInvert.begin();
  pinMode(SPEED_IN, INPUT);

  doUI();
#endif // USE_UI_CONTROL

  P.begin();
  P.displayText(curMessage, scrollAlign, scrollSpeed, scrollPause, scrollEffect, scrollEffect);
}

void loop()
{
#if USE_UI_CONTROL
  doUI();
#endif // USE_UI_CONTROL

  if (P.displayAnimate())
  {
    if (newMessageAvailable)
    {
      strcpy(curMessage, newMessage);
      newMessageAvailable = false;
    }
    P.displayReset();
  }
  readSerial();
}

```

}
> 1 votes

---
Tags: arduino-uno, led, max7219
---


# Question
Title: How can I tell the resistance of an internal pull-up resistor?
I have a SparkFun ESP8266 Thing Dev board, to which I want to perform a `digitalRead()` on one of the GPIO ports. I'm using `D15`, and I'm configuring it for input like this

```
pinMode(15, INPUT_PULLUP);

```

It does seem to work as intended, and I am able to pull it down by connecting it to ground via a 4.7kΩ resistor.

But how do I know what the actual "correct" resistor would be? I can't find any specs for the internal pullup resistor online. On a related note, I first tried using `D0`, but it didn't seem to have an internal pullup resistor, since even using `INPUT_PULLUP` didn't turn it on.

Perhaps there are specs online and I'm just not able to find them, but is there any other way (measuring?) to find out which pins will work with `INPUT_PULLUP` and if so, what their internal resistance is?

# Answer
io 0 and io 15 are with io 2 boot configuration pins of the esp8266. esp8266 dev boards have external pull-up on io 0 and io 2 and pull-down on io 15.
> 1 votes

# Answer
"The value of internal (built-in) pull-up resistor is between 30Kohm and 100Kohm."

Source: https://bbs.espressif.com/viewtopic.php?t=1079#p4097
> 0 votes

---
Tags: esp8266, voltage-level, input, resistor, pull-up
---


# Question
Title: Can you charge and use a Li-po battery at the same time?
I have a system that uses an Arduino Uno board as a "brain". All the elements in the system are powered by a single Li-po battery (3-cell, 11.1 V, 1800 mAh).

I made a circuit so the Arduino can check the battery voltage and decide when it needs to recharge. I also have a circuit that controls the battery charge sequence and interrupts the power when the battery is charged, sending a signal to the Arduino interrupting its power saving mode. The Arduino enters the power saving mode when the charging sequence is initiated. The charging circuit uses 12 V and 450 mA which I plan to supply with a 12 V, 6 W solar panel.

My question is: can I charge the battery while the Arduino is still on, but in power saving mode?

If not, how can I make this system self-charging while keeping the Arduino on continuously?

# Answer
> 11 votes
> can I charge the battery while the Arduino is still on, but in power saving mode?

You can draw power from a Li-ion battery whilst charging it, but it isn't recommended. This is because the load on the battery affects the ability to detect the different phases of charging, and determine the end-of-charge condition.

Instead you should provide a *bypass* facility so that if external power is applied the external power is routed to the Arduino to power it, but when the power is removed the battery provides the power to the Arduino.

The circuit I usually use is:

simulate this circuit – Schematic created using CircuitLab

When 5 V is applied the battery charges up. Q1 is held off. The 3.3 V regulator is then powered through D1. When the 5 V is removed Q1 is turned on by R1 pulling the gate low and the battery powers the 3.3 V regulator.

# Answer
> 2 votes
Application Note AN1149 by Microchip Inc:

> **It is NOT encouraged to attach the system load directly to Li-ion batteries when using a stand-alone Li-ion battery charge management controller with automatic termination feature.**

## Why not?

> **1. The charge may never end.**

> Most Li-ion battery chargers are based on Constant Current and Constant Voltage (CC-CV) modes. The termination is based on the ratio of charge current and preset constant current (Fast Charge). If the system draws current from the battery, the charge current will never meet the termination value. This causes the non-termination of the charge management circuit.

> **2. The total system current is limited by the charge current.**

> It is because the charger will deliver total system and battery charging current through the output pin. This solution may be feasible for some applications that run on constant current, but it is not recommended.

---

## So what's the alternative?

A load-sharing switch with a P-MOSFET:

> Q1 is OFF when the gate is high and no current flows from the battery cell to the system load

> Q1 is ON when the gate is low and current flows from the battery cell to the system load.

The App Note contains some really good practical advice on component selection, I highly recommend reading it.

# Answer
> 1 votes
If you need to charge it and run at the same time, I would recommend getting a PowerBoost module from Adafruit. They can handle both, and they also have a low-battery indicator.

---
Tags: arduino-uno, solar, lipo, charging
---


title: Prevent function inlining

text:
# Question
Title: Prevent function inlining
I'm trying to shrink the compiled code size, and I have noticed that the compiler inlines functions a lot, even the ones I have not marked "inline", but I can't manage to turn that off.

It looks like the compiler uses the -Os flag by default (optimize for low program size), because when I add it, the resulting program size is the same.

I tried adding "\__attribute\__((noinline))" to the functions but it makes no difference. Any idea how to prevent function inlining?

I'm using Visualmicro on Visual Studio Community 2017. Arduino 1.8.8. Arduino Uno board.

# Answer
As I wrote in the comments, I can't recreate this problem again. So I apologize for wasting everyone's time. But I still find it weird how the -Os flag works. I assumed it meant smallest possible size. But I now think it means "fairly small, but also make it run fast". Look at the code below, and how using the noinline attribute makes the code smaller. I added the -Os compiler flag to be sure, but I think it is already on by default.

```
class InlineClass
{
public:
    void __attribute__((noinline)) testFunc(int arg1)       // 570 bytes
    //void testFunc(int arg1)               // 602 bytes
    //inline void testFunc(int arg1)        // 602 bytes
    {
        _var1 = arg1 + 1;
        _var2 = arg1 + 2;
        _var3 = arg1 + 3;
        _var4 = arg1 + 4;
        _var5 = arg1 + 5;
    }

private:
    volatile int _var1 = 0;
    volatile int _var2 = 0;
    volatile int _var3 = 0;
    volatile int _var4 = 0;
    volatile int _var5 = 0;
};

void setup()
{
    InlineClass ic;
    ic.testFunc(1);
    ic.testFunc(2);
    ic.testFunc(3);
    ic.testFunc(4);
    ic.testFunc(5);
}

```
> 1 votes

# Answer
In my "local.h" file - macros & other definitions I tend to use a lot, just such as one you're asking about - I keep this one:

```
// Don't compile this function inline
//   '__NOINLINE void foo(void){ ... }'
#ifdef __GNUC__
#define __NOINLINE  __attribute__ ((noinline))
#else
#define NOINLINE error 'NOINLINE' not defined for this compiler
#endif

```

which both gives me a fairly simple way to invoke no-inlining, and a warning if I try to use it with a compiler for which I haven't defined its use. You don't really need the macro; you could use the gcc-dependent syntax - I just favor a simpler (and portable) symbol that could be defined for any compiler's no-inline syntax.
> -1 votes

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


# Question
Title: Ardunio Mega/ATmega2560: Using Port F or K for both analog inputs and digital outputs
On an ATmega2560, can ports have some pins used for analog inputs but others as digtial i/o? Specifically, I only need to use 3-5 analog inputs but have many digital inputs. I would like to use the remaining 3-5 pins as digital outputs if possible.

Additionally, does it make a difference if the port in question is Port F vs. Port K? For Port F, the datasheet seems to imply that all 8 of the pins are analog only if the ADC is enabled:

> Port F serves as analog inputs to the A/D Converter.
>
> Port F also serves as an 8-bit bi-directional I/O port, if the A/D Converter is not used.

For Port K, however, the datasheets port description does not have the distinction:

> Port K serves as analog inputs to the A/D Converter.
>
> Port K is a 8-bit bi-directional I/O port with internal pull-up resistors (selected for each bit).

It seems that this is definitely possible for the Arduino Uno/ATmega328P ADC port (except for the ADC6/7 pins for 32-pin form factors), but I can't seem to find anything confirming for the Arduino Mega/ATmega2560 or distinguishing between whether this is done on Port F or Port K

# Answer
> 3 votes
> On an ATmega2560, can ports have some pins used for analog inputs but others as digtial i/o?

Yes, the ADC MUX controls the selection of the pin that is connected to the converter. This is independent of the digital pin control.

Cheers!

PS: See the Arduino core source code for further details on the ADC MUX control registers.

---
Tags: arduino-mega, analogread, adc, atmega2560, digitalwrite
---


title: Hand-held programmable device needed

text:
# Question
Title: Hand-held programmable device needed
Hopefully this question is not too off-topic for this board. I need a ready-made programmable hand-held device with an ethernet-connection. Something like an Arduino with batteries and display and some buttons in a box. This is for my company so a complete ground-up assembly is too expensive and time-consuming in this case. Any hints to companies that produce something like this are welcome. And yes, I tried searching with different search-engines already. :-) Thanks for your time!

# Answer
I have no opinion about this hardware (I don't own it) so please treat my answer as information only. When I was searching through web I found M5Stack

It looks like hardware made for IoT development. It has a LCD and 3 buttons and think it can be programmed using ArduinoIDE. It's designed that you can design any hardware you want and "stack" the device on top of it. Found if available to buy from China for below 30USD.

https://www.youtube.com/watch?v=U2es-l4z2Zg
> 2 votes

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


# Question
Title: Arduino and SIM900 unavailable all the time
I have the a problem with my arduino MEGA 2560 and the SIM900 module. I want to save the outputs of the AT commands, but I never get a chance. If I print mySerial.available() I only get 0. Sending SMS works fine on the other hand.

```
Initializing...
AT+CMGF=1
AT+CNMI=2,2,0,0,0

OK
Done
AT+CMGL="REC UNREAD"

OK
0
0
0
0
0
0
0
0
0
0
0

```

This is the sketch I use:

```
#include <SoftwareSerial.h>

//Create software serial object to communicate with SIM900
SoftwareSerial mySerial(11, 10); //SIM900 Tx & Rx is connected to Arduino #7 & #8
String incoming="";
String incoming2="";
String messages="Test";
String auth_num="+49xxxxxxxxx";
char incoming_char=0;

String response = "";

const byte numChars = 32;
char receivedChars[numChars];
boolean newData = false;

int period = 6000;
unsigned long time_now = 0;

void setup()
{
  //Begin serial communication with Arduino and Arduino IDE (Serial Monitor)
  Serial.begin(9600);

  //Begin serial communication with Arduino and SIM900
  mySerial.begin(9600);

  Serial.println("Initializing...");
  delay(1000);

  mySerial.println("AT+CMGF=1");
  mySerial.println("AT+CNMI=2,2,0,0,0"); // Decides how newly arrived SMS messages should be handled
  //mySerial.println("ATE0");
  updateSerial();
  Serial.println("Done");

  //sms_versenden("xxxxxxxx", "text");
}

void loop()
{
  updateSerial();
  Serial.println(mySerial.available());
  if(millis() - time_now > period){
    time_now = millis();
    if(sms_erhalten()){
      sms_autorisiert();
    }
  }
}

void updateSerial()
{
  delay(500);
  while (Serial.available())
  {
    mySerial.write(Serial.read());//Forward what Serial received to Software Serial Port
  }
  while(mySerial.available())
  {
    Serial.write(mySerial.read());//Forward what Software Serial received to Serial Port
  }
}

void sms_versenden(String rufnummer,String text)
{
  mySerial.println("AT"); //Handshaking with SIM900
  updateSerial();

  mySerial.println("AT+CMGF=1"); // Configuring TEXT mode
  updateSerial();
  if(rufnummer.startsWith("0")){
    rufnummer.remove(0,1);
    mySerial.print("AT+CMGS=\"+49");
    mySerial.print(rufnummer);
    mySerial.println("\"");
  }else if(rufnummer.startsWith("+49")){
    mySerial.print("AT+CMGS=\"");
    mySerial.print(rufnummer);
    mySerial.println("\"");
  }else{
    return;
  }
  updateSerial();
  mySerial.print(text); //text content
  updateSerial();
  mySerial.write(26);
}

boolean sms_erhalten()
{
  mySerial.print("AT+CMGL=\"REC UNREAD\"\r");
  //recvWithEndMarker();
  Serial.println(mySerial.available());
  delay(30);
  while (mySerial.available()){
    String inData = mySerial.readStringUntil('\n');
    Serial.println("Got reponse from SIM900: " + inData);
  }
  /*if(mySerial.available()>0){

    incoming = mySerial.readString();
    Serial.print(incoming);
    delay(10);
  }*/
  updateSerial();
  if(incoming.startsWith("+CMGL:"))
  {
    return true;
  }
  else{
    return false;
  }
}

void recvWithEndMarker() {
    static byte ndx = 0;
    char endMarker = '\n';
    char rc;

    while (mySerial.available() != 0 && newData == false) {
        rc = mySerial.read();
        updateSerial();
        if (rc != endMarker) {
            receivedChars[ndx] = rc;
            ndx++;
            if (ndx >= numChars) {
                ndx = numChars - 1;
            }
        }
        else {
            receivedChars[ndx] = '\0'; // terminate the string
            ndx = 0;
            newData = true;
        }
    }
}

void showNewData() {
    if (newData == true) {
        Serial.print("This just in ... ");
        Serial.println(receivedChars);
        newData = false;
    }
}
String getResponse() {
    while(mySerial.available()>0){
        response += mySerial.read();
    }
    return response;
}

```

Thanks in advance for every idea. Bravodelta

# Answer
Rather than creating your own function used SerialEvent function in arduino. It acts as a serial interrupt in arduino. For example:

```
String inputString;
void serialEvent() {
      while (Serial.available()) {
        // get the new byte:
        char inChar = (char)Serial.read();
        // add it to the inputString:
        inputString += inChar;
        // if the incoming character is a newline, set a flag so the main loop can
        // do something about it:
        if (inChar == '\n') {
          Serial.Println(inputString);
        }
      }
    }

```
> -2 votes

---
Tags: arduino-mega, gsm
---


# Question
Title: Digispark Micro (ATTINY85) not working on Macbook Pro 2016
I just bought 2 Digispark Micro to start learning some Arduino things.

But when I try to upload the code to my Digispark, it just send me an "Device search timed out" error.

My Digispark is plugged with an USB-C to USB connector and the Red dot on the Digispark is working. The connector is working well with any other device.

**Arduino app (1.8.9) settings:**

* Tools
    + Board → Digispark (Default - 16.5 mhz)
    + Programmer → Micronucleus

I tried using the micronucleus CLI, but, even if I try plug/unplug several times (~10s between each unplug/plug) I got this :

```
> Please plug in the device ...
> Press CTRL+C to terminate the program.

```

# Answer
> 3 votes
Digisparks are known to have problems with USB3 ports (which your USB-C adaptor probably provides). Try using a cheap USB2 hub between the DigiSpark and the adaptor.

It's always a good idea to use a cheap USB hub between whatever experimental device you want to connect and your machine, so that if you wire something up incorrectly you don't end up frying an expensive laptop. This is particularly true for a device such as the digispark which does not have a real USB interface but really bit-bangs the protocol out of ordinary I/O pins.

There is no guarantee that the hub will protect you from all wiring mistakes, but it's an added level of protection.

---
Tags: attiny, mac-os, attiny85, digispark
---


title: RFID Door Lock Coding Errors

text:
# Question
Title: RFID Door Lock Coding Errors
I am trying to recreate an RFID door lock that I saw on the Arduino project hub but have ran into several issues. I had to manipulate the code slightly to make sure it was including the correct libraries and I think that solved some issues but not all. If anyone could take a look at my code and help me out that'd be awesome, I am pretty new with coding and need all the help I can get. Thank you!

Here are the error messages I receive when trying to upload the code to my arduino: Arduino: 1.8.8 (Mac OS X), Board: "Arduino/Genuino Uno"

```
rfid_based_door_automatic_management_system:66:17: error: expected unqualified-id before numeric constant
 #define SDA_D1O 9
                 ^
/Users/gavinmiles/Documents/rfid_based_door_automatic_management_system/rfid_based_door_automatic_management_system.ino:70:9: note: in expansion of macro 'SDA_D1O'
 MFRC522(SDA_D1O, RESET_D1O);
         ^
rfid_based_door_automatic_management_system:66:17: error: expected ')' before numeric constant
 #define SDA_D1O 9
                 ^
/Users/gavinmiles/Documents/rfid_based_door_automatic_management_system/rfid_based_door_automatic_management_system.ino:70:9: note: in expansion of macro 'SDA_D1O'
 MFRC522(SDA_D1O, RESET_D1O);
         ^
/Users/gavinmiles/Documents/rfid_based_door_automatic_management_system/rfid_based_door_automatic_management_system.ino: In function 'void setup()':
rfid_based_door_automatic_management_system:120:10: error: expected unqualified-id before '.' token
   MFRC522.initial();
          ^
/Users/gavinmiles/Documents/rfid_based_door_automatic_management_system/rfid_based_door_automatic_management_system.ino: In function 'void loop()':
rfid_based_door_automatic_management_system:137:12: error: 'class MFRC522' has no member named 'isCard'
   if( rfid.isCard() )
            ^
rfid_based_door_automatic_management_system:141:16: error: 'class MFRC522' has no member named 'readCardSerial'
       if( rfid.readCardSerial() )
                ^
rfid_based_door_automatic_management_system:152:33: error: 'class MFRC522' has no member named 'serNum'
               Serial.print(rfid.serNum[i], HEX);
                                 ^
rfid_based_door_automatic_management_system:154:30: error: 'class MFRC522' has no member named 'serNum'
               lcd.print(rfid.serNum[i],HEX);
                              ^
rfid_based_door_automatic_management_system:165:42: error: 'class MFRC522' has no member named 'serNum'
               if( My_RFID_Tag[i] != rfid.serNum[i] )
                                          ^
rfid_based_door_automatic_management_system:274:8: error: 'class MFRC522' has no member named 'halt'
   rfid.halt();
        ^
Multiple libraries were found for "LiquidCrystal.h"
 Used: /Users/gavinmiles/Documents/Arduino/libraries/LiquidCrystal
 Not used: /Applications/Arduino.app/Contents/Java/libraries/LiquidCrystal
Multiple libraries were found for "Servo.h"
 Used: /Users/gavinmiles/Documents/Arduino/libraries/Servo
 Not used: /Applications/Arduino.app/Contents/Java/libraries/Servo
exit status 1
expected unqualified-id before numeric constant
/Users/gavinmiles/Downloads/untitled_file.ino

```

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

```
/*
 *  RFID Module RC522
 *  Simple Project:- Arduino will read RFID Tag and Display To the Serial Monitor!
 *
 *  RFID RC522 and Arduino Uno Pin Configuration
 *
 *  RFID RC522          Arduino Uno
 *  SS/SDA              D10
 *  SCK                 D13
 *  MOSI                D11
 *  MISO                D12
 *  IRQ                 Not Connected
 *  GND                 GND
 *  RST                 D9
 *  3.3V                3.3V
 *
 *  //Note: We connected LCD to the Analog Pins.
 *  Remember, Analog Pins can be act as a Digital Pins,
 *  But Digital Pins CAN NOT be act as a Analog Pins.
 *
 *  LCD(16x2) Connections
 *
 *  VSS pin to GND
 *  VCC pin to 5V
 *  //We are connecting "Contrast pin to GND for Maximum Brightness"
 *  //You can also connect it to 10K Pot if you wish to change the Brightness Of LCD.
 *  VEE pin to GND
 *  RS pin to Analog pin A0
 *  R/W pin to ground
 *  Enable pin to Analog pin A1
 *  D4 pin to Analog pin 5
 *  D5 pin to Analog pin 4
 *  D6 pin to Analog pin 3
 *  D7 pin to Analog pin 2
 *  LED+ pin to POWER
 *  LED- pin to GND
 *
 *  Servo is Connected to Digital Pin 5
 *
 *  RGB LED
 *  From RGB LED, We need Only Red and Green Color,
 *  So we are not connecting Blue pin of the RGB.
 *
 *  Red pin to Digital pin 6
 *  Green pin to Digital pin 7
 *
 *  Buzzer to Digital pin 8
 *
 *
 *  Note:- RFID uses SPI Protocol to transfer the information.
 *  I took the Melody(for the Buzzer) from,
 *  File -> Examples -> Digital -> ToneMelody
*/

//Include sections
#include <MFRC522.h>
#include <SPI.h>
#include <LiquidCrystal.h>
#include <Servo.h>
#include "pitches.h"

//Define Component to Arduino Pins
/* Define the DIO used for the SDA (SS) and RST (reset) pins. */
#define SDA_D1O 9
#define RESET_D1O 8

/* Create an instance of the RFID library */
MFRC522(SDA_D1O, RESET_D1O);
#define SS_PIN 10
#define RST_PIN 9

#define SERVO_PIN 5

#define Red_LED 6
#define Green_LED 7

#define Buzzer 8

//initialize the library with the numbers of the interface pins
LiquidCrystal lcd(A0, A1, A2, A3, A4, A5);
Servo DoorLock;
MFRC522 rfid(SS_PIN, RST_PIN );

//Unique ID of RFID Tag, which you want to give access.
int My_RFID_Tag[5] = {0x58,0x76,0x17,0x10,0x29};

//variable to hold your Access_card
boolean My_Card = false;

// notes in the melody, taken from:
//File -> Examples -> Digital -> ToneMelody
int melody[] = {
  NOTE_C4, NOTE_G3, NOTE_G3, NOTE_A3, NOTE_G3, 0, NOTE_B3, NOTE_C4
};

// note durations: 4 = quarter note, 8 = eighth note, etc.:
int noteDurations[] = {
  4, 8, 8, 4, 4, 4, 4, 4
};

void setup()
{
  // put your setup code here, to run once:
  //set the pins as an input/output
  pinMode(Red_LED,OUTPUT);
  pinMode(Green_LED,OUTPUT);
  pinMode(Buzzer,OUTPUT);

  //Servo Connnected to pin Digital Pin 5
  DoorLock.attach(SERVO_PIN);
  //open the serial port at 9600 baudrate.
  Serial.begin(9600);
  //Initialise the LCD to 16x2 Character Format
  lcd.begin(16,2);
  //Initialise Servo and RFID
  SPI.begin();
  MFRC522.initial();
}

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

  //First Assume detected card(Or tag) is My_Card,
  //Then later we will check is it My_Card or not!
  My_Card = true;
  DoorLock.write(0); //Servo at 0 Position, Door is Closed.
  lcd.clear();
  lcd.print("Robodia Technology");
  lcd.setCursor(0,1);
  lcd.print("gy Solutions!");

  //Check if any RFID Tags Detected or not?
  if( rfid.isCard() )
  {
      //if RFID Tag is detected, check for the Unique ID,
      //and print it on the Serial Window
      if( rfid.readCardSerial() )
      {
          lcd.clear();
          lcd.print("UNIQUE ID is:- ");
          delay(500);
          lcd.setCursor(0,1); //Set LCD Cursor to Second Row, First Character

      //Unique id is 5 Digit Number.
          //Printing in HEX for better Understanding
          for( int i = 0; i < 5; i++ )
          {
              Serial.print(rfid.serNum[i], HEX);
              Serial.print(" ");
              lcd.print(rfid.serNum[i],HEX);
              lcd.print(" ");
          }
          delay(500);

      //Compare this RFID Tag Unique ID with your My_RFID_Tag's Unique ID
          for(int i = 0; i < 5; i++)
          {
              //if any one Unique ID Digit is not matching,
              //then make My_Card = false and come out from loop
              //No need to check all the digit!
              if( My_RFID_Tag[i] != rfid.serNum[i] )
              {
                My_Card = false;
                break;
              }
          }
          Serial.println();
          delay(1000);

          //If RFID Tag is My_Card then give access to enter into room
          //else dont open the door.
          if(My_Card)
          {
            Serial.println("\nWelcome To Your Room, Robodia!");
            lcd.clear();
            lcd.print("Welcome to Your");
            lcd.setCursor(0,1);
            lcd.print("Room, Robodia!");
            delay(2000);

            //Turn on the Green LED as an indication of permission is given
            //to access the room.
            digitalWrite(Green_LED,HIGH);

            //Buzzer Config, taken from:
            //File -> Examples -> Digital -> ToneMelody
            // iterate over the notes of the melody:
            int i = 0;
            while(i < 2)
            {
              for (int thisNote = 0; thisNote < 12; thisNote++)
              {
                // to calculate the note duration, take one second
                // divided by the note type.
                //e.g. quarter note = 1000 / 4, eighth note = 1000/8, etc.
                int noteDuration = 1000 / noteDurations[thisNote];
                tone(8, melody[thisNote], noteDuration);
                // to distinguish the notes, set a minimum time between them.
                // the note's duration + 30% seems to work well:
                int pauseBetweenNotes = noteDuration * 1.30;
                delay(pauseBetweenNotes);
                // stop the tone playing:
                noTone(8);
              }
              i =  i + 1;
              delay(500);
            }
            delay(1000);

            //Now, Open the Door with the help of Servo Motor
            DoorLock.write(180);
            delay(200);
            lcd.clear();
            lcd.print("Door is Open");
            lcd.setCursor(0,1);
            lcd.print("Now!");
            delay(2000);
            lcd.clear();

            //Give 10 Sec delay to enter into room
            //After that door will again closed!
            for(int i = 10; i > 0; i--)
            {
              lcd.print("Door will close");
              lcd.setCursor(0,1);
              lcd.print("in ");
              lcd.print(i);
              lcd.print(" Sec.HurryUp!");
              delay(1000);
              lcd.clear();
            }

            //Now,Door is closed and Green LED is Turned-Off.
            DoorLock.write(0);
            digitalWrite(Green_LED,LOW);
            delay(200);
            lcd.clear();
            lcd.print("Door is Close");
            lcd.setCursor(0,1);
            lcd.print("Now!");
            delay(2000);
          }

          // If RFID Tag is not My_Card then
          // Do not open the Door and
          //Turn-On Red LED and Buzzer as an indication of Warning:
          //Somebody else is trying to enter into your room.
          else
          {
            Serial.println("\nGet Out of Here !");
            lcd.clear();
            lcd.print("Card isNOT FOUND!");
            lcd.setCursor(0,1);
            lcd.print("Get Out of Here!");

            for(int i = 0; i < 7; i++)
            {
              digitalWrite(Buzzer, HIGH);
              digitalWrite(Red_LED,HIGH);
              delay(500);
              digitalWrite(Buzzer, LOW);
              digitalWrite(Red_LED,LOW);
              delay(500);
            }
            delay(1000);
          }
      }
   }
  //Put RFID Reader into Halt, untill it not detects any RFID Tag.
  rfid.halt();
}

```

# Answer
> 1 votes
I had seen many errors in your code. Some of them are as follows

1. `MFRC522.initial();` replace it with `rfid.initial();`
2. Libraries such as liquidcrystal, servo are default libraries in arduino so if you had download them from external source and copied them in your library folder please remove them.
3. This logic won't help as if the first id didn't match it will break the loop and and comparison won't go further with other and your will always find false as a result in this case.

```
      for(int i = 0; i < 5; i++)
  {
      //if any one Unique ID Digit is not matching,
      //then make My_Card = false and come out from loop
      //No need to check all the digit!
      if( My_RFID_Tag[i] != rfid.serNum[i] ) // suggested change if( My_RFID_Tag[i] == rfid.serNum[i] )
      {
        My_Card = false;//My_Card = true
        break;
      }
  }

```
4. Library functions used in code are different from those available in library, open library file and search for those function used for same purpose.
5. Remove them

```
#define SDA_D1O 9
#define RESET_D1O 8
MFRC522(SDA_D1O, RESET_D1O);

```

you are already defining them and using them here in your code

```
#define SS_PIN 10
#define RST_PIN 9
MFRC522 rfid(SS_PIN, RST_PIN );

```

---
Tags: rfid, home-automation
---


# Question
Title: Is there a way to get my MacBook's date and time into Arduino IDE?
I am using a DS3231 RTC module. It requires to set the time every time it is reset. I was wondering if I could read my MacBook's time and date and feed into the module at the setup stage. Is this possible?

P.S. I do not have to use a battery.

# Answer
You can use `__DATE__` and `__TIME__` compiler time constants in IDE and do check inside of your `setup()` function if the RTC clock is zeroed then parse and set compile time values.

```
char cr[] = __DATE__;
char ct[] = __TIME__;

```

At the compile time these macros will be replaced with text constants `"Apr 4 2019"` and `"10:35:22"` respectively.
> 1 votes

# Answer
You could use softRTC library to get date/time from your system. So program flow could be get date/time from softRTC library during setup part and then use those variables in loop set your DS2321 RTC which will always be running till you poweroff.
> -1 votes

---
Tags: arduino-mega, time, rtc
---


# Question
Title: May mulitple sensor connect to one arduino uno board since they shared same pin?
i am a Arduino beginner here. I start knowing about Arduino since my supervisor give me this project. In my project , i need to invent a car safety system to avoid animal hurting that hide under vehicle and solve drowsy driving problem. In sensor requirement, i choose to use PIR motion sensor (HC-SR501) to sense the movement of living things under the car, for the drowsy driving i choose to use pulse sensor and eye blink sensor to detect whether the driver is sleeping or not, it the driver is sleeping then it will activate alarm and led light on. But during research, i found that these 3 sensor have sharing the same pin with is the pin 2 (picture attach). So may is ask is possible to connect these all 3 sensor in one board ?? May i ask how can i do it if i connect the pins to the breadboard ?? Last question is do i need have MEMS MPU -6050 sensor in my project since i found this is with the eye blink sensor in other person research. Thank for accepting my question.

# Answer
> 2 votes
Your drawing seems to show plenty of pins available, with only pin 2 in common. If the pin is being used for an Interrupt, then one device can use a different pin instead and the code adapted to use PCINT for the interrupt.

I would suggest the PIR does not even need an interrupt, it is slow changing and polling it for activity would be just as effective.

Add some current limit resistors to your LEDs so you don't damage the IO pins.

# Answer
> 0 votes
You did not provide a picture, or any other information.

Given how little info you provided, the answer is "it depends".

PIR sensors tend to use digital lines that change state when they detect motion. You would not want to share an input line with such a PIR. (I couldn't find a spec-sheet on your PIR with a quick search.)

For devices that use serial communication, the I2C interface standard **is** designed for connecting multiple devices on the same serial bus. If you have multiple I2C devices, you should connect them all to the same pins, and it works great as long as they have different device addresses on the I2C bus.

Other types of serial interfaces are only designed for 2 devices to communicate with each other, and cannot be shared.

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


title: Read nested array item from PROGMEM

text:
# Question
Title: Read nested array item from PROGMEM
I have a 2D array of uint16\_t arrays (IR Remote Codes). Due to the size of this data in RAM I'm having all kinds of trouble when my array is larger than one code. Thus, I have been trying to move this whole structure into PROGMEM. Following various tutorials and this solution, I have come up with the code below for reading a single element out of the array and into a variable that I can feed to the IRLIB2 IRSendRaw function.

The variable that holds the code that is read out of PROGMEM is still huge and causing some problems. Is there a more direct way like a python list comprehension to access an arbitrary element and send it directly to the IRSender?

This PROGMEM\_readAnything library looks promising, but I don't have enough C++ fu to make the mental leap to implement it in my code.

```
#include <IRLibSendBase.h>    //We need the base code
#include <IRLib_HashRaw.h>    //Only use raw sender

#define RAW_DATA_LEN 68
const uint16_t sources[3][RAW_DATA_LEN] PROGMEM =
  {{8550, 4306, 530, 1606, 530, 566, 502, 1610, //power on/off
  530, 566, 502, 574, 506, 1630, 506, 566,
  506, 1630, 506, 566, 502, 1610, 530, 566,
  502, 1634, 506, 1606, 530, 570, 498, 1634,
  506, 570, 510, 562, 506, 566, 502, 1634,
  506, 1606, 530, 1610, 530, 562, 538, 538,
  530, 542, 538, 1598, 538, 1570, 558, 542,
  538, 538, 530, 542, 538, 1598, 530, 1578,
  558, 1578, 562, 1000},

  {8546, 4310, 558, 1578, 562, 538, 498, 1638,  //source CD
  530, 542, 506, 570, 502, 1634, 502, 570,
  498, 1638, 534, 538, 498, 1638, 530, 542,
  506, 1606, 554, 1582, 558, 538, 510, 1602,
  554, 546, 506, 566, 502, 570, 510, 1602,
  554, 1582, 558, 538, 510, 566, 502, 1606,
  554, 546, 502, 1610, 558, 1574, 554, 546,
  502, 570, 510, 1602, 526, 1610, 526, 574,
  506, 1602, 526, 1000},

  {8550, 4306, 530, 1606, 534, 566, 502, 1606,  //source CDR
  534, 566, 502, 570, 510, 1602, 526, 570,
  510, 1602, 534, 566, 502, 1606, 534, 566,
  506, 1602, 530, 1606, 534, 566, 502, 1610,
  530, 570, 498, 574, 506, 566, 502, 570,
  510, 1602, 526, 570, 510, 566, 502, 570,
  510, 1602, 526, 1610, 526, 1606, 534, 1602,
  534, 566, 502, 1610, 530, 1602, 534, 1602,
  526, 574, 506, 1000}};

//Create a sender
IRsendRaw mySender;

//Read out one code into a variable and send to the IR transmitter
uint16_t myCode[RAW_DATA_LEN];
for (int i = 0; i < RAW_DATA_LEN; i++) {
   myCode[i] = pgm_read_word_near(sources[0] + i);
}
mySender.send(myCode,RAW_DATA_LEN,36);

```

# Answer
The library, as it stands, doesn't support direct sending from PROGMEM. However it's not too hard to get around that - if your C++ is up to it.

The IRsendRaw class is a child class that extends the IRsendBase with a single function. You just need to do the same thing to create a new class that implements the functions in a way that can read from PROGMEM.

This is the original:

```
class IRsendRaw: public virtual IRsendBase {
  public:
    void send(uint16_t *buf, uint8_t len, uint8_t khz) {
      enableIROut(khz);
      for (uint8_t i = 0; i < len; i++) {
        if (i & 1) {
          space(buf[i]);
        }
        else {
          mark(buf[i]);
        }
      }
      space(0); // Just to be sure
    }
};

```

You just need to make your own one of those in your sketch, called something different, and which uses the progmem functions instead of accessing `buf[i]`:

```
class IRsendRawPGM: public virtual IRsendBase {
  public:
    void send(const uint16_t *buf, uint8_t len, uint8_t khz) {
      enableIROut(khz);
      for (uint8_t i = 0; i < len; i++) {
        if (i & 1) {
          space(pgm_read_word_near(buf + i));
        }
        else {
          mark(pgm_read_word_near(buf + i));
        }
      }
      space(0); // Just to be sure
    }
};

```

Now you can define your sender object as:

```
IRsendRawPGM mySender;

```

And send the data directly:

```
mySender.send(sources[0], RAW_DATA_LEN, 36);

```

(Note: this code is untested).
> 4 votes

---
Tags: memory, progmem
---


# Question
Title: ESP8266: Multiple analog inputs using software
Is there a way to get at least three analog inputs to the esp8266 (without a multiplexer)?

Each digital or analog pin on an Arduino can be configured as digital or "analog" (e.g., PWM software).

Here is a way to squeeze one additional analog input pin: hackaday.io/project/8435-2-analog-inputs-for-esp8266-without-multiplexer

Any ideas or software

# Answer
> 2 votes
1) nope it's not possible "in a straightforward way". you should use analog muxes.

2) the statement "Each digital or analog pin on an Arduino can be configured as digital or "analog" (e.g., PWM software)." means for PWM or the so called "analog output". not intended the ADC unit.

3) the link provided uses software tricks to measure 2 signals in a muxed fashion. it's up to purpose.

workarounds :

1) use CD4066 CMOS bilateral switch. it works with analog signals.

2) use GPIOs to supply voltage to measurement units. like the link you provided. it works for passives like photoresistors and for devices like LM35 temp sensor. but can't be used for devices like 3 channels analog-out accelerometers.

---
Tags: esp8266
---


# Question
Title: Limitations of connecting to many Arduinos via Ethernet?
I'm planning a project where I need to control a lot of Arduino Unos from a single PC. I'll need to send commands to the Arduinos and receive responses, as well as have the ability to update each Arduino from the PC, preferably without Arduino IDE at some point. Connecting via USB is out of the question, as I have already tried this and got miserable results, in part because of the number of Arduinos I need to control. So now I'm considering connecting the PC to an ethernet switch and then from there connect each Arduino with an ethernet shield.

Which brings me to my questions. Are there any limitations I should be aware of, if I want to pursue this setup? Will controllings tens, or even a hundred, Arduinos at the same time be a problem? How about stuff like updating a specific Arduino on the network?

My current working prototype uses a Windows PC that connects to one of multiple Raspberry Pis, which then in turn communicates with a number of Arduinos via I2C, and updates them via USB. But if I'm able to do all this directly from the main PC to the Arduinos via Ethernet, that would be fantastic.

Thanks for reading, looking forward to any answers.

# Answer
With a lot of devices on the ethernet, you may want to consider a private wire that is dedicated to those devices. That is, a second ethernet port or a VLAN off a capable switch.

As the number of devices increases, and the number of simultaneous talkers increases, you will start getting contention. Chances are a modern switch can handle this to some extent, but you were not clear on how much traffic you are planning on sending, or how often each device talks, or if it is centrally coordinated (aka "polled") or just speaking whenever.
> 1 votes

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


title: Interrupt triggering using DHT-11

text:
# Question
Title: Interrupt triggering using DHT-11
I am new at arduino. I want to write a sketch that would print the message if the temperature grows greater than 30 C. Here is my sketch can you please tell me what's wrong with it

```
#include "DHT.h"
#define DHTTYPE DHT11
#define dht_dpin D3

DHT dht(dht_dpin, DHTTYPE);

void setup()
{
 Serial.begin(9600);
 }
void loop()
{
 float t = dht.readTemperature();
 Serial.print("temp=");
 Serial.println(t);
 attachInterrupt(dht_dpin, IntCallback, CHANGE);
}
void IntCallback()
{
  float t = dht.readTemperature();
  if(t>30)
  {
    Serial.print("Alert");
  }
}

```

# Answer
You can't use an interrupt the way you are attempting to. Attaching an interrupt to a pin like that will cause the interrupt to trigger any time the digital pin's value changes. The DHT11 uses serial communication to send temp values to the Arduino. Serial communication uses lots and lots of on/off pulses on the signal line to send characters of data. Your interrupt will fire every time the DHT11 toggles the signal line.

You need to read the temp from the DHT11 in your loop, and then add an if statement that does what you want when the temp exceeds your threshold. (It looks like you just need to get rid of the attachInterrupt() call, and instead call IntCallback() every couple of seconds.
> 1 votes

# Answer
You don't even need an interrupt.Modification:

```
#include "DHT.h"
#define DHTTYPE DHT11
#define dht_dpin D3

DHT dht(dht_dpin, DHTTYPE);

void setup()
{
 Serial.begin(9600);
 }
void loop()
{
 float t = dht.readTemperature();
 Serial.print("temp=");
 if(t>30)
  {
    Serial.print("Alert");
  }
}

```
> 0 votes

---
Tags: esp8266, programming, interrupt, sketch, temperature-sensor
---


# Question
Title: Send ECG signal with NRF24L01 from Arduino to Raspberry Pi 3
I'm using nRF24L01 to send ECG samples from an Arduino to Raspberry Pi, the type of sample is double after denoising, and I stock them in a byte\[8\] to send 8 by 8 sample. When I print the sample before stockage that show the good results, but if I print data stored in the byte the signal show a lot of fluctuations. In Raspberry Pi, I can read correctly byte data like transmitted, but if I send them in a vector of double or int in reception (python) don't give the same frame transmitted.

```
#include <IIRFilter.h>
#include <FIRFilter.h>

#include <SPI.h> // Call SPI Library
#include <nRF24L01.h> // Call NRE Version Library
#include <RF24.h> // RF24 Header File

#define CE_PIN  9
#define CSN_PIN 10
const uint64_t pipe = 0xF0F0F0F0E1LL;
RF24 radio(CE_PIN, CSN_PIN);

const int ECG_samplefreq  = 200;//sampling frequcy
const int DC_offset = 511;

const double b_lp[] = {0.0026, 0.0155, 0.0388, 0.0517, 0.0388, 0.0155, 0.0026};
const double a_lp[] = {1.0000, -2.3797, 2.9104, -2.0551, 0.8779, -0.2099, 0.0218};

IIRFilter lp(b_lp, a_lp);
unsigned int i = 0;

void setup() {
  Serial.begin(9600);
  radio.begin();//Intializing NRF24L01 Module
  radio.setPALevel(RF24_PA_MAX);
  radio.setChannel(0x76);
  radio.openWritingPipe(pipe);// For Transmitting Operation, Must OpenWritingPipe
  radio.enableDynamicPayloads();
  radio.powerUp();
  pinMode(7, INPUT); // Setup for leads off detection LO +
  pinMode(8, INPUT); // Setup for leads off detection LO -

}
void loop() {
  const static unsigned long ECG_interval  = round(1e6 / ECG_samplefreq);  //sampling period = 5000 ms => 200 sample by 1 seconde
  static unsigned long ECG_prevmicros = micros();
  byte  s[8] = {0};

  if ((digitalRead(7) == 1) || (digitalRead(8) == 1)) {
    Serial.println('!');
  }

  else {
    for (int i = 0; i < 8; i++)
    {

      if (!Serial) {
        ECG_prevmicros = micros();
      }
      else if (micros() - ECG_prevmicros >= ECG_interval)
      {
        int value = analogRead(A5);
        double filtered = lp.filter( value - DC_offset);

        filtered = round( filtered + DC_offset);
        s[i] =  filtered
        Serial.println( s[i]);
        ECG_prevmicros += ECG_interval;

      }
    }
    radio.write(&s, sizeof(s) ); // sending in real time ECG sample. 8 sample by transmission . 8 => 4 oct of one sampe = 32 oct by transmission.

  }
}

```

the problem thant i put in s\[i\] a double of four octs. im searching how can i send them whithout byte array, and receive the correctly. So thankful for your help

# Answer
> 1 votes
I see multiple flaws in your code:

* `radio.write(&s, sizeof(s));` does not what you think it would. The correct statement would be `radio.write(s, sizeof(s));` without the ampersand.
* You are using `double`. Not using floating point numbers at all would be preferable.
* Your `s` is of type byte. Thus it only holds 8 bytes. So your floating point calculations are being truncated to the range \[0, 255\]. From your problem description this is not what you are trying to achieve, I think.

---
Tags: arduino-nano, nrf24l01+, raspberrypi
---


# Question
Title: Invoke a method in the main sketch from within a library
I need to use a specific library that issues error messages in the form of String texts. The library uses the `Serial.println()` function to send the messages to the Arduino IDE's serial monitor.

The problem is that I have the Serial lines from the Arduino linked to another device, therefore I can't use the Serial Monitor to see the messages. I have a method in the Main Arduino sketch that sends any String text msg generated to another device using Udp commands (wireless). This device is connected to a serial monitor unit.

My question is: How can I invoke the Udp method inside the main sketch of the Arduino program from within the aforementioned library? This would help me to convert the `Serial.print()` text messages from the library directly into Udp messages to be able to visualize them.

The Udp method I'm using is declared as `void UdpSend(String msg)` in the Arduino sketch. I'd like to use something similar inside the library to wrap the text msg and send it over to the method on the main program.

Any example or link to get this information will help.

EDIT1:

@Majenko,

1. On the target library, added: `void libUdpSend(const char *libMsg);`
2. On the sketch, I added this method (Udp comm handler):

```
 void libUdpSend(const char *libMsg)
 {
   Udp.begin(localPort);
   Udp.beginPacket(Udp.remoteIP(), localPort);
   Udp.write(libMsg);
   Udp.endPacket();
   delay(40);
 }

```
3. Added this line on the library (right after the declaration on 1.) to test through the remote serial interface:

```
libUdpSend("String wrapper has been implemented SUCCESSFULLY!");

```

When trying to compile linking the library, the following exception occurrs:

> error: expected constructor, destructor, or type conversion before '(' token `libUdpSend("String wrapper has been implemented SUCCESSFULLY!");`

I then switched to String as this is the type I want to wrap, Same steps:

1. On the target library, added: `void libUdpSend(String *libMsg);`
2. On the sketch:

```
void libUdpSend(String *libMsg)
{
  Udp.begin(localPort);
  Udp.beginPacket(Udp.remoteIP(), localPort);
  Udp.write(libMsg.c_str());
  Udp.endPacket();
  delay(40);
}

```

Now the error message says:

> request for member 'c\_str' in 'libMsg', which is of pointer type 'String\*' (maybe you meant to use '-\>' ?)

I am not an expert on pointers so I'd need some help on how to assign the pointer as argument on the `UdpWrite` function using the '-\>' command proposed by the compliler?

Let me know your thoughts on this.

# Answer
The connection between a sketch and a library is not one-way as many suppose. Things can go quite happily in both directions.

What you are proposing is something I do quite often when developing a library and I need to get some debugging information out of the library. Yes, it's possible to directly use `Serial` in the library, but that's something I don't like, and often isn't appropriate anyway, as in your situation.

However, doing it the way you propose (and I use) is actually very simple.

You just make your function in your sketch and tell the library to use it.

For example, in your sketch:

```
void debug(const char *msg) {
    Serial3.println(msg);
}

```

And in the library add the line:

```
void debug(const char *msg);

```

Then at any point in the same file (or translation unit) you can use

```
debug("I am here");

```

That is assuming that the file that you are using it in is a C++ file (`.cpp`). If it's a C file (`.c`) then you have to treat things very slightly differently. You see, C++ makes a mess of the function names (even vanilla functions like that) which means they can't be seen by C files. So you have to tell the compiler "I'd like this to be usable in a C file, please".

Which you do with a special "extern" wrapper around your function:

```
extern "C" {
    void debug(const char *msg) {
        Serial3.println(msg);
    }
}

```

And then `debug()` is usable in a C file in the same way as above.

However now it won't work in a C++ file... (round and round we go...)

Simple to fix: add the `extern "C"` to the prototype in the C++ file:

```
extern "C" {
    void debug(const char *msg);
}

```

If you want to include your "extern" in a header file that could be included into either C or C++ files it's very common to use a construct such as:

```
#if defined(__cplusplus)
extern "C" {
#endif

void debug(const char *msg);

#if defined(__cplusplus)
}
#endif

```

That will add the `extern "C"` wrapper for C++ files (identified by the presence of the macro `__cplusplus`) but omit it for C files.

I have used "const char \*" as the parameter for this example, but you can choose whatever parameters are appropriate for your usage.
> 2 votes

---
Tags: arduino-uno, esp8266, programming, arduino-ide, library
---


title: Linear Actuator Arduino Control

text:
# Question
Title: Linear Actuator Arduino Control
**Update:**

Here is my first try based on the code I found and it did not work. The first time I uploaded it, it move to the "current positional value". But did not do the void loop part. Just holds the positions.

Thanks.

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

    //Defines
    #define LINEAR_1_100PIN 11        //Linear Actuator Digital Pin
    #define LINEAR_2_100PIN 6      //Linear Actuator Digital Pin

    String msg;

    //max/min pulse values in microseconds for the linear actuators
    #define LINEAR_1_100_MIN      1050  //
    #define LINEAR_1_100_MAX      2000 //
    #define LINEAR_2_100_MIN  1050     //
    #define LINEAR_2_100_MAX  2000    //

    Servo LINEAR_1_100, LINEAR_2_100;  // create servo objects to control the linear actuators
    //int knobValue, sliderValue;  //variables to hold the last reading from the analog pins

    int linear100Value_1 = 1051;   //current positional value being sent to the linear actuator.
    int linear100Value_2 = 1051;  //current positional value being sent to the linear actuator.

    int speed = 10;

    void setup()
    {
      //initialize servos
      LINEAR_1_100.attach(LINEAR_1_100PIN, LINEAR_1_100_MIN, LINEAR_1_100_MAX);      // attaches/activates the linear actuator as a servo object
      LINEAR_2_100.attach(LINEAR_2_100PIN, LINEAR_2_100_MIN, LINEAR_2_100_MAX);  // attaches/activates the linear actuator as a servo object

      //Analog pins do not need to be initialized

      //use the writeMicroseconds to set the linear actuators to their default positions
      LINEAR_1_100.writeMicroseconds(linear100Value_1);
      LINEAR_2_100.writeMicroseconds(linear100Value_2);
    }

    void loop()
    {
   LINEAR_1_100.write(90);
   delay(1000);
   LINEAR_1_100.write(0);
   delay(1000);
   LINEAR_2_100.write(90);
   delay(1000);
   LINEAR_2_100.write(0);
   delay(1000);
    }

```

**Old Question:**

I am trying to make the code described in this tutorial:

http://learn.robotgeek.com/demo-code/118-arduino-linear-actuator-tutorial-analog-direct-control-of-small-linear-actuator.html

https://github.com/robotgeek/firgelliDirectControl/blob/master/firgelliDirectControl/firgelliDirectControl.ino

work with PWM from an Arduino, without the additional board.

So far the Arduino Examples\>Servo\>Sweep works as I would like to achieve it (delay changed to 30 ms) but very slowly and it does not seem to just go 180 steps out wait 30 ms and 180 steps in again. It sometimes moves twice in one direction. If I change the steps from 1 to 5 the servo does not move anymore (I expected it to go faster).

With the code above I understand I can control the servo with a Knob or Slider, but I would like to understand how I can control this Linear Actuator Servo with PWM from an Arduino PMW Pin (e.g. 11) and change the speed. Finally I would like to make the Servo consistently go x amount of steps out, wait for x ms and the same amount back in again.

Most importantly I would like to make sure it always ends at position 0, and that it does not accumulate errors.

Thank you for any help.

# Answer
> 1 votes
About being sure about returning to position 0 this is not a problem. You are not actually controlling anything with your PWM. You are only sending a signal to the IC inside the servo to tell it where to move the actuator. That IC knows in what position the actuator is located in any moment, usually using some kind of encoder (it's called a closed loop system) and it will make sure that it will move back exactly to `0` whenever you tell it to move to `0`.

If you want to make things clearer you can use `write` method to send value to the servo.

```
void Servo::write(int value)
{
  if(value < MIN_PULSE_WIDTH)
  {  // treat values less than 544 as angles in degrees (valid values in microseconds are handled as microseconds)
    if(value < 0) value = 0;
    if(value > 180) value = 180;
    value = map(value, 0, 180, SERVO_MIN(),  SERVO_MAX());
  }
  this->writeMicroseconds(value);
}

```

Any value from `0` to `180` will set a position to which servo will move from MIN to MAX possible position. No need for manual calculation of microseconds.

You have to remember that PWM works constantly. If you write for example `LINEAR_1_100.writeMicroseconds(1051)` this code will set some timers, counters and prescalers inside the ATmega chip on the Arduino board and the value of PWM will be sent constantly until you change it.

So the `delay(2000)` doesn't stop the PWM signal, and servo remains in constant position.

The issue is here:

```
LINEAR_1_100.writeMicroseconds(1800);
LINEAR_1_100.writeMicroseconds(1051);

```

You set the value of `1800` and then immediatelly set value of `1051`, but the ATmega didn't even have the time to send the first value to the servo. Add a `delay(1000)` after every call of `write` or `writeMicroseconds` to allow the PWM to actually be sent to the servo.

---
Tags: servo
---


title: Sending GPS data through a WiFi module

text:
# Question
Title: Sending GPS data through a WiFi module
I'm trying to send GPS data using a neo-6m GPS module through WiFi using esp8266 module, I have both of the modules working alone, but when I try using both the WiFi works but won't send the data from the GPS.

I call the GPS and save the latitude, longitude, date and time to separate variables, then try sending those variables using the WiFi to the server on the Arduino Uno, but they just show up as 0's.

```
#include <TinyGPS++.h>
#include "WiFiEsp.h"

// Emulate Serial1 on pins 6/7 if not present
#ifndef HAVE_HWSERIAL1
#include "SoftwareSerial.h"
SoftwareSerial Serial1(6, 7); // RX, TX
#endif

char ssid[] = "UPC9080883";            // your network SSID (name)
char pass[] = "OYKXVYND";        // your network password
int status = WL_IDLE_STATUS;

int ledStatus = LOW;

WiFiEspServer server(80);

// use a ring buffer to increase speed and reduce memory allocation
RingBuffer buf(8);

static const int RXPin = 4, TXPin = 3;
static const uint32_t GPSBaud = 9600;

// The TinyGPS++ object
TinyGPSPlus gps;

// The serial connection to the GPS device
SoftwareSerial Serial2(RXPin, TXPin);

double  latitude, longitude;
int days, months, years, hr, mins, secs;
void setup()
{
  pinMode(LED_BUILTIN, OUTPUT);  // initialize digital pin LED_BUILTIN as an output.
  Serial.begin(115200);   // initialize serial for debugging
  Serial1.begin(9600);    // initialize serial for ESP module
  WiFi.init(&Serial1);    // initialize ESP module

  // check for the presence of the shield
  if (WiFi.status() == WL_NO_SHIELD) {
    Serial.println("WiFi shield not present");
    // don't continue
    while (true);
  }

  // attempt to connect to WiFi network
  while (status != WL_CONNECTED) {
    Serial.print("Attempting to connect to WPA SSID: ");
    Serial.println(ssid);
    // Connect to WPA/WPA2 network
    status = WiFi.begin(ssid, pass);
  }

  Serial.println("You're connected to the network");
  printWifiStatus();

  // start the web server on port 80
  server.begin();
}

void loop()
{
  Serial1.end();
  Serial2.begin(GPSBaud);
  GPS();
  Serial2.end();
  Serial1.begin(9600);
  WiFiEspClient client = server.available();  // listen for incoming clients
  if (client) {                               // if you get a client,
    Serial.println("New client");             // print a message out the serial port
    buf.init();                               // initialize the circular buffer
    while (client.connected()) {              // loop while the client's connected
      if (client.available()) {               // if there's bytes to read from the client,
        char c = client.read();               // read a byte, then
        buf.push(c);                          // push it to the ring buffer

        // printing the stream to the serial monitor will slow down
        // the receiving of data from the ESP filling the serial buffer
        //Serial.write(c);

        // you got two newline characters in a row
        // that's the end of the HTTP request, so send a response
        if (buf.endsWith("\r\n\r\n"))
        {
          sendHttpResponse(client);
          break;
        }
      }
    }

    // close the connection
    client.stop();
    Serial.println("Client disconnected");
  }
}
void GPS() {
  while (Serial2.available() > 0) {
    gps.encode(Serial2.read());
    if (gps.location.isUpdated()) {
      // Latitude in degrees (double)
      latitude = (gps.location.lat(), 6);
      // Longitude in degrees (double)
      longitude = (gps.location.lng(), 6);

      // Day (1-31) (u8)
      days = (gps.date.day());
      // Month (1-12) (u8)
      months = (gps.date.month());
      // Year (2000+) (u16)
      years = (gps.date.year());

      // Hour (0-23) (u8)
      hr = (gps.time.hour());
      // Minute (0-59) (u8)
      mins = (gps.time.minute());
      // Second (0-59) (u8)
      secs = (gps.time.second());
      Serial.println(longitude);
      Serial.println(latitude);
      Serial.println(days);
      Serial.println(months);
      Serial.println(years);
      Serial.println(hr);
      Serial.println(mins);
      Serial.println(secs);

    }
  }
}

void sendHttpResponse(WiFiEspClient client)
{
  // HTTP headers always start with a response code (e.g. HTTP/1.1 200 OK)
  // and a content-type so the client knows what's coming, then a blank line:
  client.println("HTTP/1.1 200 OK");
  client.println("Content-type:text/html");
  client.println();

  // the content of the HTTP response follows the header:
  client.println("<br>");
  client.println("<br>");
  client.print("Latitude= ");
  client.print(latitude);
  client.print(" Longitude = ");
  client.println(longitude);
  client.println("<br>");
  client.print("Date: ");
  client.print(days);
  client.print("/");
  client.print(months);
  client.print("/");
  client.print(years);
  client.println("<br>");
  client.print("Time: ");
  client.print(hr);
  client.print(":");
  client.print(mins);
  client.print(":");
  client.print(secs);
  // The HTTP response ends with another blank line:
  client.println();
}

void printWifiStatus()
{
  // print the SSID of the network you're attached to
  Serial.print("SSID: ");
  Serial.println(WiFi.SSID());

  // print your WiFi shield's IP address
  IPAddress ip = WiFi.localIP();
  Serial.print("IP Address: ");
  Serial.println(ip);

  // print where to go in the browser
  Serial.println();
  Serial.print("To see this page in action, open a browser to http://");
  Serial.println(ip);
  Serial.println();
}

```

# Answer
> 1 votes
SoftwareSerial can't listen on two instances. There is a `.listen()` function to switch between SoftwareSerial instances.

The esp8266 AT firmware doesn't wait until you listen on the SoftwareSerial instance. If there is a connection to the server it sends +IPD and data. If the SoftwareSerial instance doesn't listen the information about client connection is lost.

You must listen to esp8266 all the time, so you can't use two SoftwareSerial instances.

You could use the RX pin of Uno to receive data from GPS module over hardware Serial.

---
Tags: wifi, gps, tinygps
---


# Question
Title: Arduino analogRead fluctuates from sensor unless USB connected
I have an Arduino connected to a 4-20 mA sensor through a current to voltage converter. When connected to the power supply the sensor reading fluctuates, as soon as I also connect it to a USB port it stabilizes and gives a correct reading (tested with other reader).

My main code is:

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

#define MINIMUM_DEWPOINT -100
#define MAXIMUM_DEWPOINT 20
#define AVG_READING_SIZE 20

float dewPoint;
uint8_t recordIndex = 0;
uint16_t analogReadingValue[20];
int sensorMin = 0;
int sensorMax = 1023;
int sensorValue = 0;

void setup()
{
    Serial.begin(9600);
    Display::init();

    for(uint8_t i = 0;i<AVG_READING_SIZE;i++)
    {
        analogReadingValue[i] = 0;
    }
}

uint16_t getAvg(uint16_t *arr,uint8_t numberOfElements)
{
    uint32_t sum = 0;
    for (uint8_t i = 0 ; i < numberOfElements ; i++)
    {
        sum += arr[i];
    }
    return  (uint16_t)(sum / numberOfElements);
}

void loop()
{
    analogReadingValue[recordIndex] = analogRead(A0);
    dewPoint = map(getAvg(analogReadingValue,AVG_READING_SIZE), sensorMin, sensorMax, MINIMUM_DEWPOINT, MAXIMUM_DEWPOINT);
    recordIndex++;

    if(recordIndex==AVG_READING_SIZE)
    {
        recordIndex = 0;
    }

    Display::displayDewpoint(dewPoint);
    Serial.println(dewPoint);
    Serial.println(getAvg(analogReadingValue, AVG_READING_SIZE));
    delay(2000);
}

```

My circuit diagram is:

# Answer
Apparently 5V reference on the 5V pin was the issue as 5V was only supplied to the Vin pin and it was referencing to 0V. Swapping the power supply from Vin to 5V solved the issue
> 1 votes

# Answer
You need a decoupling ceramic capacitor between A0 and GND. 100nF should work just fine.
> 1 votes

---
Tags: sensors, analogread, convert
---


# Question
Title: esp8266 advertising AP even when flashed with custom firmware
I bought several ESP8266 boards from an Amazon seller, and I have flashed them with custom firmware. This firmware basically sends telemetry to an MQTT server, and has some OTA functionality to self-update from a web server I run.

I flashed them from the Arduino IDE initially, although have also since updated them OTA.

These devices properly connect to the AP I have defined, get an address, and send their mqtt messages. However, they ALSO advertise an SSID that is `FaryLink_XXXXXX` where the XXXXXX relates to the MAC.

How is this possible, and how should I wipe their little brains fully?

# Answer
> 1 votes
The Espressif ESP8266 SDK is part of every Arduino sketch for the ESP8266. The SDK handles the WiFi and other basic functions of the chip.

If enabled, the SDK remembers WiFi STA and SoftAP settings and start to connect right after boot. At default it is enabled. In Arduino sketch this is controlled by `WiFi.persistent(bool)` and of course this setting is stored too.

To clear SoftAP settings, call `WiFi.softAPdisconnect()`. To only turn off SoftAP, use `WiFi.setMode(WIFI_STA)`.

---
Tags: esp8266
---


# Question
Title: I am building an robotic arm by using flex sensor, servo and 2 xbees
Rx Code:

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

void setup() {
Serial.begin(9600);
myServo.attach(9);
delay(5000);
myServo.write(0);
}

void loop() {
  while(Serial.available()==0);

    int d = Serial.read() - '0';
    if(d>0)
    {
      int pos = map(d,0,9,0,180);
      pos = constrain(pos,0,180);
      myServo.write(pos);
      Serial.println(d);

      delay(50);
      }
      else
      {};

}

```

Tx code:

```
int sensorValue = 0;         // the sensor value
int sensorMin = 1023;        // minimum sensor value
int sensorMax = 0;           // maximum sensor value
int SensorMid = 0;
const int POWER_OF_TWO_TO_AVERAGE = 6;

void setup() {
pinMode(13,OUTPUT);
  Serial.begin(9600);

  while (millis() < 10000) {
    digitalWrite(13,HIGH);
    sensorValue = analogRead(A1);
    if (sensorValue > sensorMax) {
      sensorMax = sensorValue;
    }
    if (sensorValue < sensorMin) {
      sensorMin = sensorValue;
    }
  }
  SensorMid = (sensorMin + sensorMax )/2;
  digitalWrite(13,LOW);
  }

void loop() {
int val = map(analogRead(A1),SensorMid,sensorMax,0,9);
Serial.println(val);
delay(100);
}

```

I am building a robotic arm and I am facing some problems regrading to the servos stability with the flex, I am using the flex as the transmitter and the servo as the receiver, and when I press my finger my servo doesn't move properly.

Any suggestions?

# Answer
Without knowing more about the actual problem of "doesn't move properly", what I initially see is that you are transmitting values 0-9 by using `Serial.println()`, which sends the byte data, and also a newline (ASCII value `10`), so your RX code is probably getting alternating input of the intended value, and the value `10`, which is getting subtracted from `48` (the ASCII value of `'0'`), `map`ped and `constrain`ed to `0`.

Try changing your TX script to call `Serial.print()` instead. Your receiver doesn't care about each value showing up on a new line -- it doesn't know about lines.
> 1 votes

---
Tags: arduino-uno, servo, xbee
---


title: Push and hold on/off switch for arduino

text:
# Question
Title: Push and hold on/off switch for arduino
Many electronic devices turn on/off, or more correctly on/sleep, by pressing a button and holding it for two or three seconds. I would like to put this ability into a project using an Adafruit Feather board. The sleep side is easy, I can detect a level and if it stays there for some time, run the code to put the processor to sleep. My question involves the wake up side. The chip wakes up via an interrupt.

The question then becomes, how do I generate the interrupt source only after the button has been held for the designated time? I've considered two options:

1) Use a level interrupt and an RC circuit to do the delay. 2) Have the processor wake up immediately and then implement logic to determine if it has been held "long enough" and go back to sleep if not.

Am I missing an easy option? Is there a general consensus on the best way to do this? It seems like such a normal thing that I'm surprised my searches haven't turned up any tutorials.

# Answer
> 2 votes
I would go for option 2.

You can wake up the controller immediately, but only the processor.

Then just start waiting for the "long enough" time that you defined, regulary checking the button state. If the button is still pushed, then initiate full wake up. If it is released, go back to sleep.

This is the easy option, requiring no extra hardware, and only a dozen of so of lines of code.

Another option, that exist and have a somewhat similar behaviour, is to have your processor wake up regulary on timer, and checking the state of the input. This is what is done for "radio controled" devices, for example (Where the "button" is a radio circuit that need to be switch on and off). Given a sufficiently long sleep between check, on average you will get the "long enough" delay.

This option is useful when you don't have available interrupt pins, or you need something more complex that a button as the input.

---
Tags: sleep
---


# Question
Title: Remove gravity from accelerometer of MPU-6050
I am currently working with MPU-6050. Now I want to minus gravity from my accelerometer's value as we minus the offset.

Here is the code:

```
#include <Wire.h>
#include <MPU6050.h>
//read as rool:pitch:yaw:accX:accY:accZ
MPU6050 mpu;
unsigned long timer = 0;
float timeStep = 0.01;
float pitch = 0;
float roll = 0;
float yaw = 0;
float accX = 0;
float accY = 0;
float accZ = 0;
float rollRad = 0;
float pitchRad = 0;
float yawRad = 0;

int count = 0;

Vector minusGravity(Vector vec)
{
    /*
     float x = vec.XAxis, y = vec.YAxis, z = vec.ZAxis;
     vec.XAxis -= x * cos(yawRad) - y * sin(yawRad) + x * cos(pitchRad) + z
           * sin(pitchRad) + 0;
     vec.YAxis -= x * sin(yawRad) - y * cos(yawRad) + 0 + y * cos(rollRad) -
           z * sin(rollRad);
     vec.ZAxis -= 0 - x * sin(pitchRad) + z * cos(pitchRad) + y *
           sin(rollRad) + z * cos(rollRad);
    */

    return vec;
}

float accP(float value)
{
    int x = (int)(value * 10);
    return ((float)(x)) / 10;
}

void setup()
{
    Serial.begin(115200);
    while (!mpu.begin(MPU6050_SCALE_2000DPS, MPU6050_RANGE_2G))
    {

    }
    //mpu.calibrateGyro();
    mpu.setThreshold(1);
 }

 void loop()
 {
    timer = millis();
    Vector norm = mpu.readNormalizeGyro();
    pitch = pitch + norm.YAxis * timeStep;
    roll = roll + norm.XAxis * timeStep;
    yaw = yaw + norm.ZAxis * timeStep;
    Vector normAccel = minusGravity(mpu.readNormalizeAccel());
    rollRad = roll * 0.0174533;
    pitchRad = pitch * 0.0174533;
    yawRad = yaw * 0.0174533;

    Serial.print(roll);
    Serial.print(":");
    Serial.print(pitch);
    Serial.print(":");
    Serial.print(yaw);
    Serial.print(":");
    accX = accP(normAccel.XAxis);
    accY = accP(normAccel.YAxis);
    accZ = accP(normAccel.ZAxis);
    Serial.print(accX);
    Serial.print(":");
    Serial.print(accY);
    Serial.print(":");
    Serial.println(accZ);
    delay((timeStep * 2500) - (millis() - timer));
}

```

I understand the problem is here :

```
vec.XAxis -= x * cos(yawRad) - y * sin(yawRad) + x * cos(pitchRad) + z
           * sin(pitchRad) + 0;
     vec.YAxis -= x * sin(yawRad) - y * cos(yawRad) + 0 + y * cos(rollRad) -
           z * sin(rollRad);
     vec.ZAxis -= 0 - x * sin(pitchRad) + z * cos(pitchRad) + y *
           sin(rollRad) + z * cos(rollRad);

```

New code :

```
      #include <Wire.h>
  #include <MPU6050.h>
  //read as rool:pitch:yaw:accX:accY:accZ
  MPU6050 mpu;
  unsigned long timer = 0;
  float timeStep = 0.01;
  float pitch = 0;
  float roll = 0;
  float yaw = 0;
  float accX = 0;
  float accY = 0;
  float accZ = 0;
  float rollRad = 0;
  float pitchRad = 0;
  float yawRad = 0;
  float gX = 0;
  float gY = 0;
  float gZ = -9.8;

  int count = 0;

  Vector minusGravity(Vector vec)
  {

    float x = gX, y = gY, z = gZ;
    vec.XAxis -= x * cos(yawRad) - y * sin(yawRad) ;
    vec.YAxis -= x * sin(yawRad) - y * cos(yawRad) ;

    x = vec.XAxis; z = vec.ZAxis;
    vec.XAxis -=  x * cos(pitchRad) + z * sin(pitchRad) ;
    vec.ZAxis -= - x * sin(pitchRad) + z * cos(pitchRad) ;

    y = vec.YAxis, z = vec.ZAxis;
    vec.YAxis -=  y * cos(rollRad) - z * sin(rollRad);
    vec.ZAxis -=  y * sin(rollRad) + z * cos(rollRad);

    return vec;
  }

  float accP(float value)
  {
    int x = (int)(value * 10);
    return ((float)(x)) / 10;
  }

  void setup()
  {
    Serial.begin(115200);
    while (!mpu.begin(MPU6050_SCALE_2000DPS, MPU6050_RANGE_2G))
    {

    }
    //mpu.calibrateGyro();
    mpu.setThreshold(1);
    Vector normAccel = mpu.readNormalizeAccel();
    gX = normAccel.XAxis;
    gY = normAccel.YAxis;
    gZ = normAccel.ZAxis;
  }
  void loop()
  {
    timer = millis();
    Vector norm = mpu.readNormalizeGyro();
    pitch +=  norm.YAxis * timeStep;
    roll += norm.XAxis * timeStep;
    yaw += norm.ZAxis * timeStep;
    Vector normAccel = minusGravity(mpu.readNormalizeAccel());
    rollRad = roll * 0.0174533;
    pitchRad = pitch * 0.0174533;
    yawRad = yaw * 0.0174533;
    Serial.print(roll );
    Serial.print(":");
    Serial.print(pitch );
    Serial.print(":");
      Serial.print(yaw );
    Serial.print(":");
    accX = accP(normAccel.XAxis);
    accY = accP(normAccel.YAxis);
    accZ = accP(normAccel.ZAxis);
    Serial.print(accX);
    Serial.print(":");
    Serial.print(accY);
    Serial.print(":");
    Serial.println(accZ);
    delay((timeStep * 2500) - (millis() - timer));
  }

```

It is little buggy.

Can anyone help me figure out what is my mistake ?

# Answer
I may have come to a solution :

```
Vector minusGravity(Vector vec)
{

 float x = vec.XAxis, y = vec.YAxis, z = 0;
 vec.XAxis -= x * cos(yawRad) - y * sin(yawRad) ;
 vec.YAxis -= x * sin(yawRad) - y * cos(yawRad) ;

 x = vec.XAxis; z = vec.ZAxis;
 vec.XAxis -=  x * cos(pitchRad) + z * sin(pitchRad) ;
 vec.ZAxis -= - x * sin(pitchRad) + z * cos(pitchRad) ;

 y = vec.YAxis, z = vec.ZAxis;
 vec.YAxis -=  y * cos(rollRad) - z * sin(rollRad);
 vec.ZAxis -=  y * sin(rollRad) + z * cos(rollRad);

 return vec;
}

```

Now this is far better, as after calculating effect of `roll,pitch,yaw` in every step the `x,y,z` changes. I missed that part. I was calculating directly, so it was giving me wrong value.

`vec.XAxis -= x * cos(yawRad) - y * sin(yawRad)`

then, `vec.XAxis -= x * cos(pitchRad) + z * sin(pitchRad)` doesn't give the same result as the wrong one `vec.XAxis -= x * cos(yawRad) - y * sin(yawRad) + x * cos(pitchRad) + z
 * sin(pitchRad) + 0;`
> 1 votes

---
Tags: arduino-uno, accelerometer, mpu6050, gyroscope, mathematics
---


title: NRF24L01 Networking

text:
# Question
Title: NRF24L01 Networking
We checked Xbee, ZigBee and other alternatives already and we're trying to figure out a way for good and cheap network system. NRF24l01 looks good but 32 bytes not enough actually. Even so looks like we'll use it but some questions;

Questions' scenario contains 1 master and 300 slave devices with NRF24l01. We're thinking about making a addressing system like computer networks and every message will contain device id or device group tag. Master will be at the center of the room. Room do not have any inner wall or obstacle. Maximum range is less than 100m².

1) May messages get corrupt or latency ?
2) Is there any prepared library for Arduino for this kind of communication ?
3) Do you think is there any better solution for this kind of master & slaves networking logic (*must be cheap and stable*) ?

# Answer
> 1) May messages get corrupt or latency ?

For uni-directional Master to One Slave, no, there should be no corruption (at least not caused by there being lots of slaves present). For bi-directional Master to Multiple Slaves at the same time, yes, you're going to run into problems when the slaves try and reply. Keeping your protocol really simple will be beneficial.

> 2) Is there any prepared library for Arduino for this kind of communication ?

There's nothing special about what you propose. The RF24.h library will probably do the job (though I have never used it, so don't ask me how to use it).

> 3) Do you think is there any better solution for this kind of master & slaves networking logic (must be cheap and stable) ?

They're all a bit of a muchness really. RF communication is RF communication. It's how you use it that matters.

The nRF24L01+ has a number of benefits that mean you can do some things in hardware:

* Multiple receive pipes, each with their own address - so you can have one for the device address, one for a group address, and one for a global "broadcast" address
* Auto-acknowledge and re-sending of failed packets for more reliable communication (only for one-to-one communication)
* Automatic packetisation so you don't have to worry about crafting a low-level protocol of your own
* Direct communication giving low-latency
* Power Amplifier option for greater range.

You could use WiFi, however that would struggle with so many devices (most home access points and routers can't handle more than a few dozen devices), plus it adds extra latency that it sounds like you don't want.

The nRF24L01+ is probably a good choice for this kind of communication - however, be cautious with cheap clone devices: some of them have a silicon error that causes them to not be compatible with other nRF24L01+ devices.
> 2 votes

---
Tags: wifi, nrf24l01+
---


# Question
Title: Strange behaviour with WS2812B RGB LED Strip
I tried to use a RGB LED strip, following a guide. I connected the voltage pin to the Arduino UNO **5v pin**, the ground pin to the **GRN pin** and I used the pin 5 for **DIN**.

I used this image as reference:

I tried two different libraries, with the first one, the FAST LED, I used this code:

```
#include <FastLED.h>

#define LED_PIN     5
#define NUM_LEDS    15
#define BRIGHTNESS  64
#define LED_TYPE    WS2811
#define COLOR_ORDER GRB
CRGB leds[NUM_LEDS];

#define UPDATES_PER_SECOND 100

CRGBPalette16 currentPalette;
TBlendType    currentBlending;

extern CRGBPalette16 myRedWhiteBluePalette;
extern const TProgmemPalette16 myRedWhiteBluePalette_p PROGMEM;

void setup() {
    delay( 3000 ); // power-up safety delay
    FastLED.addLeds<LED_TYPE, LED_PIN, COLOR_ORDER>(leds, NUM_LEDS).setCorrection( TypicalLEDStrip );
    FastLED.setBrightness(  BRIGHTNESS );

    currentPalette = RainbowColors_p;
    currentBlending = LINEARBLEND;
}

void loop()
{
    ChangePalettePeriodically();

    static uint8_t startIndex = 0;
    startIndex = startIndex + 1; /* motion speed */

    FillLEDsFromPaletteColors( startIndex);

    FastLED.show();
    FastLED.delay(1000 / UPDATES_PER_SECOND);
}

void FillLEDsFromPaletteColors( uint8_t colorIndex)
{
    uint8_t brightness = 255;

    for( int i = 0; i < NUM_LEDS; i++) {
        leds[i] = ColorFromPalette( currentPalette, colorIndex, brightness, currentBlending);
        colorIndex += 3;
    }
}

void ChangePalettePeriodically()
{
    uint8_t secondHand = (millis() / 1000) % 60;
    static uint8_t lastSecond = 99;

    if( lastSecond != secondHand) {
        lastSecond = secondHand;
        if( secondHand ==  0)  { currentPalette = RainbowColors_p;         currentBlending = LINEARBLEND; }
        if( secondHand == 10)  { currentPalette = RainbowStripeColors_p;   currentBlending = NOBLEND;  }
        if( secondHand == 15)  { currentPalette = RainbowStripeColors_p;   currentBlending = LINEARBLEND; }
        if( secondHand == 20)  { SetupPurpleAndGreenPalette();             currentBlending = LINEARBLEND; }
        if( secondHand == 25)  { SetupTotallyRandomPalette();              currentBlending = LINEARBLEND; }
        if( secondHand == 30)  { SetupBlackAndWhiteStripedPalette();       currentBlending = NOBLEND; }
        if( secondHand == 35)  { SetupBlackAndWhiteStripedPalette();       currentBlending = LINEARBLEND; }
        if( secondHand == 40)  { currentPalette = CloudColors_p;           currentBlending = LINEARBLEND; }
        if( secondHand == 45)  { currentPalette = PartyColors_p;           currentBlending = LINEARBLEND; }
        if( secondHand == 50)  { currentPalette = myRedWhiteBluePalette_p; currentBlending = NOBLEND;  }
        if( secondHand == 55)  { currentPalette = myRedWhiteBluePalette_p; currentBlending = LINEARBLEND; }
    }
}

void SetupTotallyRandomPalette()
{
    for( int i = 0; i < 16; i++) {
        currentPalette[i] = CHSV( random8(), 255, random8());
    }
}

void SetupBlackAndWhiteStripedPalette()
{
    fill_solid( currentPalette, 16, CRGB::Black);
    currentPalette[0] = CRGB::White;
    currentPalette[4] = CRGB::White;
    currentPalette[8] = CRGB::White;
    currentPalette[12] = CRGB::White;

}

// This function sets up a palette of purple and green stripes.
void SetupPurpleAndGreenPalette()
{
    CRGB purple = CHSV( HUE_PURPLE, 255, 255);
    CRGB green  = CHSV( HUE_GREEN, 255, 255);
    CRGB black  = CRGB::Black;

    currentPalette = CRGBPalette16(
                                   green,  green,  black,  black,
                                   purple, purple, black,  black,
                                   green,  green,  black,  black,
                                   purple, purple, black,  black );
}

const TProgmemPalette16 myRedWhiteBluePalette_p PROGMEM =
{
    CRGB::Red,
    CRGB::Gray,
    CRGB::Blue,
    CRGB::Black,

    CRGB::Red,
    CRGB::Gray,
    CRGB::Blue,
    CRGB::Black,

    CRGB::Red,
    CRGB::Red,
    CRGB::Gray,
    CRGB::Gray,
    CRGB::Blue,
    CRGB::Blue,
    CRGB::Black,
    CRGB::Black
};

```

and with the second library, Adafruit\_Neopixel

```
#include <Adafruit_NeoPixel.h>
#define PIN 5
#define NUM_LEDS 15
// Parameter 1 = number of pixels in strip
// Parameter 2 = pin number (most are valid)
// Parameter 3 = pixel type flags, add together as needed:
//   NEO_KHZ800  800 KHz bitstream (most NeoPixel products w/WS2812 LEDs)
//   NEO_KHZ400  400 KHz (classic 'v1' (not v2) FLORA pixels, WS2811 drivers)
//   NEO_GRB     Pixels are wired for GRB bitstream (most NeoPixel products)
//   NEO_RGB     Pixels are wired for RGB bitstream (v1 FLORA pixels, not v2)
Adafruit_NeoPixel strip = Adafruit_NeoPixel(NUM_LEDS, PIN, NEO_GRB + NEO_KHZ800);

void setup() {
  strip.begin();
  strip.show(); // Initialize all pixels to 'off'
}

// *** REPLACE FROM HERE ***
void loop() {
  RGBLoop();
}

void RGBLoop(){
  for(int j = 0; j < 3; j++ ) {
    // Fade IN
    for(int k = 0; k < 256; k++) {
      switch(j) {
        case 0: setAll(k,0,0); break;
        case 1: setAll(0,k,0); break;
        case 2: setAll(0,0,k); break;
      }
      showStrip();
      delay(3);
    }
    // Fade OUT
    for(int k = 255; k >= 0; k--) {
      switch(j) {
        case 0: setAll(k,0,0); break;
        case 1: setAll(0,k,0); break;
        case 2: setAll(0,0,k); break;
      }
      showStrip();
      delay(3);
    }
  }
}
// *** REPLACE TO HERE ***

void showStrip() {
 #ifdef ADAFRUIT_NEOPIXEL_H
   // NeoPixel
   strip.show();
 #endif
 #ifndef ADAFRUIT_NEOPIXEL_H
   // FastLED
   FastLED.show();
 #endif
}

void setPixel(int Pixel, byte red, byte green, byte blue) {
 #ifdef ADAFRUIT_NEOPIXEL_H
   // NeoPixel
   strip.setPixelColor(Pixel, strip.Color(red, green, blue));
 #endif
 #ifndef ADAFRUIT_NEOPIXEL_H
   // FastLED
   leds[Pixel].r = red;
   leds[Pixel].g = green;
   leds[Pixel].b = blue;
 #endif
}

void setAll(byte red, byte green, byte blue) {
  for(int i = 0; i < NUM_LEDS; i++ ) {
    setPixel(i, red, green, blue);
  }
  showStrip();
}

```

I don't know why, but only some of the leds in the strips make lights and only blue lights. How can I fix this problem? I also tried to change the **Din** pin using 4, 5 and 6, but nothing changed.

**EDIT**

I found that all my led were broken... I bought a new strip and now I have a prototype perfectly working using any of the code above. Thanks for helping me

# Answer
> 1 votes
In the first sketch you use

```
#define LED_TYPE    WS2811

```

While you have WS2812

Each led strip type has different timings, so it can occur that some LEDs will flash, or are on or off while they should not be, if the wrong model is selected.

Probably the first LEDs work better than later ones.

# Answer
> 1 votes
What makes you sure replacing the LED strip was the solution? I suggest running the LED strip from the Arduino +5V is a likely problem (too much current drawn) and using a different LED strip you've just been lucky that it works now.

Try with a separate power supply for the LEDs but connect grounds together. If you don't have another 5V power supply which can supply at least 1 Amp, try limiting the brightness and/or number of LEDs *in software* to see if it works and if so, then try with the original strip.

---
Tags: arduino-uno, rgb-led, neopixel
---