message:
Usbasp Arduino Uno Bootloader Flash Error - Win 10

I'm trying to flash an Arduino Uno using usbasp but i'm getting the following error,I have checked all the connection and voltage using multimeter but still this error:

```
Arduino: 1.8.8 (Windows 10), Board: "Arduino/Genuino Uno"

C:\Users\SillyMonster\Desktop\arduino-1.8.8\hardware\tools\avr/bin/avrdude -CC:\Users\SillyMonster\Desktop\arduino-1.8.8\hardware\tools\avr/etc/avrdude.conf -v -patmega328p -cusbasp -Pusb -e -Ulock:w:0x3F:m -Uefuse:w:0xFD:m -Uhfuse:w:0xDE:m -Ulfuse:w:0xFF:m

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

         System wide configuration file is "C:\Users\SillyMonster\Desktop\arduino-1.8.8\hardware\tools\avr/etc/avrdude.conf"

         Using Port                    : usb
         Using Programmer              : usbasp
         AVR Part                      : ATmega328P
         Chip Erase delay              : 9000 us
         PAGEL                         : PD7
         BS2                           : PC2
         RESET disposition             : dedicated
         RETRY pulse                   : SCK
         serial program mode           : yes
         parallel program mode         : yes
         Timeout                       : 200
         StabDelay                     : 100
         CmdexeDelay                   : 25
         SyncLoops                     : 32
         ByteDelay                     : 0
         PollIndex                     : 3
         PollValue                     : 0x53
         Memory Detail                 :

                                  Block Poll               Page                       Polled
           Memory Type Mode Delay Size  Indx Paged  Size   Size #Pages MinW  MaxW   ReadBack
           ----------- ---- ----- ----- ---- ------ ------ ---- ------ ----- ----- ---------
           eeprom        65    20     4    0 no       1024    4      0  3600  3600 0xff 0xff
           flash         65     6   128    0 yes     32768  128    256  4500  4500 0xff 0xff
           lfuse          0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
           hfuse          0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
           efuse          0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
           lock           0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
           calibration    0     0     0    0 no          1    0      0     0     0 0x00 0x00
           signature      0     0     0    0 no          3    0      0     0     0 0x00 0x00

         Programmer Type : usbasp
         Description     : USBasp, http://www.fischl.de/usbasp/

avrdude: auto set sck period (because given equals null)
avrdude: warning: cannot set sck period. please check for usbasp firmware update.
avrdude: error: program enable: target doesn't answer. 1
avrdude: initialization failed, rc=-1
         Double check connections and try again, or use -F to override
         this check.

avrdude done.  Thank you.

Error while burning bootloader.

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

**I have tried different three other `Usbasp` but still same error**

[![Different USPasp][1]][1]

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

body: The problem was with the Arduinos i have received from AliExpress All of them are using WAVGAT AVGA 328P-AU chips. I flasthed other Atmel MEGA 328P chip based Arduinos using USbasp and it's working fine. But i dont know how to flash those WAVGAT AVGA 328P-AU chips.


sender: user

message:
How to programme a button per colour for a neopixel strip?

I am trying to make a particular pixel in a neopixel strip, turn green, red or blue depending which button has been pressed and to stay on until pressed off again (like a toggle), but currently when I press one of the buttons it flashes the correct colour when button is pressed down but isn't acting as a toggle switch and then goes to a white light.
<!-- language-all: lang-cpp -->

    #include <Adafruit_NeoPixel.h>
    #ifdef __AVR__
    #include <avr/power.h> // Required for 16 MHz Adafruit Trinke
    #endif

    #define BUTTON_PIN1  2
    #define BUTTON_PIN2  10
    #define BUTTON_PIN3  11
    #define PIXEL_PIN    6  // Digital pin 6 connected to the NeoPixels.

    #define PIXEL_COUNT 13  // Number of NeoPixels

    // Declare our NeoPixel strip object:
    Adafruit_NeoPixel strip(PIXEL_COUNT, PIXEL_PIN, NEO_GRB + NEO_KHZ800);

    boolean oldState1 = HIGH;
    boolean newState1 = HIGH;

    boolean toggle1 = LOW;

    boolean oldState2 = HIGH;
    boolean newState2 = HIGH;

    boolean toggle2 = LOW;

    boolean oldState3 = HIGH;
    boolean newState3 = HIGH;

    boolean toggle3 = LOW;

    void setup() {
    Serial.begin(9600);
    pinMode(BUTTON_PIN1, INPUT_PULLUP);
    pinMode(BUTTON_PIN2, INPUT_PULLUP);
    pinMode(BUTTON_PIN3, INPUT_PULLUP);
    strip.begin(); // Initialize NeoPixel strip object (REQUIRED)
    strip.show();  // Initialize all pixels to 'off'
    }

    void loop() {
    updateButtonState1();
    updateButtonState2();
    updateButtonState3();

    }

    void updateButtonState1() {

     // Get current button state.
     newState1 = digitalRead(BUTTON_PIN1);

     if ((newState1 == LOW) && (oldState1 == HIGH)) {
     delay(50);
     newState1 = digitalRead(BUTTON_PIN1);
     if (newState1 == LOW) {
       toggle1 = !toggle1;
      }
     }
     oldState1 = newState1;

    if (toggle1 == HIGH) {
    strip.setPixelColor(2, 245, 15, 15); //electrical/fire hazard (red)
    } else {
    strip.setPixelColor(2, 0, 0, 0);
    }
    strip.show(); // Update strip with new contents
    }

    void updateButtonState2() {

    // Get current button state.
     newState2 = digitalRead(BUTTON_PIN2);

    if ((newState2 == LOW) && (oldState2 == HIGH)) {
     delay(50);
     newState2 = digitalRead(BUTTON_PIN2);
     if (newState2 == LOW) {
       toggle2 = !toggle2;
       }
      }
     oldState2 = newState2;

      if (toggle2 == HIGH) {
      strip.setPixelColor(2, 13, 50, 190); //Leak (blue)
      } else {
      strip.setPixelColor(2, 0, 0, 0);
      }
     strip.show(); // Update strip with new contents
     }

     void updateButtonState3() {

     // Get current button state.
     newState3 = digitalRead(BUTTON_PIN3);
     if ((newState3 == LOW) && (oldState3 == HIGH)) {
      delay(50);
      newState3 = digitalRead(BUTTON_PIN3);
      if (newState3 == LOW) {
        toggle3 = !toggle3;
      }
     }
     oldState3 = newState3;

     if (toggle3 == HIGH) {
     strip.setPixelColor(2, 58, 233, 65); //bins/recylcing (green)
     } else {
       strip.setPixelColor(2, 0, 0, 0);
      }
      strip.show(); // Update strip with new contents
    }

sender: assistant

body:
You do not really have to use an array for this, though I do agree that it's the cleanest solution.

Here is a simplified version of your code, do mind you'll still have to do the button handling yourself (by setting buttonpressed to 'true' when the button is pressed.

Also, when adding more colors to the array, you'll have to manually adjust 'totalColors'.

    void setup() {
      //Color/pixel declarations based on https://learn.adafruit.com/adafruit-neopixel-uberguide/arduino-library-use
      uint32_t magenta = strip.Color(255, 0, 255);
      uint32_t greenishwhite = strip.Color(0, 64, 0, 64);

      //https://www.arduino.cc/reference/en/language/variables/data-types/array/
      uint32_t colors[] = {magenta, greenishwhite};
      unsigned char totalColors = 2;
      unsigned char currentColor = 0;
    }

    void loop() {
      if (buttonpressed) {
        //Change the "currentColor" index every time the button is pressed, but make it start at 0 when it reached the end.
        currentColor++;
        if (currentColor >= totalColors) {
          currentColor = 0;
        }

        //From the array of colors, pick the one with the index "currentColor" and show it.
        ledstrip.fill( colors[currentColor] , 0, strip.numPixels() - 1);
        ledstrip.show();

        buttonpressed = false; //Reset flag, so this doesn't get executed until next time button is pressed.
      }
    }

You should be able to replace the first 3 lines (setting up the array) with a single:

    uint32_t colors[] = {strip.Color(255, 0, 255,  strip.Color(0, 64, 0, 64)};

But I had it split up to better show the idea of the array.

Alternatively you could do:

    switch(currentColor){
      case 0:
        //Color RED
      break;
      case 1:
        //Color GREEN
      break;
      case 2:
        //Color BLAUW
      break;
    }


message:
How does input from IR receiver to Arduino UNO board work?

I have a very simple circuit with an Elegoo IR receiver module connected to an Arduino UNO. The three wires are connected correctly with the data wire (Y) connected to pin 8. The code works fine, as every time I press button on the remote, the Serial Monitor displays the corresponding button description.

However, I do not understand how Arduino's pin 8 knows which IR button has been pushed. My understanding is that pin 8 can read either 5V or 0V, but to know which of 20+ remote buttons has been pushed it would have to read PWM. But pin 8 does not the PWM icon next to it and yet it works fine. Unless the PWM icon applies only to pin output? Or is there another way I have failed to find info about?

Thanks!

body:
The remote control emits encoded IR-bursts (each button has its own code) which are transformed into electrical pulses by the sensor (ref. 6. in here: http://eeshop.unl.edu/pdf/VS1838-Infrared-Receiver-datasheet.pdf). On the arduino those pulses are decoded using a proper library.
That means pin 8 is not reading any analog or pwm signal, but TTL-logic at 5V.


body:
You confuse the different technologies here.

1. PWM is only an output, not an input. So every pin marked with the PWM symbol can OUTPUT a PWM signal. Reading a signal is a totally different task with different hardware involved.

2. The IR receiver does not output a PWM (meaning Pulse Width Modulation) signal to the Arduino. It ouputs the demodulated IR signal.

So here is what happens: The remote a code, that consists of different periods of "light on" and "light off" (giving pulses of different length, which encode the data from binary format). Since you want to seperate the remotes signal from any other IR signal, that might roam through the air, the remote also modulates the pulses with a special frequency (often this is 38kHz, but might be another frequency around that). This means that every pulse will be chopped into shorter pulses at the specified frequency. This translates to something like: "light on and off with 38kHz for duration x" --> "light off" --> "light on and off with 38kHz for duration y" --> ...

The receiver module senses the IR light comming in and will electronically discard all signals, that don't have the special frequency, and does the demodulation on this. The outputted signal does not have the 38kHz frequency in it anymore. Just the pulses of different length, that encode the data, meaning

The Arduino then reads the length of the pulses (that only consists of sequences of 0V and 5V) and decodes them into a number. This number represents the pressed button.

A proper library for the Arduino can read the different data protocols used in common IR remotes.


message:
Data type conversion problem

I have a Wemos D1 board with a OLED display using the u8g2 library.

I am printing my MAC-adress on the serial port & would like to print the same information on the OLED:
<!-- language-all: lang-cpp -->

    #include <ESP8266WiFi.h>
    #include <U8g2lib.h>
    byte mac[6];
    setup(){
      Serial.println(WiFi.macAddress());
      WiFi.macAddress(mac);
      u8g2.drawStr(1,10,WiFi.macAddress());
      u8g2.sendBuffer();
    }

This does not work. It prints the MAC-address on the serial port but not on the OLED.

I get: no known conversion for argument 3 from 'String' to 'const char*

How can I print the MAC-information on my oled using the u8g2-library?

body:
As said by @Mikael Patel
You need to append ``.c_str()`` to ``u8g2.drawStr(1,10,WiFi.macAddress());`` creating the line: ``u8g2.drawStr(1,10,WiFi.macAddress().c_str());``

The problem is that ``WiFi.macAddress()`` returns a ``String`` not the needed ``const char*`` by the ``drawStr`` function. ``c_str`` converts the ``String`` object into a ``const char*``.

Please look at the documentation of the ``u8g2`` library for the ``drawStr`` function.

[link][1]

And here the documentation for ``String``

[link][2]

  [1]: https://github.com/olikraus/u8g2/wiki/u8g2reference#drawstr
  [2]: https://www.arduino.cc/reference/en/language/variables/data-types/stringobject/


message:
declared variable inside void setup is forgotten in void loop

if i declare a var in void setup() and try to do something with it in void loop(), it just says that the variable is undeclared. here is the code:

    #include "Servo.h"

    void setup() {
     Servo servo1;
     int x_key = A0;
     servo1.attach(2);
     pinMode(A0, INPUT);
     pinMode(2, OUTPUT);

     int x_position = 90;
    }

    void loop() {
     if (analogRead(A0) < 512) {
      x_position++;
      servo1.write(x_position);
     }
    }

body:
Yes, that is how C and C++ (and most other C-like languages) work. Variables have "scope". Any variable define inside a pair of curly braces (between a `{` and a `}`) is only visible inside those braces.

If you want to reference a variable in both `setup()` and `loop()`, you have to make it a global variable, defined at the top of your code.

    #include "Servo.h"
    Servo servo1;
    int x_position = 90;  //Define your global var(s) here

    void setup() {
        int x_key = A0;  //This var only exists inside the setup function
        servo1.attach(2);
        pinMode(A0, INPUT);
        pinMode(2, OUTPUT);

    }

    void loop() {
        if (analogRead(A0) < 512) {
            x_position++;
            servo1.write(x_position);
        }
    }


message:
HTTP myphp request error RFID

This program is a program which readings of rfid are saved to myphp database. I have a problem when running the code The wifi is connected but when the code doesn't save im assuming that the problem is in this part of the code client.print("GET /rfid/nodemcu_rfid/rfid_read.php?allow="); Since i have done a wire shark capture and notice a **Bad Request error 400** as shown in the screen shot. [![enter image description here][1]][1]

**IP Addresses: 192.168.0.14 Is the php server , 192.168.0.19 is the nodemcu**

ALL THE CODE :
<!-- language-all: lang-cpp -->

    #include<SoftwareSerial.h>
    #include <ESP8266WiFi.h>
    #include <WiFiClient.h>
    #include <ESP8266WebServer.h>
    #include <ESP8266mDNS.h>
    #include <SPI.h>
    #include <MFRC522.h>

    const char* ssid = "ARRIS-84AB";
    const char* password = "your SSID password ";
    //WiFiClient client;
    char server[] = "192.168.0.14";   //eg: 192.168.0.222
    #define SS_PIN 2 //FOR RFID SS PIN BECASUSE WE ARE USING BOTH ETHERNET SHIELD AND RS-522
    #define RST_PIN 15
    #define No_Of_Card 3

     WiFiClient client;

    //WiFiServer server(80);
    SoftwareSerial mySerial(8,9);
    MFRC522 rfid(SS_PIN,RST_PIN);
    MFRC522::MIFARE_Key key;
    byte id[No_Of_Card][4]={
      {44,153,22,219},             //RFID NO-1
      {112,224,72,84},             //RFID NO-2
      {151,94,80,84}              //RFID NO-3
    };
    byte id_temp[3][3];
    byte i;
    int j=0;
    void setup()
    {
     Serial.begin(115200);
      delay(10);
      mySerial.begin(115200);
      SPI.begin();
      rfid.PCD_Init();

        for(byte i=0;i<6;i++)
      {
        key.keyByte[i]=0xFF;
      }

      // Connect to WiFi network
      Serial.println();
      Serial.println();
      Serial.print("Connecting to ");
      Serial.println(ssid);

      WiFi.begin(ssid, password);

      while (WiFi.status() != WL_CONNECTED) {
        delay(500);
        Serial.print(".");
      }
      Serial.println("");
      Serial.println("WiFi connected");

      // Start the server
    //  server.begin();
      Serial.println("Server started");
      Serial.print(WiFi.localIP());
      delay(1000);
      Serial.println("connecting...");
     }
    void loop()
    {  // Check if a client has connected
      int m=0;
      if(!rfid.PICC_IsNewCardPresent())
      return;
      if(!rfid.PICC_ReadCardSerial())
      return;
      for(i=0;i<4;i++)
      {
       id_temp[0][i]=rfid.uid.uidByte[i];
                 delay(50);
      }

       for(i=0;i<No_Of_Card;i++)
      {
              if(id[i][0]==id_temp[0][0])
              {
                if(id[i][1]==id_temp[0][1])
                {
                  if(id[i][2]==id_temp[0][2])
                  {
                    if(id[i][3]==id_temp[0][3])
                    {
                      Serial.print("your card no :");
                      for(int s=0;s<4;s++)
                      {
                        Serial.print(rfid.uid.uidByte[s]);
                        Serial.print(" ");

                      }
                      Serial.println("\nVALID");
                      Sending_To_DB();
                      j=0;

                                rfid.PICC_HaltA(); rfid.PCD_StopCrypto1();   return;
                    }
                  }
                }
              }
       else
       {j++;
        if(j==No_Of_Card)
        {
          Serial.println("inVALID");
          Sending_To_DB();
          j=0;
        }
       }
      }

         // Halt PICC
      rfid.PICC_HaltA();

      // Stop encryption on PCD
      rfid.PCD_StopCrypto1();
     }

     void Sending_To_DB()   //CONNECTING WITH MYSQL
     {
       if (client.connect(server, 80)) {
        Serial.println("connected");
        // Make a HTTP request:
        Serial.println("GET /rfid/rfidread.php?allow=");     //YOUR URL /rfid/rfidread.php?allow
        client.print("GET /rfid/nodemcurfid/rfidread.php?allow=");     //YOUR URL /rfid/rfidread.php?allow  /var/www/html/rfid/rfid_read.php
        if(j!=No_Of_Card)
        {
          Serial.println('1');
          client.print('1');
        }
        else
        {
          Serial.println('0');
          client.print('0');
        }
        Serial.println("&id=");
        client.print("&id=");
        for(int s=0;s<4;s++)
                      {
                        Serial.println(rfid.uid.uidByte[s]);
                        client.print(rfid.uid.uidByte[s]);

                      }
        client.print(" ");      //SPACE BEFORE HTTP/1.1
        client.print("HTTP/1.1");
        client.print("Host: ");
         client.println(server);
        client.println("Host: 192.168.0.14");//eg: 192.168.0.222
        client.println("Connection: close");
        client.println();
      } else {
        // if you didn't get a connection to the server:
        Serial.println("connection failed");
      }
      client.stop();
     }

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

body:
Your problem is here:

    client.print(" ");      //SPACE BEFORE HTTP/1.1
    client.print("HTTP/1.1");
    client.print("Host: ");
     client.println(server);
    client.println("Host: 192.168.0.14");//eg: 192.168.0.222
    client.println("Connection: close");
    client.println();

That ends up with:

    ....(your request)... HTTP/1.1Host: 192.168.0.14
    Host: 193.168.0.14
    Connection: close

Not only are you sending the Host header twice, but you're not adding the line ending after the HTTP version.

Instead it should look more like:

    client.print(" ");      //SPACE BEFORE HTTP/1.1
    client.println("HTTP/1.1"); // <-- Note the use of println not print
    client.print("Host: ");
    client.println(server);
    client.println("Connection: close");
    client.println();


message:
Problems when racing multiple IR controlled Arduino robots

We are attempting to race 3 IR-controlled Arduino robots (Elegoo IR kit), but the IR signal from each remote seems to be picked up by all three receivers. It is possible to create a unique bond between each IR remote and its receiver? Lego Mindstorms IR remote has channels to solve this problem. Anything I can do with Arduino?

body:
Not familiar with Elegoo kit... Question is are they using 1 way or 2 way communication? If they use 1 way communication(which is most likely) there's not much you can do since multiple IR signals interfere with each other, and you would need the toys to send back acknowledge signals to the controller, to do error correction... In that case the most you can do is give them each a unique id, and make them ignore anything else then commands associated with their unique id.

If they do 2 way communication you can also make the controller only send a command when a button is pressed, and when it's released, instead of continuous transmission, while also making sure that the command is understood by the receiver. That minimizes interference for other controllers. And if the command was not understood then wait random milliseconds, and repeat it until the receiver understands it.


body: IR remote signals are OOK-modulated with different base frequencies (the most common are  36 kHz, 38 kHz and 40 kHz). Elegoo seem to use 38 kHz transmitters/receivers, so if you manage to find 36/40 kHz devices, you'll get 3 channels with somewhat reduced interference.


message:
How to convert digital signal to analog value

I have spwm output from arduino, and when i read on analogread it shows only 1023 and 0, because it is digital signal.
Is there any way to convert these spwm value into analog value reading

body:
The problem seems to be clear to you: for slow systems a pwm signal can be considered analog, but measuring at higher rates and without a filter reveales the digital nature behind pwm and all you see is either logic high (1023) or low (0).
Possible solutions are:

 1. apply a filter in hardware (LC low-pass)
 2. apply a filter in software (e.g. by calculating a running mean)
 3. attach interrupts to the rising/falling edge of your signal and measure the high/low time to calculate the duty cycle

Which of those options to choose will mainly depend on the PWM frequency you want to measure. For low frequency I recommend option 3 (special cases are duty cycles around 0% and 100% as there are no edges), for higher frequencies I would use option 1/2.


message:
Connecting arduino with MATLAB

I installed Octave support package for Arduino and it is listed in the packages installed when pkg list command is run.But when the command  "a= arduino('COM8')";
is run,"error: serial: Error opening the interface: No such file or directory" is shown.Please respond.

body:
Using `clear` command on Octave before executing `a=arduino('COM8')` will remove this problem.

Use it like this:

    clear
    a=arduino('COM8')


message:
How to find out the maximum used stack space?

I am creating an Arduino sketch which involves quite some classes, and I want to check if it will run on an Arduino Uno or Mega (2 KB vs 8 KB SRAM).

So far my global variables take up around 1,200 bytes, and I expect this will rise. However, beyond that I need to make sure the stack memory is not using up too much. **How can I find the maximum used stack size?**.

I can check manually by calculating the maximum function stack and calculating all parameters + local variables, but this is a very tedious job (especially since my application changes still a lot).

Or another way: I know it is possible to get the free space, but should I add this in 'strategic' locations or in the beginning of all functions and continue from there? (there will be many of them).

Or is there preferable some static way of checking this?

The application works within Visual Studio C++ as stand alone too, so maybe that helps for some solution.

I expect the stack size easily to be a few hundred bytes (which is quite a lot for the Arduino Uno SRAM).

body:
Knowing the stack size is pretty easy: the stack pointer is initially
set to `RAMEND` and goes down as the stack grows. Thus:

<!-- language: lang-c++ -->

    static inline size_t stack_size()
    {
        return RAMEND - SP;
    }

> should I add this in 'strategic' locations [...]

Obviously, the result will depend on where this is evaluated. Ideally
you should test this in the deepest parts of your call chain, as this is
where the stack will be at its maximum size. Note that ISRs stack on top
of all your regular code.

**Edit**: There is no easy way to know the _maximum_ stack size. You
could get an approximation by sampling the stack at regular intervals,
e.g.:

    #include <util/atomic.h>

    volatile size_t min_sp = RAMEND;

    ISR(TIMER0_COMPA_vect)
    {
        if (SP < min_sp)
            min_sp = SP;
    }

    static inline size_t max_stack_size()
    {
        size_t min_sp_copy;
        ATOMIC_BLOCK(ATOMIC_FORCEON) {
            min_sp_copy = min_sp;
        }
        return RAMEND - min_sp_copy;
    }

If you enable `TIMER0_COMPA` interrupt in `setup()`:

    TIMSK0 |= _BV(OCIE0A);

then the stack size will be sampled every 1.024 ms. Note, however,
that this ISR is itself using some stack space for its own purposes
(9 bytes in my experiment), and that this is not sampling other
ISRs or critical sections.


body:
Initialize the entire SRAM space from the top of the heap to the bottom of the stack, either during setup, or in a modified version of the Arduino-provided main() function, with some unlikely pattern, such as {0x55, 0xAA, ...} or "UnusedUnused...".

After your program has run a while, examine memory for dirty footprints, reading up from the top of heap to find the highest heap excursion, and down from the stack-pointer to find the lowest address used by stack. You could use a debugger if you have one, or just a hex & ASCII dump to the terminal. Pick through it with whatever tools you have handy on your PC. If there's been no collision and you're using a memory dump, it's pretty easy to start somewhere in the middle that wasn't disturbed, and scroll in either direction. The place where your initialized pattern has been overwritten usually stands out very plainly.


message:
How to drive Arduino UNO as a counter triggered by 555 timer's output (astable mode)

I have an Arduino Uno and a 555 timer configured to astable mode.

What I'm trying to do is to program my Arduino to increase a "counter" variable (counter++) everytime it gets triggered by 555 timer's output (through analogIN pin).

**My problem is** that Arduino takes 555 timer's output as a continuous triggering and increases my counter as long as the pulse in the analogIN lasts.
So instead of incrementing by 1, it is increased by approximately 97 (sometimes more or less).

I need to take the analog in as a "packet" so everytime analogIN is triggered, no matter how long the pulse lasts, it will be treated as a single event and not as continuous triggering.

What do I have to change?

My code:

    int counter = 0;

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

    }

    void loop() {
      if(analogRead(A0) > 250) {
        counter++;
        Serial.println(counter);
      }

    }

Thanks

body:
You need to create a [finite state machine][1] with 2 states:

 1. Waiting for input from 555 to go high.  When this happens increment the counter & advance to the next state.
 2. Waiting for the input from the 555 to go low.  When this happens advance to the next state.  That is, the first state.

In the following [Arduino "State Change Detection (Edge Detection) for pushbuttons" example / tutorial][2] you do not need the complex code to debounce the switch.  However, the edge detection and state machine portion of the code can likely be applied to your project.

  [1]: https://en.wikipedia.org/wiki/Finite-state_machine
  [2]: https://www.arduino.cc/en/Tutorial/StateChangeDetection


body:
I recommend using one of the atmega's counter modules. That way you can count the pulses synchronuously to your program (real paralellism!) and you also don't have to implement any edge-detection youself as the counter module already provides this feature.

A search for "pulse counter" will lead to many tutorials on how to do that.


message:
Arduino Hardware serial pins with RS485

I tried asking a question in my earlier post - https://arduino.stackexchange.com/questions/65311/serialevent-with-rs485-communication it helped me understand Hardware serial and Software serial but i had few more questions for which i started this new thread. Now i didn't write any code yet, but i will be using same code as my earlier post if i get expert inputs.

My Project - I have 6 Arduino nano which will do some simple task, mostly its one way communication at a time, like once master send message to slave i don't want immediate response slave will push button or something and then it will send response to master. So its rare that i will have two way communication at same time.

RS485 - I am going to use RS485 as distance is around 40ft.

Now my questions -

1 - Can i use Hardware serial pins with RS485 for 40ft distance, i tested code and it does work but i couldn't test that for 40ft. So not sure if it works or not.

2 - Is it good idea to use hardware serial pins for my project i explained, as i see plus and minus over internet and making me confuse. I see majority people recommend Hardware pins though.

3 - Is there limitation connecting multiple arduino nano with this approach, i only did this with 2 so far.

I would appreciate your inputs, which will make me decide to go on right path. Sorry i didn't post any code because my post is more to understand correct path to be followed...

body:
> 1 - Can i use Hardware serial pins with RS485 for 40ft distance, i tested code and it does work but i couldn't test that for 40ft. So not sure if it works or not.

Yes.

> 2 - Is it good idea to use hardware serial pins for my project i explained, as i see plus and minus over internet and making me confuse. I see majority people recommend Hardware pins though.

Yes. SoftwareSerial is awful.

> 3 - Is there limitation connecting multiple arduino nano with this approach, i only did this with 2 so far.

Yes. The MAX485 and similar chips can only handle up to about 30 devices on one bus. The exact number is in the datasheet for the chip.


message:
Voltage measure range of an arduino?

I recently thought of using an Arduino to measure voltage and I stumbled across the problem that what is the max voltage I can measure??? It is an Arduino Uno and I am thinking that I would also display the voltage measured on a 16 * 2 LCD screen.My guess is max of 5 volts but if this is correct how can I increase its range?

body:
Without any further configuration, the ADC (Analog Digital Converter) of the Atmega328P (which is build onto the Arduino Uno) uses Vcc as voltage reference (meaning 5V in the case of the Arduino Uno). A voltage of 5V will result in the maximal value (which is 1023, since this is a 10bit ADC). So the voltage range in this case is 0 to 5V.

The Arduino Uno has an extra pin, where you can supply an own reference voltage. But it's limit is tied to the ADCs supply voltage `AVcc`, which is 5V for the Arduino Uno rev3 (as shown in the [schematics][1] of the Uno). The reference voltage should then be in the range of 1V to `AVcc`. So this still gives you only a range of 0V to 5V or smaller.

When you use a standalone Atmega328P, you can make `AVcc` a bit higher than the chips supply voltage `Vcc`, but at maximum `Vcc + 0.3V`.

You can check all these numbers by looking into the [datasheet][2] of the Atmega328P, chapter 28.9 (Electrical Characteristics --> ADC Characteristics).

---

How to increase this range depends greatly on your requirements. If you simply need a constant higher range, you can simply put a voltage divider in front of the analog input. Or you can use a more complex circuit involving an op-amp (amplifier ciruit, here with amplification factor below 1). You can even build this to be variable.

Should it be, that your wanted voltage range exceeds the 5V greatly, for example, if you want to measure mains voltage (230V for most europe, 110V in USA), you should definitely take great care and never connect this directly to electronic like the Arduino. High voltages (especially at high possible currents) should always be handled with great care.

  [1]: https://www.arduino.cc/en/uploads/Main/Arduino_Uno_Rev3-schematic.pdf
  [2]: http://ww1.microchip.com/downloads/en/DeviceDoc/Atmel-7810-Automotive-Microcontrollers-ATmega328P_Datasheet.pdf#page=265


body:
The ATmega328's (it's the microcontroller on the uno) absolut maximum rating is `Vcc + 0.5V` for any pin (except the reset pin) while Vcc must not be higher than 6V.

In order to measure higher voltages you have to use a voltage divider ([read this][1]) to adjust the input voltage to the range `0V - Vcc`.

  [1]: https://en.m.wikipedia.org/wiki/Voltage_divider


message:
Value read is not changing while rotating pot in arduino?

I am trying to read voltage using analogRead in Arduino Uno from a voltage divider circuit consisting of 1k resistor and 10k pot. The Pot used is bourns 3296. The values obtained only range from 1011 to 1023? Why is the count not reducing further if I rotate the pot?

(this how i have connected the circuit, but the pot is the one that i have mentioned above, i couldn't find that kind in the software, but i have made the connection this way only)
[![this how i have connected the circuit, but the pot is the one that i have mentioned above, i couldn't find that kind in the software, but i have made the connection this way only ][1]][1]

    int analogPin = A0;

    // variable to store the value read
    float val = 0;

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

    void loop() {
      Serial.println(val); // read the input pin
      val = analogRead(analogPin); // debug value
    }

Since potentiometer itself is a voltage divider, I have tried connecting as per the answer, the ends of the 10k pot to 5V and ground , and the slider pin to the analog pin A0. The new circuit is as shown below, but I am still unable to get the value ranging from 0 to 1023. The values returned only vary in between 1010 to 1023. What is going wrong? How do I get the full range?
[![pot interfacing with arduino uno][2]][2]

  [1]: https://i.stack.imgur.com/FIqI3.png
  [2]: https://i.stack.imgur.com/HFQ2t.png

body:
A potentiometer is already a voltage divider by itself. The outer contacts are connected to the ends of a resistor strip. The middle pin is connected to a wiper, which can slider over the strip, dividing the strip into 2 parts. So you connect it like it is described at the start of your sketch (before the last edit): The outer pins to 5V and ground respectively and the middle pin to the analog input. (When using this in different circuits, keep in mind, that you should not draw too much current from the middle pin. Don't drive any load directly from it. The analog input does only draw a very small amount, so that's absolutely no problem.)

When adding a constant resistor in series with the pot, you are only adding a dead range, that cannot be set with the circuit.

---

> what does those voltage dividers with pots serve purpose for?

Only the pot: Potentiometers are mostly used to give a setpoint, a user controlled voltage, which can be read by a microcontroller or used directly for controlling further electronics.

With an additional resistor: You can put in an additional resistor at the high side of the pot, to lower the voltage further. For example if you - for whatever reason - have to use a higher voltage for the voltage divider, than the microcontroller can handle. You can calculate the value of the resistor, so that the voltage on the analog pin will never exceed the limits. But this scenario must be very rare. I didn't encounter such a situation ever.


body:
OK, I am unable to leave a comment (< 50) so...

Use this link to learn about the AREF pin on the Arduino, this may not be your problem but it is good to know about anyway:
https://arduino.stackexchange.com/questions/47760/what-is-arduino-adc-reference

Your pot MAY be broken. Measure the resistance of the pot with an ohm meter, from the center pin to either of the side pins. Verify when you turn it the resistance varies from 10K to 0.

You can also measure the voltage it is providing your Arduino by measuring the voltage it presents to pin A0. Verify the voltage changes little by little from +5 to 0 when you turn it back and forth.

You list the pot as being a "bourns 3296" which the data sheets show as a "**Multiturn** / Cermet / Industrial / Sealed" pot.

Just so you know, when you adjust it you will have to turn it 25 turnes to fully adjust it through its entire range. The data sheet shows "Effective Travel.........25 turns nom."


message:
How to compose an HTTP GET request URL with key/value parameters

I am experimenting with some code running on an ESP8266 board to retrieve data using a web API. I would like to store the host address and key/value parameters (API key etc.) of the GET request as constants/variables (I'm not sure which is better) and then use them to compose the full GET URL.

**How can I compose the full URL from separate strings/char arrays including the correct syntax for the key/values pairs?**

EDIT: Just adding that I am using the ESP8266HTTPClient library.

The example I have been following uses a basic API URL with no parameters and stores the host URL as follows:

    const char* host = "http://somehost.com/dir/1";

(Side question: please explain the difference between `const char* host` and `const char *host` if there is one)

Using this simple URL I can successfully retrieve the JSON data using this method:

    HTTPClient http;
    http.begin(host);
    int httpCode = http.GET();
    Serial.print("HTTP RESPONSE: ");
    Serial.println(httpCode);
    if (httpCode > 0) {
      String payload = http.getString();
      Serial.println("PAYLOAD:");
      Serial.println(payload);
    }
    http.end()

I am looking into using the "ArduinoJson" library to manage the json data instead of String, but am more interested in figuring out how to compose the URL at the moment.

What I would like to achieve is adding key/value parameters stored as variables to the host URL e.g.:

    const char* host = "http://somehost.com/dir/1";
    char* app = "123";
    char* user = "123456"
    char* api_key = "XXXXXXXXXXXXX";

And then join them with strings or char arrays to create the full URL, or simply pass the host address plus the parameter values to a function that composes the URL or sends the full GET request(with the parameter "key=var", question mark, and ampersands etc.):

    http://somehost.com/dir/1/?appid=123&userid=123456&key=XXXXXXXXXXXXX

This was very easy to achieve in python using the "requests" HTTP library. I was able to store the key/value parameters as a dict and then pass the host address and the parameter dict to the `requests.get` function and it would compose the URL automatically.

I guess there is more than one question buried in there, but the main one is "what is the best way to compose the full URL without hard coding the whole thing?" An example would be so I could change some parameters such as appid by user input before making the GET request.

I am unsure if I am using the right approach using the character arrays, constants or variables, whether I am using the right approach by trying to compose it manually, and in general what the best practices are for doing this efficiently and avoiding memory fragmentation (which is a problem when using string variables?). This device will be required to run constantly and periodically make these GET requests.

body:
> Side question: please explain the difference between const char* host and const char *host if there is one

There is no difference; n.b. the arduino IDE uses C++! If you don't know C or C++ you should learn that first.

> "what is the best way to compose the full URL without hard coding the whole thing?"

This is basically the same question as how do you manipulate, i.e. compose, composite, concatenate, C strings. [c string functions][1]

here is a quick example, without error checking, etc.:

    const char* host = "http://somehost.com/dir/1";
    char* app = "123";
    char* user = "123456"
    char* api_key = "XXXXXXXXXXXXX";

    char urlout[255];

    // we are going to start here
    strcpy(urlout, host);
    strcat(urlout, "/?appid=");
    strcat(urlout, app);
    strcat(urlout, "&userid=");
    strcat(urlout, user);
    strcat(urlout, "&key=");
    strcat(urlout, api_key);

    // urlout == "http://somehost.com/dir/1/?appid=123&userid=123456&key=XXXXXXXXXXXXX"

  [1]: http://lmgtfy.com/?q=c string functions


message:
exit status 1 'mySerial' does not name a type

I just can't make it work for some reason. I tried `#include <SoftwareSerial.h>` and I tried `#include "SoftwareSerial.h"`. Can someone help me?

    #include <SoftwareSerial.h>

    SoftwareSerial mySerial(10, 11);

    uint16_t buf[256];

    void setup() {
      Serial.begin(9600);
      while(!Serial);
      for(int i = 0; i < 256; i++)
        buf[i] = (uint16_t)i;
    }
      mySerial.begin(4800);
      mySerial.println("Hello, world"); //printLn  L, not I

    void loop() {
      Serial.write((uint8_t*)buf, 512);
      if (Serial.available()) {
        mySerial.write(Serial.read());
      }
    }

body:
simple mistake mySerial.begin(4800);
  mySerial.println("Hello, world"); lines was out of void {}

    #include <SoftwareSerial.h>

    SoftwareSerial mySerial(10, 11);

    uint16_t buf[256];

    void setup() {
      Serial.begin(9600);
      while(!Serial);
      for(int i = 0; i < 256; i++)
        buf[i] = (uint16_t)i;
       mySerial.begin(4800);
      mySerial.println("Hello, world"); //printLn  L, not I
    }

    void loop() {
      Serial.write((uint8_t*)buf, 512);
      if (Serial.available()) {
        mySerial.write(Serial.read());
      }
    }


message:
I am not able to set the correct configuration of sound module

I have been trying to make sound reactive LED lights but my sound module is detecting only very close voice the LED react only when I press it to the speaker with my hands I have tried to set the potentiometer many times but I got unsuccessful I have connected the Analogue output to Arduino.

The [voice module][1] I used:

[![Voice module][2]][2]

I have used the following code-
<!-- language-all: lang-cpp -->

    #include <FastLED.h>

    /** BASIC CONFIGURATION  **/

    //The amount of LEDs in the setup
    #define NUM_LEDS 10
    //The pin that controls the LEDs
    #define LED_PIN 6
    //The pin that we read sensor values form
    #define ANALOG_READ 0

    //Confirmed microphone low value, and max value
    #define MIC_LOW 0.0
    #define MIC_HIGH 737.0
    /** Other macros */
    //How many previous sensor values effects the operating average?
    #define AVGLEN 15
    //How many previous sensor values decides if we are on a peak/HIGH (e.g. in a song)
    #define LONG_SECTOR 5

    //Mneumonics
    #define HIGH  3
    #define NORMAL 2

    //How long do we keep the "current average" sound, before restarting the measuring
    #define MSECS 2000
    #define CYCLES MSECS / DELAY

    /*Sometimes readings are wrong or strange. How much is a reading allowed
    to deviate from the average to not be discarded? **/
    #define DEV_THRESH 0.8

    //Arduino loop delay
    #define DELAY 1

    float fscale( float originalMin, float originalMax, float newBegin, float newEnd, float inputValue, float curve);
    void insert(int val, int *avgs, int len);
    int compute_average(int *avgs, int len);
    void visualize_music();

    //How many LEDs to we display
    int curshow = NUM_LEDS;

    /*Not really used yet. Thought to be able to switch between sound reactive
    mode, and general gradient pulsing/static color*/
    int mode = 0;

    //Showing different colors based on the mode.
    int songmode = NORMAL;

    //Average sound measurement the last CYCLES
    unsigned long song_avg;

    //The amount of iterations since the song_avg was reset
    int iter = 0;

    //The speed the LEDs fade to black if not relit
    float fade_scale = 1.2;

    //Led array
    CRGB leds[NUM_LEDS];

    /*Short sound avg used to "normalize" the input values.
    We use the short average instead of using the sensor input directly */
    int avgs[AVGLEN] = {-1};

    //Longer sound avg
    int long_avg[LONG_SECTOR] = {-1};

    //Keeping track how often, and how long times we hit a certain mode
    struct time_keeping {
      unsigned long times_start;
      short times;
    };

    //How much to increment or decrement each color every cycle
    struct color {
      int r;
      int g;
      int b;
    };

    struct time_keeping high;
    struct color Color;

    void setup() {
      Serial.begin(9600);
      //Set all lights to make sure all are working as expected
      FastLED.addLeds<NEOPIXEL, LED_PIN>(leds, NUM_LEDS);
      for (int i = 0; i < NUM_LEDS; i++)
        leds[i] = CRGB(0, 0, 255);
      FastLED.show();
      delay(1000);

      //bootstrap average with some low values
      for (int i = 0; i < AVGLEN; i++) {
        insert(250, avgs, AVGLEN);
      }

      //Initial values
      high.times = 0;
      high.times_start = millis();
      Color.r = 0;
      Color.g = 0;
      Color.b = 1;
    }

    /*With this we can change the mode if we want to implement a general
    lamp feature, with for instance general pulsing. Maybe if the
    sound is low for a while? */
    void loop() {
      switch(mode) {
        case 0:
          visualize_music();
          break;
        default:
          break;
      }
        delay(DELAY);       // delay in between reads for stability
    }

    /**Funtion to check if the lamp should either enter a HIGH mode,
    or revert to NORMAL if already in HIGH. If the sensors report values
    that are higher than 1.1 times the average values, and this has happened
    more than 30 times the last few milliseconds, it will enter HIGH mode.
    TODO: Not very well written, remove hardcoded values, and make it more
    reusable and configurable.  */
    void check_high(int avg) {
      if (avg > (song_avg/iter * 1.1))  {
        if (high.times != 0) {
          if (millis() - high.times_start > 200.0) {
            high.times = 0;
            songmode = NORMAL;
          } else {
            high.times_start = millis();
            high.times++;
          }
        } else {
          high.times++;
          high.times_start = millis();

        }
      }
      if (high.times > 30 && millis() - high.times_start < 50.0)
        songmode = HIGH;
      else if (millis() - high.times_start > 200) {
        high.times = 0;
        songmode = NORMAL;
      }
    }

    //Main function for visualizing the sounds in the lamp
    void visualize_music() {
      int sensor_value, mapped, avg, longavg;

      //Actual sensor value
      sensor_value = analogRead(ANALOG_READ);

      //If 0, discard immediately. Probably not right and save CPU.
      if (sensor_value == 0)
        return;

      //Discard readings that deviates too much from the past avg.
      mapped = (float)fscale(MIC_LOW, MIC_HIGH, MIC_LOW, (float)MIC_HIGH, (float)sensor_value, 2.0);
      avg = compute_average(avgs, AVGLEN);

      if (((avg - mapped) > avg*DEV_THRESH)) //|| ((avg - mapped) < -avg*DEV_THRESH))
        return;

      //Insert new avg. values
      insert(mapped, avgs, AVGLEN);
      insert(avg, long_avg, LONG_SECTOR);

      //Compute the "song average" sensor value
      song_avg += avg;
      iter++;
      if (iter > CYCLES) {
        song_avg = song_avg / iter;
        iter = 1;
      }

      longavg = compute_average(long_avg, LONG_SECTOR);

      //Check if we enter HIGH mode
      check_high(longavg);

      if (songmode == HIGH) {
        fade_scale = 3;
        Color.r =  8;
        Color.g = 1;
        Color.b = -2;
      }
      else if (songmode == NORMAL) {
        fade_scale = 3;
        Color.r = -1;
        Color.b = 6;
        Color.g = -2;
      }

      //Decides how many of the LEDs will be lit
      curshow = fscale(MIC_LOW, MIC_HIGH, 0.0, (float)NUM_LEDS, (float)avg, -1);

      /*Set the different leds. Control for too high and too low values.
              Fun thing to try: Dont account for overflow in one direction,
        some interesting light effects appear! */
      for (int i = 0; i < NUM_LEDS; i++)
        //The leds we want to show
        if (i < curshow) {
          if (leds[i].r + Color.r > 255)
            leds[i].r = 255;
          else if (leds[i].r + Color.r < 0)
            leds[i].r = 0;
          else
            leds[i].r = leds[i].r + Color.r;

          if (leds[i].g + Color.g > 255)
            leds[i].g = 255;
          else if (leds[i].g + Color.g < 0)
            leds[i].g = 0;
          else
            leds[i].g = leds[i].g + Color.g;

          if (leds[i].b + Color.b > 255)
            leds[i].b = 255;
          else if (leds[i].b + Color.b < 0)
            leds[i].b = 0;
          else
            leds[i].b = leds[i].b + Color.b;

        //All the other LEDs begin their fading journey to eventual total darkness
        } else {
          leds[i] = CRGB(leds[i].r/fade_scale, leds[i].g/fade_scale, leds[i].b/fade_scale);
        }
      FastLED.show();
    }
    //Compute average of a int array, given the starting pointer and the length
    int compute_average(int *avgs, int len) {
      int sum = 0;
      for (int i = 0; i < len; i++)
        sum += avgs[i];

      return (int)(sum / len);

    }

    //Insert a value into an array, and shift it down removing
    //the first value if array already full
    void insert(int val, int *avgs, int len) {
      for (int i = 0; i < len; i++) {
        if (avgs[i] == -1) {
          avgs[i] = val;
          return;
        }
      }

      for (int i = 1; i < len; i++) {
        avgs[i - 1] = avgs[i];
      }
      avgs[len - 1] = val;
    }

    //Function imported from the arduino website.
    //Basically map, but with a curve on the scale (can be non-uniform).
    float fscale( float originalMin, float originalMax, float newBegin, float
        newEnd, float inputValue, float curve){

      float OriginalRange = 0;
      float NewRange = 0;
      float zeroRefCurVal = 0;
      float normalizedCurVal = 0;
      float rangedValue = 0;
      boolean invFlag = 0;

      // condition curve parameter
      // limit range

      if (curve > 10) curve = 10;
      if (curve < -10) curve = -10;

      curve = (curve * -.1) ; // - invert and scale - this seems more intuitive - postive numbers give more weight to high end on output
      curve = pow(10, curve); // convert linear scale into lograthimic exponent for other pow function

      // Check for out of range inputValues
      if (inputValue < originalMin) {
        inputValue = originalMin;
      }
      if (inputValue > originalMax) {
        inputValue = originalMax;
      }

      // Zero Refference the values
      OriginalRange = originalMax - originalMin;

      if (newEnd > newBegin){
        NewRange = newEnd - newBegin;
      }
      else
      {
        NewRange = newBegin - newEnd;
        invFlag = 1;
      }

      zeroRefCurVal = inputValue - originalMin;
      normalizedCurVal  =  zeroRefCurVal / OriginalRange;   // normalize to 0 - 1 float

      // Check for originalMin > originalMax  - the math for all other cases i.e. negative numbers seems to work out fine
      if (originalMin > originalMax ) {
        return 0;
      }

      if (invFlag == 0){
        rangedValue =  (pow(normalizedCurVal, curve) * NewRange) + newBegin;

      }
      else     // invert the ranges
      {
        rangedValue =  newBegin - (pow(normalizedCurVal, curve) * NewRange);
      }

      return rangedValue;
    }

  [1]: https://robu.in/wp-content/uploads/2016/03/robu-3-22-462x392.jpg
  [2]: https://i.stack.imgur.com/yZyIb.jpg "Voice module"

body:
The potentiometer is only supposed to modify the threshold at which the Digital Output Pin will output a HIGH or LOW value. The Analog Output Pin should be not altered by the potentiometer.

I think your sound module might not be the best for your project, if you are working with weak audio signals. It suits more for projects like clap detectors and such. You might be able to use that sensor for detect weaker signals if you put an audio amplifier after the Analog Output Pin, or change the Analog Reference value on the Arduino.


message:
Unexplainable int behavior in encoder/LED project

I am trying to use a rotary encoder to cycle through the brightest versions of R, G & B. And it works! Red goes to blue just fine. Then G happens. For some reason, the int for green goes completely haywire. And it does this the same way on two Arduinos.

So my question is this: why would two, identically assigned variables treat `++` completely differently? After hours (and hours and hours) of looking, I'm completely out of possible answers.

```cpp
#include <Encoder.h>
#include <FastLED.h>

/* Encoder */
Encoder myEnc(2, 3);
const int swPin = 4 ;
long oldPosition  = -999;

/* LEDs */
#define LED_PIN     7
#define NUM_LEDS    150
CRGB leds[NUM_LEDS];

/* RGB Loop */
volatile int cycle = 1;
volatile int brightness = 0;
volatile int r = 127;
volatile int g = 0;
volatile int b = 0;

void setup() {
  pinMode(swPin, INPUT);
  Serial.begin(9600);
  FastLED.addLeds<WS2812, LED_PIN, GRB>(leds, NUM_LEDS);
}

void loop() {
  // Read from rotary encoder.
  long newPosition = myEnc.read();

  if (newPosition != oldPosition) {
    oldPosition = newPosition;
    Serial.println(newPosition); /* Sends elsewhere */
  }

  /* Will eventually move this inside the above if
   * statement so the color shift is controlled by
   * a rotary encoder.  Down here for debugging.
   */
  delay(50);
  updateColor( );
}

void updateColor(  ) {

  Serial.println(" "); // For readability.

  if ( brightness >= 127 ) {
    brightness = 1;
    if ( cycle > 6 ) {
      cycle = 1;
    } else {
      cycle++;
    }
  } else {
    brightness++;
  }

  if ( cycle == 1) {
    b++;
  }
  else if ( cycle == 2) { /* rb --> b */
    r--;
  }
  else if ( cycle == 3) { /* b --> bg */
    g++;
  }
  else if ( cycle == 4) { /* bg --> g */
    b--;
  }
  else if ( cycle == 5) { /* g --> rg */
    r++;
  }
  else if ( cycle == 6) { /* g --> rg */
    g--;
  }
  else {
    Serial.print("==================== ");
  }

  /* Debugging */
  Serial.print("brightness:");
  Serial.print(brightness);
  Serial.print("   cycle:");
  Serial.print(cycle);
  Serial.print("   r:");
  Serial.print(r);
  Serial.print(" g:");
  Serial.print(g); // goes completely bonkers
  Serial.print(" b:");
  Serial.print(b);
  Serial.println(" ");

  for (int i = 0; i <= NUM_LEDS; i++) {
    leds[i].setRGB( r, g, b );
  }

  FastLED.show();

}
```

spits out the following in the serial monitor :

```
brightness:1   cycle:1   r:127 g:0 b:1

brightness:2   cycle:1   r:127 g:127 b:2

brightness:3   cycle:1   r:127 g:32639 b:3

brightness:4   cycle:1   r:127 g:32639 b:4

brightness:5   cycle:1   r:127 g:32639 b:5

brightness:6   cycle:1   r:127 g:32639 b:6

```

Red and blue are doing exactly what I want. Green is off on Mars.

Any/all help would be enormously appreciated.  Thanks in advance.

body:
Here:

    CRGB leds[NUM_LEDS];

you are defining an array of `NUM_LEDS` objects of the `CRGB` type.
Valid indices for this array range from `0` to `NUM_LEDS-1`.

Here:

    for (int i = 0; i <= NUM_LEDS; i++) {
      leds[i].setRGB( r, g, b );
    }

you are accessing the array elements at indices `0` to `NUM_LEDS`. The
last iteration is an out-of-bounds access, which is causing memory
corruption. You should instead write

    for (int i = 0; i < NUM_LEDS; i++) ...


message:
Exception Handling with the Arduino IDE

I'm using a port of the STL found [here](https://github.com/mike-matera/ArduinoSTL) and trying to debug with a simple ```try{...}catch{...}``` loop. When compiling with the Arduino IDE, I get the error message

> exception handling disabled, use -fexceptions to enable.

I'm not quite sure what this means. Can the Arduino simply not support exceptions? Or is ```-fexceptions``` a compiler flag I can enable?

body:
Arduino is a very limited platform, and handling exceptions requires quite a bit of hidden code to properly unwind the stack wherever the exception occurs.

So the default is to turn it off and teach users to not use exceptions in arduino and instead other type of error handling.


body:
As you have already found out, add `-fexceptions` to the compiler flags. This can be done by modifying the `platform.txt` of your Arduino IDE installation.

See https://github.com/arduino/ArduinoCore-avr/blob/master/platform.txt#L28. There is `-fno-exceptions` defined, so you have to remove that, too.


message:
Serial monitor shows repeated CIPSEND and CIPCLOSE

I'm trying to build a heart rate monitor using ESP-01. The code compiles and uploads well but once uploaded, in the serial monitor it shows the following. It keeps repeat CIPSEND and CIPCLOSE over and over.
What could cause this?
Could it be faulty hardware or is it a problem with the code?

```none
 AT+CIPSTART="TCP","184.106.153.149",80
 AT+CIPSEND=29
 AT+CIPCLOSE
 AT+CIPSTART="TCP","184.106.153.149",80
 AT+CIPSEND=29
 AT+CIPCLOSE
 AT+CIPSTART="TCP","184.106.153.149",80
 AT+CIPSEND=29
 AT+CIPCLOSE
 AT+CIPSTART="TCP","184.106.153.149",80
```

body:
The reason that you are seeing those messages on the serial monitor is because the code is *telling* it to print those messages on the serial monitor.

Every time a message is sent to the ESP8266 it is also sent (for debugging purposes) to the Serial.


message:
SG90 servo motor not working

I tried to test a servo motor for a project using this simple circuit but the motor won't move. I've used this before with the same setup and code and it worked, but now suddenly nothing works, even tried a different servo motor.
I have tried changing arduinos, changing signal pins , changing servos but nothing works. I had got them to work only a few days back but now suddenly i cant and i dont know where im going wrong.
**here is my circuit** :- [image of circuit][1]

  [1]: https://drive.google.com/file/d/1bN1CF5VlAhcG8v71h5JyR1pCtpMfZNL6/view?usp=drivesdk

    #include <Servo.h>
    Servo myservo;
    int pos = 0;
    void setup()
    {
    myservo.attach(9);
    }
    void loop()
    {
    for (pos = 0; pos <= 180; pos += 1)
    {
    myservo.write(pos);
     delay(15);
    }
    for (pos = 180; pos >= 0; pos -= 1)
    {
     myservo.write(pos);
    delay(15);
    }
    }

body:
There's nothing wrong with your code. Check your wiring:

 - Servo brown  -> Gnd
 - Servo red    -> +5v (not +3v)
 - Servo Orange -> pin 9
 - Connections at the servo-connector and at the Arduino are electrically sound
 - Try swapping the 3 jumper wires (the only parts you didn't say you'd swapped)


message:
Schematic with Atmega32U4 and WS2812 Led (Smiley Shape). Does it work?

I'm new here and I'm a newbie in electronics. Since 1 year I'm playing around with Arduino (different types) and now I want to build my own thing: a smiley with WS2812D-F5 RGB leds. But I'm not sure if I did any misstakes. Is it possible that an expert in electronics can check my schematic? That would be very kind, nice and cool :)

Functions: The switch SW1 is connected on D8 (PB4) and if pushed the smiley changes from sad to happy. pushed again it changes again and so on.

Because the WS2812 leds needs a lot of current, I have added some different possibilities to power the whole thing: 1x DC jack connected on a voltage regulator that output 5V fixed and two pins for a LiPo 3.7V that ist connected too on the voltage regulator. I dont know if it works if the LiPo has only 3.7V.

Well.. then I added a power switch, micro usb, FTDI and SPI connection. If one fails to burn the bootloader or to upload a sketch, I have more possibilities to do that ;)

Yeah I think thats it. If I forgot something, just ask me. Thanks a lot!

Kind regards.

Greetings from Switzerland

delf
[![Schematic WS2912 atmega32u4 smiley][1]][1]

Edit 15.5.19 18:00
Ok, I just changed the schematic based upon your great advices :) Thanks a lot to everyone. I changed/added the regulator. Current output=3A (each one). Should  be enough. But I'm not sure if I can divide the current in that way.

What do you think? :)

Greetings to everyone :)

[![Version 1.2][2]][2]

  [1]: https://i.stack.imgur.com/HNfG5.png
  [2]: https://i.stack.imgur.com/Pw1vh.png

body:
No. That circuit will not work.

The moment you turn on more than a few of the LEDs the regulator will go into meltdown. No matter how powerful your power supply is, that regulator is the bottleneck and will overheat the moment you try and light your smiley face.

The regulator (a venerable 7805 - I mean, come on, that's from the ark. There's far better modern regulators now...) is rated for a maximum of 1A. That is with *very good heatsinking and thermal management, and an input voltage only slightly above 5V + the dropout voltage*.  Your circuit can draw up to about 4A. That's 4x what the regulator is rated for when it's at its most optimim - probably 6x to 8x what your arrangement would be able to provide.

For this kind of circuit you *need* a switching regulator. One that can provide many many times the current of a linear regulator like the 7805 (or the more modern LM1117-5.0).  You need one that will provide at least 4A, and ideally a little more for some extra headroom. So you're looking at 5A.

With a decent efficiency you could then run the whole thing from a 12V input with 2.5A minimum current. Assuming 85% efficiency:

* 12V @ 2.5A = 30W
* 85% of 30W = 25.5W
* 25.5W @ 5V = 5.1A

So a 12V, 2.5A supply being fed into a 5V, 5A switching regulator with at least 85% efficiency will allow your circuit to operate more reliably.

You also need to take care with your PCB layout (assuming you are designing this for building on a PCB). Switching regulators take a certain amount of care when laying them out. You should refer to the recommended PCB layout in the datasheet for your chosen regulator and stick as closely to that as you can.

Also handling larger currents requires more thought put into your traces.  [This site](https://www.7pcb.com/trace-width-calculator.php) has a handy trace width calculator.

As an example: for a 5A trace over a distance of 5cm with (standard) 1oz copper your trace should be at least 2.77mm wide. That will give a 10C temperature rise in the trace at room temperaure (25C to 35C).


body:
On the FTDI header you need to swap the TX and RX pins. The TX of the FTDI should connect the the RX of the Arduino, and vice-versa.

Also, on the FTDI header, the USBVCC pin is connected directly to the 5V pin. I would want to connect my PC to that header if external power is applied to your board. If you're never going to use that pin to power the board, you could leave it disconnected. The same applies to the USB port.

I'd have the LiPo connector bypass the regulator, as all it does is drop the voltage even lower. A LiPo is around 4.2V when full. The 3.7V is only it's nominal voltage.

D1 is in a weird location. If you want to use it to prevent reverse polarity, move it between the jack, and the input of the voltage regulator.


message:
Help with Bluetooth shield

Hey guys I have this Bluetooth shield

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

Does anybody know how I can get it to connect to Arduino?
I can't find any guides on it.

I have this serial program that I want to use to turn on a led.
but I can't seem to enter AT mode, or get any indication that besides it connecting to my Mac it's receiving or transmitting any signals.

Anybody got any tips for tutorials/tips for tests for a MAC OSX user?

UPDATE: here is a better foto

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

I'm trying to run this Arduino code. that uses a 1 to turn a led on and a 0 to turn it off. I want to send these 1's and 0's through a Mac program called Bluterm. I connect it to the HC-05 BUT it doesn't send me anything back. (THE LED IS GREEN, IT'S CONNECTED ON MAC AND ON BLUTERM)

Here is my Arduino code:

```

int led = 13;
int value = 0;

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

}

void loop() {
  if (Serial.available() > 0) {
    value = Serial.read();
    delay(5);

    if (value == '1') {
      digitalWrite(led, HIGH);
      Serial.println("LED IS ON");

    }

    if (value == '0') {
      digitalWrite(led, LOW);
      Serial.println("LED IS OFF");

    }

  }
  }

```

UPDATE 2: Here is the code from the PDF that was shipped with my shield:

```

unsigned int timeout=0; unsigned char state=0;
ISR(TIMER2_OVF_vect) {
TCNT2 = 0; timeout++;
if (timeout>61) {
state=1;
timeout=0; }
}
void init_timer2(void) {
//Timer2 Service
TCCR2A |= (1 << WGM21) | (1 << WGM20);
TCCR2B |= 0x07; // by clk/1024
ASSR |= (0<<AS2); // Use internal clock - external clock not used in Arduino
TIMSK2 |= 0x01; TCNT2 = 0; sei();
}
void setup() {
//Timer2 Overflow Interrupt Enable
Serial.begin(9600);
pinMode(2,INPUT); pinMode(13,OUTPUT); attachInterrupt(0,cleantime,FALLING); init_timer2();
}
void loop() {
switch(state) {
case 0:
digitalWrite(13,LOW); break;

case 1: digitalWrite(13,HIGH); Serial.print("Hellow BT"); break;
} }
void cleantime() {
timeout=0;
state=0; }

```

Anybody can help me decipher this code? none of this looks familiar to me
thanks guys,

juriaan

UPDATE 3:

[![enter image description here][3]][3]

UPDATE 4

[![enter image description here][4]][4]

  [1]: https://i.stack.imgur.com/5Tlxe.jpg
  [2]: https://i.stack.imgur.com/PqK2Y.jpg
  [3]: https://i.stack.imgur.com/jn01K.png
  [4]: https://i.stack.imgur.com/QPmib.png

body:
You need to understand the basics before you try running code to "do things":

1. The shield can run in two modes: AT command mode, which is used to configure it, and Transparent UART mode, which is used to communicate.
2. Communication with the Arduino is done through UART serial, and the pins used for that communication are selected using the big bank of jumpers.
3. Nothing will happen until you have configured the shield using AT commands.

To progress you really need the manual for the shield. This should be available from wherever you purchased it.  That will detail:

* What the positions of the jumpers mean
* What the AT command set of the module is
* What the baud rate is which you need to use to communicate

And if it's any good:

* Example code

Once you have at least the first set of those bits of information you can write some software for the Arduino which will pass anything received on Serial through to the bluetooth shield, and anything received from the bluetooth shield back through to Serial.  You can then use the serial monitor in the IDE to interact with the shield and configure it in the way you need it.

Once you know how to configure it you can then write some better software for the Arduino that does any startup configuration you need and then operates on the data coming in through Transparent UART mode.


message:
ESP32 IR remote

my board is a firebeetle esp32 that I am using as an IR remote.

After using the Ken Shirrif IRremote library for about 6 months successfully, then the time came to change a few things on the web front end. This has been a disaster.

I tried to recompile my working code that the board is currently using and got errors everywhere I turned.

So i switched libraries to this one;

https://github.com/ExploreEmbedded/Arduino-IRremote

Now it does compile successfully, with the only change between the two libraries was to pull out the pin I defined for IR tx in the Ken Shirriff library. For example; previously my code looked like this to work with the old library.
<!-- language-all: lang-cpp -->

    IRsend irsend(33);

Now it looks like this;

    IRsend irsend;

As stated, it does compile; only issue is that IR doesn't work. It says in the library that pin 5 is defined as the tx pin for the ESP32 in boarddefs. Snip from boarddefs where I believe pin 5 is defining IR tx.

    // ESP32 has it own timer API and does not use these macros, but to avoid ifdef'ing
    // them out in the common code, they are defined to no-op. This allows the code to compile
    // (which it wouldn't otherwise) but irsend will not work until ESP32 specific code is written
    // for that -- merlin
    // As a warning, sending timing specific code from an ESP32 can be challenging if you need 100%
    // reliability because the arduino code may be interrupted and cause your sent waveform to be the
    // wrong length. This is specifically an issue for neopixels which require 800Khz resolution.
    // IR may just work as is with the common code since it's lower frequency, but if not, the other
    // way to do this on ESP32 is using the RMT built in driver like in this incomplete library below
    // https://github.com/ExploreEmbedded/ESP32_RMT
    #elif defined(IR_TIMER_USE_ESP32)
    #define TIMER_CHANNEL       1
    #define TIMER_LENGHT        8 //8-bit Timer
    #define TIMER_PWM_PIN      5
    #define TIMER_ENABLE_PWM    ledcAttachPin(TIMER_PWM_PIN, TIMER_CHANNEL);
    #define TIMER_DISABLE_PWM   ledcDetachPin(TIMER_PWM_PIN);
    #define TIMER_RESET
    #define TIMER_ENABLE_INTR
    #define TIMER_DISABLE_INTR
    #define TIMER_INTR_NAME

    //---------------------------------------------------------
    // Unknown Timer
    //
    #else
    # error "Internal code configuration error, no known IR_USE_TIMER# defined\n"
    #endif

    #endif // ! boarddefs_h

I know it says that IR with the ESP32 will not work, but it said the same thing for several libraries that i've used that do work, most notably the one by Ken; which appears to have moved here.

https://github.com/z3t0/Arduino-IRremote

Quick example of my code;

    #include "IRremote.h"
      IRsend irsend;
    int khz = 38;
    String input;
      String tv;
    void changehdmi() {
    if (Server.args() > 0 ) {
      for ( uint8_t i = 0; i < Server.args(); i++ ) {
        if (Server.argName(i) == "input") {
          input = String(Server.arg(i));
          Serial.println("input is " + input);
        }
        if (Server.argName(i) == "tv") {
          tv = String(Server.arg(i));
          Serial.println("tv is " + tv);
        }

      }
    }
    if (input == "1" && tv == "1") {
      unsigned int irSignal[] = {9000, 4450, 600, 550, 550, 550, 600, 550, 550, 550, 600, 500, 600, 550, 550, 600, 550, 550, 600, 1650, 550, 1700, 550, 1700, 550, 1700, 550, 1700, 550, 1700, 550, 1650, 600, 1650, 550, 1700, 550, 550, 600, 550, 550, 1700, 550, 550, 600, 500, 600, 550, 550, 600, 550, 550, 600, 1650, 550, 1700, 550, 550, 600, 1650, 550, 1700, 550, 1700, 550, 1700, 550}; // NEC FF906F
      irsend.sendRaw(irSignal, sizeof(irSignal) / sizeof(irSignal[0]), khz);
    }
    else if (input == "2" && tv == "1") {
      unsigned int irSignal[] = {9000, 4500, 550, 550, 600, 550, 550, 550, 550, 600, 550, 550, 600, 550, 550, 550, 550, 550, 600, 1650, 600, 1700, 500, 1700, 600, 1700, 500, 1700, 550, 1700, 550, 1700, 550, 1700, 550, 1700, 550, 550, 550, 1700, 550, 1700, 550, 1700, 550, 550, 550, 550, 600, 550, 550, 550, 600, 1700, 500, 600, 550, 550, 600, 500, 600, 1650, 600, 1650, 600, 1650, 550}; // NEC FFB847
      irsend.sendRaw(irSignal, sizeof(irSignal) / sizeof(irSignal[0]), khz);
    }

Has anyone gotten this to work recently? The libraries that are available seem to have lost support for this functionality.

body:
For the ESP32, you should really check out [IRremoteESP8266](https://github.com/crankyoldgit/IRremoteESP8266), which also works on your board, and is frequently updated, very widely used, and lets you use any compatible GPIO pin easily.

Here's a sample of a simple IR send demo:

```
#include <Arduino.h>
#include <IRremoteESP8266.h>
#include <IRsend.h>

#define IR_PIN 4

IRsend irsend(IR_PIN);  // Set the GPIO to be used to sending the message.

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

void loop() {
  Serial.println("NEC");
  irsend.sendNEC(0x00FFE01FUL);
  delay(2000);
}
```

This example will send an NEC code very 2 seconds. The library also has extensive support for other formats, as well as raw.

If you want to be extra safe, the creator of the project menions [here](https://github.com/crankyoldgit/IRremoteESP8266/discussions/1556#discussioncomment-1149046) that GPIO 4 and 18 are safe, but I know for a fact that many other ESP32 pins are okay to use as well.


message:
LM393 Speed sensor - Counting pulses

I'm trying to calculate de rotation speed of a dc motor.

I'm using the sensor shown in the picture and a slotted disk attached to the motor. The results I was getting made no sense and after several tests I realised the following:

Most of the times I manually blocked or unblocked the sensor, two pulses were counted. That would mean that for each tooth of the slotted disk, up to four pulses were counted instead of one.

Bellow is a test code. I count pulses on the interrupt handler and reset the counter when calculating the motor speed.

Am I doing something wrong or is the sensor suffering from bouncing signals?

    int encoderCounter = 0;
    int encoderDiscSlots = 21;

    int encoderPin = 19;

    void encoderIncrementISR()
    {
      encoderCounter++;
    }

    double calculateMotorSpeed(int interval)
    {
      Serial.print("enc ");
      Serial.println(encoderCounter);
      double rpm = (encoderCounter*1.0/encoderDiscSlots)*60000/interval;

      encoderCounter = 0;
      return rpm;
    }

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

      pinMode(encoderPin, INPUT_PULLUP);

      attachInterrupt(digitalPinToInterrupt(encoderPin), encoderIncrementISR, RISING);
    }

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

      delay(1000);
      double rpm = calculateMotorSpeed(1000);
      Serial.print("rpm ");
      Serial.println(rpm);
    }

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

The sensor uses the LM393 IC from TI, a spec sheet can be found [here][2]

  [1]: https://i.stack.imgur.com/31flG.jpg
  [2]: https://5.imimg.com/data5/VQ/DC/MY-1833510/lm393-motor-speed-measuring-sensor-module-for-arduino.pdf

body:
I've done some more search on the interwebs and found [someone][1] (in Spanish) describing the same problem. That person owns an oscilloscope and could confirm that there is some bouncing on the data signal both going up and down.

The hardware solution presented is to place a 100 nF capacitor between the signal pin and ground.

I've tried it and it works.

  [1]: https://androminarobot.blogspot.com/2016/04/tutorial-sobre-el-encoder-fotoelectrico.html


message:
ADS1115, ZMPT101b and Arduino Uno listing program for AC measurement

I got problem in my result where my ADC read cannot give the biggest and the lowest ADC Value if I am using ADS1115. meanwhile, when I am not using ADS1115 I can get the biggest and the lowest ADC Value using a listing program that I use before. Thank u, need for help.

[![Result with ADS][1]][1]

[![Result without ADS][2]][2]

[![Program with ADS[![\]\[3\]][3]][3]]
[![program without ADS][4]][4]

  [1]: https://i.stack.imgur.com/FwF1J.png
  [2]: https://i.stack.imgur.com/IXTX1.png
  [3]: https://i.stack.imgur.com/xCJwC.png
  [4]: https://i.stack.imgur.com/SEMha.png

body:
The ZMPT101b is a transformer which converts voltage. You can read the output with analog pin.

The ADS1115 is an analog to digital converter. It reads the analog voltage the same way as the analog pin of your Arduino does. The result then can be read over I2C as a register value. You can't read it with analogRead.

So you can use the ADS1115 to convert the analog output of the ZMPT101b.

To read the digital value from the ADS1115 with Arduino, use the Wire library or find a library for the ADS1115. For example [this one][1].

I use ADC121 with Wire library. I initialize it in setup()

      const byte REG_ADDR_RESULT = 0x00;
      const byte REG_ADDR_CONFIG = 0x02;

      // initialize the Wire library
      Wire.begin();
      Wire.setClock(400000);

      // configure the ADC
      Wire.beginTransmission(I2C_ADC121);
      Wire.write(REG_ADDR_CONFIG);
      Wire.write(REG_ADDR_RESULT);
      Wire.endTransmission();

      // set the 'result' register as default
      Wire.beginTransmission(I2C_ADC121);
      Wire.write(REG_ADDR_RESULT);
      Wire.endTransmission();

and then in code I read the value with this function

    unsigned short adcRead() {
      Wire.requestFrom(I2C_ADC121, 2); // request 2 bytes
      byte buff[2];
      Wire.readBytes(buff, 2); // read 2 bytes
      return (buff[0] << 8) | buff[1]; // get the result as 16 bit number
    }

  [1]: https://github.com/adafruit/Adafruit_ADS1X15


message:
How to program the nodeMCU through OTA using GPRS?

I'm using a NodeMCU in one of my projects. The setup is in a remote location. That place doesn't have WiFi so I'm using GPRS (GSM SIM800V) for sensor data collection to my server. Right now I need to update my new firmware to that NodeMCU.

Is it possible do OTA using GPRS (GSM SIM800V)?

body:
Yes, it is possible, but it takes some work on your part.

I recently had to implement OTA updates for the ESP32 over an RS-485 link, and it's actually pretty simple to manage. The hard part (for you) is the communication connection.

Performing an update (assuming the flash is already partitioned and set up right for OTA updates) is a case of "starting" the update, passing the update manager the flash data, then "ending" the update:

1. `Update.begin(size)` - This starts the upgrade process. You need to provide the expected size of the flash data at this point.
2. `Update.write(*data, length)` - Pass a block of flash data to the updater for writing.  An alternative is to read directly from a `Stream` class, which will try and read the number of bytes specified in the `size` parameter to `begin`.
3. `Update.end()` - This will finish it all off and switch the bootloader to load from the new flash. If it worked fine it will return `true`, otherwise, it will return `false`.

Assuming the above worked, you can no reset the board with `ESP.restart()`

For added security you can also pass an MD5 hash of the data to `Update.setMD5(md5)` and the updater will check that the uploaded data matches that MD5 hash.

Of course, all this needs implementing in your program that is running on the target device *before* you try and do any OTA updates. And, of course, you need to arrange the actual upgrade channel to get the commands and data through to the target in the first place.

So:

1. Implement a method of getting the data to the target
2. Implement the updater code
3. Go to the device and upgrade the firmware
4. From that point on you should be able to use OTA updates through your own chosen mechanism.


message:
ESP8266 NODEMCU V3, HOW TO USE AND CONTROL V3 OUTPUT POWER

this is my very first post in here so I apologise if I am not giving you all the information that I should.

I am creating this topic to ask you help regarding how to control and use the v3 output of my Nodemcu.

I have a script which is working fine to power on and off a led by using one of the GPIO and the ground. However, my project requires to power on a small motor for about 2 seconds and then stop it. If I connect this motor to one of the GPIO and the ground I can control it but it runs very slow. If I connect the motor to the 3V output it goes fine but I can't turn it on or off. The motor requires 3V to run properly. How can I turn it on and off by powering it from that 3V output?

What am I missing?

I have a 4n25 chip which I saw in a video that has been used for a similar project however the vide is in Portuguese and I am not able to follow it properly.

Can please someone advice?

Thank you for your time,

Ade

body:
You cannot control the "V3" output. It's a 3.3V power supply output. Think of it like a battery. It's always on and always giving power.

Instead, you need to add a "switch" to control that power that the ESP8266 can itself control, such as a MOSFET or a motor driver (H-Bridge).


message:
Speed Control of Brushless DC Motor

I cannot understand the code of controlling the speed of brushless dc motor using ESP8266 WiFi Module.

 I found it in- https://ubidots.com/blog/speed-control-for-brushless-motors-with-an-esp8266-2/

The part that I cannot understand is-
```arduino

float btof(byte * payload, unsigned int length) {

  char * demo = (char *) malloc(sizeof(char) * 10);

  for (int i = 0; i < length; i++) {

    demo[i] = payload[i];

  }

float value = atof(demo);

  free(demo);

  return value;
}

// Callback to handle subscription

void callback(char* topic, byte* payload, unsigned int length)

{

    value = btof(payload, length);

      value = map(value, 0, 1023, 0, 180);

//Map the 0-100 values from the slider to the 0-180 to use the servo lib.

 ESC.write(value);

//Send the value (PWM) to the ESC

}
```
Please help me with the code!

body:
 1. `Callback function` must be data send from server to the ESP.
 2. `Payload` is the data byte sent from server.
 3. `Length` is the size of data in bytes.
 4. `BTOF` is basically byte to float converter which converts all the data byte received into single floating variable and return that floating point value.
 5. `ECS.write` must be the function that write the value to the servo motor controller H-bridge IC. It belongs to servo library.
 6. Value range that can be mapped into this ECS.write is between 0-180 so `map` function will use that will convert the `floating point data` received from `btof` function.
 7. Basic definition of `map()` function:

`Map function` maps a number from one range to another. That is, a value of fromLow would get mapped to toLow, a value of fromHigh to toHigh, values in-between to values in-between, etc.

Does not constrain values to within the range, because out-of-range values are sometimes intended and useful. The constrain() function may be used either before or after this function, if limits to the ranges are desired.

Note that the "lower bounds" of either range may be larger or smaller than the "upper bounds" so the map() function may be used to reverse a range of numbers.

Syntax:

    map(value, fromLow, fromHigh, toLow, toHigh)

Then `ECS.write(value)` will write that mapped value to servor motor controller H-Bridge.


message:
Arduino nano / uno analog pin

I'm working on a project where I need 7 analog pins.
I read the datasheet of Ardnuino Uno : 6 analog pins available.
So I decided to use an arduino mega with 16 analog pin available.
Then I saw the arduino nano had 8 analog pins.
But when I read the datasheet, both arduino uno and nano use Atmega328
In my final project, I will not use the board but only the pdip chip (analog pins are from pin number 23 to 28).
Is it possible to "convert" another pin of the pdip to be an analog pin ?

Thank you

body:
No, this is not possible. The [datasheet of the ATmega328P][datasheet]
states it has:

> * 8-channel 10-bit ADC in TQFP and QFN/MLF package
> * 6-channel 10-bit ADC in PDIP Package

If you want to use a bare chip, it won't be possible with a PDIP
package.

[datasheet]: http://ww1.microchip.com/downloads/en/DeviceDoc/ATmega48A-PA-88A-PA-168A-PA-328-P-DS-DS40002061A.pdf


body: A Nano and some ProMinis have all 8 analog input pins available from the 32-pin TQFP Atmega328P package. An Uno only has 6 of the 8 available in the 28-pin DIP package. Instead of the bare 28-pin DIP, use one of the 32-pin TQFP parts, on a breakout board, or as a packaged 'system' board; a Promini is the 328P with resonator and voltage regulator, connect to it with external FTDI module for programming/debugging; the Nano which goes a step further and adds a USB interface chip.


message:
Basic if endif not working and I'm puzzled

I got this small code I'm trying things on for like an hour.

    int receivers = 0;
    #if defined(PPM_RECEIVER)
      receivers++;
    #endif

And I just cannot get it working, It keeps returning a "'receivers' does not name a type" on line 4.

body: You can't use commands like `receivers++` outside of a function.  That is runtime executable code, and has to be run from inside a function. Global scope doesn't get executed in the same way as code in a function.


message:
Switch statement cases not executing

Overview:
I am trying to use a switch statement to run different tests. A main menu is displayed on the serial monitor, and then the user is given the option to enter their menu choice in the serial monitor. The menu choice entered in the serial monitor should subsequently run the appropriate case statement.

Issues:
 1. When I enter a choice the case statement for that choice does not run
 2. When I enter a choice my the serial monitor scrolls through my menu 3 times displaying 49, then 13, then 10.

Questions:

 1. Why are my case statements not executing?
 2. Why does the serial monitor scroll three times displaying these random numbers?

    ```
    //////////////PREPROCESSOR DIRECTIVES/////////

    #include <Wire.h>

    /////////////GLOBAL VARIABLES////////////////

    int ADDRESS_SLAVE = 0x08;
    int ADDRESS_VERSION = 0x00;
    int ADDRESS_STATUS = 0x01;
    int ADDRESS_ENABLE = 0x02;
    int ADDRESS_CONFIG = 0x03;
    int ADDRESS_RESTART = 0x04;
    int ADDRESS_STARTUP_STATE = 0X05;
    int ADDRESS_COMPENDISREG1 = 0X07;
    int ADDRESS_COMPENDISREG2 = 0X08;
    int ADDRESS_COMPENDISREG3 = 0X09;
    int ADDRESS_COMPENDISREG4 = 0X0A;
    int ADDRESS_FAULT = 0X0B;
    int ADDRESS_FAULTMASK = 0X0C;
    int ADDRESS_TEST_MODE = 0X0D;

    ////////////SETUP CONDITIONS/////////////////

    void setup()
    {
     Wire.setClock(100000);
     Wire.beginTransmission(byte(ADDRESS_SLAVE));
     Serial.begin(9600);
    }

    ////////////MAIN FUNCTION///////////////////

    void loop()
    {

      int choice = 0;

      int const
                //Clock 100
                CLOCK_FREQ_P = 101,
                CLOCK_FREQ_DIV4 = 102,
                CLOCK_FREQ_DIV8 = 103,
                CLOCK_FREQ_DIV16 = 104,
                CLOCK_FREQ_DIV32 = 105,
                CLOCK_INT_SUPPLY_IBIAS = 106,
                CLK_OK = 107,

                //Bandgap 200
                BG_2p5V = 200,
                BG_MAX_LOAD = 201,
                BG_VBE = 202,
                BG_VP = 203,
                BG_VGATE = 204,
    mainMenu();

       choice = menuChoice();

       switch(choice)
       {
        case CLOCK_FREQ_P :
        {
          Serial.println(F("CLOCK_FREQ_P Not yet built out"));
          while(Serial.available() > 0)
            {
               int choice = Serial.read();
            }

          delay(10000);
        }
        break;

        case CLOCK_FREQ_DIV4:
        {
          Serial.println(F("CLOCK_FREQ_DIV4 Not yet built out"));
        }
        break;

        case CLOCK_FREQ_DIV8:
        {
          Serial.println(F("FREQ_DIV8 Not yet built out"));
        }
        break;

        case CLOCK_FREQ_DIV16:
        {
          Serial.println(F("CLOCK_FREQ_DIV16 Not yet built out"));
        }
        break;

        case CLOCK_FREQ_DIV32:
        {
          Serial.println(F("CLOCK_FREQ_DIV32 Not yet built out"));
        }
        break;

        case CLOCK_INT_SUPPLY_IBIAS:
        {
          Serial.println(F("CLOCK_INT_SUPPLY_IBIAS Not yet built out"));
        }
        break;

        case CLK_OK:
        {
          Serial.println(F("CLK_OK Not yet built out"));
        }
        break;

        case BG_2p5V:
        {
          Serial.println(F("BG_2p5V Not yet built out"));
        }
        break;

        case BG_MAX_LOAD:
        {
          Serial.println(F("BG_MAX_LOAD Not yet built out"));
        }
        break;

        case BG_VBE:
        {
          Serial.println(F("BG_VBE Not yet built out"));
        }
        break;

        case BG_VP:
        {
          Serial.println(F("BG_VP Not yet built out"));
        }
        break;

        case BG_VGATE:
        {
          Serial.println(F("BG_VGATE Not yet built out"));
        }
        break;

        delay(500);
    }

    ////////////////FUNCTIONS/////FUNCTIONS/////FUNCTIONS/////FUNCTIONS///////////////////////////

    //*******************************************
    //**      Function: Main Menu Display
    //**      Passes: nothing
    //**      Returns: nothing
    //*******************************************

    void mainMenu()
    {
      //Prints main menu to the serial monitor
      Serial.println();
      Serial.println(F("\t\t\t\t\t\t\t\t\t\t       ******************************"));
      Serial.println(F("\t\t\t\t\t\t\t\t\t\t       ******************************"));
      Serial.println(F("\t\t\t\t\t\t\t\t\t\t       **         MAIN MENU        **"));
      Serial.println(F("\t\t\t\t\t\t\t\t\t\t       ******************************"));
      Serial.println(F("\t\t\t\t\t\t\t\t\t\t       ******************************"));
      Serial.println();
      Serial.println(F("\t\t\t\t\t\t ********************************************************************************************************************"));
      Serial.println(F("\t\t\t\t\t\t **   Please type in the number of the test you want to run in the command line window at the top of the screen.   **"));
      Serial.println(F("\t\t\t\t\t\t ********************************************************************************************************************"));
      Serial.println();
      Serial.println();
      //                                        ******************
      //                                        ***  TOP MENU  ***
      //                                        ******************

      Serial.print(F("\t\t\t CLOCKGEN \t\t\t\t BANDGAP \t\t\t GPIO "));
      Serial.println();
      Serial.print(F("\t\t\t   (1) CLK_FREQ_P \t\t\t   (8) BG_2p5V \t\t\t   (13) GPIO0_PD \t (21) GP1_N_Buff \t (29) GP2_Buff_Max \t  "));
      Serial.println();
      Serial.print(F("\t\t\t   (2) CLK_FREQ_Div_4 \t\t\t   (9) BG_MAX_LOAD \t\t   (14) GPIO0_PU \t (22) GP1_W_Buff \t (30) GP2_Buff_Min "));
      Serial.println();
      Serial.print(F("\t\t\t   (3) CLK_FREQ_Div_8 \t\t\t   (10) BG_VBE \t\t\t   (15) GP0_N_Buff \t (23) GP1_Buff_Max \t (31) GPIO3_PD ") );
      Serial.println();
      Serial.print(F("\t\t\t   (4) CLK_FREQ_Div_16 \t\t\t   (11) BG_VP \t\t\t   (16) GP0_W_Buff \t (24) GP1_Buff_Min \t (32) GPIO3_PU "));
      Serial.println();
      Serial.print(F("\t\t\t   (5) CLK_FREQ_Div_32 \t\t\t   (12) BG_VGATE \t\t   (17) GP0_Buff_Max \t (25) GPIO2_PD \t\t (33) GP3_N_BUFF "));
      Serial.println();
      Serial.print(F("\t\t\t   (6) CLK_INT_Supply_(IBias)\t\t\t\t\t\t   (18) GP0_Buff_Min \t (26) GPIO2_PU \t\t (34) GPIO3_W_BUFF "));
      Serial.println();
      Serial.print(F("\t\t\t   (7) CLK_OK \t\t\t\t\t\t\t\t   (19) GPIO1_PD \t (27) GP2_N_Buff \t (35) GP3_BUFF_Max "));
      Serial.println();
      Serial.print(F("\t\t\t\t\t\t\t\t\t\t\t\t   (20) GPIO1_PU \t (28) GP2_W_Buff \t (36) GP3_BUFF_Min "));
      Serial.println();
      Serial.println();
      //                                        *********************
      //                                        ***  CENTER MENU  ***
      //                                        *********************

      Serial.print(F("\t\t\t VBUS COMPARITOR \t\t\t\t\t\t\t VAC COMPARITOR \t\t ISNS COMPARITOR \t\t TSNS COMPARITOR"));
      Serial.println();
      Serial.print(F("\t\t\t   (37) CLK_FREQ_P \t(47) BG_2p5V \t(57) GPIO0_PD \t\t\t   (61) GP1_N_Buff \t\t  (68) GP2_Buff_Max \t\t   (74) VB 2.715V Comparitor Test"));
      Serial.println();
      Serial.print(F("\t\t\t   (38) CLK_FREQ_P \t(48) BG_2p5V \t(58) GPIO0_PD \t\t\t   (62) GP1_N_Buff \t\t  (69) GP2_Buff_Max \t\t   (75) VB 2.715V Comparitor Test"));
      Serial.println();
      Serial.print(F("\t\t\t   (39) CLK_FREQ_P \t(49) BG_2p5V \t(59) GPIO0_PD \t\t\t   (63) GP1_N_Buff \t\t  (70) GP2_Buff_Max \t\t   (76) VB 2.715V Comparitor Test"));
      Serial.println();
      Serial.print(F("\t\t\t   (40) CLK_FREQ_P \t(50) BG_2p5V \t(60) GPIO0_PD \t\t\t   (64) GP1_N_Buff \t\t  (71) GP2_Buff_Max \t\t   (77) VB 2.715V Comparitor Test"));
      Serial.println();
      Serial.print(F("\t\t\t   (41) CLK_FREQ_P \t(51) BG_2p5V \t\t\t\t\t   (65) GPIO0_PD \t\t  (72) GP1_N_Buff \t\t\t\t"));
      Serial.println();
      Serial.print(F("\t\t\t   (42) CLK_FREQ_P \t(52) BG_2p5V \t\t\t\t\t   (66) GPIO0_PD \t\t  (73) GP1_N_Buff \t\t\t\t"));
      Serial.println();
      Serial.print(F("\t\t\t   (43) CLK_FREQ_P \t(53) BG_2p5V \t\t\t\t\t   (67) GPIO0_PD \t\t\t\t\t"));
      Serial.println();
      Serial.print(F("\t\t\t   (44) CLK_FREQ_P \t(54) BG_2p5V \t\t\t\t\t\t\t\t\t\t\t\t"));
      Serial.println();
      Serial.print(F("\t\t\t   (45) CLK_FREQ_P \t(55) BG_2p5V \t\t\t\t\t\t\t\t\t\t\t\t"));
      Serial.println();
      Serial.print(F("\t\t\t   (46) CLK_FREQ_P \t(56) BG_2p5V \t\t\t\t\t\t\t\t\t\t\t\t"));
      Serial.println();
      Serial.println();
      Serial.println();
      //                                        *********************
      //                                        ***  BOTTOM MENU  ***
      //                                        *********************

      Serial.print(F("\t\t\t QR COMPARITOR \t\t\t ADC \t\t\t MS Driver \t\t\t AC Driver \t\t\t Active Clamp FET \t\t  V10"));
      Serial.println();
      Serial.print(F("\t\t\t   (78) CLK_FREQ_P \t\t  (84) BG_2p5V \t\t  (87) GPIO0_PD \t\t  (96) GP1_N_Buff \t\t  (100) AC_FET_LEAKAGE \t\t   (1400) V10MIN_V10_OK_FAL"));
      Serial.println();
      Serial.print(F("\t\t\t   (79) CLK_FREQ_P \t\t  (85) BG_2p5V \t\t  (88) GPIO0_PD \t\t  (97) GP1_N_Buff \t\t  (101) AC_FET_LEAKAGE_SWEEP"));
      Serial.println();
      Serial.print(F("\t\t\t   (80) CLK_FREQ_P \t\t  (86) BG_2p5V \t\t  (89) GPIO0_PD \t\t  (98) GP1_N_Buff \t\t  (102) AC_FET_RDS_ON"));
      Serial.println();
      Serial.print(F("\t\t\t   (81) CLK_FREQ_P \t\t\t\t\t  (90) BG_2p5V \t\t\t  (99) GPIO0_PD"));
      Serial.println();
      Serial.print(F("\t\t\t   (82) CLK_FREQ_P \t\t\t\t\t  (91) BG_2p5V"));
      Serial.println();
      Serial.print(F("\t\t\t   (83) CLK_FREQ_P \t\t\t\t\t  (92) BG_2p5V"));
      Serial.println();
      Serial.print(F("\t\t\t\t\t\t\t\t\t\t  (93) CLK_FREQ_P"));
      Serial.println();
      Serial.print(F("\t\t\t\t\t\t\t\t\t\t  (94) CLK_FREQ_P"));
      Serial.println();
      Serial.print(F("\t\t\t\t\t\t\t\t\t\t  (95) CLK_FREQ_P"));
      Serial.println();
      Serial.println();
      Serial.println();
      Serial.println();
      Serial.println();
      Serial.println();

    }

    //*******************************************
    //**      Function: menuChoice
    //**      Passes: nothing
    //**      Returns: integer for menu choice
    //*******************************************

    int menuChoice()
    {
      int selection = 0;

      while (Serial.available() == 0);
      {
      selection = Serial.read();
      Serial.print("You entered: ");
      (int)Serial.println(selection, DEC);
      }
      return selection;
    }
    ```

body:
I think the issue is with the `menuChoice()` function. Try replacing it with this:
<!-- language-all: lang-cpp -->

    int menuChoice()
    {
      int selection = 0;
      const byte bufferSize = 16;
      char inputBuffer[bufferSize + 1];

      if(Serial.available() > 0){
        // 50 bytes more in compile size using parseInt() vs
        // char buffer and atoi().
        // selection = Serial.parseInt();
        Serial.readBytesUntil('\n', inputBuffer, bufferSize);
        selection = atoi(inputBuffer);
        memset(inputBuffer, 0, sizeof(inputBuffer));
        Serial.print("You entered: ");
        Serial.println(selection, DEC);
      }

      return selection;
    }

Of course, you could use `parseInt()` instead of the `char` buffer and `atoi()`, but the compile size is 50 bytes more.


message:
WiFi or Bluetooth to communicate between several Arduinos and a Raspberry Pi

So I want to set up a network of outdoor sensors (temperature and humidity) connected to an Arduino (and at some point a second or third Arduino further away with its own sensors). Then I'd like this Arduino to wirelessly transmit this data to a Raspberry Pi running some sort of server that can receive the data and then upload it to the cloud. I'm assuming WiFi is the best method to do this because of range and the number of devices at once? Would I just have to get each Arduino a WiFi module and what kind of range can I expect from this setup?

body: I would also suggest using WIFI (ESP8266) as you need to create a local network in which all devices will communicate to single host connected to the same network. If range will be issue you can use LORAWAN network for the same. LORAWAN provide high network range and if industrial gateway is used you can connect 10000 nodes(arduino in your case) communicating to the single server at a time.Else WIFI will the good.


message:
PT100 and MAX31865 readings showing wrong

I am using PT100 (3 Wire) to measure the temperature with Arduino Uno and MAX31865.
I have connected everything perfectly.
Configuration in the code i am using is :

    max1.begin(MAX31865_3WIRE);

And the output is:

**output**

    RTD value: 0
    Ratio = 0.00000000
    Resistance = 0.00000000
    Temperature = -242.02

I am testing it in a room temperature.

My question is , is there any settings or calibration that i need to do, or any other way to test the PT100 sensor, because the temperature is showing correct readings ?

body:
I nearly have the same problem. I use five of the MAX31865-Boards with 2-Wire Termocouples on an Arduino Nano. Two of the five boards are working perfectly. The other 3 boards show exactly the same wrong behaviour you described. My temperature readings are exactly like yours (-242.02).

But I think I found the reason for the not working ones: The two working boards I bought on Amazon. The other three not working boards I bought on AliExpress. Maybe I (and maybe you too) got really bad fakes from China and they are simply dead :(

*(BTW: If I remove one working board from the SPI bus and read out the temperature with the arduino, I get also the value of -242.02. This value seems to be an error value in the Adafruit MAX31865 library)*

**EDIT: Fixed it with a workaround!Like shown in the picture below, simply remove the wrong component (SMD Capacitor) and create a solder bridge . See comments for more informations!**

Here is a picture of my modification of one chinese board as requested by the comments:

[![Modification of the chinese MAX31865 driver board][1]][1]

(It's not the best solution, but it works. For final using you should get the right filter ferrite and solder it on the board!)

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