message:
Powering Arduino Pro Mini with different voltage, fuse setting

Arduino Pro Mini commonly comes in two packages, 5V 16MHz and 3.3V 8MHz.

 1. The only difference between those two boards are regulator and clock crystal, right?
 2. What happens if I supply 2V to VCC pin of 5V 16MHz board?
 3. What happens if I supply 2V to RAW pin of 5V 16MHz board?
 4. What happens if I supply 5V to VCC pin of 3.3V 8MHz board?
 5. What happens if I supply 5V to RAW pin of 3.3V 8MHz board?

I read from some websites stating that Arduino Pro Mini power consumption can be reduced by removing regulator.

 6. Does removing regulator cause VCC pin = RAW pin?

[Jean][1] created a custom board for Arduino Pro Mini rated at 1MHz 1.8V.

 7. Which pin should I supply voltage after changing fuse setting? (Jean changed the fuse setting but I am not sure where to connect the supply voltage of 1.8V)
 8. Related to question 7, is there a need to remove regulator to supply 1.8V?
 9. Can I supply higher voltage (3V) on board with 1.8V fuse setting?

Reason for question/ Confusion

I want to power Arduino Pro Mini using 3V coin cell. Battery voltage decreases after usage to around 2V. I am thinking of simply inserting 3V coin cell to Arduino with 1.8V setting. But regulator may hinder the operation. That is why I am confused. Sites I visited states the possibility of using lower voltage after changing fuse setting but did not mention where to connect and whether regulator need to be removed.

Furthermore, ATmega328p datasheet states the VCC range is 1.8V to 5.5V. If that is so, why not just plug those voltage to VCC pin of Arduino Pro Mini instead of specifically 5V or 3.3V. Question 1-5 should clear my confusion on this.

  [1]: https://www.iot-experiments.com/arduino-pro-mini-1mhz-in-arduino-ide/

body:
Read the datasheet once more. A certain voltage is needed for a certain clock frequency. There is a graph somewhere.

Since the Atmega328p is able to run up to 5.5V for VCC, that 5.5V is for every clock frequency.

Using 2V for VCC is not enough to run it at 16MHz. According to the datasheet even 3.3V is not enough. But 3.3V and 16MHz will work (it is outside the specifications though).

The RAW pin is the voltage before the voltage regulator, right ? Depending on the voltage regulator you can apply a large range of voltage.
See the [pinout][1].

When you remove the voltage regulator, the RAW pin is open. Sometimes I remove the voltage regulator and use 3 AA batteries and feed the 4.5V into the VCC (or 5V pin) of a 8MHz ATmega328p board.

1. Yes. The bootloader and sketch have to know the clock frequency. A sketch compiled for 8MHz is for a 8MHz Arduino board and a sketch compiled for 16MHz is for a 16MHz Arduino board.
2. 2V is too low. 3.3V should work.
3. 2V is too low. 3.3V depends on the voltage regulator.
4. No problem. The voltage regulator gets a reverse voltage.
5. No problem.
6. No. See the schematic.
7. To VCC.
8. Not a "must", but it is highly preferred to remove the voltage regulator, so no current is leaking towards the voltage regulator which gets a reverse voltage.
9. Yes. The fuses are to lower/disable the BOD, so a higher voltage is no problem.

This is the best tutorial about the power of the Atmega328p : [Nick Gammon about Power][2]

**ADDED**

I forgot to mention to remove the led as well.
This is a [Pro Mini with a coin cell][3].

Lowering the clock speed will make it run at lower voltages, but that will not always reduce the used energy. Doing a calculation at a slow speed takes more time than the same calculation at high speed (and going into sleep mode after that).

**ADDED 2**

When a low voltage is supplied (for example 2V to a 5V 16MHz Arduino board), the voltage regulator will not work. How much current/voltage is still passed on depends on the voltage regulator. With the BOD disabled, and the microcontroller runs below its required voltage, anything weird can happen. Parts of the chip will work and parts will not. That is why the BOD was invented in the first place (to reset the chip and avoid weird things to happen). I think it is very unlikely that the microcontroller will get damaged with a (too) low voltage.

  [1]: http://www.pighixxx.com/test/2016/07/pro-mini-pinout/
  [2]: https://www.gammon.com.au/power
  [3]: http://www.home-automation-community.com/arduino-low-power-how-to-run-atmega328p-for-a-year-on-coin-cell-battery/


sender: user

message:
Can I use the Arduino Uno's 3.3v pin while powered by a 9 volt battery?

I have an Arduino Uno. It has a 3.3v pin that I would like to use to power another module that requires 3.3v, and nothing more. If I power my Arduino Uno with a 9 volt battery, will this pin output 3.3v, or will it give more than that?

sender: assistant

body: The 3.3v is regulated and will always output 3.3v if the device is powered on.


message:
Writing a new function: configMotor(speed, direction)

How can I create a function that can control a DC motor's speed and direction?

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

    configMotor(int speed, direction){
       pwmVal = speed;

       //need help with code for picking direction
    }

    //move FORWARD
    void moveForward(){
      analogWrite(pwn, pwmVal);
      delay(sDelay);
      digitalWrite(ina, HIGH);
      digitalWrite(inb, LOW);
    }

    //move BACKWARD
    void moveBackward(){
      analogWrite(pwn, pwmVal);
      delay(sDelay);
      digitalWrite(ina, LOW);
      digitalWrite(inb, HIGH);
    }

I don't know what to write in the code for `configMotor` function so that it can choose going forward or backward.

body:
All you need to do is pass a parameter to config that says forward or backwards (was direction).
This parameter then sets the values of that the pins INA/B will be set to, because they are opposite.

Does that make sense?  If not add a comment with you question and I'll try and clarify.

    int inaDirection = LOW;
    int inbDirection = LOW;

    void configMotor( int speed, bool forwards = true)
    {
       pwmVal = speed;
       inaDirection = forwards?HIGH:LOW;   // ? and : are the same as an if statement, just more compact.
       inbDirection = forwards?LOW:HIGH;
    }

    // move no need for forward and reverse anymore
    void move()
    {
        analogWrite(pwn, pwmVal);
        delay(sDelay);
        digitalWrite(ina, inaDirection);
        digitalWrite(inb, inbDirection);
    }


message:
Arduino continuously reading ADC value using interrupt

I have a mono jack audio act as analog input for arduino UNO. The microphone outputs voltage that varies in terms of `amplitude` (volume) and `frequency`. In order to get the high sampling rate, I use prescaler 16 and set high baudrate for serial communication to print the value. I save the analog read from that jack audio to `buffer` array with maximum value is 256 (8-bit). This is my code (I modify from the Nick Gammon's blog about ADC [here][1]) :

    const byte adcPin = 0;  // A0

    const int MAX_RESULTS = 256;

    volatile int results [MAX_RESULTS];
    volatile int resultNumber;

    void setup ()
      {
      Serial.begin (230400);
      Serial.println ();

      // reset Timer 1
      TCCR1A = 0;
      TCCR1B = 0;
      TCNT1 = 0;
      TCCR1B = bit (CS11) | bit (WGM12);  // CTC, prescaler of 8
      TIMSK1 = bit (OCIE1B);
      OCR1A = 39;
      OCR1B = 39;   // 20 uS - sampling frequency 50 kHz

      ADCSRA =  bit (ADEN) | bit (ADIE) | bit (ADIF);   // turn ADC on, want interrupt on completion
      ADCSRA |= bit (ADPS2);  // Prescaler of 16
    //  ADCSRA |= (1 << ADPS1) | (1 << ADPS0);    // 8 prescaler for 153.8 KHz
      ADMUX = bit (REFS0) | (adcPin & 7);
      ADCSRB = bit (ADTS0) | bit (ADTS2);  // Timer/Counter1 Compare Match B
      ADCSRA |= bit (ADATE);   // turn on automatic triggering

    }

    // ADC complete ISR
    ISR (ADC_vect)
    {
        results[resultNumber++] = ADC;
        if(resultNumber == MAX_RESULTS)
        {
          ADCSRA = 0;  // turn off ADC
        }
    }

    EMPTY_INTERRUPT (TIMER1_COMPB_vect);

    void loop () {

      while (resultNumber < MAX_RESULTS)
        { }

      for (int i = 0; i < MAX_RESULTS; i++)
      {
        Serial.println (results [i]);
      }
    }

With that code, I got a nice result of sinusoidal graph represented audio value up to 4000 Hz like this :

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

But one thing that didn't work is if I change the volume or frequency (while displaying data) of analog input (jack audio), the graph I print and display via serial plot audio **won't change**. So I had to close it and open again to see the change. The question is how can I achieve the continuous and real time reading of this ? Thank you very much.

  [1]: http://gammon.com.au/adc
  [2]: https://i.stack.imgur.com/irwJY.png

body:
reset the `resultNumber` to 0 after you have written it to serial. and turn interrupts back on

    void loop () {

      while (resultNumber < MAX_RESULTS)
        { }

      for (int i = 0; i < MAX_RESULTS; i++)
      {
        Serial.println (results [i]);
      }
      resultNumber = 0;
      ADCSRA =  bit (ADEN) | bit (ADIE) | bit (ADIF)| bit (ADPS2) | bit (ADATE);
       // turn ADC back on
    }


message:
How do I set a continuous servo to turn on until a switch is flicked?

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

I am trying to get a servo to be activated by a momentary button. The arm on the servo will then swing around, which then activates a toggle switch. The activation of this toggle switch will then reverse the direction of the servo making the arm swing back. When the arm gets to the centre of the box, the other end of the arm will then turn the toggle switch the other way, which will then tell some Arduino code to turn the servo off.

Here is the schematic:

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

Here is my code:

    #include <Servo.h>
    Servo servo1;

    int button = 2; //Assigning pin 2 for the momentary button
    int buttonval = 0; //Creating a variable for the buttons value
    int green = 12;
    int red = 13; //Assigning the green and red LED to pin 12 and pin 13
    int red = 13;
    int Closed = 8; //Assigning the Inputs of the toggle switch to 8 and 7
    int Open = 7;
    int Closedval = 0; //Creating two blank variables for the states of the switch
    int Openval = 0;

    void setup() {
      servo1.attach(4); //Assigning the data pin for the servo
      servo1.write(1); // Giving a starting speed to the servo
      pinMode(button, INPUT); // Setting up the input pin for the momentary button
      digitalWrite(button, HIGH); //  turn on pull up resistors
      pinMode(Closed, INPUT); //Setting up the inputs for the two states of the toggle switch
      pinMode(Open, INPUT);
      pinMode(green, OUTPUT); //Changing the pin modes to OUTPUT for the two LEDS
      pinMode(red, OUTPUT);
      digitalWrite(Closed, HIGH);
      //Turning on pull up resistors for the two inputs from the toggle switch
      digitalWrite(Open, HIGH);
    }

    void loop() {
      Closedval = digitalRead(Closed); //Assign 'Closedval' to the value of Closed
      Openval = digitalRead(Open); //Assign 'Openval' to the value of Open

      if (Closedval == HIGH) {
        servo1.write(180);
        // If 'Closedval' is 'HIGH' then change the servo to 180 (make the servo go anticlockwise)
      }

      if (Openval == HIGH) {
        servo1.write(86);
        // If 'Openval' is 'HIGH' then change the servo to 86 (stop the servo)
      }

      digitalWrite(red, Closedval); // Change the value of the Red LED to Closedval
      digitalWrite(green, Openval); // Change the Value of the Green LED to Openval
    }

Any help would be appreciated.

  [1]: https://i.stack.imgur.com/9wbtL.jpg
  [2]: https://i.stack.imgur.com/JifOe.jpg
  [3]: https://i.stack.imgur.com/AJx1S.png

body:
Your are not debouncing your input buttons, which means that `digitalRead(Closed)` (and Open) will be HIGH in one execution of `loop` and in the next pass, 3 millis later, it will be LOW.

The servo probably need over 50ms to complete the action (you don't said what servo are you using).

You need to wait for the action to be completed before trying to move it in another direction.

You didn't post your schematic, so may be you wired things wrong. How can we know?

Usually the first step when you find a problem is add `Serial.print` to know what is working and what not, and then correct the problem.


message:
How do I call functions sequentially without using the Delay function?

I've been messing with the Adafruit Neopixel lib, and I'm trying to replace some of the delay functions with mills ( so that I don't block the serial port ). So far I have the following code;

    void loop() {
      currentMillis = millis();

      colorWipe(strip.Color(255, 0, 0), 50); // Red
      colorWipe(strip.Color(0, 255, 0), 50); // Green
      colorWipe(strip.Color(0, 0, 255), 50); // Blue
      colorWipe(strip.Color(0, 0, 0, 255), 50); // White RGBW
    }

    void colorWipe(uint32_t c, uint8_t wait) {
      if (currentMillis - previousMillis >= 200) {
        for(uint16_t i=0; i<strip.numPixels(); i++) {
          strip.setPixelColor(i, c);
          strip.show();
          //delay(wait);
          Serial.println("Light");
          previousMillis = currentMillis;
        }
       Serial.println("Done");
      }
    }

The issue I'm running into ( and I do understand this is fundamental concept in Arduino programming ) is how to run sequential functions, like the ones in loop, while still not blocking the main loop. The way this currently functions, it runs through the first colorWhipe loop and then just keeps iterating.

body:
I'm assuming you want to run each `colorWipe` for 200 ms, one after another.

You need a state machine to timing each `colorWipe`, like this:

    void loop()
    {
     static int state = 0;
     static unsigned long previousMillis = 0;
     unsigned long currentMillis = millis();

     if(currentMillis - previousMillis >= 200) {
      previousMillis = currentMillis;

      switch(state) {
      case 0 :
       colorWipe(strip.Color(255, 0, 0), 50); // Red
                state++;
       break;

      case 1 :
       colorWipe(strip.Color(0, 255, 0), 50); // Green
                state++;
       break;

      case 2 :
       colorWipe(strip.Color(0, 0, 255), 50); // Blue
                state++;
       break;

      case 3 :
       colorWipe(strip.Color(0, 0, 0, 255), 50); // White RGBW
       Serial.println("Done");
       state = 0;
      }
     }
    }

    void colorWipe(uint32_t c, uint8_t wait)
    {
     for(uint16_t i=0; i<strip.numPixels(); i++) {
      strip.setPixelColor(i, c);
      strip.show();
      //delay(wait);
      Serial.println("Light");
     }
    }

In each `loop` you will be waiting 200 ms before doing anything. When the times comes, you will enter the `if` with `state==0` and you will execute the first 'colorWipe'. After that, you *advance* the state by adding 1 to `state` variable.

Then you will be entering `loop` and doing nothing for another 200 ms. When that time pass, you will enter the `ìf` with state==1. Now the second `colorWipe` will be executed.

When the last colorWipe is executed, you set `state` to zero and begin again.


body:
Assuming the commented out delay in colorWipe should still happen then you need to nest the state machines:

    void loop()
    {
        static bool waiting=false;
        static int state = 0;
        static unsigned long previousMillis = 0;
        unsigned long currentMillis = millis();
        if(waiting){
            if(currentMillis - previousMillis >= 200){
                waiting = false;
            }
        }

        if(!waiting  && currentMillis - previousMillis >= 50) {
            previousMillis = currentMillis;

            switch(state) {
            case 0 :
                if(colorWipe(strip.Color(255, 0, 0))){ // Red
                    state++;
                    waiting = true;
                }
                break;

            case 1 :
                if(colorWipe(strip.Color(0, 255, 0))){ // Green
                    state++;
                    waiting = true;
                }
                break;

            case 2 :
                if(colorWipe(strip.Color(0, 0, 255))){ // Blue
                    state++;
                    waiting = true;
                }
                break;

            case 3 :
                if(colorWipe(strip.Color(0, 0, 0, 255))){ // White RGBW
                    state++;
                    state = 0;
                }
                break;
            }
        }
    }

    int wipeState = 0;
    bool colorWipe(uint32_t c)
    {

        strip.setPixelColor(wipeState , c);
        strip.show();

        Serial.println("Light");
        wipeState++;
        if(wipeState == strip.numPixels()){
            wipeState = 0;
            return true;
        }
        return false;
    }


body:
Here's an OOP solution. (It seems a lot of Arduino programmers shy away from C++ classes, but I use them all the time).

Since you don't want to block `loop()`, you need to create a function that will set the pixel (if time has expired) and return immediately. I would create a class to encapsulate the pixel strip.

The way this works is the class has a `loop()` function that needs to be called every time in the main program's `loop()` function. The class's `loop()` will either return (almost) immediately or it will update the pixel. Which will also be very quick. This allows you to do other things in the main `loop()`.

Disclaimer: I just whipped this up, there may be bugs.

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

    // A class to encapsulate the neo pixel strip.
    class color_strip {
        protected:
        Adafruit_NeoPixel pixels;
        uint32_t last_ms;
        uint32_t color;
        uint32_t duration = 0;
        int current_pixel;
        bool first_time;

        public:
        // Constructor
        color_strip(int num_pixels, int pin) {
            strip = Adafruit_NeoPixel(num_pixels, pin, NEO_GRB + NEO_KHZ800);
        }

        // Call this from setup()
        void setup() {
           strip.begin();
        }

        // Call this to start a wipe
        // param duration_ms is how long the entire wipe should take
        void wipe(RGB color, uint32_t duration_ms) {
            // Calculate how long to light each pixel
            duration = duration_ms / strip.numPixels()
            // Initialize this data for loop()
            last_ms = millis();
            first_time = true;
            this->color = strip.Color(color.red, color.green, color.blue);
            current_pixel = 0;
        }

        void loop() {
            // Is there something to do? Only if duration != 0
            if (0 != duration) {
                // Time to change pixel?
                uint32_t current_ms = millis();
                if (current_ms - last_ms >= duration || first_time) {
                    first_time = false;
                    // Finished the entire wipe?
                    if (current_pixel == strip.numPixels()) {
                        duration = 0;
                    }
                    else {
                        // Set the pixel
                        strip.setPixelColor(current_pixel++, color);
                        strip.show();
                        // Save
                        last_ms = ms;
                    }
                }
            }
        }

        // Returns true if doing a wipe, else false
        bool working() {return duration != 0;}
    };

Usage: you can create an array of colors. You then cycle through all these colors. If you want to add more colors, simply add to the array.

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

    // Helper struct to store rgb
    struct RGB {
        byte red, green, blue;
    };
    RGB all_colors[] = {
        {255, 0, 0},
        {0, 255, 0},
        {0, 0, 255},
        {0, 0, 0}
        // Add more colors here, if needed
    };
    // Need to keep track of the current color being displayed
    byte current_color = 0;
    const byte num_colors = sizeof(all_colors) / sizeof(all_colors[0]);

    // Here's the actual object
    // Change the parameters to whatever they need to be in your setup
    color_strip strip(number_of_pixels, pin_number);

    void setup()
        // Call the class setup function
        strip.setup();
    }

    void loop()
    {
        // If the strip has completed its wipe, set it to next color
        if (!strip.working()) {
            current_color = (current_color + 1) % num_colors;
            strip.wipe(all_colors[current_color], 1000);
        }
        // Call the class loop(). It will return quickly so won't block
        // the rest of the program
        strip.loop();

        // Do other stuff here...
    }


message:
Why is this IIR Filter unstable on the Arduino Due?

I am using an Accelerometer (on the MPU6050) and connected it to the **Arduino Due**. In order to filter the signal I am using an IIR Filter with the following transfer function:

H(z) = Y(z)/X(z) = B/A

B = 0.00000376 + 0.00001127*z^(-1) + 0.00001127*z^(-2) + 0.00000376*z^(-3)

A = 1 - 2.9372*z^(-1) + 2.8763*z^(-2) - 0.9391*z^(-3)

which is an IIR 3th Order Butterworth, Cutoff Freq: 0.5Hz, Samling Freq: 100Hz. These numbers can be calculated by any IIR calculator.

Thus, then discrete equation is:

y[n] = 0.00000376*x[n] + 0.00001127*x[n-1] + 0.00001127*x[n-2] + 0.00000376*x[n-3] + 2.9372*y[n-1] - 2.8763*y[n-2] + 0.9391*y[n-3]

I first tried it on the Arduino UNO. Then I found out that decimal point **precision** (float & double) on the UNO is **only 6-7 digits**. But the therm "B" in the transfer function has for example (0.00000376) **9 digits**. I thought this is the porblem, so I switched to Arduino Due and now I am using double (instead of float) which should have **enough precision**.

It is still unstable. It is not oscillating but getting bigger. I also tried an IIR 4th Order Butterworth, Cutoff Freq: 1Hz, Samling Freq: 100Hz. This one is oscillating.

However, the only IIR that seems to be stable is an IIR 3th Order Butterworth, Cutoff Freq: 1Hz, Samling Freq: 100Hz.

I have no idea so far what the problem is. Could anyone help please?

body:
1. The precision of a float is about 7 **significant** digits. The
   constant term of B in your transfer function (0.00000376) has only 3
   significant digits.
2. Your transfer function has a pole at _z_ = 1. It is thus not really
   stable, but only _marginally_ stable. Any parasite DC component in
   the input will make the output drift without bounds.

It seems to me that your problem is not related to the implementation of
the filter on the Arduino, but rather to the filter design. Where did
you get that transfer function from?

**Edit**: I looked at the filter you are trying to make. It turns out it
is very sensitive to the precision of the coefficients of A(z). If you
try to add these coefficients, they _almost_ cancel out: their sum is
about 3e-5. At zero frequency, both A and B are 3e-5, and the transfer
function, which is their ratio, is 1. By rounding the coefficients to
four decimal places, you made the cancellation exact, and the transfer
function infinite.

Just write the transfer function with more decimal places in the
coefficients and it should work:

H(z) = 3.75592×10−6 (1 + 3 z−1 + 3 z−2 + z−3)
         ÷ (1 − 2.9371759 z−1 + 2.8763097 z−2 − 0.9391038 z−3)


message:
How to connect an Arduino and a WAMP server's MySQL database?

I'm trying to connect an Arduino Mega to my WAMP server's database using MySQL connector for attendance logging. But it shows "Connection failed".

What is my WAMP server's IP address?

I connect my laptop and Arduino with a router so:

- My laptop is 192.168.1.2
- My Arduino is 192.168.1.3

I think this is correct.

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

    /*
      MySQL Connector/Arduino Example: basic insert
      This example demonstrates how to issue an INSERT query to store data in a
      table. For this, we will create a special database and table for testing.
      The following are the SQL commands you will need to run in order to setup
      your database for running this sketch.

      CREATE DATABASE test_arduino;
      CREATE TABLE test_arduino.hello_arduino (
        num integer primary key auto_increment,
        message char(40),
        recorded timestamp
      );

      Here we see one database and a table with three fields; a primary key that
      is an auto_increment, a string, and a timestamp. This will demonstrate how
      to save a date and time of when the row was inserted, which can help you
      determine when data was recorded or updated.

      INSTRUCTIONS FOR USE

      1) Create the database and table as shown above.
      2) Change the address of the server to the IP address of the MySQL server
      3) Change the user and password to a valid MySQL user and password
      4) Connect a USB cable to your Arduino
      5) Select the correct board and port
      6) Compile and upload the sketch to your Arduino
      7) Once uploaded, open Serial Monitor (use 115200 speed) and observe
      8) After the sketch has run for some time, open a mysql client and issue
         the command: "SELECT * FROM test_arduino.hello_arduino" to see the data
         recorded. Note the field values and how the database handles both the
         auto_increment and timestamp fields for us. You can clear the data with
         "DELETE FROM test_arduino.hello_arduino".

      Note: The MAC address can be anything so long as it is unique on your network.

      Created by: Dr. Charles A. Bell
    */

    #include <Ethernet.h>
    #include <MySQL_Connection.h>
    #include <MySQL_Cursor.h>

    byte mac_addr[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };

    IPAddress server_addr(192, 168, 1, 3); // IP of the MySQL *server* here
    char user[] = "root"; // MySQL user login username
    char password[] = ""; // MySQL user login password

    // Sample query
    char INSERT_SQL[] = "INSERT INTO test_arduino.hello_arduino (message) VALUES ('Hello, Arduino!')";

    EthernetClient client;
    MySQL_Connection conn((Client *)&client);

    void setup() {
      Serial.begin(115200);
      while (!Serial); // wait for serial port to connect
      Ethernet.begin(mac_addr);
      Serial.println("Connecting...");
      if (conn.connect(server_addr, 3306, user, password)) {
        Serial.println("Connected Successfully...");
        delay(1000);
      } else
        Serial.println("Connection failed.");
    }

    void loop() {
      delay(2000);
      Serial.println("Recording data.");
      // Initiate the query class instance
      MySQL_Cursor *cur_mem = new MySQL_Cursor(&conn);
      // Execute the query
      cur_mem->execute(INSERT_SQL);
      // Note: since there are no results, we do not need to read any data
      // Deleting the cursor also frees up memory used
      delete cur_mem;
    }

body:
As gre_gor pointed out, it looks like your connecting to the wrong ip.

Change:

    IPAddress server_addr(192, 168, 1, 3); // IP of the MySQL *server* here

To:

    IPAddress server_addr(192, 168, 1, 2); // IP of the MySQL *server* here


message:
Physical safety: Prevent linear actuator from crushing my fingers

Our project consists of an old wooden barrel, whose top lid is opened/closed with a simple linear actuator. I am a bit afraid that it might crush somebody's fingers while closing.

How could I detect trapped objects effectively?

Elevators often have light barriers, but the problem here is that the opening has a 360° border.
Force sensitive resistors seem to be an option too. However, since the border is a circle, I guess applying them would not work too well (folding issues) and look bad on a vintage barrel.

*I'm very sorry if I maybe created a duplicate here and I would like to encourage me to provide links to similar questions. I simply couldn't come up with useful search words for my problem.*

body:
The easiest way to prevent things becoming trapped is to take reasonable steps to prevent things getting near the "danger zone", so a barrier 2 metres around the barrel would be a good start.  Probably it would be an impractical idea, but...

A physical barrier of some sort would be the best idea, because that is less likely to suffer a failure than an electronic system (well assuming it has been designed right).  If you are using an electronic system then it needs to "fail-safe", when it suffers a failure it must adopt its safe state (barrel open).

You could surround the lid with IR lights and receivers in the lip.  They would need to be spaced at a distance where an arm/finger couldn't get between the lid and lip without breaking a beam.  This solution would only work over the last few inches, because of the angle of the beams.  If all receivers had a signal the it would be safe to close.  The problem is the receivers would need to be close together to prevent transgression.

Monitoring the current drawn by the actuator and the position of the actuator might be another.  I am assuming that there is an increase in current draw when the lid actually closes, and a similar increase in draw when something is trapped.  If the lid isn't fully closed when the current increases then something is trapped.

The final way I can think of is probably the most effective.  As the barrel closes don't close it the last few inches, allow it to 'fall' as the actuator descends.  This means if there is an object in there the actuator isn't pulling the lid down and the object will hold the lid against gravity.  This would be done by having a channel in the mounting block for the actuator 'pin'/ connection point to slide up and down.

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

OK Its not an electrical solution.

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


message:
What is Clock pin and Data pin, Orientation in Grove LED bar

I'm trying to use Grove LED Bar with Arduino

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

> Grove – LED Bar is comprised of a 10 segment LED gauge bar and an
> MY9221 LED controlling chip. It can be used as an indicator for
> remaining battery life, voltage, water level, music volume or other
> values that require a gradient display. There are 10 LED bars in the
> LED bar graph: one red, one yellow, one light green, and seven green
> bars. Demo code is available to get you up and running quickly. It
> lights up the LEDs sequentially from red to green, so the entire bar
> graph is lit up in the end.

In the github example there are `Clock pin`, `Data pin` and `Orientation`.

    // Arduino Clock pin, Data pin, Orientation
    // Grove_LED_Bar bar(7, 6, 0);

https://github.com/Seeed-Studio/Grove_LED_Bar/blob/master/LP examples/BasicControl/BasicControl.ino

But I have no idea what are they. Where can I find the documentation for them?

  [1]: https://i.stack.imgur.com/yXUPw.gif

body:
on the LED circuit board there are a few connections, notably DI and DCKI.

The DI pin is the data pint and DCKI is the clock pin.

According to the [header][1] orientation is about which way the pins are oriented red-to-green or green-to-red. It affects at which end led 1 is.

[1]: https://github.com/Seeed-Studio/Grove_LED_Bar/blob/master/Grove_LED_Bar.h


body:
**How to connect Grove to your board**

You need a Grove Expansion Board which to attach the Grove modules. The Grove Expansion Board provides the processing power, and the modules offer the input sensors and output actuators of your system. There are many Grove Expansion Board for different platform already, they include Arduino UNO, Particle Phone, BeagleBone board etc.

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

**Features**

There are intotal 16 grove connectors on the Base Shield, here we use a table to show the details.

**Specification**

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

Apart from the rich grove connectors, on the board you can also see an RST button, a green LED to indicating power status, ICSP pin, a toggle switch and four row of pinouts. There is no need to explain the RST button and LED, but you really need to know below two features that is very important for your usage.

1.Power Compatible:

Every Grove connector has four wires, one of which is the VCC. However, not every micro-controller main board needs a supply voltage of 5V, some need 3.3V. That's why we add a power toggle switch to Base Shield v2 so that you can select the suitable voltage of the micro-controller main board you are using via this switch.

For example, if you are using Arduino UNO with Base Shield v2, please turn the switch to 5v position; while using Seeeduino Arch with Base Shield v2, please turn the switch to 3.3v.

2.Board Compatible:

The pinout of Base Shield V2 is the same as Arduino Uno R3, however Arduino Uno is not the board one that the Base Shield V2 is compatible with, here we listed the boards that we have confirmed that can be used with Base Shield V2.

    Arduino Uno

    Seeeduino V4.2

    Arduino Mega / Seeeduino Mega

    Seeduino LoraWan

    Arduino Leonardo / Seeeduino Lite

    Arduino 101

    Arduino Due

    Intel Edison

    Linkit One

  [1]: https://i.stack.imgur.com/R4UVX.jpg
  [2]: https://i.stack.imgur.com/bAh8k.png


message:
Visual Studio for Arduino - Deep Search Issue

Finally got some time to play with my Arduino. I downloaded the Arduino editor and wrote a quick sketch which worked fine.

I then downloaded the Visual Studio extension from  VisuaMicro. I configured it to point towards my Arduino directory, which in my case is : C:\Program Files\WindowsApps\ArduinoLLC.ArduinoIDE_1.8.10.0_x86__mdqgnx93n4wtt

I created a new Arduino project and copied the same sketch it. When I try to build it I get errors as below:

    Compiling debug version of 'Sketch1' for 'Arduino/Genuino Uno'
    Build Folder:
    file:///C:/Users/bbbsb/AppData/Local/Temp/VMBuilds/Sketch1/uno/Debug
    Additional Defines: VM_DEBUG;VM_DEBUG_ENABLE
    1;VM_DEBUG_BANDWIDTH_THROTTLE_MS 50;VM_DEBUGGER_TYPE_HARDWARESERIAL
    0;VM_DEBUGGER_TYPE_SOFTWARESERIAL 1;VM_DEBUGGER_TYPE_FASTSERIAL
    2;VM_DEBUGGER_TYPE_USB 3;VM_DEBUGGER_TYPE_TEENSY 4;VM_DEBUGGER_TYPE_UART
    5;VM_DEBUGGER_TYPE_USART 6;VM_DEBUGGER_TYPE_USBSERIAL
    7;VM_DEBUGGER_TYPE_TTYUART 8;VM_DEBUGGER_TYPE_NET_CONSOLE
    9;VM_DEBUGGER_TYPE_Uart 10;VM_DEBUGGER_TYPE_COSA
    11;VM_DEBUGGER_TYPE_CDCSerialClass 12;VM_DEBUGGER_TYPE_HARDWARESERIAL1
    13;VM_DEBUGGER_TYPE_HARDWARESERIAL2 14;VM_DEBUGGER_TYPE_HARDWARESERIAL3
    15;VM_DEBUGGER_TYPE_NET_UDP 16;VM_DEBUGGER_TYPE_USBAPI
    17;VM_DEBUGGER_TYPE_SERIALUSB 18;VM_DEBUGGER_TYPE
    VM_DEBUGGER_TYPE_HARDWARESERIAL;VM_DEBUG_BREAKPAUSE;
    Architecture Tools:
    file:///C:/Program Files/WindowsApps/
    ArduinoLLC.ArduinoIDE_1.8.10.0_x86__mdqgnx93n4wtt/hardware/tools/avr/bin/
    Api: 1.1706.25-9.061
    Sketch Book: file:///C:/Users/bbbsb/Documents/Arduino
    Sketch Include Paths
    Core Include Paths
    Include Path     file:///C:/Program Files/WindowsApps/ArduinoLLC.ArduinoIDE_1.8.10.0_x86__mdqgnx93n4wtt/hardware/arduino/avr/cores/arduino
    Include Path     file:///C:/Program Files/WindowsApps/ArduinoLLC.ArduinoIDE_1.8.10.0_x86__mdqgnx93n4wtt/hardware/arduino/avr/variants/standard
    Searching for libraries ...
    "C:\Program Files\WindowsApps\ArduinoLLC.ArduinoIDE_1.8.10.0_x86__mdqgnx93n4wtt\hardware\tools\avr\bin\avr-g++" -c -g -Os -w -std=gnu++11 -fpermissive -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics -flto -w -x c++ -E -CC -mmcu=atmega328p -DVM_DEBUG_BREAKPAUSE -
    DVM_DEBUGGER_TYPE=VM_DEBUGGER_TYPE_HARDWARESERIAL -
    DVM_DEBUGGER_TYPE_SERIALUSB=18 -DVM_DEBUGGER_TYPE_USBAPI=17 -
    DVM_DEBUGGER_TYPE_NET_UDP=16 -DVM_DEBUGGER_TYPE_HARDWARESERIAL3=15 -
    DVM_DEBUGGER_TYPE_HARDWARESERIAL2=14 -DVM_DEBUGGER_TYPE_HARDWARESERIAL1=13 -
    DVM_DEBUGGER_TYPE_CDCSerialClass=12 -DVM_DEBUGGER_TYPE_COSA=11  -
    DVM_DEBUGGER_TYPE_Uart=10 -DVM_DEBUGGER_TYPE_NET_CONSOLE=9 -
    DVM_DEBUGGER_TYPE_TTYUART=8 -DVM_DEBUGGER_TYPE_USBSERIAL=7 -
    DVM_DEBUGGER_TYPE_USART=6 -DVM_DEBUGGER_TYPE_UART=5 -
    DVM_DEBUGGER_TYPE_TEENSY=4 -DVM_DEBUGGER_TYPE_USB=3 -
    DVM_DEBUGGER_TYPE_FASTSERIAL=2 -DVM_DEBUGGER_TYPE_SOFTWARESERIAL=1 -
    DVM_DEBUGGER_TYPE_HARDWARESERIAL=0 -DVM_DEBUG_BANDWIDTH_THROTTLE_MS=50 -
    DVM_DEBUG_ENABLE=1 -DVM_DEBUG   -DF_CPU=16000000L -DARDUINO=10805  -
    DARDUINO_AVR_UNO -DARDUINO_ARCH_AVR -I"C:\Program Files\WindowsApps\ArduinoLLC.ArduinoIDE_1.8.10.0_x86__mdqgnx93n4wtt\hardware\arduino\avr\cores\arduino" -I"C:\Program Files\WindowsApps\ArduinoLLC.ArduinoIDE_1.8.10.0_x86__mdqgnx93n4wtt\hardware\arduino\avr\variants\standard" "C:\Users\bbbsb\AppData\Local\Temp\VMBuilds\Sketch1\uno\Debug\Sketch1.cpp" -o "nul"
    Access is denied
 Preprocess: "C:\Program Files\WindowsApps\ArduinoLLC.ArduinoIDE_1.8.10.0_x86__mdqgnx93n4wtt\hardware\tools\avr\bin\avr-g++" -c -g -Os -w -std=gnu++11 -fpermissive -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics -flto -w -x c++ -E -CC -mmcu=atmega328p -DVM_DEBUG_BREAKPAUSE -
    DVM_DEBUGGER_TYPE=VM_DEBUGGER_TYPE_HARDWARESERIAL -
    DVM_DEBUGGER_TYPE_SERIALUSB=18 -DVM_DEBUGGER_TYPE_USBAPI=17 -
    DVM_DEBUGGER_TYPE_NET_UDP=16 -DVM_DEBUGGER_TYPE_HARDWARESERIAL3=15 -
    DVM_DEBUGGER_TYPE_HARDWARESERIAL2=14 -DVM_DEBUGGER_TYPE_HARDWARESERIAL1=13 -
    DVM_DEBUGGER_TYPE_CDCSerialClass=12 -DVM_DEBUGGER_TYPE_COSA=11 -
    DVM_DEBUGGER_TYPE_Uart=10 -DVM_DEBUGGER_TYPE_NET_CONSOLE=9 -
    DVM_DEBUGGER_TYPE_TTYUART=8 -DVM_DEBUGGER_TYPE_USBSERIAL=7 -
    DVM_DEBUGGER_TYPE_USART=6 -DVM_DEBUGGER_TYPE_UART=5 -
    DVM_DEBUGGER_TYPE_TEENSY=4 -DVM_DEBUGGER_TYPE_USB=3 -
    DVM_DEBUGGER_TYPE_FASTSERIAL=2 -DVM_DEBUGGER_TYPE_SOFTWARESERIAL=1 -
    DVM_DEBUGGER_TYPE_HARDWARESERIAL=0 -DVM_DEBUG_BANDWIDTH_THROTTLE_MS=50 -
    DVM_DEBUG_ENABLE=1 -DVM_DEBUG   -DF_CPU=16000000L -DARDUINO=10805 -
    DARDUINO_AVR_UNO -DARDUINO_ARCH_AVR -I"C:\ProgramFiles\WindowsApps\ArduinoLLC.ArduinoIDE_1.8.10.0_x86__mdqgnx93n4wtt\hardware\arduino\avr\cores\arduino" -I"C:\Program Files\WindowsApps\ArduinoLLC.ArduinoIDE_1.8.10.0_x86__mdqgnx93n4wtt\hardware\arduino\avr\variants\standard" "C:\Users\bbbsb\AppData\Local\Temp\VMBuilds\Sketch1\uno\Debug\Sketch1.cpp" -o "nul"
    Object reference not set to an instance of an object

 An error was encountered during the 'Deep Search' library discovery process.
Debug build failed for project 'Sketch1'

I've obviously not setup something correctly but cnnot work out what?
Any ideas?

body: If I remember well, you have to "import" the libraries for your project from within Visual Micro.


body: I had the same problem and just tried it as per1234 suggested: installed the full windows version (not the windows app version), configured the VS extension accordingly and now it builds (same code).


message:
Wiring light sensor OPB704WZ to Arduino Due

I would like to create a tachometer with the light sensor OPB704WZ.

I followed this schema [https://tonyrobotdt081.wordpress.com/2014/04/10/report-on-the-light-sensor-opb704wz/][2] on a bread board (for now), and tried to measure the voltage difference on the signal pin (green on the schema).

[![Light sensor][1]][1]

Problem is, I don't see a clear difference between a white surface and a black one; It does change if I put the sensor closer or further away, but that's about all I can see.

Is there something else I need to add to my wiring to make the difference between high and low depending on the luminosity more obvious? I know others have been able to use this sensor for the same purpose.

  [1]: https://i.stack.imgur.com/2YlmM.png
  [2]: https://tonyrobotdt081.wordpress.com/2014/04/10/report-on-the-light-sensor-opb704wz/

body:
You expect that the white surface to reflect the infrared light and the black surface does not.

Your theory is correct; white surfaces should reflect pretty much all light and the black surface should absorb all light.

The problem is that the black surface is reflecting enough light to turn the photo-transistor on.

The theory is correct but in the real world this is not perfect. For example a white surface is not completely white. Likewise no black surface is completely black.

We also know that a mirror is much better at reflecting light than a white surface. The black surface could be shiny. I am looking at my shiny black monitor stand, and even though it is black I can still see the reflection of the window.

I suggest trying with a number of black surfaces (such as paint, card, cloth) and finding the one that works best. I would imagine that chalk board paint would work well at absorbing and diffusing the infrared light. Also experiment with the distance away from the surface. You may have to move it further away from the surface.

If I am imagining your tachometer right, your sensor will see a reflective surface and then it will see empty space (and then repeat). This should work fine. Give it a try.


message:
Multitasking for music light sculpture

First of all, I'm new so please don't think this is dumb. I am creating a light culture with RGB LEDs that should play to programmed music. I have uploaded the following code to a spark fun redbird for now, but will later put it on a arduino mega. My circuit is working fine mostly except for the fact that the lights and music play separately and not next to each other. Note: this is just trial code, I will put my own music and light sequencing in later.

    const int buzzerPin = 6;    // connect the buzzer to pin 6
    const int RED_PIN = 11;
    const int GREEN_PIN = 12;
    const int BLUE_PIN = 13;
    const int RED_PIN2 = 8;
    const int GREEN_PIN2 = 9;
    const int BLUE_PIN2 = 10;
    const int songLength = 18;  // sets the number of notes of the song

    const int DISPLAY_TIME = 100;
    // Notes is an array of text characters corresponding to the notes
    // in your song. A space represents a rest (no tone)

    char notes[songLength] = {
      'c', 'd', 'f', 'd', 'a', ' ', 'a', 'g', ' ', 'c', 'd', 'f', 'd', 'g', ' ', 'g', 'f', ' '};

    // beats[] is an array of values for each note. A "1" represents a quarter-note,
    // "2" a half-note, and "4" a quarter-note.
    // Don't forget that the rests (spaces) need a length as well.

    int beats[songLength] = {
      1, 1, 1, 1, 1, 1, 4, 4, 2, 1, 1, 1, 1, 1, 1, 4, 4, 2};

    int tempo = 113;  // The tempo is how fast to play the song (beats per second).

    void setup()
    {
      pinMode(buzzerPin, OUTPUT);  // sets the  buzzer pin as an OUTPUT
       pinMode(RED_PIN, OUTPUT);
      pinMode(GREEN_PIN, OUTPUT);
      pinMode(BLUE_PIN, OUTPUT);
       pinMode(RED_PIN2, OUTPUT);
      pinMode(GREEN_PIN2, OUTPUT);
      pinMode(BLUE_PIN2, OUTPUT);
    }

    void loop()
    {
      mainColors();        // Red, Green, Blue, Yellow, Cyan, Purple, White
      int i, duration; //

      for (i = 0; i < songLength; i++) // for loop is used to index through the arrays
      {
        duration = beats[i] * tempo;  // length of note/rest in ms

        if (notes[i] == ' ')          // is this a rest?
          delay(duration);            // then pause for a moment
        else                          // otherwise, play the note
        {
          tone(buzzerPin, frequency(notes[i]), duration);
          delay(duration);            // wait for tone to finish
        }
        delay(tempo/10);              // brief pause between notes
      }

      // We only want to play the song once, so we pause forever
      }
      // If you'd like your song to play over and over, remove the while(true)
      // statement above

    int frequency(char note)
    {
      int i;
      const int numNotes = 8;  // number of notes we're storing
      char names[numNotes] = {
        'c', 'd', 'e', 'f', 'g', 'a', 'b', 'C'    };
      int frequencies[numNotes] = {
        262, 294, 330, 349, 392, 440, 494, 523    };

      // Now we'll search through the letters in the array, and if
      // we find it, we'll return the frequency for that note.

      for (i = 0; i < numNotes; i++)  // Step through the notes
      {
        if (names[i] == note)         // Is this the one?
        {
          return(frequencies[i]);     // Yes! Return the frequency and exit function.
        }
      }
      return(0);  // We looked through everything and didn't find it,
      // but we still need to return a value, so return 0.
    }

    void mainColors()
    {
      // Red
      digitalWrite(RED_PIN, HIGH);
      digitalWrite(GREEN_PIN, LOW);
      digitalWrite(BLUE_PIN, LOW);
       digitalWrite(RED_PIN2, HIGH);
      digitalWrite(GREEN_PIN2, HIGH);
      digitalWrite(BLUE_PIN2, HIGH);
      delay(DISPLAY_TIME);

      // Green
      digitalWrite(RED_PIN, LOW);
      digitalWrite(GREEN_PIN, HIGH);
      digitalWrite(BLUE_PIN, LOW);
        digitalWrite(RED_PIN2, HIGH);
      digitalWrite(GREEN_PIN2, LOW);
      digitalWrite(BLUE_PIN2, HIGH);
      delay(DISPLAY_TIME);

      // Blue
      digitalWrite(RED_PIN, LOW);
      digitalWrite(GREEN_PIN, LOW);
      digitalWrite(BLUE_PIN, HIGH);
       digitalWrite(RED_PIN2, LOW);
      digitalWrite(GREEN_PIN2, HIGH);
      digitalWrite(BLUE_PIN2, HIGH);
      delay(DISPLAY_TIME);

      // Yellow (Red and Green)
      digitalWrite(RED_PIN, HIGH);
      digitalWrite(GREEN_PIN, HIGH);
      digitalWrite(BLUE_PIN, LOW);
        digitalWrite(RED_PIN2, HIGH);
      digitalWrite(GREEN_PIN2, HIGH);
      digitalWrite(BLUE_PIN2, LOW);
      delay(DISPLAY_TIME);

      // Cyan (Green and Blue)
      digitalWrite(RED_PIN, LOW);
      digitalWrite(GREEN_PIN, HIGH);
      digitalWrite(BLUE_PIN, HIGH);
        digitalWrite(RED_PIN2, LOW);
      digitalWrite(GREEN_PIN2, LOW);
      digitalWrite(BLUE_PIN2, HIGH);
      delay(DISPLAY_TIME);

      // Purple (Red and Blue)
      digitalWrite(RED_PIN, HIGH);
      digitalWrite(GREEN_PIN, LOW);
      digitalWrite(BLUE_PIN, HIGH);
        digitalWrite(RED_PIN2, LOW);
      digitalWrite(GREEN_PIN2, HIGH);
      digitalWrite(BLUE_PIN2, LOW);
      delay(DISPLAY_TIME);

      // White (turn all the LEDs on)
      digitalWrite(RED_PIN, HIGH);
      digitalWrite(GREEN_PIN, HIGH);
      digitalWrite(BLUE_PIN, HIGH);
        digitalWrite(RED_PIN2, HIGH);
      digitalWrite(GREEN_PIN2, LOW);
      digitalWrite(BLUE_PIN2, LOW);
      delay(DISPLAY_TIME);
    }

body:
You need a *state machine*. It goes like this:

You divide your actions in states. Each state is a collection of actions that must performed in group (sequentially). In your case, you have one state for each note and for each ligth color and a duration.

Now, your score (music + light) is made of a sequence of states:

    > state 1: Play Fa, Light up RED - Duration 500ms.
    > state 2: Play Re, Light down RED - Duration 200ms. ...
    >
    > state n: Play Fa, Light up BLUE - Duration 250 ms.

You have many states; put them in an array and then loop across the array.

The code looks like this:

    typedef struct {
     int note;  // Musical note
     int color; // Led color
     int length; // Duration in ms
    } STATE;

    STATE score[] = {
     {0, 0, 0},
     {FA, BLUE, 500},
     [RE, RED, 400},
        ...
       {FA, GREEN, 400}
       };

    int state = 0;

    void loop()
    {
     static unsigned long stateStart = 0;

     if(state == sizeof(score) / sizeof(STATE)) {
      //  reset and start again
      state = 0;
      stateStart = 0;
     }

     if(millis() - stateStart >= score[state].time) {
      // Advance state and play next thing
      state++;
      playNote(score[state].note, duration);
      playColor(score[state].color);
      stateStart = millis();
     }

    }

    void playNote(int note, duration)
    {
     // Play a note.
    }

    void playColor(int color)
    {
     // Light up a color.
    }

Note: this is just the general idea. You must adapt and adjust things, like how you code note and colors. You better Google "Arduino state machine".

My code probably contains errors, but I gave you a starting point.

You have to implement playNote and playColor.


message:
I need help setting up my Arduino Uno with the port

I'm using a Windows computer, and if I recall correctly I installed the IDE using the installer, so I probably don't need to manually install the drivers. However, I can't figure out how to set up the serial port with the Arduino. For me under Tools, there's no "Serial Port" option but instead "Serial Monitor" and "Serial Plotter."

When I tried to upload my file, it failed. When I clicked Serial Plotter, it gave this error message:

    Arduino: 1.8.4 (Windows 8.1), Board: "Arduino/Genuino Uno"

    Sketch uses 940 bytes (2%) of program storage space. Maximum is 32256 bytes.
    Global variables use 9 bytes (0%) of dynamic memory, leaving 2039 bytes for
    local variables. Maximum is 2048 bytes.
    avrdude: ser_open(): can't open device "\\.\COM1":
    The system cannot find the file specified.

    Problem uploading to board.
    See http://www.arduino.cc/en/Guide/Troubleshooting#upload for suggestions.
    Board at COM1 is not available

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

How am I supposed to resolve this?

body: I figured it out by following the tutorial by Adafruit. I had to install it manually in order for it to work.


message:
Arduino Due custom platform for school and library installation

I have made a custom-development hardware for our school, where you can plug in an Arduino Due. It is mainly for driving all kind of motors and reading sensor signals. Therefore I added a custom SAM board into board.h based on a copy of the Arduino Due. Furthermore I need a global PWM frequency on all PWM Channels of 20 kHz. So I also changed the variants.h file.

(I have not found a solution that is setting all the underling Timer/Counters for PWM on the Due Pins 2, 3, 4, 5, 6, 7, 8, 13 to 20 kHz by user code, I think this is only possible with the variants.h file - because some timers can not be reset after they where set within the Arduino IDE once)

**The Question now:**
Today all students have to find and modify their variants.h file, which can be located almost anywhere! (Sometimes it is located in the support packages of Matlab...).

Is there an easy solution to give the students one .zip containing the Arduino IDE already with the custom Board included?
There is the Arduino IDE working without installation for download on the Arduino website. But how can I add my custom SAM board to it?

body:
1. Exit the Arduino IDE.
1. Create a folder in the Arduino IDE installation folder named `portable`. This will cause the Arduino IDE to run in [portable mode](https://www.arduino.cc/en/Guide/PortableIDE).
1. Start the Arduino IDE.
1. Tools > Board > Boards Manager
1. Wait for the download to finish.
1. Click on "Arduino SAM Boards".
1. Click "Install".
1. Wait for installation to finish.
1. Make your modifications to the Arduino SAM Boards hardware package installed at `{Arduino IDE installation folder}/portable/packages/arduino/hardware/sam`.
1. If necessary, configure **File > Preferences** to your liking.
1. Exit the Arduino IDE.
1. Zip the Arduino IDE installation folder.

When you run the Arduino IDE in portable mode it causes hardware packages installed via Boards Manager to be installed to the portable folder, rather than a folder outside the Arduino IDE installation folder. It also stores preferences.txt in the portable folder. This means you can supply a .zip file that contains a copy of the Arduino IDE with the customized Arduino SAM Boards package already installed.

By default it will also set the sketchbook folder to be there but that can be changed via **File > Preferences > Sketchbook location** if you like.


message:
floor( 1.0f ) bugged?

I just displayed the value for floor( 1.0f ) and surprisingly, it's 0.

Anyone knows about that? Is there a fix in libc expected any time soon?

I've been looking at libc::floor.s but it's a bit dodgy and 1) I don't want to break my other existing code and 2) don't have time for that so I'll add an epsilon at the moment (but that defeats the purpose of floor)...

Thanks for posting any fix or idea on how to bypass the issue.

body:
I ran this sketch:

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

    void loop() {
      Serial.println(floor(1.0f));
    }

It outputs "1.0"


message:
How does the microcontroller know which clock to use?

I had seen some tutorials on how to assemble an Arduino on a breadboard. They all just place the external crystal oscillator according to the circuit and then, just burn the bootloader and it starts working. According to my little knowledge the fuse bits have to be set before using the external clock.

My question is - How does the microcontroller know which clock to use internal or external? Is there any setting already in the bootloader that tells the microcontroller to use the external clock?

body: Burning the bootloader via the Arduino IDE also sets the fuse bits according to its configuration files.


message:
Can't upload arduino code on the board due to some programmer issues

As I connected my arduino-uno board and made sure of the "Board" selected, and the "Port" selected as well. There is a problem while uploading, I tried updating the arduino IDE, reinstalling all the arduino drivers, I tried to borrow a new arduino board from a friend and I am 100% sure it is working.

The message I get from the IDE:

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

    avrdude: Version 6.3, compiled on Jan 17 2017 at 12:00:53
             Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
             Copyright (c) 2007-2014 Joerg Wunsch

             System wide configuration file is "C:\Program Files (x86)\Arduino\hardware\tools\avr/etc/avrdude.conf"

             Using Port                    : COM5
             Using Programmer              : arduino
             Overriding Baud Rate          : 115200
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x1d
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 2 of 10: not in sync: resp=0x1d
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 3 of 10: not in sync: resp=0x1d
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 4 of 10: not in sync: resp=0x1d
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 5 of 10: not in sync: resp=0x1d
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 6 of 10: not in sync: resp=0x1d
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 7 of 10: not in sync: resp=0x1d
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 8 of 10: not in sync: resp=0x1d
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 9 of 10: not in sync: resp=0x1d
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 10 of 10: not in sync: resp=0x1d

    avrdude done.  Thank you.

    Problem uploading to board.  See http://www.arduino.cc/en/Guide/Troubleshooting#upload for suggestions.

Thanks in advance!

body:
Try changing baud rate to 9600.

Another thing to check is the chip your Uno has. My Uno has the atmega328. Make sure you select that board.


body:
I faced the same problem while uploading.

avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_recv(): programmer is not responding

To solve that I changed my port to another USB port and I selected the particular port, Its uploaded successfully. But it's in MacBook not in Windows.

Try this once, by changing the port.


message:
How to reset an arduino while being able to know which button has been pressed?

Context
-------

I keep the board in sleep mode and want to wake it with different buttons. I need to know which button has been pushed on boot.

In the following schematic, **SW-R** is actually used to reset the board.

If I hold **SW-D5** or **SW-D6** *while* pushing **SW-R**, the code can detect which button I pushed.

Problem
-------

I don't want to have to push 2 buttons at the same time and, *being new to electronic*, I don't know how to wires things up so it reset and set a pin to HIGH simultaneously.

Question
-------

How can I reset the board and trigger a HIGH on an IO corresponding to a button while it boot?

Considering the HIGH only need to be hold for less than a second, can it be simply achieved with capacitors and/or transistors? If so, how? Or any other suggestion?

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

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

<!-- End schematic -->

The actual code example only contain 1 button but I'll have many.

<!-- language-all: c -->

    #include <Spi.h>
    #include <Arduino.h>
    #include <ESP8266WiFi.h>

    int buttonPin = D5;

    void setup() {
      pinMode(buttonPin, INPUT);
      pinMode(BUILTIN_LED, OUTPUT);

      int buttonValueAtBoot = digitalRead(buttonPin);
      Serial.begin(115200);
      Serial.println();

      if (buttonValueAtBoot == HIGH) {
        // I want to trigger this code pushing only 1 button
        // should also work with many buttons
        Serial.println("button was pressed");
      }

      digitalWrite(BUILTIN_LED, HIGH);
    }

    void loop() {
      delay(5000);
      ESP.deepSleep(0);
    }

body:
Just found that I can change pins behavior. Inverting things a little bit, I can get my pins to work as LOW instead of as HIGH.

That way, I only need 1 button to trigger a reset and change pin status. Plus, grounding the reset is done temporarily because of the capacitor, which is what I need.

Here is the new schema

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

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

<!-- End schematic -->

New code
----

    #include <Spi.h>
    #include <Arduino.h>
    #include <ESP8266WiFi.h>

    int buttonPin = D5;

    void setup() {
      pinMode(buttonPin, INPUT_PULLUP);
      pinMode(BUILTIN_LED, OUTPUT);

      int buttonValueAtBoot = digitalRead(buttonPin);
      Serial.begin(115200);
      Serial.println();

      if (buttonValueAtBoot == LOW) {
        Serial.println("button was pressed");
        digitalWrite(BUILTIN_LED, HIGH);
      }

      // Avoid problem when the button is hold
      while (digitalRead(buttonPin) == LOW) {
        // wait before going to deepsleep
        // or the capacitor will be drained
        delay(1);
      }

      Serial.println("going to sleep");
      ESP.deepSleep(0);
    }

    void loop() {
    }


message:
What is a faster alternative to parseInt()?

I'm making an LED spectrum analyzer with an Arduino Due and my PC. The audio processing is done on the PC, and then sent to the Arduino. The exact data sent is a 'coordinate', or more specifically, a number representing a particular band, and another number representing the maximum amplitude of that band. There are 11 bands. Each coordinate has a x and a y value, separated by a comma, and then sent on a new line.

This is my code as of now:

    void loop() {
      if (Serial.available()) {
        xCoord = Serial.parseInt();
        yCoord = Serial.parseInt();
        if (xCoord != 0) {
          int r, g, b;
          for (int i = 0; i < 8; i++) {
            int fromCoordToIndex = ((xCoord - 1) * 8) + i;
            //
            //do some calculations for the color
            //
            strip.setPixelColor(fromCoordToIndex, strip.Color(r, g, b));
            strip.show();
          }
        }
      }
    }

The problem is `parseInt` seems to be very very slow (it's not the timeout issue, it's set to 1). From what I can see, it seems to be skipping some data, so every now and then a band gets missed out. The only way I can fix this is to insert a delay between each coordinate being sent. I found that 40 ms works ok, but remember there are 11 bands, so that means about half a second to refresh the whole board, which feels like a slide show...

I've tried inputting individual characters and then using `toInt`, I've tried `parseInt` obviously, I've tried native USB (it's a Due), and I've tried fiddling with baud rates. None seems to have had any effect.

body:
> Premature optimization is the root of all evil (or at least most of
> it) in programming. Donald Knuth.

I don't know how fast/slow parseInt() is. Neither do you. You have to time it first.

OK. Maybe it's really slow, but is it the slowest part of your code? Slow compared to what?

Is `parseInt` what you need? `parseInt` doesn't convert negative values and it can time-out (but still return zero ... Duh!).

If you read the whole line as a String and then parse the values, you avoid the time-out problem and you can also verify that the data is correct.

This sketch show how to process your data:

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

      String lines[] = {
        "1,1",
        "10,20",
        "11,1000",
      };
      int channel;
      int value;

      for (int i=0; i < 3; i++) {
        sscanf(lines[i].c_str(), "%d,%d", &channel, &value);
        Serial.print("channel="); Serial.print(channel);
        Serial.print(" value="); Serial.println(value);
      }
    }

    void loop() {
    }

Well, I'm using `sscanf`, that's slower than `parseInt` for sure, but it get the job done. I doubt you (or me) can do it better, and there more useful thing to do with our time.

Edit:

I profiled

    sscanf("0001,0001", "%d,%d", &channel, &value);

with an Arduino UNO and it took 147us to convert a single par of values.


body:
Instead of using parseint, send the data for the 11 bands in a very specific form to the Arduino so the Arduino can 'parse' it very easily.

Maybe instead of sending text, send 33 bytes for RGB (3) times 11 bands are the levels (0-255) of the consecutive channels. Than there is no conversion needed (except for reading the bytes).


body:
The annoying thing about `parseInt()` is not its speed, it's the fact
that it relies on a timeout. If the timeout is too long, it slows you
down. If it's too short, it may induce errors.

A safer way to parse the sort of messages you are using is to buffer all
the incoming characters until you find a carriage return, then parse the
whole line. For example:

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

    // Just echo the messages with a different separator.
    void parse(char *buffer)
    {
        char *s = strtok(buffer, ",");
        int x = atoi(s);
        s = strtok(NULL, ",");
        int y = atoi(s);
        Serial.print(x);
        Serial.print(':');
        Serial.println(y);
    }

    void loop()
    {
        static char buffer[BUFFER_SZ];
        static size_t lg = 0;
        while (Serial.available()) {
            char c = Serial.read();
            if (c == '\r') {        // carriage return
                buffer[lg] = '\0';  // terminate the string
                parse(buffer);
                lg = 0;             // get ready for next message
            }
            else if (lg < BUFFER_SZ - 1) {
                buffer[lg++] = c;
            }
        }
    }

Note that you should add some error checking when you call `strtok()`.


body:
Your data has 11 channels and a single value for each channel. The values will be presented in graphic format, so it fits in the range 0-255 without degrading the presentation. You always can scale your readings to your display's resolution.

You then send these 11 values in binary form. One byte per channel plus one byte to separate one data set from another. You don't need to send the channel number, just the values.

At the Arduino end you read 12 bytes and then loop thru it converting the bytes to ints.

    #define CHANNELS 11

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

      while(!Serial);
    }

    void loop()
    {
      char packet[CHANNELS + 1];
      int values[CHANNELS];

      // Read 12 bytes (11 bytes of data + 1 byte delimiter)
      int nBytes = Serial.readBytes(packet, sizeof(CHANNELS + 1));

      if(nBytes == CHANNELS + 1) {
        // Convert bytes to ints;
        for(int i=0; i<CHANNELS; i++) {
          values[i] = packet[i];
        }
      } else {
         // Error.
         }

      // Here you display your graph.
    }

This code doesn't have any error-detection. For that you can add an extra byte with the checksum of the whole dataset.


body:
I seem to have fixed it by lowering the baud rate from 115200 to 9600. [This][1] answer inspired the change. Apparently, the higher the baud the faster the information is sent, but the higher the likelihood of an error, and the lower the baud rate, the slower it is sent, but the more reliable it is.

  [1]: https://arduino.stackexchange.com/questions/296/how-high-of-a-baud-rate-can-i-go-without-errors


body:
```cpp
#include <SoftwareSerial>
SoftwareSerial s1(5,6);

void setup {
s1.begin(9600);
s1.setTimeout(50); //sets the timeout of parseint() to 50ms

}
```

Please note that lowering the timeout too much can cause errors, i would not go below 10.


message:
Space needed for local String variable

I tried to run this code on my Arduino Uno clone (which has no function so far and is a shortend version of my programm):

    String rules [16][5] ={
       {"B0 B5", "", "", "cs S0", "", },
       [...]
    };

    void setup() {
      Serial.begin(9600);
      String foo = "bar";
      Serial.println(foo);
    }

    void loop() {
    }

I left the `rules` array out, but it is quite big. It isn't used yet, but it contains rules how to react on certain situations (which should be used later).

As the Arduino IDE gives the following after complilig:

    Sketch uses 4316 bytes (13%) of program storage space. Maximum is 32256 bytes.
    Global variables use 1174 bytes (57%) of dynamic memory, leaving 874 bytes for local variables. Maximum is 2048 bytes.

When I run this sketch there is nothing on the serial monitor. If it works, there should appear `bar`, but it does not. The Arduino sends only a linebreak over the serial, but no text.

When I remove some characters from that array so that there are about 900 bytes the script works and prints `bar` to the serial monitor.

So, aren't 874 bytes not enough to store a three-character string? Why does it need 900 bytes to store such a short string?

body:
You are requesting 80 String objects.

Each String object allocates memory to store its data. When you provide a string constant that string constant data's length is used for the allocated data size (including the NULL character at the end), and the string constant data copied in.

On top of that you have a bunch of other data that is needed for the String class to do its work. The total size of a String object is 6 bytes.

So the memory you need for your array of Strings can be calculated as:

* Let C be the total number of characters in all the string constants
* Let N be the number of String objects in the array
* Let T be the total number of bytes.

    T = N * 6 + C + N

With no string constant data that would be:

    T = 80 * 6 + 80

That's 560 bytes already, before you even start thinking about putting in the string constant data.

Also you may like to add to that the fact that the compiler *may* (though I am not certain on this) be also copying the string constants into RAM first because they aren't forced into PROGMEM with the F() macro.

So since you only have 2KiB of RAM to begin with, and a quarter of that is instantly gobbled up with your array, you can see how things might not be too happy.

Oh, and the String's internal storage is allocated at run time, not compile time, so the compiler can't know that it'll overflow - only when you run the program will it overflow and things go horribly wrong.

So you need to ask yourself "Why do I even want an array of String objects?" and the answer is most certainly: "Under no circumstances do you ever want an array of String objects". In fact I am a strong advocate of *never* using String objects ever, for any reason whatsoever.

If your data is constant there is absolutely no reason to store it as String objects. It's constant. It should remain constant. Copying it into a String object means it's no longer constant and wastes many many resources.


message:
Arduino Mega 2560 LED is dim when powered from digital output

My circuit is a simple one, I am using an arduino atmega 2560.
One 5mm red LED connected in series with a 150 ohm resistor.
If I didn't make some kind of goof, a red LED has a voltage drop of 2 volts and operates at 20 ma.
So my calculations were, 5-2=3volts.
3V/150=20 mA. So I put a 150 ohm resistor.
My code to control it is the following:

    int red = 48;

    void setup() {
    pinMode(OUTPUT,red);
    }

    void loop() {
    digitalWrite(red,HIGH);
    }

When I run the code the red LED is dimly lit, when connected to the 5V on the board it lights brightly.
When I measured the voltage between pin48 and ground I got 1.7 volts.
When connected directly to the 5V and GND the voltage between them is 4.95V.
Measuring a pin with nothing connected set at HIGH results in a 4.99V reading.
Is my board malfunctioning or have I missed something?

body: The `pinMode()` arguments are backwards. As it is the LED is powered through the input pullup resistor, which is about 20-50kohm.


message:
Arduino pro mini not compiling after changing fuse to 128khz

I used Arduino UNO as ISP to change the fuse setting of Arduino Pro Mini. Using avrdude cmd, I successfully changed it to 8MHz setting. Due to curiosity, I decided to try changing it to 128kHz. But that ends up me being unable to further program it. The Pro Mini still works but just cant change fuse through avrdude cmd, burn bootloader and upload. Does 128kHz really leave atmega328p like that?

On one computer, the below error appears.

    avrdude: stk500_recv(): programmer is not responding

On another computer, the below error appears

    avrdude: Expected signature for ATmega328P is 1E 95 0F
    Double check chip, or use -F to override this check
    Wrong microcontroller found. Did you select the right board from the Tools > Board menu?

There are actually more errors because I trial and error different ways to solve it, i.e Nick Rammon's Atmega_Board_Programmer, cmd command with varying parameters (baud rate, programmer), inserting capacitor on UNO. But I dont remember every one of them because the `not in sync:resp=0x..` differs from time to time

There is one method which I have not try, high voltage programming mode. I would try it out if it was detachable but atmega328p on Pro Mini is SMD. Is it possible to high voltage program on Pro Mini? Ultimately I am stuck.

Ignoring what I have done, I would once again like to try out every method you guys recommend. Hopefully everything can be step by step and the thing I want to know most is the setting of '`Board`', '`Processor`' and '`Programmer`' in Tools.

I would give my best response possible to you guys who is willing to help me out. Thank you

body: At that clock rate each programming clock cycle must be at least 3 system clock cycles, which means that the programmer either must use a *much* slower SPI rate, 42kHz or less, or it must provide an external pulse train to clock the device manually. Modify the ArduinoISP sketch to either use a slower clock or to provide an external clock to the target.


body:
Thanks to Ignacio, I found an answer. If anyone ever burn the fuse to 128kHz, got stuck there and wish to revert back to normal speed, download this [sketch][1]. Note that I am using Arduino UNO as ISP and Arduino Pro Mini as the target board

If you read the comment in the sketch carefully, you will see `How to proceed:`. The below is what I did.

 1. Remove any pin connection on Arduino UNO
 2. Plug Arduino UNO to PC
 3. Open the downloaded sketch and uncomment `#define LOW_SPEED`
 4. On Arduino IDE `Tools` menu, make sure settings are: `Board: Arduino/Genuino UNO`, `Programmer: AVRISP mkII` and upload the code
 5. After uploading, unplug Arduino UNO from PC
 6. Connect Pro Mini to UNO, making sure there is capacitor between reset and ground pin on UNO
 7. Plug Arduino UNO to PC
 8. Open CMD and type `avrdude -P com5 -b 19200 -c avrisp -p m328p -U lfuse:w:0xFF:m -U hfuse:w:0xDA:m -U efuse:w:0x05:m`. Change `com5` to your UNO com port. The fuse are [default][2] Pro Mini setting.
 9. You should see `avrdude: safemode: Fuses OK <E:05, H:DA, L:FF>`. Unplug UNO from PC
 10. Remove pin connection on Arduino UNO
 11. Plug Arduino UNO to PC
 12. Now comment `#define LOW_SPEED` and upload the code.
 13. After uploading, unplug Arduino UNO from PC
 14. Connect Pro Mini to UNO like before and plug to PC
 15. On Arduino IDE `Tools` menu, make sure settings are: `Board: Arduino Pro or Pro Mini`, `Atmega328 (5V, 16MHz)`,`Programmer: Arduino as ISP`
 16. Burn Bootloader and it is complete

Apologies for lengthy and repetitive steps. Many solutions skip many steps which leaves me in doubt. So I do not want that to happen to other people. Though I won't go into the details of setting up avrdude CMD in step 8.

  [1]: https://github.com/adafruit/ArduinoISP/blob/master/ArduinoISP.ino
  [2]: http://www.codingwithcody.com/2011/06/25/arduino-default-fuse-settings/


message:
How to keep a pin LOW for a small amount of time after pushing a button and while device is booting?

Context
------

I keep the board in deepsleep mode and want to wake it with different buttons. I need to know which button has been pushed on boot. The board is immediately put back in deepsleep mode afterward.

I've been able to reset the board and pull a pin LOW at the same time. (see circuit below). The reset pin is momentarily pulled low so it reset the board effectively.

I'm not an electronic engineer, just a hobbyist, so any other method to do something are always welcome.

Problem
------

With the actual code/circuit, I *need* to hold the button until the device boot up so it can detect button was pushed but **I would like to be able to just push the button quickly** instead of having to hold it.

Question
-----

How to add some sort of delay that will "hold" the **SW-D5** button until the board boot?

Or anything that keep my D5 pin LOW for a short amount of time after the button has been pushed?

I think something in the range of 500 to 1000 milliseconds would be enough.

My actual circuit
-----

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

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

<!-- End schematic -->

My code
----

<!-- language-all: c -->

    #include <Spi.h>
    #include <Arduino.h>
    #include <ESP8266WiFi.h>

    int buttonPin = D5;

    void setup() {
      // Read pin value as soon as possible after boot
      pinMode(buttonPin, INPUT_PULLUP);
      int buttonValueAtBoot = digitalRead(buttonPin);

      pinMode(BUILTIN_LED, OUTPUT);
      Serial.begin(115200);
      Serial.println();

      if (buttonValueAtBoot == LOW) {
        Serial.println("D5 was pressed");

        // Do something useful here like making an HTTP request.
        digitalWrite(BUILTIN_LED, LOW);
      }

      // Avoid problem when the button is being hold
      while (digitalRead(buttonPin) == LOW) {
        // wait before going to deepsleep
        // or the capacitor will be drained
        delay(1);
      }

      Serial.println("going to sleep");
      ESP.deepSleep(0);
    }

    void loop() {
    }

body:
A simple RC network should do the job.

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

Ok. A quick explanation of what we have here.  C1 and R1 are the same as you have at the moment for your reset circuit. R1 is the existing pullup resistor in the Wemos. R3 recharges the C1 when the button is released. It's effectively the pullup for the button.

D2 is to separate the two parts of the circuit. It prevents R3 from charging the capacitor C2.

The magic happens with C2 and R2. Pressing SW1 discharges C2, and the GPIO goes low.  When you release SW1 C2 charges up again through R2.  When the voltage across C2 rises to the VIH of the GPIO the GPIO will go high.

D1 is to protect the GPIO from the negative pulse you can get from C2 as it discharges.

Here's a simulation. Top line is the GPIO, bottom is RESET.

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

VIH for the ESP8266 is 0.75VIO, so 75% of 3.3V, or 2.475V.

The charge time of the capacitor C2 is calculated as T=RC, where T is the time taken to charge up to 63% of the supply voltage (2.08V)

With the shown values the time taken to rise to 63% of 3.3V will be 10,000 x 0.0001 seconds, or 1 second.  So to get to 75% it will take a little longer than 1 second.  75% is about 1.4T, so if T is 1 as in the above equation then it will take 1.4 seconds (1 * 1.4) to rise enough for the GPIO to register as HIGH.

Note these times are all from the moment you *release* the button. Reset has already happened before that time.

Also the internal pullup of the GPIO should be **disabled** otherwise it will also charge the capacitor and the charge time will be reduced. Since you don't know that resistor value it then becomes impossible to calculate what the charge time will be. Simplest to just disable it and only use the external resistor R2.

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


message:
Limit to number of sensors attached to Arduino

Is there any limitation on how many sensors can be attached to one Arduino board? I am making elderly smart ban and I want to use GPS, GSM, gyroscope, pulse sensor, temperature sensor and I2C OLED. Right now I have only gyroscope, pulse sensor and GPS connected to Arduino Uno but I would like to add more stuff and also I am considering using Arduino Nano or only ATmega328P chip for finished product. My main concern is power.

body:
There is no answer that can be given to you that is "correct". However, there are things for you to consider in your design process:

1. Can you fit all the code in flash, and the required variables in RAM?
2. Does the chip have all the IO you need, and can you use the required internal / interfacing peripherals in the right combinations to satisfy your requirements
3. Do the devices fit within your power budget (battery capacity, required run-time, power regulation efficiency).

The Arduino is just a component. It belongs in a circuit, and that circuit is what determines everything else. The ATMega328P has certain power requirements, as do all the other components in your circuit. It is up to you to design the right power system to provide that power with the right efficiency and power saving options (switching off circuit segments when not needed to save power), etc.

For prototyping and experimenting the Arduino provides a rudimentary power supply which is wildly inefficient. Not recommended for any battery powered scenario or any high current usage.


message:
Error declaring two-dimensional array: 'x' was not declared in this scope

I'm trying to declare a 2-D array where each letter in the alphabet is keyed to a corresponding LED in my LED strip. But when I try to declare the array, Arduino flags the values and gives me a "not declared in this scope" error. I have no idea why. Am I missing a library or is it incorrect syntax?

Some of the places I've looked say to make sure it's declared globally. I've declared the array before void setup but it still doesn't work. Here's what I've got before void setup:

    #include <Adafruit_NeoPixel.h>

    #ifdef __AVR__
      #include <avr/power.h>
    #endif

    #define PIN 6

    // Parameter 1 = number of pixels in strip
    // Parameter 2 = Arduino pin number (most are valid)
    // Parameter 3 = pixel type flags, add together as needed:
    //   NEO_KHZ800  800 KHz bitstream (most NeoPixel products w/WS2812 LEDs)
    //   NEO_KHZ400  400 KHz (classic 'v1' (not v2) FLORA pixels, WS2811 drivers)
    //   NEO_GRB     Pixels are wired for GRB bitstream (most NeoPixel products)
    //   NEO_RGB     Pixels are wired for RGB bitstream (v1 FLORA pixels, not v2)
    //   NEO_RGBW    Pixels are wired for RGBW bitstream (NeoPixel RGBW products)
    Adafruit_NeoPixel strip = Adafruit_NeoPixel(50, PIN, NEO_GRB + NEO_KHZ800);

    //Create a 2-D array to store each letter and
    //its corresponding LED number
    char charKey[26][2]={
      {a, 0},
      {b, 2},
      {c, 4},
      {d, 6},
      {e, 8},
      {f, 20},
      {g, 18},
      {h, 16},
      {i, 14},
      {j, 12},
      {k, 10},
      {l, 22},
      {m, 24},
      {n, 26},
      {o, 28},
      {p, 30},
      {q, 40},
      {r, 38},
      {s, 36},
      {t, 34},
      {u, 32},
      {v, 42},
      {w, 44},
      {x, 46},
      {y, 48},
      {z, 50}
    };

body:
Without quotes, a, b, c etc. are just names. You didn't declare any of them, so the compiler complains.
Put single quotes around the letters to let the compiler know that they are char literals.


message:
Arduino industrial 101 digital pins

I don't see anything that has been clear about which digital pins map to which physical ones. If someone could point me in the right direction it would be a big help.

For exampleThrough trial and error, i've found that if i set digital pin 3 in the Arduino IDE, it is mapped to D0 on J6, but surely this is documented somewhere?

body:
I found what i was looking for on the arduino github repository.

Arduino/hardware/arduino/avr/variants/


message:
Can I control a cellphone's lcd (+touch screen)?

I had an Xperia txt pro just laying around and tried to revive it. I burned it like an idiot using 5v in the battery pins by accident :/
So I decided to read it apart and got to the lcd, can I use my Arduino Mega to control it? Bc I have no idea how to use it.

These are the pins[![these are the pins][1]][1]

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

body:
No. For two reasons:

1. You will struggle to find the pinout of the TFT (or even identify the model). It will have most likely been custom made for the phone.
2. The Arduino doesn't have a GPU to drive it. Arduinos need a TFT with built in GPU since they lack the resources to drive one directly.


message:
Can the Mouse library scroll horizontally?

I'm using the [Mouse](https://www.arduino.cc/en/Reference/MouseKeyboard) library with an ATmega32U4 connected to Linux via USB.

I would like to issue horizontal scroll commands, but the [Mouse.move()][1] function only seems to accept X movement, Y movement and vertical scroll parameters.

How can I send horizontal scroll commands from the Arduino to the computer?

  [1]: https://www.arduino.cc/en/Reference/MouseMove

body:
As suggested in the comments, I edited the core libraries to achieve this.

I'm using [PlatformIO][1], so the library files I needed to edit were here:

    ~/.platformio/packages/framework-arduinoavr/libraries/Mouse/src/

And the required changes (to change a `wheel` parameter for horizontal (`h`) and vertical (`v`) scroll parameters were as follows:

**Mouse.h**

Change the declaration of `move()`:

    ...
    void move(signed char x, signed char y, signed char h = 0, signed char v = 0);
    ...

**Mouse.cpp**

Add the following to the report descriptor after the last `INPUT` message:

    ...
    0x05, 0x0c,        //       USAGE PAGE (Consumer Devices)
    0x0a, 0x38, 0x02,  //       USAGE (AC Pan)
    0x15, 0x81,        //       LOGICAL_MINIMUM (-127)
    0x25, 0x7f,        //       LOGICAL_MAXIMUM (127)
    0x75, 0x08,        //       REPORT_SIZE (8)
    0x95, 0x01,        //       REPORT_COUNT (1)
    0x81, 0x06,        //       INPUT (Data, Var, Rel)
    ...

Change the definition of `move()`:

    void Mouse_::move(signed char x, signed char y, signed char h, signed char v)
    {
     uint8_t m[5];
     m[0] = _buttons;
     m[1] = x;
     m[2] = y;
     m[3] = v;
     m[4] = h;
     HID().SendReport(1, m, 5);
    }

<hr>

The following terminal commands were also useful in testing these changes:

    # List input devices
    xinput --list

    # List device capabilities
    xinput --list <device-id>

    # Watch for data sent from the device
    watch -n 0.1 xinput query-state <device-id>

  [1]: http://platformio.org


body:
Horizontal Scroll is achieved by holding shift when scrolling vertically.

Do this instead:

    Keyboard.press(KEY_LEFT_SHIFT);
        Mouse.move(0, 0, 1);
        Keyboard.releaseAll();


message:
Problems connecting Adafruit Feather M0 to network

I'm trying to connect my Adafruit Feather M0 board to an existing WiFi network. Whenever I use the "ConnectWithWPA" example sketch, I receive "Attempting to connect to WPA SSID: "MyNetwork" " in the serial window, where "MyNetwork" is the SSID for the WiFi I wish to connect to. The network never gets connected. The WiFi I want to connect is WPA, password protected. When I connect the feather to an open network (one without a password) it does in fact get connected. The problem only occurs when I try to connect to a network with SSID and password.

Does anyone know what the problem may be?

    #include <SPI.h>
    #include <WiFi101.h>

    #include "arduino_secrets.h"
    ///////please enter your sensitive data in the Secret tab/arduino_secrets.h
    char ssid[] = SECRET_SSID;        // your network SSID (name)
    char pass[] = SECRET_PASS;    // your network password (use for WPA, or use as key for WEP)
    int status = WL_IDLE_STATUS;     // the WiFi radio's status

    void setup() {
      //Configure pins for Adafruit ATWINC1500 Feather
      WiFi.setPins(8,7,4,2);
      //Initialize serial and wait for port to open:
      Serial.begin(9600);
      while (!Serial) {
        ; // wait for serial port to connect. Needed for native USB port only
      }

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

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

        // wait 10 seconds for connection:
        delay(10000);
      }

      // you're connected now, so print out the data:
      Serial.print("You're connected to the network");

     }

    void loop() {
      // check the network connection once every 10 seconds:
      delay(10000);
      }

body: I was able to get the Feather board communicating with my WiFi network after I updated my Arduino IDE and firmware. Hope this helps anyone else facing this problem.


message:
How to determine which pins_arduino.h file is used?

For some applications I need access to the registers that control the output/input and high/low state of pins.  For example pin 10 on a adalogger is `PORTB` with a mask of `_BV(6)`.  This information can be found in `pins_arduino.h`.  For some boards many variants get installed.  I turned on verbose compiling and looked through the output there as well as looking through `boards.txt` and `platform.txt`.  In that output I see an include to a directory with a `pins_arduino.h` file but there is nothing in that file but a definition for `BUILTIN_LED`.

When I run a function like `digitalWrite(13,HIGH);` how does it know which registers to use for pin 13?  Since my board has this pin, and `digitalWrite(13, HIGH);` makes an LED light up ... it's working.

body:
In the boards.txt file for the core in question you have a line for each board:

    xxxx.build.variant=yyyy

where yyyy is the name of the folder in variants for the board.

For instance, the Uno, has:

    uno.build.variant=standard

which relates to:

    variants/standard

with the `pins_arduino.h` file in it for that board.


message:
How to use IRremote library with atmega8a

A few days ago I tested  a circuit on a  breadboard based on a ATmega8a with 1 MHz internal oscilator. It sould turn on and off a relay based on a IR code that is received and if it matches the programmed in the EEPROM it shoud enable or disable the relay. Now I developed a PCB and soldered everything together but now it isn't working. On an Arduino Nano it is working ok.

    #include <IRremote.h>
    #include <EEPROM.h>

    int RECV_PIN = 11;
    int RELAY_PIN = 4;
    int setpin = 3;
    unsigned long work_at;
    unsigned long adres;
    unsigned long irbuffer;
    IRrecv irrecv(RECV_PIN);
    decode_results results;

    void dump(decode_results *results) {

        if(digitalRead(setpin) == 0){
          work_at = results->value;
          Serial.println(work_at, HEX);
        }
        irbuffer = results->value;

    }

    void eeprom_writer(){
      if (irrecv.decode(&results)) {
        if(digitalRead(setpin) == 0 && work_at != 0){
          EEPROM.put(0, work_at); //put walue
          Serial.println(work_at, HEX);
          adres = work_at;
          Serial.println(adres, HEX);
          delay(1000); //wait
       }
      }
    }
    void setup()
    {
      EEPROM.get(0, adres);
      pinMode(setpin, INPUT_PULLUP);
      pinMode(RELAY_PIN, OUTPUT);
      Serial.begin(9600);
      irrecv.enableIRIn(); // Start the receiver
    }

    int on = 0;
    unsigned long last = millis();

    void loop() {
      if (irrecv.decode(&results)) {
        // If it's been at least 1/4 second since the last
        // IR received, toggle the relay
      //  if(&results == adres){
          dump(&results);
          if (millis() - last > 250) {
            on = !on;
            if(on == true && adres == irbuffer){
              delay(5000);
              digitalWrite(RELAY_PIN, on ? HIGH : LOW);
              dump(&results);
            }else if(on != true  && adres == irbuffer){
              digitalWrite(RELAY_PIN, on ? HIGH : LOW);
              dump(&results);
              delay(5000);
            }
          }
        //}
    //    Serial.println(dump(&results));
    //    Serial.println(count, DEC);

        eeprom_writer();
        last = millis();
        irrecv.resume(); // Receive the next value
      }
    }

body: Changing the internal oscillator to 8MHz helped.


message:
Unable to compare two integer values in Arduino Mega

I wrote Arduino code (code is given at the end) to compare two integer values. The steps I took was:

1. Give input to DC motor to rotate it using serial port. Input was: `G254`
2. Then I store it in `XX` string and using `XX.remove(0,1);` I removed `G` from `G254`. `XX` now become `254`
3. Then I used `Serial1.println("P");` to get position of motor after rotation. I stored this value in `ZZ` string using `String  ZZ = Serial1.readString();`. `ZZ` will be `P254`.
4.  And using `XX.remove(0,1);` I removed `P` from `P254`. `ZZ` now become `254`.
5. Now, I convert both `XX` and `ZZ` into integer from string using  `XX.toInt(); ZZ.toInt();` .
6. After that, I compare both values using:

>     if (XX == ZZ)
>     {
>         Serial.println("BOTH ARE EQUAL");
>     }
>     else
>     {
>         Serial.println("BOTH ARE NOT EQUAL");
>     }

But it shows `BOTH ARE NOT EQUAL` which is not true. I want to know where I'm making a mistake?

Code I used:

    void setup() {
        // put your setup code here, to run once:
        Serial.begin(9600);
        Serial1.begin(9600);

        pinMode(13, OUTPUT);
    }

    void loop() {
        // put your main code here, to run repeatedly:
        if (Serial.available() > 0)
        {
            Serial1.println(Serial.readString());

            String  XX = Serial1.readString();
            XX.remove(0,1);

            Serial1.println("P");

            String  ZZ = Serial1.readString();
            ZZ.remove(0,1);

            XX.toInt();
            ZZ.toInt();
            Serial.println(ZZ);
            Serial.println(XX);
            Serial.println(typeof(XX));

            if (XX == ZZ)
            {
                Serial.println("BOTH ARE EQUAL");
            }
            else
            {
                 Serial.println("BOTH ARE NOT EQUAL");
            }
        }
    }

Thanks.

body:
You should use

     int x = XX.toInt()

Without the int x = part, the string is converted and the result (the integer) is not used.

Also comparing strings should be done with the strcmp function. The problem is that if you compare two strings, you compare the pointers to those strings and two strings can have equal texts but (probably) not equal addresses.


body:
There are several issues with your code.

First, never assume that Serial.readString() will returns you a complete String; it can time out and return nothing, or return just an incomplete value.

`Serial.available() > 0` doesn't imply that the reading is complete ...

Second, Serial.readString() returns everything, include the possible \r\n at the end of the string.

Here is a little sketch that shows a `toInt` implementation fit for you case. Run this sketch to see how it works.

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

    void loop() {
      String x = Serial.readString();
      Serial.print(x); Serial.print("=");
      Serial.println(myToInt(x));
    }

    int myToInt(String x) {
      char* p = x.c_str();
      int val = 0;

      while(*p != 0 && !isdigit(*p)) {
        p++;
      }

      while (*p != 0 && isdigit(*p)) {
        val = val * 10 + (*p - '0');
        p++;
      }
      return val;
    }


message:
Pull EN pin of regulator to ground

I have an Adafruit Huzzah Feather with ESP8266 board, but I think my question will apply to most all boards (as most all have an onboard regulator). Most regulators have an Enable pin (EN) as does my Adafruit board. Apparently, I can shut down the regulator by pulling this pin low. I have a specific application where an external device will provide a high signal to me when I want the device to turn on, otherwise, I want it off at all times. So, what I have is a 1k resistor pulling the EN pin low, to ground. I tried other values 10-20k but they did not pull enough low to shut down the regulator. For example, 20k pulled me down from 3.3V to 2.6V but the regulator stayed on. On the other hand, 1k pulls me down to .3V on the EN pin and this shuts it down.

Then, when the external device gives me the high signal, which I have also tied to the EN pin, this will pull it back up and turn on the regulator.

This seems to be working just fine, but I wanted to ask if this sounds reasonable (I know this is a general question but I want to know if there is a better way). A specific, related question would be am I wasting too much power by using a 1k resistor when powered up or pulled high since some of the supply current will be dumped via the 1k resistor to ground.

UPDATE: In looking at the schematic on the Adafruit site, it appears that they have pulled EN to the input via a 10k resistor. So, I am fighting that which is probably why values over 10k do not pull it down enough to turn off. If I was doing the board design, I would have reversed this and pulled EN low by default but this is not the case when using the off the shelf board. So, I guess any value below 10k should work, like 4.7k? I guess I could also remove their pull up if I wanted to get really crazy. Thoughts on all of this?

Thanks!

body:
A better solution would be to use a PNP transistor to control the EN pin. A PNP is ON when the input to it is LOW (or lower than the collector minus 0.7V, that is).

Take this circuit, for instance:

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

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

<!-- End schematic -->

When the GPIO is HIGH the transistor Q1 is turned off (GPIO >= VCC-0.7). Also if the GPIO pin is disconnected it is turned off because R3 pulls it up to VCC.

Set the GPIO LOW and Q1 turns on since the base is now lower than VCC-0.7V. With Q1 turned on it connects the EN pin to ground, so it becomes LOW.

If you replace the PNP with an NPN (there's more chance you have one in your bits box) you can basically invert the logic:

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

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

<!-- End schematic -->

Now when the GPIO is LOW or pulled *down* by R3 Q1 is off and EN is pulled HIGH. Set the GPIO HIGH and Q1 turns on and connects EN to ground setting it LOW.

In both these scenarios the EN pin defaults to HIGH. If you want it to default to LOW until you activate the GPIO pin (i.e., during bootloader operation when the GPIO is in INPUT mode) you can reverse R3 so it becomes a pull-down (for the PNP) or a pull-up (for the NPN).