body:
I have a keypad like this: [![][1]][1]

[here][2] is another, closer look at the bottom part.

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

this is my code:

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

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

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

        if (x == 500) {
          break;
        }

        delay(500);

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

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

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

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

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

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

  [1]: https://i.stack.imgur.com/QcMwH.png
  [2]: https://i.stack.imgur.com/rUwS5.png

title: Keypad giving random inputs

Answers: 1

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

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


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

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

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

Simple code:

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

    #define TxPin 7
    #define RxPin 6

    SoftwareSerial ESPrelay(RxPin, TxPin);

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

     readRx();

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

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

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

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

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

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

[![enter image description here][1]][1]

  [1]: https://i.stack.imgur.com/xUNBf.jpg

title: Arduino UNO + ESP8266 WiFi Relay by LC Technology

Answers: 1

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

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

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


body:
I'm trying to decode my Panasonic television remote using the IR_RECEIVE sketch below.

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

This is the code:

 /* Raw IR decoder sketch!

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

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

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

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

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

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

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

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

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

  currentpulse++;
 }

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

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

This is the output:

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

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

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

I tried resetting and re-uploading.

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

title: Arduino Uno keeps looping on setup() everytime I press a specific button on the remote

Answers: 1

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

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


body:
I have found that the `n` parameter of `snprintf()` seems to be ignored in my code.

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

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

title: Why is 'n' parameter of snprintf ignored?

Answers: 3

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

See this [snprintf() reference][1].

  [1]: http://www.cplusplus.com/reference/cstdio/snprintf/

body:
A test sketch for the Arduino Uno:

    char buffer[10];

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

    void loop() {
    }

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

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

  [1]: http://www.cplusplus.com/reference/cstdio/snprintf/
  [2]: http://www.cplusplus.com/reference/cstdio/vsnprintf/

body:
For completion, the man page for [`fprintf`][1] states:

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

and, more relevant:

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

  [1]: http://man7.org/linux/man-pages/man3/fprintf.3p.html


body:
Before bothering anybody, I've been Googling this issue for the last three weeks and have not been able to solve the issue, so must reach out for help.

My son has done multiple Arduino projects after having a Creation Crate subscription, and now we're working on a project together.  We bought a 28BYJ-48 stepper with driver, and figured it'd be just a question of copy-and-paste coding and we'd be in business.

I've tried the Arduino library, the AccelStepper library, countless other sketches from various websites and for some reason the stepper only vibrates when it's supposed to turn CCW.  There was one sketch we were using that used Serial Monitor to enter in the number of steps, and when i'd do a minus number of steps, it'd go CCW, but the next day no longer would!  I thought this was a motor or driver issue, but we've bought three more motor/drivers and still have the same problem.  In researching an answer, I've seen some people say to switch IN 3 & 4 but I still get same results.

We've been connecting 8 to IN1, 9 to IN2, 10 to IN3 and 11 to IN4.  Using a separate 5V power supply to the driver which is also grounded to the Arduino (have tried both ground pins just in case that makes a difference, but no).  We've also tried changing for another Arduino and this hasn't made a difference either.

we've tried multiple sketches from multiple sources, here's one as an example:

    #include <Stepper.h>

    const int stepsPerRevolution = 200;  // change this to fit the number of steps per revolution
    // for your motor

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

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

    void loop() {
      // step one revolution  in one direction:
      Serial.println("clockwise");
      myStepper.step(stepsPerRevolution);
      delay(500);

      // step one revolution in the other direction:
      Serial.println("counterclockwise");
      myStepper.step(-stepsPerRevolution);
      delay(500);
    }

The Serial Monitor will state that it's turning CCW, but it isn't.  Any help would be much appreciated!  What we thought would be a simple step in our project has become a major roadblock!

title: Stepper Motor won't reverse/turn CCW

Answers: 2

body:
I had this issue myself, when I tried to use these stepper motors (which are to be honest really crappy ones, but very cheap). Vibrating mostly means, that the phases of the motor are not activated in the correct order. These motors seem to work with an activation pattern for half steps (I don't know, if the motor is really doing half steps with this, because I didn't counted them for a whole revolution. But at least they worked). The [Stepper library][1] (I assume from your code, that you are using this one) isn't meant for this driver, so it will turn on the phases in a wrong order and always two phases at the same time (as for full steps).

I had success, when driving the 4 phases of the driver with the following pattern (for half steps):

    1000
    1100
    0100
    0110
    0010
    0011
    0001
    1001

I also found hints on the web (on a [german site][2], just for reference, if you can read german), that - despite being meant for half steps - you can drive the motor with full steps with the Stepper library as well. You would have to change the order of pins in the definition of the stepper:

    Stepper myStepper(stepsPerRevolution, 8, 10, 9, 11);

This assumes the wiring as: D8->IN1, D9->IN2, D10->IN3, D11->IN4. Note, that using full steps means 2048 steps per revolution.

---

I also found a library specific for this stepper motor, but I haven't tested it: [Stepper_28BYJ_48][3]

---

Now you can decide yourself, which way you want to go. I personally would go for the full steps with the official Arduino Stepper library.

---

About the number of steps per revolution: I don't know, why the stepper doesn't work with a vale of 2048. But since the library only uses this to wrap up the correct phases for the revolutions, you can use a lower value, that is dividable by 4. For example 32, which is the number of full steps per revolution of the actual motor (it is attached to gears with a factor of 64). That should work.

  [1]: https://github.com/arduino-libraries/Stepper
  [2]: https://blog.thesen.eu/es-geht-doch-schrittmotor-28byj-48-mit-der-original-arduino-stepper-library/
  [3]: https://github.com/thomasfredericks/Stepper_28BYJ_48

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

This guy just flipped IN2 and IN3 and it solved the problem of going forwards and backwards. It worked for me and here is the code.

    #include <Stepper.h> // Include the header file

    // change this to the number of steps on your motor
    #define STEPS 64

    // create an instance of the stepper class using the steps and pins
    Stepper stepper(STEPS, 8, 10, 9, 11);

    int Pval = 0;
    int potVal = 0;

    void setup() {
      Serial.begin(9600);
      stepper.setSpeed(200);
    }

    void loop() {

    potVal = map(analogRead(A0),0,1024,0,100);
    if (potVal>Pval)
      stepper.step(10);
    if (potVal<Pval)
      stepper.step(-10);

    Pval = potVal;

    Serial.println(Pval); //for debugging
    }


body:
I'm using the PCA9685 module with its Adafruit library. In my code I have one object of the servodriver class that has 14 channels (controlling 14 servos basically).

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

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

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

title: How to change speed of multiple servos acting at the same time with PCA9685 module?

Answers: 1

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

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

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


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

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

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

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

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

title: Serial Moniter is repeating output

Answers: 1

body:
Change

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

to

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

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


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

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

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

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

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

Thank you so much.

title: Increase and Decrease Motor Speed

Answers: 1

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

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


body:
I'm using my Arduino Uno to control a [5V 1A solenoid][1].

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

[![5V 1A solenoid controlled by N-Channel MOSFET linked to Arduino Uno I/O pin, powered by Arduino Uno's built in 5V output][4]][4]

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

[![5V 1A solenoid controlled by N-Channel MOSFET linked to Arduino Uno I/O pin, powered by 5V 12A power supply][6]][6]

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

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

Thanks,

Max

  [1]: https://www.sparkfun.com/products/11015
  [2]: https://www.sparkfun.com/datasheets/Components/General/RFP30N06LE.pdf
  [3]: https://www.digikey.com/product-detail/en/diodes-incorporated/1N5818-T/1N5818DICT-ND/190657?utm_adgroup=Semiconductor Modules&slid=&gclid=EAIaIQobChMIscCI99-V3gIVF8ZkCh3w-AZxEAAYASAAEgJnrfD_BwE
  [4]: https://i.stack.imgur.com/hQjAR.png
  [5]: https://www.amazon.com/PHEVOS-Universal-Switching-Raspberry-Computer/dp/B074YHN8D1/ref=sr_1_1?ie=UTF8&qid=1538973367&sr=8-1&keywords=PHEVOS 5v 12A Dc Universal
  [6]: https://i.stack.imgur.com/so1p2.png

title: Solenoid "vibrates" instead of pushing

Answers: 1

body:
From your schematics it looks like:

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

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

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


body: I am planning to to use ultrasonic sensors mounted on a drone for obstacle avoidance. I am not sure if the sensors would be capable of detecting a Net Like obstacle in its path.

title: Does a normal Ultra-Sonic sensor (HC SR04) sense through a Football Net like obstacle?

Answers: 1

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


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

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

title: Adafruit Trinket M0 persistent storage?

Answers: 1

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

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

  [1]: https://github.com/cmaglie/FlashStorage


body:
So I want to make the same effect as a colorwipe (like going around in a circle turning leds on till they all turn on) except that instead of going from off to 100% brightness immediately I need it to look more natural by making it fade from off to on gradually to a single color and the LEDS should stay on after the fade on is complete. This is my current code and i cant figure out how to make it fade. everything ive found on google is massively complex to do a simple thing. is it really that complex to accomplish this?

    #include <Adafruit_NeoPixel.h>
    #define PIN 6
    #define NUM_LEDS 24
    Adafruit_NeoPixel strip = Adafruit_NeoPixel(NUM_LEDS, PIN, NEO_GRBW + NEO_KHZ800);

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

    void loop() {
      colorWipe(strip.Color(255, 255, 255, 255), 70); //white

    }

    // Fill the dots one after the other with a color
    void colorWipe(uint32_t c, uint8_t wait) {
      for(uint16_t i=0; i<strip.numPixels(); i++) {
        strip.setPixelColor(i, c);
        strip.show();
        delay(50);
      }
    }

title: How do i fade a colorwipe from off to on in 1 color?

Answers: 2

body:
See [my answer here](https://arduino.stackexchange.com/a/48855/10794).

Code from that answer:

    /*
     *
     * NeoPixels demo - fades colours (in array) up and down
     *
     */

    #include <SPI.h>
    #include <NeoPixels_SPI.h>

    const unsigned int PIXELS = 8; // Number of pixels in the string

    void setup()
      {
      ledsetup();
      } // end of setup

    float patterns [] [3] = {
      { 1, 0, 0 },  // red
      { 0, 1, 0 },  // green
      { 0, 0, 1 },  // blue
      { 1, 1, 0 },  // yellow
      { 1, 0, 1 },  // magenta
      { 0, 1, 1 },  // cyan
      { 1, 1, 1 },  // white
      { 160.0 / 256, 82.0 / 256, 45.0 / 256 },  // sienna
      { 46.0 / 256, 139.0 / 256, 87.0 / 256 },  // sea green

    };

    // number of items in an array
    #define ARRAY_SIZE(x) (sizeof(x) / sizeof((x)[0]))

    void loop()
      {

      for (byte i = 0; i < ARRAY_SIZE (patterns); i++)
        {
        // fade up
        for (byte m = 0; m < 100; m++)
          {
          showColor (PIXELS, patterns [i] [0] * m, patterns [i] [1] * m, patterns [i] [2] * m);
          delay (10);
          } // end of for

        // fade down
        for (byte m = 100; m > 0; m--)
          {
          showColor (PIXELS, patterns [i] [0] * m, patterns [i] [1] * m, patterns [i] [2] * m);
          delay (10);
          } // end of for
        } // end of for each array item

      } // end of loop

body:
Note that the "wait" variable is not actually used in your colorwipe function.

The colorwipe function seems to turn them all on in succession. The only thing you need to do is add fading to it.

    for(uint16_t i=0; i<strip.numPixels(); i++) {
        for(uint8_t brightness=0; brightness<maxBrightness; brightness++){
           strip.setPixelColor(i, strip.Color(brightness, brightness, brightness, brightness );
           strip.show();
           delay(wait);
      }


body:
I recently upgraded my MacBook Pro to Mojave. Now I'm not able to connect to my Arduino board with ch340g usb-to-serial chip. It is a Arduino board with AtMega 328 and ESP8266 integrated. I downloaded the drivers from the Chinese website for the ch340 and also removed old installations, like some tutorials tell me. I just can't get a `/dev/cu.*` port (besides the `/dev/cu.Bluetooth-Incoming-Port`.

I do have an external FTDI usb to serial board. I didn't get to it to try to connect it.

Does someone know how to get the ch340 to work on MacOS Mojave, or as a last resort: use the FTDI to program/monitor the Arduino board?

title: Connect to ch340 on MacOS Mojave

Answers: 2

body:
this my problem too.
i found these solutions

 1. m[ac-usb-serial][1] app
 2. a topic in [arduino][2] forum

make sure delete old usb driver in these path

/Library/Extensions/usbserial.kext

and

 /System/Library/Extensions/usb.kext

then install it again [download link][3]

  [1]: https://www.mac-usb-serial.com/
  [2]: https://forum.arduino.cc/index.php?topic=570440.0
  [3]: https://drive.google.com/file/d/1lUYkw-mCOekJjY1MVA5YuEbERHNWNCZW/view

body:
Ok, this is the solution for me:

remove all old drivers:

    sudo rm -rf /Library/Extensions/usbserial.kext
    sudo rm -rf /System/Library/Extensions/usb.kext

Now reboot the computer.

And then (very important, because it took me 10 cables to find the right one) use a **fully connected** cable ;-)

Now I have these ports:

    /dev/cu.wchusbserial1410
    /dev/cu.usbserial-1410


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

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

The combined code I have drafted is there:

      #include <Stepper.h>

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

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

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

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

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

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

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

        }

title: How to get the encoder position while the rotary motor is moving

Answers: 1

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

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

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


body:
I want to obtain the `.hex` file from my Arduino sketch. I have followed various guides but there is no `.hex` file in my output folder.

How can I obtain my hex file?

Here are my preferences:

> [![Arduino IDE preferences][1]][1]

This is the contents of my output folder

> [![Output folder][2]][2]

  [1]: https://i.stack.imgur.com/jePRw.png "Arduino IDE preferences"
  [2]: https://i.stack.imgur.com/nnMG3.png "Output folder"

title: Why is there no hex file generated when I "build binary output" from the Arduino IDE?

Answers: 2

body:
Based on your setting with the URL for esp8266 package and bin file name with "...generic" I assume you want it for esp8266.

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

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

body:
##Current versions of Arduino IDE

Use the menu option in the Arduino IDE:

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

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

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

Here is a screenshot for OS X:

> [![Export compiled Binary menu option][3]][3]

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

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

---

##Older versions of Arduino IDE

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

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

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

> [![Arduino IDE Preferences menu][7]][7]

> [![Arduino IDE Preferences dialog][8]][8]

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

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

5. Change the following line

        export.delete_target_folder=true

  to

        export.delete_target_folder=false

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

  [1]: https://forum.arduino.cc/index.php?topic=131655.msg2445740#msg2445740
  [2]: https://forum.arduino.cc/index.php?topic=131655.0
  [3]: https://i.stack.imgur.com/GhdPn.png "Export compiled Binary menu option"
  [4]: https://forum.arduino.cc/index.php?topic=131655.msg3118445#msg3118445
  [5]: https://forum.arduino.cc/index.php?topic=131655.msg3399334#msg3399334
  [6]: http://arduinoisfun.blogspot.in/2016/01/taking-out-hex-file-from-arduino.html
  [7]: https://i.stack.imgur.com/SUgn2.png "Arduino IDE Preferences menu"
  [8]: https://i.stack.imgur.com/Zd2te.jpg "Arduino IDE Preferences dialog"


body:
I want to combine these three sketches into one.

RAIN SENSOR:

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

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

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

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

LIGHT SENSOR:

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

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

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

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

SMOKE SENSOR:

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

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

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

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

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

 - the `greenLED` and;
 - the `redLED`.

title: Can you help me combining these sensor sketches as one in Arduino

Answers: 1

body:
### Variable renaming

1. Rename `thresholdValue` in the first two sketches to `rainSensorThreshold`, and `lightSensorThreshold` respectively, and `sensorThres` to `smokeSensorThreshold` in the third sketch.

2. Rename `sensorValue` in the first two sketches to `rainSensorValue`, and `lightSensorValue` respectively, and `analogSensor` to `smokeSensorValue` in the third sketch.

### Change the Analog pin

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

    int ldrPin = A0;

### Consistant LED pins

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

    int greenLed = 11;
    int redLed = 12;

to

    int greenLED = 6;
    int redLED = 7;

### Recompile each sketch

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

### Combine the code

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

 - Global variables
 - `setup()`
 - `loop()`


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

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

title: Playing MP3 Shield tracks

Answers: 1

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

implementation of the playTrack function:

    uint8_t SFEMP3Shield::playTrack(uint8_t trackNo){

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

      //tack the number onto the rest of the filename
      sprintf(trackName, "trackd.mp3", trackNo);

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

change it to:

    uint8_t SFEMP3Shield::playTrack(uint8_t trackNo){

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

      //tack the number onto the rest of the filename
      sprintf(trackName, "trackd.mp3", trackNumber);

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


body:
![enter image description here](https://i.stack.imgur.com/nWTUX.png)
Hello all,
I'm working on RGB LED strip SMD 5050 5m
This all setup is working on 12v 2A with about diagram.
I want to use same connection with 100m of LED strip using Arduino.
Please support regarding this topic.
H/W details :
Arduino uno
Hc-05 bt module
12v 1.2 amp supply
Td140 pnp transistor
SMD 5050 LED strip 60 LED/m

title: RGB LED strip 100m

Answers: 1

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

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

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

Good luck with your circuit!


body:
I'm trying to run a Nema 17 motor with a l298N motor Driver for a school project. The issue is that I am running the motor with PWM to avoid overheating of the driver, however the resulting noise at the default frequency is extremely aggravating.

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

title: Changing PWM on Arduino Mega, pins 9 & 10 to 20 to 25 KHz

Answers: 1

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

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

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

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

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

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

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

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

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

Also check that your motor driver can handle the frequency.


body:
I have a **[CNC Shield][1]** on top of an **Arduino Uno** [(GRBL pinout)][2] that controls 2 stepper motors through [a4988][3] drivers and it is working like a charm.

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

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

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

  [1]: https://www.google.ca/search?biw=1920&bih=943&tbm=isch&sa=1&ei=n4TOW7eNONGa_Qavj4eQDg&q=CNC shield pinout&oq=CNC shield pinout&gs_l=img.3...1027.1106.0.1207.2.2.0.0.0.0.107.107.0j1.1.0....0...1c.1.64.img..2.0.0....0.oRXgLHXaWjI#imgrc=TvbYa1eErVZtTM:
  [2]: https://www.google.ca/search?q=grbl+pinout+arduino&source=lnms&tbm=isch&sa=X&ved=0ahUKEwjQ383lvJveAhVGpFkKHeOmBAwQ_AUIDigB&biw=1920&bih=943#imgrc=vx7m9YRUDwnTtM:
  [3]: https://www.google.ca/search?q=a4988&source=lnms&tbm=isch&sa=X&ved=0ahUKEwiSj_nLwpveAhWQq1kKHV3FDN0Q_AUIDigB&biw=1920&bih=943#imgrc=s-_Efs_BmWkgOM:
  [4]: https://www.google.ca/search?q=mpu6050 pinout&tbm=isch&source=iu&ictx=1&fir=HoKY3HCvU5ukaM%3A%2CeeFmV1QetaP_CM%2C_&usg=AI4_-kSbhYvAc7XSWNmnHOmVQhtYTwbMHw&sa=X&ved=2ahUKEwiP3LG3vJveAhUiwVkKHRyeAAkQ9QEwCXoECAYQFg#imgrc=GYJF8Nah-qpxeM:

title: How to connect a MPU-6050 to an Arduino that already has a CNC Shield V3 on top of it?

Answers: 2

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

to something like

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

    `#define Z_DIRECTION_BIT   7  // Uno Digital Pin 7`
Clear that one out, and you should be able to use pin 7 as an I/O.

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

I hope this was a bit helpful!

[![enter image description here][1]][1]

EDIT:

I realized I didn't specify how to exactly free up A5. It has been assigned to the probe in the cpu_map.

[![enter image description here][2]][2]

  [1]: https://i.stack.imgur.com/EyiwN.png
  [2]: https://i.stack.imgur.com/3Ge23.png

body: MPU6050 can use only I2C. Those are pins A4 and A5 on an Uno. 5V and ground are 5v and ground, no matter from which pin


body:
I have an Arduino Uno I need to connect to Wi-Fi to make HTTP POST Requests to a Raspberry Pi Web Server.

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

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

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

title: Are there any Wi-Fi modules for the Arduino Uno that may connect to an external Wi-Fi Antenna?

Answers: 1

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

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

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


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

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

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

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

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

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

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

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

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

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

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

    }

title: How to convert this sketch to keep only one if-else statement?

Answers: 2

body:
Sure:

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

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

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

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

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

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

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

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

body:
First find the duplicated code.

E.g. the fragment

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

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

is repeated three times.

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

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

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

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

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

And call respectively:

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

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

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


body:
I have an Arduino Uno and a string of WS2811 LEDs. I am still trying to get started on this project, which is creating [a Stranger Things wall][1]. I've installed FastLED and uploaded the sample program "Blink" to the Arduino, which appears to upload correctly. However, the lights don't blink.

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

 - Here's the setup I'm trying to follow.
[![enter image description here][3]][3]

Thanks in advance for any help!

  [1]: https://www.instructables.com/id/Arduino-Based-Stranger-Things-Lights/
  [2]: https://i.stack.imgur.com/T4wRq.jpg
  [3]: https://i.stack.imgur.com/gh2hr.jpg

title: How do I know if my Arduino is connected to my LEDs?

Answers: 1

body: The sample code sets the data pin to 3, but I was using 6. Noob mistake.


body:
How do I use the keyboard to cycle through Arduino windows on a mac?

In my System preferences, I have (default):

`Keyboard` -> `Shortcuts` -> `Move focus to next window` = <kbd> Cmd ⌘ </kbd> <kbd> ` </kbd>

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

I am using fully updated MacOS 10.14 and Arduino IDE 1.8.7

title: Mac shortcut for next window - IDE 1.8.7 problem

Answers: 2

body: Just by trying, I found that <kbd> Cmd ⌘ </kbd> <kbd> Shift </kbd> <kbd> ` </kbd> cycles through *all* windows (maybe in reverse).

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

Update:

> When you upgrade to Arduino 1.8.7,

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

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

Update 2:

The OP asked me to note that he

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

Update 3:

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

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


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

Thanks for everything :)

title: How to build a robot that can stop at a certain point using an altimeter

Answers: 1

body:
have fun playing with the Arduino and some sensors! It is a great platform to learn. For your task, look into the Bosch sensor modules [BME280](https://cdn-shop.adafruit.com/datasheets/BST-BME280_DS001-10.pdf) (pressure with temperature and humidity) or [BMP280](https://cdn-shop.adafruit.com/datasheets/BST-BMP280-DS001-11.pdf) (just pressure). You can expect maybe +-1 meter of accuracy. Or check the precision version [BME388](https://datasheet.octopart.com/BMP388-Bosch-Tools-datasheet-103686868.pdf) that could give you +-50cm. Go to the [adafruit shop](https://www.adafruit.com/category/114) and try a few of the breakout boards. They provide great library and documentation support.

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

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


body:
It seems to me that humidity is getting high in one room in the basement in my house. To monitor the situation temporarily, I would like to build a very small wifi-mesh network to exchange these humidity data to a locally installed raspberry pie server. Most of the time the networking would be in idle state, every some 5 minutes sending the humidity sensor data over mqtt to the server.

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

I tried this code:

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

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

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

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

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

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

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

        wifi_it++;
        delay(500);
      }

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

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

    void loop(void){

    }

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

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

title: Bridging the wifi networks on nodemcu: how to set the esp8266 as wifi extender, simplest case

Answers: 1

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

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

something like this (not tested):

    void loop() {

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

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

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


body:
I'm trying to create an UART connection between a Nano and an NodeMCU, running MicroPython.

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

Connections :

Nano Rx --> ESP Tx

Nano Tx --> ESP Rx

Nano USB -- > Mac running `repl`

ESP USB --> Linux running `Arduino IDE`

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

Appreciate any help.

title: UART connection between Arduino Nano and NodeMCU

Answers: 1

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

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

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

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


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

Thanks.

[![enter image description here][1]][1]

[![enter image description here][2]][2]

  [1]: https://i.stack.imgur.com/uYOUd.jpg
  [2]: https://i.stack.imgur.com/h56nl.jpg

title: Where does the sound come from this board?

Answers: 2

body: That looks like a piezo buzzer, the component that had the sticker on it. It's likely louder now, with the sticker removed.

body:
this is a PCB mountable piezo buzzer. it makes sound in your "RFID Proximity Entry Door Secure Lock Access Control System"

[![enter image description here][1]][1]

  [1]: https://i.stack.imgur.com/VZbIX.jpg


body:
I am trying to make a launch controller, which will turn on with a key. Like the one in this photo below:

[![Switch Controller][1]][1]

  [1]: https://i.stack.imgur.com/y5D79.png

title: Is there a key switch for Arduino?

Answers: 2

body: A key switch is just a normal switch. What you do with it depends on how you wire it and code for it.

body:
Check for example [here][1] for a key switch (see picture below).

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

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

[![enter image description here][2]][2]

  [1]: https://www.aliexpress.com/item/1pc-mini-key-switch-Lock-Switch-Security-Power-Locks-phone-switch/32799985398.html?spm=2114.search0104.3.86.1e172335PfIKpH&ws_ab_test=searchweb0_0,searchweb201602_5_10065_5024915_10068_318_319_317_10696_450_10084_10083_10618_452_535_534_10304_533_10307_10820_532_10301_10821_204_10843_10059_10884_323_10887_100031_320_321_322_5728515_10103_448_449,searchweb201603_35,ppcSwitch_0&algo_expid=24658571-3e24-48b0-bd58-540bb5cb5392-12&algo_pvid=24658571-3e24-48b0-bd58-540bb5cb5392&transAbTest=ae803_4
  [2]: https://i.stack.imgur.com/iWQtW.png


body:
I can't seem to integrate an nRF module to my nodeMCU.
I just want to verify my code but an error message keeps popping up

Below is the sketch:

    #include <SPI_Class.h>
    #include <nRF24L01.h>
    #include <RF24.h>
    #include <ESP8266WiFi.h>
    #define PIN_CE D4
    #define PIN_CSN D3
    RF24 radio(PIN_CE, PIN_CSN);

    struct package{
      int id = 1;
      int location = 1;
      char timeStamp = "date/time"
    };

    typedef struct package Package;
    Package data;

    public int data1=data.id;
    public int data2=data.location;
    public char data3=data.timeStamp;

    byte  address[][6] = "00001"

    const char* ssid = "Jino";
    const char* pass = "myinternet";

    char server[] = "cdgresearch.000webhostapp.com";

    WiFiClient client;

    int led = 2;

    void setup() {
      Serial.begin(9600);
      WiFi.begin(ssid,pass);
      pinMode(led,OUTPUT);
      digitalWrite(led, HIGH);
      delay(500);
      Serial.println("Connecting to: ");
      Serial.println(ssid);
      Serial.print("Connecting");
      while(WiFi.status() != WL_CONNECTED)
      {

        delay(1000);
        Serial.print(".");
      }

      delay(300);
      digitalWrite(led, LOW);
      Serial.println();
      Serial.println("Successfully connected to the network");
      Serial.print("NodeMCU IP Address: ");
      Serial.println(WiFi.localIP());

      delay(1000);

      radio.begin();
      radio.setChannel(115);
      radio.setPALevel(RF24_PA_LOW);
      radio.openWritingPipe(address[0]);
      delay(1000);
    }

    void loop() {
      // put your main code here, to run repeatedly:
      delay(9000);
      sendData();
    }

    void sendData(){
      Serial.println("Sending Data...");
      delay(1000);
      if (client.connect(server, 80)){
        WiFi.printDiag(Serial);
        Serial.println("Connected to server");
        client.print("GET /tag2.php?");
        client.print("incoming=Id ");
        client.print(data1);
        client.print("&incoming2=Loc");
        client.print(data2);
        client.println(" HTTP/1.1");
        client.println("Host: cdgresearch.000webhostapp.com");
        client.println("Connection: close");
        client.println();
        Serial.println();

        while(client.connected()){
          while(client.available()){
            Serial.write(client.read());
           }
          }
        radio.write(&data,sizeof(data));

        Serial.print("\nPackage: ");
        Serial.println(data1);
        Serial.print("Location: ")
        Serial.println(data2)
        Serial.println(data3)
        data1+=1;
        data2+=1;
        delay(1000);

      }

      else{
        Serial.println("Failed to Connect to server...");
        }

      client.stop();
      Serial.println("Disconnected from Server");
      while(client.status()!=0){
        delay (10);
       }
      }

and this error comes up in the console:
[![enter image description here][1]][1]

even if I use the #include<SPI.h>, still this pops out
[![enter image description here][2]][2]

  [1]: https://i.stack.imgur.com/aFdLw.png
  [2]: https://i.stack.imgur.com/RUCZi.png

title: How to integrate nRF24L01 to esp8266 nodeMCU?

Answers: 3

body:
I can confirm that it's possible to connect the two with TMRH20's RF24 library, which seems to be what you are using (judging by the name of the library). I'm currently building something with those very two components.

*Instead, the error is that **SPI_Class.h** can't be found by the IDE*. I can't recognize the name either, but if that is from attempting to include SPI to interface with the NRF24L01, you'd want **SPI.h** instead.

body:
Your error is: .../packages/esp8266/hardware/esp8266/2.4.2/libraries/SPI/**src/SPI.h**:1:23: fatal error: SPI_Class.h: No such file or directory...

You have some wrong SPI library there. The original folder `packages/esp8266/hardware/esp8266/2.4.2/libraries/SPI` doesn't contain `src` subfolder.

body: I reinstalled Arduino IDE and the libraries that I need, it works fine now. It must be because someone used my laptop and installed some rfid libraries which caused some problems in the libraries folders.


body:
This problem just started after 3 days of working on a project.

I am using Arduino IDE in Windows 10.

When I go to upload "Blink," everything works fine. I connect the USB (sometimes I have to change the port from COM6 to COM5) and upload and it blinks. All good. Well, one weird thing: sometimes I'll upload Blink when it's COM5 and then after the upload I'll notice that the Arduino has switched to COM6. So I have to go in and manually update the Port.

But after I switch to whichever Port has MKR1000 listed on it and go to upload my other more complicated program that uses WiFi and the Nokia 5110 LCD, it seems to throw the Arduino for a loop. All of a sudden it either won't upload properly or say port cannot be found and starts disconnecting from the port about 15 seconds after I connect it, and I'm not able to upload anything.

Anyone have any clues what might be going on? Thank you.

Adding some information about the connections from NOKIA 5110 (also using a breadboard in between):

RST: to pin 6  on MKR1000
CE: to pin 4 on MKR1000
DC: to pin 7 on MKR1000
Din: to pin 3 on MKR1000
Clk: to pin 5 on MKR1000
VCC:to VCC on MKR1000
BL: to VCC on MKR1000
GND: to GND on MKR1000

title: Why does attaching Nokia 5110 LCD make my otherwise fine MKR1000 disconnect USB after 15 secs?

Answers: 2

body:
The MKR board connects to computer over native USB support of the MCU. The handling of the USB is done by Arduino core functions linked at build to your sketch.

A consequence of using the native USB port is, if your sketch has a problem, it influences the USB communication. In this case you can activate the bootloader to handle the USB port and the upload. It is done by **double clicking the reset button on board**.

This applies to other SAMD boards (Zero, M0) and to AVR boards with native USB port (Leonardo, Micro) too.

body: Are you powering MKR1000 via USB? That only gives you about 1/2 amp of total current. I wonder if you're exceeding the available current of your power source. Add up the peak current requirements of your Arduino, (with WiFi active) the LCD, etc.


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

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

Answers: 1

body:
First, I think 40 mA to output from a GPIO is not a wise idea, because those are [Arduino Pin Current Limitations][1].

What you can do is:

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

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

  [1]: https://playground.arduino.cc/Main/ArduinoPinCurrentLimitations


body:
I wonder how to calculate pulldown resistor to make interrupt work?
I need to connect 5 buttons to A0 and get pressing event via interrupts.
Using different resistors, finally, I made work only 4 buttons. On 5th interrupt does not fire.
Currently I use the following resistors for the buttons:

    R1  Vout
    0  5,00
    2,7K 4,45
    5K  3,70
    10K  2,77
    22K  1,78

And Pulldown Resistor = 22K.

If pulldown Resistor = 10K I can get event for 1-3 button only.
Looks like the voltage 1,78V is quite low.
But I’d liked make it work with 1V at most.
I use RISING mode.

PS. Arduino Nano

title: Pull-down resistor value for interrupts

Answers: 1

body:
An Arduino running at 5V needs at least 3.0V on the pin to read it as rising high.  You probably want to go a little more than that.  So that means your lowest voltage has to be like 3.3V or so.

Note that the analog pins don't have an external interrupt, you'll have to use pin change interrupts and then read with analogRead in the ISR.  So you can't use "RISING".  The pin change interrupts act on any edge.  So they'll trigger when falling as well.

That's a pretty poor way to handle these buttons.  Normally one would just poll buttons like this.  If your loop takes so long that you might miss a human pressing a button then perhaps you should look at that instead.


body:
I have a simple connection here:

 - A WS2812B 5m 300 leds strip 5V;
 - A Power Supply MS-150-5 150W 5V;
 - Arduino with a simple code to blink 10 first leds;

TEST:
If I connect my power supply to my LED with a wireless controller with some saved presets, everything works fine. Colors, red, blue, white ( some voltage downhere ), but ok, working.
If take off the wireless controller and connect the LED to the Arduino, GND,+5, DATA, with a simple code, it's ok, 10 leds blinking, working fine.
BUT if I connect only the data to Arduino and connect the power to my power supply, now all the stripe go crazy, show no sense colors.

The Arduino code is ok, voltage is ok. Power supply is big enough. Even say to blink only one light is turning on all leds.

I was with a differente power supply before, same but 70w and was working ok. Now with 150w is not working. Why is not working with this one that is bigger? Maybe any noise ?

I'm connecting the power supply directly to the LED and only using the Arduino Data.

title: WS2812B LED Stripe going crazy with Arduino and External Power Supply

Answers: 2

body: Tks for reply guys. Thats correct. I have connected the GND of the external power supply with the GNC of Arduino and everything is fine.

body: Just make sure the Gnd from the Arduino and power supply are connected together - otherwise it would cause a common issue. Another recommendation would be to include a capacitor, usually a size of 1000uf is recommended.


body: This is probably a cry for help for a circuit diagram which involves connecting ESP8266 with ADS1115 with ACS712 and ZMPT101B(voltage sensor). Since both of them uses analog pins, and using a diode separator is not a proper idea in real-life. Therefore I ended up using the ADS1115 for more analog pins, which should be working fine. I am not a electrical engineer so I am having real trouble as to how to fix all Four of them together. Can any one help me with a circuit diagram for this? Any links or research papers links, etc. Thanks

title: Circuit diagram for ACS712 and ZMPT101B with ESP8266 using ADS1115

Answers: 2

body:
Step one is to get the ADC working.  Once that is done everything else will fall pretty much into place.

The ADC you have chosen is an I2C device.  The ESP8266 doesn't have I2C as such, but it does provide a software-emulated I2C implementation.  This can be used on any pair of pins, but the default ones are GPIO4 for the data (SDA) and GPIO5 for the clock (SCL) (this corresponds to the Arduino Uno using pins A4 and A5 for I2C, so it should be easy to remember).

Once you have that working the wiring for the rest is the same as for any other system. The only thing that differs is that your analogue inputs are on the ADC chip, not the main module.

Here's a block diagram to get you started:

<!-- Begin schematic: In order to preserve an editable schematic, please
     don't edit this section directly.
     Click the "edit" link below the image in the preview instead. -->

![schematic](https://i.stack.imgur.com/qv2lL.png)

<!-- End schematic -->

This is assuming:

* Single voltage output from each of your sensor modules
* I2C pullup resistors provided by either ESP8266 or ADS1115 (add your own if not)
* All modules providing the required support components for the chip

body: The ADS1115 use I2C a.k.a. Wire to communicate with MCU. Default Wire pins on esp8266 are io 5 SCL and io4 SCA. I recommend to use this pins. Of course the module needs 3.3 V and ground.


body: I am using an ESP8266 NodeMCU v0.1 and Sparkfun M6E Nano UHF Rfid reader. How to connect NodeMCU to M6E Nano UHF Rfid reader?

title: How to connect Sparkfun M6E Nano UHF Rfid reader and ESP8266 NodeMCU 0.1

Answers: 1

body: The interface of Sparkfun M6E Nano UHF Rfid reader is Serial TTL. So you should connect it to Serial pins of the NodeMcu. Don't use USB then, because it is connect to Serial too.


body:
I have early midnight accident of my Lolin/Wemos boards. I tried uploads my sketch with a assembly `VIN` to `GND` as my reset button, when i uploads my sketch at more one hundred times, i get my boards cannot be online again or my port cannot readable to my Ubuntu as `/dev/ttyXXX`. usually when i plugged the Usb3.0 cable, the blink led should be turn on at my boards but i didn't get it. How  i can re-flash my boards to be online again?

Thanks in advance.

title: Unexpected accident of my board, CH341 issue for Linux or Dead ESP?

Answers: 3

body:
Shorting VIN to GND will over-stress the diode that is in-line with the power coming in from the USB.

The result
----

* The diode will blow and you will not get power from the USB to power the board.
* The PC may detect "over-current" and shut down the USB port
* The USB port on the computer may be damaged

How do you fix it?
----

* Replace the diode if blown.
* Use a different USB port.

How do you work around it?
----

* Provide an external 5V power source to VIN & GND if the diode is blown

How do you avoid it happening in future?
----

* **NEVER short VIN to GND, even for a short time.**  There is a reset pin **RST** provided for the purpose of resetting the board.

body:
If the device still blinks and boots and whatnot, but doesn't connect to the computer, you've probably only broken the USB part of the NodeMCU.

Use the USB-TTL of another MCU. If you have an Uno, it's RST>GND, GND>GND, TX-RX, RX-TX. Mind GPIO 0+15 for programming. You can also use a USB TTL adapter, aka "an FTDI", the kind they used to use before everything had cheap built-in USB chips.

body:
Thanks to @Majenko my pal, from him advice i get a alternative ideas for fixed my issue.

**What i tried :**

1. I found [this][1] and I took my Uno, i pined 5v (Uno) to 5v (Esp) and i declared 13 pinout as the led blinky and then i uploaded "BlinkyWithoutDelay" sketch, it's seems doesn't work.
2.  I pined 5v (Uno) to 5v (Esp), Gnd (Uno) to Gnd (Esp) and i declared 13 pinout (Uno) to D3 pinout (Esp) and then i uploaded "BlinkyWithoutDelay" sketch, it's seems doesn't work.
3. I tried from Majenko advice to provide a Usb phone charger and connected white wire to 5v (Esp) and black wire to Gnd (Esp) without Uno board, and then i uploaded "BlinkyWithoutDelay" sketch, it's seems doesn't work.
4. From the 2nd point and the 3rd point, i run 2nd point without declared D3 pinout as the led blinky, and i changed from 5v to 3v3 (Uno and Esp), and after uploaded the sketch, it's seems the dim light (Esp) works like dim light (Uno) but i still cannot get my port for my esp, i had idea to unplugged my Uno and i changed from 5v to 3v3 and i uploaded my sketch, it's seems works to me. but i still cannot 5v properly or really death.

**The Solution**

From the 4th points , the solution is i provide a external power to 3v3 (esp) and i plugged to Usb2.0, i also plugged Usb3.0 as serial communication. when i uploaded "BlinkyWithoutDelay" sketch, it's seems works. The conclusion is my 5v pinout really death cause the diode for 5v pinout is blown up therefore i changed to 3v3 pinout.

**See my damaged board below**

[![this][2]][2]

That's also solved another my Esp boards. hope anyone didn't make a shorted between 5v to Gnd like me.

Thanks.

  [1]: https://forum.arduino.cc/index.php?topic=504901.msg3446033#msg3446033
  [2]: https://i.stack.imgur.com/bGF7s.jpg


body:
I have this challenge of receiving data when I send a command to voice recognition v3 module. The UART connections are okay, but when I send a command I don't receive a response on the terminal.

The prolific USB-TTL with drivers installed blinks when I send a command but still I get no response. Please help with debugging.

title: Elechouse Voice Recognition v3 module not responding when I send command using Access port serial tool

Answers: 1

body:
The module can't communicate with Serial Monitor over a USB to TTL Serial adapter. It uses binary communication. Use Arduino, Arduino [library][1] and one of the example sketches of the library to communicate with the VR module.

And read the [manual][2].

  [1]: https://github.com/elechouse/VoiceRecognitionV3
  [2]: https://www.elechouse.com/elechouse/images/product/VR3/VR3_manual.pdf


body:
I have an Arduino mega that is being used to control relays and ultrasonic sensors.  The relays that I am using is a 4 DPDT Signal Relay Module Model: D-256 Series and the other is a 4 channel Single pole Relay for Arduino. I am only using 3 channels of each relay. At any given time I only output to 2 channels from each relay at a time. I tested the relay to ensure they worked with the Arduino and they ran fine.

Once I connected the Ultrasonic sensors to the board as well, the board would not power and the voltage regulator got extremely hot. I would assume the total current draw was too high from the outputs and VCC of the Arduino.

I think that if I take my 9V battery and run it through a voltage regulator 7805 then I can run the VCC power of the relays with the battery instead of the VCC from the Arduino. This would result in me only running a VCC to the 4 ultrasonic sensors, the triggers for the ultrasonics from the Arduino, and the output signals fora maximum of 2 channels per relay board resulting in 4 relays. Most of the time it is only 2 relays.

Would I be able to power the relay boards VCC with the 9V running through a 5v regulator instead of the arduino so that I can reduce the current running through the Arduino?

title: Voltage Regulator getting too hot

Answers: 2

body:
It sounds like a power-to-ground short circuit, either a fault in the Ultrasonic sensor or in the connection to the Arduino.

Check your connections, and if you have an Ohm-meter, check the resistance between the sensor's power and ground pins.

Current consumption is a function of the device being powered, not of the power-supply, unless the supply lacks the capacity to provide as much current as the device needs.

Note that 9v batteries (the small brick aka a "transistor battery") is not well suited to supplying much current and probably will not power your Mega, or not for long, anyway. They are much better suited for long-term powering of very low current devices, such as a smoke detector.

body:
What could be going on here apart from what @JRobert has suggested, is, LM7805 could be generating a lot of heat loss.

4 X Ultrasonic sensors (SR HC-04) would draw 60mA.

2 X Relays (SRD-05VDC-SL-C) would draw 71.4 X 2 i.e 142.8mA.(Depends on from where you signal it)
The Arduino mega would draw anywhere between 200 - 500 mA.(even more)

The amount loss you will have is (9-5)V * (202.8 + 250)mA
i.e. around **2 Watts**. **This is a lot of heat**. I'm not even sure the LM7805 would be able to handle it.

**Solution**: use a switching regulator like the one mentioned here: https://electronics.stackexchange.com/questions/21131/efficient-low-power-regulation-i-e-9-5-volts


body: Question is odd, but I want to know that how I connect nodmcu with a laptop wifi without using any router. Is it possible if yes then how?

title: How can I connect nodemcu with laptop wifi

Answers: 1

body: Configure and activate the access point mode on NodeMCU. It creates a WiFi network and you can connect to this network with your computer.


body:
    char webpage[] PROGMEM = R"=====(
    <html>
      <head>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/svg.js/2.6.6/svg.min.js"></script>
      </head>
      <body>
      </body>
    </html>
    )=====";

I found a problem when using the raw string literal in Arduino IDE.
My code cannot compile if i have http:// link inside the string.

I found that it should be related to how Arduino IDE thought the string after // are comments and during compile time those string are ignored and my codes break.

It looks like the arduino ide's compiler removes all //comment in the code first, before it try to compile the raw string literal and then cause the issue.

As a test I try to debug it by changing my code to https:/-/ the program can be compile as now there is no // in the raw string literal

Is there any workaround?

title: Arduino IDE c++ 11 raw string literal have issues with // in http://, complier thinks // is comment

Answers: 3

body:
Escape the two quote marks inside the string using a backslash (literal quotes).

Without the escape characters, the URL is "outside" of a string because the quote marks are string delimiters.

    char webpage[] PROGMEM = R"=====(
    <html>
      <head>
        <script src=\"https://cdnjs.cloudflare.com/ajax/libs/svg.js/2.6.6/svg.min.js\"></script>
      </head>
      <body>
      </body>
    </html>
    )=====";

body:
    char webpage[] PROGMEM = R"=="==(
    <html>
      <head>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/svg.js/2.6.6/svg.min.js"></script>
      </head>
      <body>
      </body>
    </html>
    )=="==";

inspired by answer provided by @jsotola  if i used the syntax like this R"=="==()=="==" the link will become inside the quote. and hence the ide's complier regards it as a string and won't think // is comment and now the code can complie and the link works.

body:
The C & C++ compilers don't look for language syntax inside quoted strings (except for character-escapes such as '\n'). That is the point of quoting the string.

This program just compiled Ok for me:

    const char webpage[] PROGMEM = R"=====(
    <html>
      <head>
        <script src=\"https://cdnjs.cloudflare.com/ajax/libs/svg.js/2.6.6/svg.min.js\"></script>
      </head>
      <body>
      </body>
    </html>
    )=====";

    void setup() {
    }

    void loop() {
    }

'//' within the string did not cause any problem. Your example did get an error message that the variable 'webpage' had to be const to put it in Flash memory so I added the 'const' keyword, but that is the only change I made.

If you do that, and your compiler is still complaining, there is some other issue than the '//'.


body:
I am using an ultrasonic sensor SR04 with Arduino Uno and a sample program which I got from the library. However, my output reading is only 4 cm even when there is no object in front of it. I even used another sample program which had the same output. Is the problem in sensor or library?

    #define TRIGGER_PIN  12
    #define ECHO_PIN     11
    #define MAX_DISTANCE 200

    NewPing sonar(TRIGGER_PIN, ECHO_PIN, MAX_DISTANCE);

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

    void loop() {
      delay(50);
      Serial.print("Ping: ");
      Serial.print(sonar.ping_cm());
      Serial.println("cm");
    }

[![enter image description here][1]][1]

[![enter image description here][2]][2]

  [1]: https://i.stack.imgur.com/A9gIN.jpg
  [2]: https://i.stack.imgur.com/EJir7.jpg

title: My Ultrasonic sensor is only showing 4cm range?

Answers: 2

body: Looks to me like your powering the SR04 with 3.3v instead of 5v.

body:
I recommend, if you want reliability, that you upgrade to the HY-SRF05 sensor.  The problem with the SR04 is that when there is nothing in front of the sensor (or the target is beyond the limit) the sensor sometimes "locks up," and you have to reset it to get it working correctly again.  The SR04's are a few cents cheaper than the others; there's a reason for that.

Also, there's more than one library available for these sensors.  I recommend the NewPing library by Tim Eckel available from here:  <https://bitbucket.org/teckel12/arduino-new-ping/wiki/Home>

I am not affiliated with Tim in any way, but he's got a good library.


body:
 I am using the WiFi library and trying to store the IP address in a character buffer so that I can print it out to an lcd that only accepts character buffers. My code for doing this:

     char * IPAD = new char[40
     IPAddress ip = WiFi.localIP();
     Serial.println(ip);
     char * bufIP = new char[40]();
     sprintf(bufIP, "%s", inet_ntop(ip));
     lcd.string(ip);

But when I compile this I get the error:

    "inet_ntop' was not declared in this scope"

Help?

title: How to copy IPAddress class into character buffer? Getting error: "inet_ntop' was not declared in this scope"

Answers: 1

body:
An `IPAddress` is a class. You can't use it like a number (although in certain circumstances you can assign it to a `uint32_t` and it gives you the numeric representation).

Also, the `inet_*` functions are only really relevant on a POSIX system with a full network stack - i.e., a computer, not a little Arduino without a proper networking stack.

You can, though, easily access the individual bytes of the IP address through the `[]` operator and place them into a char array with the right format:

    sprintf(bufIP, "%d.%d.%d.%d", ip[0], ip[1], ip[2], ip[3]);


body:
I'm building my first arduino project and I encountered a strange problems;

I build a haunted house based upon that instructables tutorial:
https://www.instructables.com/id/Control-Your-Halloween-Decorations-With-Arduino/

Every prop works, I tried to light them on and off (it works), but when I try to use all of them, a few doesn't work.

There is my code; Is it something I'm doing wrong?

    int propSqueDans = 4;
    int propClownImmo = 5;
    int propClownJambes = 6;
    int propSqueBal = 7;
    int propSqueMini = 8;
    int propSpider = 9;
    int propChauSou = 10;
    int propFantChai = 11;

    int SensorPin = 3; // sensor connected to analog pin 3
    int SensorVal = 0; // variable to store the value read

    void setup() {
      pinMode(propSqueDans, OUTPUT);// sets the digital pin as output
      pinMode(propClownImmo, OUTPUT);
      pinMode(propClownJambes, OUTPUT);
      pinMode(propSqueBal, OUTPUT);
      pinMode(propSqueMini, OUTPUT);
      pinMode(propChauSou, OUTPUT);
      pinMode(propFantChai, OUTPUT);
      pinMode(propSpider, OUTPUT);
      Serial.begin(9600);

      }

    void loop() {
        SensorVal = analogRead(SensorPin); // read the input pin

        if (SensorVal >100) {
        Serial.write("Danse + Clown Immo \n");
        digitalWrite(propSqueDans, HIGH);
        digitalWrite(propClownImmo, HIGH);
        delay(10000);
        Serial.write("Spider + Fangtôme + Clown jambes \n");
        digitalWrite(propSpider, HIGH);
        digitalWrite(propFantChai, HIGH);
        digitalWrite(propClownJambes, HIGH);

        delay(5000);
        Serial.write("Squelette balance + sque mini \n");
        digitalWrite(propSqueBal, HIGH);
        digitalWrite(propSqueMini, HIGH);

        delay(5000);
        Serial.write("Chauve souris \n");
        digitalWrite(propChauSou, HIGH);

        delay(20000);

        digitalWrite(propSqueDans, LOW);
        digitalWrite(propClownJambes, LOW);
        digitalWrite(propSqueBal, LOW);
        digitalWrite(propSqueMini, LOW);
        digitalWrite(propChauSou, LOW);
        digitalWrite(propFantChai, LOW);
        digitalWrite(propSpider, LOW);
        digitalWrite(propClownImmo, LOW);
        delay(5000);
        }

      }

Thank you for your help !

title: Arduino pins not working

Answers: 1

body:
My best guess (not knowing what the pins are driving) is that your trying to draw too much current from the Arduino gpio.

Ref: https://playground.arduino.cc/Main/ArduinoPinCurrentLimitations


body:
So i created a class and when i created objects and use them, they seem to share their variables between each other ( the currentReading, previousReading and the time variable). how can i create objects that have their own variables so that type of conflict cant happen?

code : ( read the buttons and print them in the lcd screen)

    #include <LiquidCrystal.h>

    LiquidCrystal lcd(6, 5, 3, 2, 1, 0);

    class button {
      public:
        void SetupButton(int pino);
        int Read();

      private:
        int _pin;
    };

    void button::SetupButton(int pin) {
      pinMode(pin, INPUT_PULLUP);
      _pin = pin;

    }

    int button::Read() {
      static boolean currentReading, previousReading = 1;
      static unsigned long time;

      currentReading = digitalRead(_pin);// reading
      if (previousReading - currentReading  == 1) { // when reading gos from 1 to 0
        time = millis();
      }

      if (currentReading - previousReading == 1 && (50 < (millis() - time) < 500)) {     // when reading gos back to 1 before 500ms
        previousReading = currentReading;
        return 1;
      }

      if (3000 > (millis() - time) && (millis() - time) > 500 && !currentReading) { // when reading keeps in 0 after 500ms
        previousReading = currentReading;
        return 2;
      }

      if ((millis() - time) > 3000 && !currentReading) { // // when reading keeps in 0 after 3000ms
        previousReading = currentReading;
        return  3;
      }

      previousReading = currentReading; // current reading becomes the previous

      return 0;
    }

    button up;
    button down;

    void setup() {
      lcd.begin(16, 2);
      up.SetupButton(A0);
      down.SetupButton(A1);

    }
    void loop() {

      lcd.setCursor(0, 0);
      lcd.print(up.Read());
      lcd.print(down.Read());

    }

ps :  i already know how to do this without using classes but doing it with classes makes the code much cleaner so i am trying to achieve this

title: How to create objects with their own variables?

Answers: 1

body:
I was tempted to re-write your code (I am quite rusty on c++), but you may be better to start with an existing class.

There is a Button class on the Arduino site. See https://playground.arduino.cc/Code/Button

You could use this or study to see a more usual c++ implementation and adapt your code.

Virtually ALL c++ classes include a constructor. I would use instead of SetupButton

    void button::button(int pin) {
      this->_pin=pin;
      pinMode(pin, INPUT_PULLUP);
    }

and add `uint8_t previousReading;` and `unsigned long time;` to your class as private variables.