message:
Why is the piezo buzzer not making any sound?

My ciruit:
[![enter image description here][1]][1]

My code:

    // Pin 13 has a LED connected on most Arduino boards.
    // give it a name:
    int led = 13;
    const int buttonPin = 2;

    // the setup routine runs once when you press reset:
    void setup() {
      // initialize the digital pin as an output.
      pinMode(led, OUTPUT);
      pinMode(buttonPin, INPUT_PULLUP);
    }

    // the loop routine runs over and over again forever:
    void loop()
    {
      bool buttonState = digitalRead(buttonPin);
      while (buttonState == LOW)
      {
       digitalWrite(led, HIGH);   // turn the LED on (HIGH is the voltage level)
       delay(1000);               // wait for a second
       digitalWrite(led, LOW);    // turn the LED off by making the voltage LOW
       delay(1000);               // wait for a second
       tone(12,260);
      {
     }
      }
    }
What I wish to do, is that when the button is pressed, and the Led's start to blink, I want the piezo buzzer to make a sound. I have never worked with them before so I am having troubles getting results. Is it that the setup is wrong or the code needs extra lines than just the `tone(12,260);` that I added?
  [1]: https://i.stack.imgur.com/NTkHd.jpg

body:
Both the code and the circuit have problems.

In the code:

• If the `while (buttonState == LOW)` loop is ever entered, it will never be left, because `buttonState`, the controlling variable, does not change within the loop.

The simplest fix is to remove the line `bool buttonState = digitalRead(buttonPin);` and replace `while (buttonState == LOW)` with `while (!digitalRead(buttonPin))`, which says to loop while `digitalRead(buttonPin)` is not true; ie, while it is false, or low.

• The empty braces, `{ }` at the end of the `while` loop are superfluous and should be deleted.

In the circuit diagram:

• Neither of the leads of the buzzer is attached to the Arduino circuit, so it won't make any sound.  Note, `tone(12,260);` tells the Arduino to use pin 12 for tone output.

To fix this problem, run a wire from pin 12 to one side of the buzzer, and a wire to ground for the other side of the buzzer.

• A blue LED in series with a red LED might or might not turn on when supplied with 5 V.  For example, if the [red LED takes 1.8 V and the blue LED takes 3.3 V to turn on](http://www.evilmadscientist.com/2012/resistors-for-leds/), the 5.1 V total is too high to be turned on by 5 V signals.  Remove one of the two LEDs, and move the wires to the other LED to complete a circuit.


sender: user

message:
I2C between 2 or more Arduino boards

HELLO I have already connected with I2C 2 Arduino's all is working with comunication on Bus I2C. My Setup is :
MASTER with LCD I2C , RTC1037
SLAVE some sensor not I2C

I allready put 2 pullup resistor 10Kohm on SDA and SCL

I need to switch off the slave arduino but when i switch off the Slave board the Master Arduino stop working.Why? It's possible to continue working with master board and the slave board switch off? Thank's for help

sender: assistant

body:
You need to isolate the slave device from the I2C bus since it is causing interference with the signals.

Adafruit have published a good [application note](https://cdn-shop.adafruit.com/datasheets/an97055.pdf) about level shifting in I2C busses using MOSFETs, and it also contains a bit about bus isolation:

> **2.3.4 Isolation of the powered-down “Lower voltage” section.**
>
> An additional feature of the level shifter circuit in figure 2 is the isolation of the “Lower voltage” section when
VDD1 is switched off. In that case VDD1 is about 0 Volt and the MOS-FET’s [sic] are switched off because VGS is
below the threshold voltage. The “Higher voltage” section is not hindered and stays operational. To assure a
noise margin, the MOS-FET’s should have a minimum threshold voltage VGS(th) of e.g. 0.4V and VDD1 must
stay below this value. The isolation feature can also be applied if no level shifting is required, VDD1 and VDD2
may have the same value, e.g. both 3.3V or both 5V.


message:
Arduino LCD Display 2x16 custom char byte limit

Some years ago I stumble with a problem while using the 2x16 LCD. What happened was that there was a limit to how may byte arrays I could declare. So my project came to a halt because I needed to create more custom characters to advance any further...

The lcd accept custom characters to store them but I suppose there is a limit to this, am I wrong?

I'm trying to create a set of custom characters that move on screen. Since there are a lot of animations I need several of them to have a smooth animation. The problem resides in the limit of characters I can pre-establish after executing lcd.begin()

I don't post code because to my understanding that is not relevant and because sincerely is a crap since I wrote it down when I was learning programming some years ago. I want to resolve this so I can rewrite the code.

LCD version: QAPASS 1602A

Here is an example:

byte Ghost[8] = {
  0b00000,
  0b01110,
  0b01110,
  0b10101,
  0b11111,
  0b11111,
  0b11111,
  0b10101
};

lcd.createChar(0, Ghost);

So the right question is: Do I need to reset the LCD chip then declare the new characters to the lcd to make it available? How?

body:
> there was a limit to how may byte arrays I could declare.

If the problem was that you ran out of free RAM, then the fix is to move those byte arrays into program space.

Atmega 328 processors (Uno) are very RAM-limited. Fortunately you can assign constant data - fixed character strings, lookup tables for math, fonts, CRC calculation, etc - to be stored in program space which is much more generous. The upside is you can free lots of RAM in an application like yours that needs lots of constant data. The downside is that access to the data is a little bit slower:

    // Definitions for data in program space
    #include <avr/pgmspace.h>

    // Place the character table in Flash
    byte const Ghost[8] PROGMEM = {
       0b00000,
       0b01110,
       0b01110,
       0b10101,
       0b11111,
       0b11111,
       0b11111,
       0b10101
    };

    // Read a byte of character data
    OneByte = pgm_read_byte(&Seg7_segtbl[index]);

Update:

> LCD version: QAPASS 1602

If that has an Hitachi HD44780 controller on it, [its datasheet][1]says it has a 64-byte character RAM - more than enough for a full display of 2 x 16 unique characters, but if you need a wider choice of characters than a set of 64, you may need to re-load the RAM with a custom sub-set for any given screen-full. For animating, though, you'll probably need all of the individual parts of each animation in the LCD RAM at once; reloading during animation will most likely disturb the smoothness. One possibility is to load part of a subset between animation frames - if that's even possible. (I haven't studied this controller to that level of detail).

  [1]: https://www.sparkfun.com/datasheets/LCD/HD44780.pdf


message:
M0 pro: SPI communication, code works on Uno, but not in M0. Using ICSP port

I am trying to establish a communication between a sensor and a M0 -pro using SPI. The code :

        #include <SPI.h>

        unsigned int result  = 0;
        void readAngle();

        void setup() {
          Serial.begin(9600);
          SPI.setBitOrder(MSBFIRST);
          SPI.setClockDivider(SPI_CLOCK_DIV8); //sets the clock speed for data transfer, slowed down 8 times
          SPI.setDataMode (SPI_MODE1);

          digitalWrite(11,HIGH);
          pinMode(11,OUTPUT);

          SPI.begin();
          SerialUSB.println("First Try");
    }

        void loop() {
          readAngle();
          SerialUSB.println(result);
          delay(500);

    }

        void readAngle(){
            digitalWrite(11,LOW); //Turn SS on, start communication
            result = SPI.transfer16(0xFFFF); // the read command and the response received
            result = (result << 2) >> 2; // get rid of the last 2 bits, error(14) + parity(15)
            digitalWrite(11,HIGH); //Turn SS of

    }

The code works perfectly with an UNO, but with M0, it event doesnt print the first `SerialUSB.println("First Try");`. The moment i erase the lines that have SPI commands in it, the serial monitor starts working again. As i said in the titel i am using the ICSP port on M0. I use the native usb port to programm.

I think i am missing something very basic. I checked many different forum posts, but there is no indication of M0 requiring other SPI commands. Any help is much appriciated.

PS: i didnt go into detail with the sensor and its datasheet because since it works fine with uno, the cause of the problem should be it.

body: Which version of the Arduino IDE are you using ? If its an older one, try to get the latest one, sometimes that solves issues like the one you have.


body:
You must declare that the pin as an output before you use it.

Do this by using the [`pinMode()`][1] function, like this:

    pinMode(11, OUTPUT);          // sets the digital pin 11 as output

Add the above line at the beginning of your `setup()` function.

  [1]: https://www.arduino.cc/reference/en/language/functions/digital-io/pinmode/


message:
Program Arduino Uno via Nano

To keep the question short:

I'm trying to burn a bootloader on my Arduino Uno using an Arduino Uno. Could someone please tell me the pin connections? Thanks.

body:
To burn a bootloader from source Nano to target Uno make the following connections:

    Nano.Pin   Uno.Pin

    10         Reset

    11         11

    12         12

    13         13

    GND        GND

See here for more details: https://www.arduino.cc/en/Tutorial/ArduinoToBreadboard


message:
Weird result printing an array using a loop

first of all I'm sorry for my english.

My problem is that I want to use an array of numbers on a function, but I'm getting a weird result inside a for loop. Doing some tests I've seen that it happens even in the simplest sketch so I should be doing something wrong.

I've created a two level int and I want to iterate through the second level using a for loop. Outside the for loop all data gotten from that array is OK, but just inside the loop I'm just getting garbage as if the array was not initialized.

My simple sketch is this:

    const int number_small[][14] PROGMEM = {
      {124, 124, 387, 387, 399, 399, 443, 443, 483, 483, 387, 387, 124, 124},
    };

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

      Serial.print(String(number_small[0][0]) + "\n");
      Serial.print(String(number_small[0][1]) + "\n");
      Serial.print(String(number_small[0][2]) + "\n");
      Serial.print(String(number_small[0][3]) + "\n");
      Serial.print(String(number_small[0][4]) + "\n");
      Serial.print(String(number_small[0][5]) + "\n");
      Serial.print(String(number_small[0][6]) + "\n");
      Serial.print(String(number_small[0][7]) + "\n");
      Serial.print(String(number_small[0][8]) + "\n");
      Serial.print(String(number_small[0][9]) + "\n");
      Serial.print(String(number_small[0][10]) + "\n");
      Serial.print(String(number_small[0][11]) + "\n");
      Serial.print(String(number_small[0][12]) + "\n");
      Serial.print(String(number_small[0][13]) + "\n\n\n");

      for (int i = 0; i<14; i++){
        Serial.print("I: " + String(i) + " - " + String(number_small[0][i]) + "\n");
      }
    }

    void loop() {
    }

And the output is:

    124
    124
    387
    387
    399
    399
    443
    443
    483
    483
    387
    387
    124
    124

    I: 0 - 0
    I: 1 - 184
    I: 2 - 0
    I: 3 - 1
    I: 4 - 0
    I: 5 - -18248
    I: 6 - -18248
    I: 7 - -18248
    I: 8 - 0
    I: 9 - 135
    I: 10 - 0
    I: 11 - 0
    I: 12 - 769
    I: 13 - 0

What I'm doing wrong?,

Thanks!!

body:
Constants like `String(number_small[0][0])` are optimized by compiler during the build (=compile time).

However that's not the case of loop. So you have to use specific functions for reading values from `PROGMEM` in the runtime:

    for (int i = 0; i<14; i++){
      Serial.print("I: ");
      Serial.print(i);
      Serial.print(" - ");
      Serial.println((int)pgm_read_word(number_small[0]+i));
    }

Btw: Don't use string concatenations. These are extremely hungry for the memory. See Majenko's article: [The Evils of Arduino Strings][1]

  [1]: https://hackingmajenkoblog.wordpress.com/2016/02/04/the-evils-of-arduino-strings/


body:
I was sure that I was doing something wrong and yes... Finally I did another test (storing the array on SRAM instead on PROGMEM) and it worked, so I've changed my "research direction" and I've found the solution.

With my initial sketch I was reading the PROGMEM from outside the loop, but from inside the loop what i read is the SDRAM, so I've to use the **pgm_read** functions to force to read from PROGMEM, and now finally is working:
> pgm_read_word(number_small[0] + i)

    const int number_small[][14] PROGMEM = {
      {124, 124, 387, 387, 399, 399, 443, 443, 483, 483, 387, 387, 124, 124},
    };

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

      Serial.print(String(number_small[0][0]) + "\n");
      Serial.print(String(number_small[0][1]) + "\n");
      Serial.print(String(number_small[0][2]) + "\n");
      Serial.print(String(number_small[0][3]) + "\n");
      Serial.print(String(number_small[0][4]) + "\n");
      Serial.print(String(number_small[0][5]) + "\n");
      Serial.print(String(number_small[0][6]) + "\n");
      Serial.print(String(number_small[0][7]) + "\n");
      Serial.print(String(number_small[0][8]) + "\n");
      Serial.print(String(number_small[0][9]) + "\n");
      Serial.print(String(number_small[0][10]) + "\n");
      Serial.print(String(number_small[0][11]) + "\n");
      Serial.print(String(number_small[0][12]) + "\n");
      Serial.print(String(number_small[0][13]) + "\n\n\n");

      int i;
      for (i = 0; i<14; i++){
        Serial.print("I: " + String(i) + " - " + String(pgm_read_word(number_small[0] + i)) + "\n");
      }
    }

    void loop() {
    }

Thanks and greetings!!


body:
I refined your own answer:

 - No need to use String to print a numeric value; just print the value.
 - No need to add "\n" add the end of `print`, use `println`instead.
 - No need to concatenate strings for printing; just print them one by one.
 - In a `for` loop, declare the control variable *inside*

Code

    const int ITEMS = 14;
    const int number_small[][ITEMS] PROGMEM = {
      {124, 124, 387, 387, 399, 399, 443, 443, 483, 483, 387, 387, 124, 124},
    };

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

      for (int i=0; i < ITEMS; i++) {
        Serial.println(pgm_read_word(number_small[0]+i));
      }
      Serial.println();  Serial.println();
      for (int i = 0; i < ITEMS; i++){
        Serial.print("I: "); Serial.print(i); Serial.print(" - " );
        Serial.println(pgm_read_word(number_small[0] + i));
      }
    }

    void loop() {
    }


message:
Is EEPROM's location relocated on sketch compile?

I assumed the microcontroller has 3 components as per storing data:
- flash memory for the program
- RAM for variables
- EEPROM for non-volatile user-storage

And I always assumed those are separate chips on the board. However, working directly with a RobotDyn Uno R3 leads me to believe I may be wrong somehow.

I compiled this program:

    #include <EEPROM.h>

    struct SettingsStruct {
      String server;
      String port;
      String user;
      String password;
      String description;
    } gSettings = {
      "192.168.1.6",
      "8080",
      "fci blah vlak",
      "zangazang4",
      "Extra string here"
    };

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

      //saveConfig();

      Serial.print(F("EEPROM size is: "));
      Serial.print(EEPROM.length());
      Serial.print(F(" bytes"));
      Serial.println("");

      loadConfig();
      Serial.print(F("Server: "));
      Serial.print(gSettings.server);
      Serial.println("");
      Serial.print(F("Port: "));
      Serial.print(gSettings.port);
      Serial.println("");
      Serial.print(F("Username: "));
      Serial.print(gSettings.user);
      Serial.println("");
      Serial.print(F("Password: "));
      Serial.print(gSettings.password);
      Serial.println("");
      Serial.print(F("Description: "));
      Serial.print(gSettings.description);
    }

    void loop()
    {
      // nope
    }

    void loadConfig() {
        for (unsigned int t=0; t<sizeof(gSettings); t++)
          *((char*)&gSettings + t) = EEPROM.read(t);
    }

    void saveConfig() {
      for (unsigned int t=0; t<sizeof(gSettings); t++)
        EEPROM.write(t, *((char*)&gSettings + t));
    }

Problem is that each time I add new elements to the struct, and I run the program, the serial prints different things. I recognize previously saved strings but they are right shifted, meaning that somehow the ZERO address of EEPROM might have moved backwards and previously saved strings move right and offocurse, appear on other struct variables.

This leads me to believe the actual EEPROM is related with the flash memory and depends on it on each compile. As if the ZERO address of EEPROM is established after each compile.

Can anyone confirm this or lead me to some documentation relating this? It's a weird mystery that I would like to clear out.

body:
The EEPROM is a completely separate part of the silicon inside the chip. It has no address of its own.

You are making a fundamental error in what you are doing, though - you cannot directly store the contents of strings by looking at the addresses of those strings. The data in them is dynamically allocated in RAM and is completely separate from the object. You will have to come up with a different way to store your data.


message:
MAX7219 not behaving as expected

I have 2 rows of 12 MAX7219 connected in series with DOUT to DIN (rows are isolated). Now the thing is I am using `LedControl` Library to work with it. The problem is the last 4 Matrices on both the rows don't work. The sequence in my code is like this where `(row, column, matrix)` is used to define the row and column of the matrix and I am talking about a single ROW from two ROWs of 12.

    Sequence in Code      What Happens
    ----------------      -----------------
    (0, 1, 0)             (0, 1, 0)
    (0, 1, 1)             (0, 1, 9)
    (0, 1, 2)             (0, 1, 1)
    (0, 1, 3)             (0, 1, 10)
    (0, 1, 4)             (0, 1, 2)
    (0, 1, 5)             (0, 1, 11)
    (0, 1, 6)             (0, 1, 3)
    .                     .
    .                     .
    .                     .
    (0, 1, 11)            (0, 1, 8)

Now I can understand why does this happens. This code works like this even if the `Device Count` is 8.

Code:

    #include "LedControl.h"
    LedControl row1=LedControl(2,4,3,12);
    LedControl row2=LedControl(5,7,6,12);

    unsigned long delaytime=500;

    void setup() {
      int d_row1 =row1.getDeviceCount();
      for(int address=0;address<d_row1;address++) {
        row1.shutdown(address,false);
        row1.setIntensity(address,15);
        row1.clearDisplay(address);
      }

      int d_row2 =row2.getDeviceCount();
      for(int address=0;address<d_row2;address++) {
        row2.shutdown(address,false);
        row2.setIntensity(address,15);
        row2.clearDisplay(address);
      }
    }

    void loop() {
      int devices=row1.getDeviceCount();
      for (int i = 0; i < devices; i++){
        delay(delaytime);
        row1.setLed(i,0,0,true);
        row2.setLed(i,0,0,true);
        delay(delaytime);
        row1.setLed(i,0,0,false);
        row2.setLed(i,0,0,false);
      }
    }

**EDIT**
I just noticed something, there is no data going to the last 4 matrices. The timings of the blinking of the LEDs on last 4 matrices does not ties correctly (500ms) but it is in fact 250ms (i.e. half time). It means the blinks on last 4 matrices are between pulses of the first 4 matrices.

body: Have you checked the wiring between matrices and/or swapped modules in case there is a faulty one in the sequence?


body:
Looking at your library source, it seems the number of devices is clamped at 8. This isn't a hard limit imposed by the chip but rather practical design. SPI, especially at high speeds, can get unreliable when the bus capacitance, related to the cable lengths, gets so high that signals are skewed beyond recognition. Also the buffer in the library used to hold the row data is 64 bytes in size, intended to hold the data for 8 devices with 8 rows each.

You can edit the library to make it support 12 devices though it will require attention to detail like, increasing the buffer to 96 bytes, getting rid of short-circuits within the methods that make sure that no more than 8 devices can be addressed, for-loops, etc.


body:
After fiddling around with various Libraries, I came across this one.

[MD_MAX72XX][1]

It has all the functionalities that I needed with a good Simple Wiki to get you started.

Also it is simple enough that even a noob like me could figure it out.

Regards

  [1]: https://github.com/MajicDesigns/MD_MAX72XX "MD_MAX72XX"


message:
Can I use NodeMCU with Arduino to connect to wifi or do I need a separate module?

I am just starting out with electronics. I got a Arduino Mega 2560 board and am able to do simple things like blink. Now I want to start a project on IoT and want to connect this board with internet. I got some leads [here][1]. While googling ESP8266, I came across NodeMCU which has a processor too. I already have Arduino, so can I use only the wifi module of NodeMCU and connect it to Arduino?

  [1]: https://arduino.stackexchange.com/questions/432/how-can-i-connect-to-an-arduino-using-wifi

body: NodeMCU already has a processor built in with the WiFi so you don't need a separate processor. If you just want to add WiFi to your Arduino board use an ESP8266 board connected to the Arduino. That is essentially the WiFi part of NodeMCU.


body:
I went through almost the exact same thing you are going through when I was looking at the ESP8266 boards (the NodeMCU is one of those).  I too discovered that the NodeMCU is a micro computer in itself, even more powerful than the Arduino UNO!

You can even code the NodeMCU using the Arduino IDE.  As has been said previously, I'd use your NodeMCU directly to accomplish what you want to do.


message:
What is the worst time case for Arduino Mega?

I'm going to implement home automation using an Arduino Mega with 8*6=48 channels relay in my new home. I have prepared an Android app for an HC-05 Bluetooth controller. How much time can I keep running an Arduino Mega with all the appliances in a home? Can I keep it working 24/7 for a while?

body:
Yes.

(For better guidance than that, we'd need to know more.)


body:
I would be wary of going "all in" if the MCU holds+controls the state of all the relays, especially if there's networking happening in the sketch. That creates a single-point of failure for the whole house. I've found that a brief power outage or an MCU freeze/reboot resets the state. That can be frustrating and downright dangerous in a emergency situation.

An obvious solution is to save the relay states in EEPROM or externally on a server. The issue with those is that EEPROM wears out, and your server might not be available soon after a power-cycle when the MCU needs it to resume (router re-connecting, computer rebooting slower than MCU, etc).

The real solution, and the one that preserves life-safety is having local hardware state for each relay. You need the ability to both read state from the Arduino, and change the state from the Arduino. This can be as simple (yet expensive) as physically latching relays, or a capacitor-backed 1-bit state machine like an RS flip-flop. You can build the flip-flop in a variety of circuits, from shift registers, to a 555, to a simple NPN+n-channel MOSFET coupling (my pref).

The big downside is that this needs two pins for each relay. But, with such "smart relays", you can unplug the Arduino and nothing happens around the house. It also allows non-Arduino things (even a simple button/switch) to control the state of a relay, no matter what's happening with the Arduino at the time, but with the ability of the Arduino to react to that change and not over-write or forget the state. The MCU can reboot on a schedule to keep responsive, without anyone noticing the reboot.

Yes, it adds more complexity and cost, but a manageable amount of both, and the satisfaction difference is hard to truly express. In short, any system should work as reliably as lights did 100 years ago: switches work, and never unexpectedly change. If lights are not working or are turning off unexpectedly in a small fire, things can get ugly quick, especially with guests.


body:
> Can I keep it working 24/7 for a while?

yes, if properly designed.


message:
Nick Gammon "Camera shutter speed timer"

I am reading the period of pulses from a 600ppturn shaft encoder, using the [FreqPeriod library][1], by Martin Nawrath.

This works using counter1 and the comparator on pin6 and pin7 on the Arduino Uno.

[![ Counter and Capture unit][2]][2]

The period duration for 1-2500Hz is being used in a midi musical instrument to give a speed to volume and a note change at a fixed speed.
This has worked well on the Uno but now I want to use a Mega (which does not have both comparator pins).

So I have tried using the Nick Gammon interrupt sketch. This has produced very erratic results returning both positive and many negative numbers (shown by using "volatile long period;" in the monitor.

Can you tell me what is happening and would it be better to use a counter instead of interrupts?

Hope I have given enough information to be getting on with, many thanks.

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

    // Camera shutter speed timer
    // Author: Nick Gammon
    // Date: 15th January 2012

    volatile boolean started;
    volatile unsigned long startTime;
    volatile unsigned long endTime;
    volatile unsigned long period;
    volatile unsigned long lfrq;

    // interrupt service routine
    void isr () {
        if (started)
            endTime = micros ();
        else
            startTime = micros ();
        started = !started;
    } // end of Pulse Width

    void setup () {
        digitalWrite (2, HIGH); // pull-up
        Serial.begin (9600);
        Serial.println (" Pulse Width test = ");
        attachInterrupt (digitalPinToInterrupt (2), isr, CHANGE); //CHANGE RISING
    } // end of setup

    void loop () {
        if (endTime) {
            period = (endTime - startTime) * 32 ; // pulse width?
            Serial.print (" \n  ");
            Serial.print ( " period =  ") ;
            Serial.print (period) ;
            lfrq = 16000000.0 / period;
            Serial.print(" Hz = "); // one rev per sec = 26666 micros period
            Serial.print( lfrq );
            endTime = 0;
        }
    } // end of loop

  [1]: http://interface.khm.de/index.php/lab/interfaces-advanced/frequency-measurement-library/
  [2]: https://i.stack.imgur.com/jNuNi.jpg

body:
> Can you tell me what is happening [...]?

Not really, but here is a wild guess: your input signal is bouncy, the
ISR fires too often, your loop cannot keep up with the rate, and you end
up accessing `endTime` in the ISR and loop simultaneously.

If you have a scope, look at your encoder signal. Is it clean?

> would it be better to use a counter instead of interrupts?

Using the input capture feature of a timer will give you the best
possible accuracy, as you will have single-cycle resolution. In
contrast, `micros()` has only 4 µs resolution (64 times worse) and
the ISR may be delayed by up to ≈ 16 µs by the `TIMER0_OVF`
ISR.

You can use the FreqPeriod library you linked to as an inspiration for
writing your own timer-based code, but it will require some changes:

* As pointed out by Nick Gammon in a comment, you don't need the analog
  comparator, nor the conditioning RC network, as the encoder's outputs
  are already digital. Or you may use a low-pass filter if the encoder
  is bouncy.

* You will use the input capture pins of either timer 4 (digital pin 49)
  or timer 5 (digital pin 48). The other input capture pins are not
  available on the Mega's pin headers.

* You will replace `ISR(ANALOG_COMP_vect)` by either `ISR(TIMER4_CAPT)`
  or `ISR(TIMER5_CAPT)` (the relevant “capture event” ISR). No need to
  adjust a comparator threshold in the ISR.

* In the `begin()` method, you will leave the analog comparator alone,
  and you will enable the capture event interrupt.

Obviously you will have to study [the
datasheet](http://www.atmel.com/Images/Atmel-2549-8-bit-AVR-Microcontroller-ATmega640-1280-1281-2560-2561_datasheet.pdf)
before start coding.


body:
> Could this be so?

because the code is faulty: there is no assurance of atomicity between startTime and endTime. ie. the interrupts could have arrived, multiple times, while the if loop is executing.

two ways to fix it:

1. calculate period in the isr; or

2. clear endTime once the clock starts in the isr.


body:
While you are doing all those things with those volatile variables in the loop function, the interrupt can still be firing.  If it fires in the middle of a read of startTime or endTime then you get might get part of the variable holding old value and part holding new value and when you put it together it makes garbage.

You need to do a cli() at the beginning of loop to turn off interrupts and quickly make local copies of all those variables and then sei() to turn interrupts back on.  Now you can safely work with the copies you made.


message:
5pt font for Neopixel shield

I have a 5x8 Neopixel shield for my Arduino. I want to display text on it, while it is in "landscape mode", i.e. a only 5pt high text. The default font that is used by the `print`command is 8pt high. How can I load a font with 5pt height into my code?

I understand that the Neopixel library depends on `Adafruit GFX`, which allows for different fonts. But changing the font according to the Adafruit tutorial on GFX to one of the supplied fonts does not return any readable text (only a moving line of dots). I found this [font converter][1] and used it to produce a 5pt font, but again only a moving dot appears.

This is my code (basically the Neomatrix example with modified orientation of the matrix):

    // Adafruit_NeoMatrix example for single NeoPixel Shield.
    // Scrolls 'Howdy' across the matrix in a portrait (vertical) orientation.

    #include <Adafruit_GFX.h>
    #include <Adafruit_NeoMatrix.h>
    #include <Adafruit_NeoPixel.h>
    #include <Fonts/Dialog_plain_5.h>
    #ifndef PSTR
     #define PSTR // Make Arduino Due happy
    #endif

    #define PIN 6

    Adafruit_NeoMatrix matrix = Adafruit_NeoMatrix(8, 5, PIN,
      NEO_MATRIX_TOP     + NEO_MATRIX_LEFT+
      NEO_MATRIX_ROWS + NEO_MATRIX_PROGRESSIVE,
      NEO_GRBW  + NEO_KHZ800);

    const uint16_t colors[] = {
      matrix.Color(255, 0, 0), matrix.Color(0, 255, 0), matrix.Color(0, 0, 255) };

    void setup() {
      matrix.setFont(&Dialog_plain_5);
      matrix.begin();
      matrix.setTextWrap(false);
      matrix.setBrightness(30);
      matrix.setTextColor(colors[0]);
    }

    int x    = matrix.width();
    int pass = 0;

    void loop() {
      matrix.fillScreen(0);
      matrix.setCursor(x, 0);
      matrix.print(F("Howdy"));
      if(--x < -36) {
        x = matrix.width();
        if(++pass >= 3) pass = 0;
        matrix.setTextColor(colors[pass]);
      }
      matrix.show();
      delay(100);
    }

and this is the content of the font file:

    // Created by http://oleddisplay.squix.ch/ Consider a donation
    // In case of problems make sure that you are using the font file with the correct version!
    const uint8_t Dialog_plain_5Bitmaps[] PROGMEM = {

     // Bitmap Data:
     0x00, // ' '
     0xF0, // '!'
     0xC0, // '"'
     0x07,0xF2, // '#'
     0x79,0xF4, // '$'
     0xD1,0x10,0xB0, // '%'
     0x88,0xCA, // '&'
     0x80, // '''
     0x2A,0x00, // '('
     0x15,0x00, // ')'
     0x08,0x00, // '*'
     0x01,0x1C,0x40, // '+'
     0x00, // ','
     0xC0, // '-'
     0x00, // '.'
     0x6A,0x00, // '/'
     0xD6,0xE0, // '0'
     0xC9,0x20, // '1'
     0x62,0x48, // '2'
     0xE8,0xE0, // '3'
     0x26,0x62, // '4'
     0x08,0x90, // '5'
     0x7A,0xE0, // '6'
     0x25,0x20, // '7'
     0xEA,0xE0, // '8'
     0xD5,0xE0, // '9'
     0x00, // ':'
     0x00, // ';'
     0x02,0xC6, // '<'
     0x77, // '='
     0x06,0x16, // '>'
     0xD0, // '?'
     0x27,0xB7,0x66,0x00, // '@'
     0x4A,0x68, // 'A'
     0xFA,0xD0, // 'B'
     0x68,0x86, // 'C'
     0xE9,0x9A, // 'D'
     0xDA,0x40, // 'E'
     0x9A,0x40, // 'F'
     0x78,0xB5, // 'G'
     0xBE,0xD0, // 'H'
     0xF0, // 'I'
     0x55,0x40, // 'J'
     0xAC,0xCA, // 'K'
     0x92,0x40, // 'L'
     0x9F,0xF9, // 'M'
     0xBF,0xD0, // 'N'
     0x69,0x96, // 'O'
     0xF7,0x40, // 'P'
     0x69,0x96,0x00, // 'Q'
     0xEA,0xCA, // 'R'
     0x91,0x60, // 'S'
     0x21,0x08,0x40, // 'T'
     0xB6,0xE0, // 'U'
     0xAA,0xA4, // 'V'
     0xAF,0xBC,0xA0, // 'W'
     0xA4,0x4A, // 'X'
     0x53,0x08,0x40, // 'Y'
     0x64,0x88, // 'Z'
     0xAA,0x80, // '['
     0xAA,0x40, // '\'
     0x55,0x40, // ']'
     0x61, // '^'
     0x70, // '_'
     0x00, // '`'
     0xDE,0x80, // 'a'
     0x9A,0xE0, // 'b'
     0x92,0x00, // 'c'
     0x3E,0xD0, // 'd'
     0xDE,0x00, // 'e'
     0x49,0x20, // 'f'
     0xF6,0xA0, // 'g'
     0x9E,0xD0, // 'h'
     0xF0, // 'i'
     0x55,0x40, // 'j'
     0x9A,0x60, // 'k'
     0xF0, // 'l'
     0xFD,0x6A, // 'm'
     0xF6,0x80, // 'n'
     0xD7,0x00, // 'o'
     0xD7,0x40, // 'p'
     0xF6,0xB0, // 'q'
     0x2A, // 'r'
     0x4C,0x80, // 's'
     0x49,0x20, // 't'
     0x16,0xD0, // 'u'
     0xB9,0x00, // 'v'
     0xD7,0x60, // 'w'
     0xCB,0x00, // 'x'
     0xB9,0x40, // 'y'
     0x68, // 'z'
     0x4A,0x24, // '{'
     0xF8, // '|'
     0x48,0xA4 // '}'
    };
    const GFXglyph Dialog_plain_5Glyphs[] PROGMEM = {
    // bitmapOffset, width, height, xAdvance, xOffset, yOffset
       {     0,   1,   1,   3,    0,    0 }, // ' '
       {     1,   1,   4,   3,    0,   -4 }, // '!'
       {     2,   2,   2,   3,    0,   -4 }, // '"'
       {     3,   4,   4,   5,    0,   -4 }, // '#'
       {     5,   3,   5,   4,    0,   -4 }, // '$'
       {     7,   5,   4,   6,    0,   -4 }, // '%'
       {    10,   4,   4,   5,    0,   -4 }, // '&'
       {    12,   1,   2,   2,    0,   -4 }, // '''
       {    13,   2,   5,   3,    0,   -4 }, // '('
       {    15,   2,   5,   3,    0,   -4 }, // ')'
       {    17,   3,   3,   4,    0,   -4 }, // '*'
       {    19,   5,   4,   6,    0,   -4 }, // '+'
       {    22,   2,   3,   3,    0,   -2 }, // ','
       {    23,   2,   1,   3,    0,   -2 }, // '-'
       {    24,   2,   1,   3,    0,   -1 }, // '.'
       {    25,   2,   5,   3,    0,   -4 }, // '/'
       {    27,   3,   4,   4,    0,   -4 }, // '0'
       {    29,   3,   4,   4,    0,   -4 }, // '1'
       {    31,   4,   4,   4,    0,   -4 }, // '2'
       {    33,   3,   4,   4,    0,   -4 }, // '3'
       {    35,   4,   4,   5,    0,   -4 }, // '4'
       {    37,   3,   4,   4,    0,   -4 }, // '5'
       {    39,   3,   4,   4,    0,   -4 }, // '6'
       {    41,   3,   4,   4,    0,   -4 }, // '7'
       {    43,   3,   4,   4,    0,   -4 }, // '8'
       {    45,   3,   4,   4,    0,   -4 }, // '9'
       {    47,   2,   3,   3,    0,   -3 }, // ':'
       {    48,   2,   4,   3,    0,   -3 }, // ';'
       {    49,   4,   4,   5,    1,   -4 }, // '<'
       {    51,   4,   2,   5,    0,   -3 }, // '='
       {    52,   4,   4,   5,    0,   -4 }, // '>'
       {    54,   2,   4,   4,    0,   -4 }, // '?'
       {    55,   5,   5,   6,    0,   -4 }, // '@'
       {    59,   4,   4,   4,    0,   -4 }, // 'A'
       {    61,   3,   4,   4,    0,   -4 }, // 'B'
       {    63,   4,   4,   4,    0,   -4 }, // 'C'
       {    65,   4,   4,   5,    0,   -4 }, // 'D'
       {    67,   3,   4,   4,    0,   -4 }, // 'E'
       {    69,   3,   4,   4,    0,   -4 }, // 'F'
       {    71,   4,   4,   5,    0,   -4 }, // 'G'
       {    73,   3,   4,   4,    0,   -4 }, // 'H'
       {    75,   1,   4,   2,    0,   -4 }, // 'I'
       {    76,   2,   5,   2,   -1,   -4 }, // 'J'
       {    78,   4,   4,   4,    0,   -4 }, // 'K'
       {    80,   3,   4,   4,    0,   -4 }, // 'L'
       {    82,   4,   4,   5,    0,   -4 }, // 'M'
       {    84,   3,   4,   4,    0,   -4 }, // 'N'
       {    86,   4,   4,   5,    0,   -4 }, // 'O'
       {    88,   3,   4,   4,    0,   -4 }, // 'P'
       {    90,   4,   5,   5,    0,   -4 }, // 'Q'
       {    93,   4,   4,   4,    0,   -4 }, // 'R'
       {    95,   3,   4,   5,    1,   -4 }, // 'S'
       {    97,   5,   4,   4,   -1,   -4 }, // 'T'
       {   100,   3,   4,   4,    0,   -4 }, // 'U'
       {   102,   4,   4,   4,    0,   -4 }, // 'V'
       {   104,   5,   4,   6,    0,   -4 }, // 'W'
       {   107,   4,   4,   4,    0,   -4 }, // 'X'
       {   109,   5,   4,   4,   -1,   -4 }, // 'Y'
       {   112,   4,   4,   6,    1,   -4 }, // 'Z'
       {   114,   2,   5,   3,    0,   -4 }, // '['
       {   116,   2,   5,   3,    0,   -4 }, // '\'
       {   118,   2,   5,   3,    0,   -4 }, // ']'
       {   120,   4,   2,   5,    0,   -4 }, // '^'
       {   121,   4,   1,   4,   -1,    1 }, // '_'
       {   122,   2,   1,   4,    0,   -4 }, // '`'
       {   123,   3,   3,   5,    1,   -3 }, // 'a'
       {   125,   3,   4,   4,    0,   -4 }, // 'b'
       {   127,   3,   3,   4,    0,   -3 }, // 'c'
       {   129,   3,   4,   4,    0,   -4 }, // 'd'
       {   131,   3,   3,   5,    1,   -3 }, // 'e'
       {   133,   3,   4,   3,   -1,   -4 }, // 'f'
       {   135,   3,   4,   4,    0,   -3 }, // 'g'
       {   137,   3,   4,   4,    0,   -4 }, // 'h'
       {   139,   1,   4,   2,    0,   -4 }, // 'i'
       {   140,   2,   5,   2,   -1,   -4 }, // 'j'
       {   142,   3,   4,   4,    0,   -4 }, // 'k'
       {   144,   1,   4,   2,    0,   -4 }, // 'l'
       {   145,   5,   3,   6,    0,   -3 }, // 'm'
       {   147,   3,   3,   4,    0,   -3 }, // 'n'
       {   149,   3,   3,   4,    0,   -3 }, // 'o'
       {   151,   3,   4,   4,    0,   -3 }, // 'p'
       {   153,   3,   4,   4,    0,   -3 }, // 'q'
       {   155,   2,   4,   3,    0,   -4 }, // 'r'
       {   156,   3,   3,   5,    0,   -3 }, // 's'
       {   158,   3,   4,   3,   -1,   -4 }, // 't'
       {   160,   3,   4,   4,    0,   -4 }, // 'u'
       {   162,   3,   3,   4,    0,   -3 }, // 'v'
       {   164,   4,   3,   5,    0,   -3 }, // 'w'
       {   166,   3,   3,   4,    0,   -3 }, // 'x'
       {   168,   3,   4,   4,    0,   -3 }, // 'y'
       {   170,   2,   3,   5,    1,   -3 }, // 'z'
       {   171,   3,   5,   4,    0,   -4 }, // '{'
       {   173,   1,   6,   2,    0,   -4 }, // '|'
       {   174,   3,   5,   4,    0,   -4 } // '}'
    };
    const GFXfont Dialog_plain_5 PROGMEM = {
    (uint8_t  *)Dialog_plain_5Bitmaps,(GFXglyph *)Dialog_plain_5Glyphs,0x20, 0x7E, 7};

[1]: http://oleddisplay.squix.ch/#/home

body:
I was having the same problem until I read the library source code. Later I found the documentation reference.

The classic font cursor position is defined as the top-left corner of the character cell. For GFX and custom fonts it is the 'y' position is relative to the baseline of the character cell.

My display is 5 by 5. The TomThumb font is 3 by 5. Instead of `matrix.setCursor(x, 0);` I needed to use `matrix.setCursor(x, 5);` so the 'y' coordinate corresponds with the bottom of the pixel matrix, not the top.

It's described in [Adafruit's docs](https://learn.adafruit.com/adafruit-gfx-graphics-library/using-fonts).


message:
Arduino interrupt not called using PinChangeInterrupt

I am new to Arduino and I was trying to figure out how to use an interrupt. When I ran this it would read my magnet but the interrupt would never be called and I couldn't figure out if anyone can help me that would be great.

Thanks.

Here is the code

    #include <PinChangeInterrupt.h>

    //#define INTERRUPT_PIN 12
    #include <Math.h>

    #define RADIUS 3
    const int hallPin = 7; // the number of the hall effect sensor pin
    const int ledPin =  13; // the number of the LED pin
    // variables will change:
    int hallState = 0; // variable for reading the hall sensor status
    double inital_val = 0.0;
    double distance = inital_val;

    void setup() {
      // initialize the LED pin as an output:
      pinMode(ledPin, OUTPUT);
      pinMode(hallPin, INPUT);
      //attachInterrupt(hallPin, calc_distance, HIGH);
      // initialize the hall effect sensor pin as an input:
      attachInterrupt(digitalPinToInterrupt(hallPin), calc_distance , HIGH);
      Serial.begin(9600);
    }

    void loop() {
      //read the state of the hall effect sensor:
      hallState = digitalRead(hallPin);
      if (hallState == LOW) {
        // turn LED on:
        Serial.print("Main Loop: HallState LOW\n");
        digitalWrite(ledPin, HIGH);
        Serial.print(distance, 2);
        Serial.print("\n");
      } else {
        Serial.print("Main Loop: HallState HIGH\n");
        // turn LED off:
        digitalWrite(ledPin, LOW);
      }
    }

    void calc_distance() {
      Serial.print("INTERRUPT! \n");
      if (digitalRead(hallPin) == HIGH) {
        Serial.print("YES!\n");
        distance += PI * 2 * RADIUS;
      } else {
        Serial.print("NO!\n");
      }
    }

body:
The attachInterrupt function is only for normal interrupts. Read the reference: [attachInterrupt][1]

When you need the Pin Change Interrupts, there is a library for that: [EnableInterrupt][2]

Try to keep the interrupt routine as short as possible. Do not use the Serial functions in calc_distance because the Serial functions themself use also interrupts.

The Arduino Mega does not have 'double' floating point variables, the compiler changes it into 32-bit 'float' variables. You are reading the interrupt pin for a test ? I don't understand why you do that. Please make "distance" a volatile variable. In the loop function, the interrupts should be turned off when reading "distance". Because "distance" is a 4 bytes 'float' variable and the Arduino Mega is a 8-bits microcontroller. An interrupt could occur when the "distance" is only read for a part from memory.

  [1]: https://www.arduino.cc/en/Reference/attachInterrupt
  [2]: https://github.com/GreyGnome/EnableInterrupt


message:
Slackbot integration using ESP8266 gets "ssl->need_bytes=16432 > 6859"

I'm trying to use [Uri Shaked Slackbot code][1] using an [Adafruit Feather Huzzah ESP8266 WiFi][2].

I have created the Slackbot integration and copied the API key. The code connects to the WiFi and does the time configuration but then hangs when connecting to slack with the error message in the serial monitor.

> ssl-need_bytes=16432 > 6859

    /**
       Arduino Real-Time Slack Bot
       Copyright (C) 2016, Uri Shaked.
       Licensed under the MIT License
    */

    #include <Arduino.h>
    #include <ESP8266WiFi.h>
    #include <ESP8266WiFiMulti.h>
    #include <ESP8266HTTPClient.h>
    #include <WebSocketsClient.h>
    #include <ArduinoJson.h>
    #include <Adafruit_NeoPixel.h>

    #define SLACK_SSL_FINGERPRINT "AC 95 5A 58 B8 4E 0B CD B3 97 D2 88 68 F5 CA C1 0A 81 E3 6E" // If Slack changes their SSL fingerprint, you would need to update this
    #define SLACK_BOT_TOKEN "https://slack.com/api/rtm.start?token=[MY TOKEN]" // Get token by creating new bot integration at https://my.slack.com/services/new/bot
    #define WIFI_SSID       "[My WIFI]"
    #define WIFI_PASSWORD   "[WiFi Password]"

    #define LEDS_PIN        2
    #define LEDS_NUMPIXELS  8
    #define WORD_SEPERATORS "., \"'()[]<>;:-+&?!\n\t"

    ESP8266WiFiMulti WiFiMulti;
    WebSocketsClient webSocket;

    Adafruit_NeoPixel pixels(LEDS_NUMPIXELS, LEDS_PIN, NEO_GRB + NEO_KHZ800);

    long nextCmdId = 1;
    bool connected = false;

    /**
      Sends a ping message to Slack. Call this function immediately after establishing
      the WebSocket connection, and then every 5 seconds to keep the connection alive.
    */
    void sendPing() {
      DynamicJsonBuffer jsonBuffer;
      JsonObject& root = jsonBuffer.createObject();
      root["type"] = "ping";
      root["id"] = nextCmdId++;
      String json;
      root.printTo(json);
      webSocket.sendTXT(json);
    }

    /**
      Input a value 0 to 255 to get a color value.
      The colors are a transition r - g - b - back to r.
    */
    uint32_t wheel(byte wheelPos) {
      wheelPos = 255 - wheelPos;
      if (wheelPos < 85) {
        return pixels.Color(255 - wheelPos * 3, 0, wheelPos * 3);
      }
      if (wheelPos < 170) {
        wheelPos -= 85;
        return pixels.Color(0, wheelPos * 3, 255 - wheelPos * 3);
      }
      wheelPos -= 170;
      return pixels.Color(wheelPos * 3, 255 - wheelPos * 3, 0);
    }

    /**
      Animate a NeoPixel ring color change.
      Setting `zebra` to true skips every other led.
    */
    void drawColor(uint32_t color, bool zebra) {
      int step = zebra ? 2 : 1;
      for (int i = 0; i < LEDS_NUMPIXELS; i += step) {
        pixels.setPixelColor(i, color);
        pixels.show();
        delay(30 * step);
      }
    }

    /**
      Draws a rainbow :-)
    */
    void drawRainbow(bool zebra) {
      int step = zebra ? 2 : 1;
      for (int i = 0; i < LEDS_NUMPIXELS; i += step) {
        pixels.setPixelColor(i, wheel(i * 256 / LEDS_NUMPIXELS));
        pixels.show();
        delay(30 * step);
      }
    }

    /**
      Looks for color names in the incoming slack messages and
      animates the ring accordingly. You can include several
      colors in a single message, e.g. `red blue zebra black yellow rainbow`
    */
    void processSlackMessage(char *payload) {
      char *nextWord = NULL;
      bool zebra = false;
      for (nextWord = strtok(payload, WORD_SEPERATORS); nextWord; nextWord = strtok(NULL, WORD_SEPERATORS)) {
        if (strcasecmp(nextWord, "zebra") == 0) {
          zebra = true;
        }
        if (strcasecmp(nextWord, "red") == 0) {
          drawColor(pixels.Color(255, 0, 0), zebra);
        }
        if (strcasecmp(nextWord, "green") == 0) {
          drawColor(pixels.Color(0, 255, 0), zebra);
        }
        if (strcasecmp(nextWord, "blue") == 0) {
          drawColor(pixels.Color(0, 0, 255), zebra);
        }
        if (strcasecmp(nextWord, "yellow") == 0) {
          drawColor(pixels.Color(255, 160, 0), zebra);
        }
        if (strcasecmp(nextWord, "white") == 0) {
          drawColor(pixels.Color(255, 255, 255), zebra);
        }
        if (strcasecmp(nextWord, "purple") == 0) {
          drawColor(pixels.Color(128, 0, 128), zebra);
        }
        if (strcasecmp(nextWord, "pink") == 0) {
          drawColor(pixels.Color(255, 0, 96), zebra);
        }
        if (strcasecmp(nextWord, "orange") == 0) {
          drawColor(pixels.Color(255, 64, 0), zebra);
        }
        if (strcasecmp(nextWord, "black") == 0) {
          drawColor(pixels.Color(0, 0, 0), zebra);
        }
        if (strcasecmp(nextWord, "rainbow") == 0) {
          drawRainbow(zebra);
        }
        if (nextWord[0] == '#') {
          int color = strtol(&nextWord[1], NULL, 16);
          Serial.println("Color");
          Serial.print(color);
          if (color) {
            drawColor(color, zebra);
          }
        }
      }
    }

    /**
      Called on each web socket event. Handles disconnection, and also
      incoming messages from slack.
    */
    void webSocketEvent(WStype_t type, uint8_t *payload, size_t len) {
      switch (type) {
        case WStype_DISCONNECTED:
          Serial.printf("[WebSocket] Disconnected :-( \n");
          connected = false;
          break;

        case WStype_CONNECTED:
          Serial.printf("[WebSocket] Connected to: %s\n", payload);
          sendPing();
          break;

        case WStype_TEXT:
          Serial.printf("[WebSocket] Message: %s\n", payload);
          processSlackMessage((char*)payload);
          break;
      }
    }

    /**
      Establishes a bot connection to Slack:
      1. Performs a REST call to get the WebSocket URL
      2. Conencts the WebSocket
      Returns true if the connection was established successfully.
    */
    bool connectToSlack() {
      // Step 1: Find WebSocket address via RTM API (https://api.slack.com/methods/rtm.start)
      HTTPClient http;

      Serial.printf("Connecting to\n");
      Serial.printf(SLACK_BOT_TOKEN);
      Serial.printf("\n");

      http.begin(SLACK_BOT_TOKEN, SLACK_SSL_FINGERPRINT);
      int httpCode = http.GET();

      if (httpCode != HTTP_CODE_OK) {
        Serial.printf("HTTP GET failed with code %d\n", httpCode);
        return false;
      }

      pixels.setPixelColor(3, pixels.Color(0, 2, 0));
      pixels.show();

      WiFiClient *client = http.getStreamPtr();
      client->find("wss:\\/\\/");
      String host = client->readStringUntil('\\');
      String path = client->readStringUntil('"');
      path.replace("\\/", "/");

      // Step 2: Open WebSocket connection and register event handler
      Serial.println("WebSocket Host=" + host + " Path=" + path);
      webSocket.beginSSL(host, 443, path, "", "");
      webSocket.onEvent(webSocketEvent);

      pixels.setPixelColor(4, pixels.Color(0, 2, 0));
      pixels.show();

      return true;
    }

    void setup() {
      Serial.begin(115200);
      Serial.setDebugOutput(true);

      pixels.begin();
      drawColor(pixels.Color(2, 0, 0), false);

      pixels.setPixelColor(0, pixels.Color(0, 2, 0));
      pixels.show();

      WiFiMulti.addAP(WIFI_SSID, WIFI_PASSWORD);
      while (WiFiMulti.run() != WL_CONNECTED) {
        delay(100);
      }

      pixels.setPixelColor(1, pixels.Color(0, 2, 0));
      pixels.show();

      configTime(3 * 3600, 0, "pool.ntp.org", "time.nist.gov");

      pixels.setPixelColor(2, pixels.Color(0, 2, 0));
      pixels.show();
    }

    unsigned long lastPing = 0;

    /**
      Sends a ping every 5 seconds, and handles reconnections
    */
    void loop() {
      webSocket.loop();

      if (connected) {
        // Send ping every 5 seconds, to keep the connection alive
        if (millis() - lastPing > 5000) {
          sendPing();
          lastPing = millis();
        }
      } else {
        // Try to connect / reconnect to slack
        connected = connectToSlack();
        if (!connected) {
          delay(500);
        }
      }
    }

  [1]: https://github.com/urish/arduino-slack-bot
  [2]: https://www.adafruit.com/product/2821

body:
@mach @Axel

I replaced use `rtm.start` with `rtm.connect` as per April 2017 Slack Recent Updates https://api.slack.com/changelog
and this got rid of the error on my Wemos.

    http.begin("https://slack.com/api/rtm.connect?token=" + SLACK_BOT_TOKEN, SLACK_SSL_FINGERPRINT);


message:
Can regular Arduino pins be used during SPI?

I have a circuit in which I'm using an Arduino Pro Mini to interface with an RF69 radio via SPI. The SCK pin on the Pro Mini is pin 13, which also happens to be the LED pin. Is it possible to write pin 13 high and low in the same sketch that I'm interfacing with the radio? I don't need to do SPI communication simultaneously with the LED. I can put the radio to sleep then use the LED. I'm wondering if this will some how mess up the SPI communication or if everything will be OK.

body:
I did not check the datasheet of the RF69, but it is customary for SPI devices to have a “slave select” input pin. When such a device is _not_ selected, it will leave its MISO pin in high impedance and completely ignore whatever may happen on the MOSI and SCK pins. This effectively disconnects the device from the SPI bus. In this situation you show be able to play with the LED without disturbing the device.

Beware that the slave select pin is usually active low: write it to `HIGH` to _deselect_ the device.


message:
USB and Arduino: Power Arduino, charge LiPo, and transfer data at the same time

I was hoping to design my own Arduino board for a recent project of mine, a portable project that was powered by a 3.7 LiPo battery. Most ideally, I wanted to replace the USB B port with a single USB Micro port that implements the following features:

1. Provides power to the Arduino while it is plugged in (just like a regular Arduino does).
2. Connect the D+ and D- pins of the USB to the Arduino somehow to allow for on-board programming (however the Arduino accomplishes this already, I'll refer to this as the "onboard usb/serial converter"). I want it to keep it programmable on-the-go.
3. Charges an on-board 3.7V LiPo Battery. I was hoping to use [Adafruit's PowerBoost 500 Shield][1] as a reference for my schematic.

However, I haven't been able to find a schematic or example that implements **all 3 features** above at the same time **from the same USB port**. I don't have much experience with charging circuits, so the following questions might sound dumb. Below are some solutions I was thinking of that probably won't work, but I wanted to make sure:

1. Connect the Output Voltage of the LiPo Battery to the V+/GND supply of the USB cable (probably not safe to connect all V+ sources together).
2. Just connect the D+/- data cables to the "onboard usb/serial converter" without connecting the Vbat/Vusb somehow, have the USB V+/GND connect to the LiPo charging circuit, and the Battery Voltage power the Arduino.

I know some devices have this charging/data-transfer functionality (e.g. my phone can transfer photos to my computer while being powered on and charging at the same time), but I'm wondering how it's possible to have similar functionality for an Arduino board. Any advice?

Absolute worst case, I'll just have 2 USB ports, one for charging the LiPo and one for Serial Communication/Programming

**EDIT:** The idea of using an ATMega32U4 seems appealing (despite the 3.3V vs 5V operating voltage), mainly because it has a pin for VBUS for USB and Vcc for main power. But I was wondering how to do this on say an ATMega328P that doesn't have a pin for VBUS.

  [1]: https://www.adafruit.com/product/2078

body:
I'd recommend using the Arduino Leonardo as a reference for your circuit. Its pretty much the same as an Arduino UNO but has a built in USB interface so you don't need the USB-Serial converter.

I'd also recommend running the chip at 3.3V. That way you can use a linear regulator to regulate the 3.7V battery voltage down. Otherwise you'd need a boost converter to bump the voltage up to 5V which needs more parts.

If you follow those recommendations then all you will need is a LiPo charging IC to handle the charging. You'll need to add an ISCP header to flash the initial Leonardo bootloader, but after that you can use USB and the Arduino IDE to program it.

I did exactly this for a school project a while back. You can find the schematics here: https://github.com/seanwatson/ece4416-project/blob/master/hardware/rev2/sw-4416-project-v2-sch.pdf


body:
Following on from Sean Watson's answer, I would probably use the Bare Conductive Touch Board as your reference. It's a Leonardo derivative with all the features you're asking for. Full disclosure - I work at Bare Conductive and worked on the design of the board.

Eagle schematic and board file are [here][1]. Also, since this board successfully passed CE and FCC radiated emissions and immunity testing, you know that the reference design is sound for this if you want to create a product to sell.

The design uses a boost converter to allow for 5V operation - if you run the Atmega32u4 (or Atmega328) at 3.3V, you don't get guaranteed correct operation with a 16 MHz clock (check the data sheet). Since the Arduino bootloader for the Leonardo is written for a 16 MHz clocked MCU, this saves you the task of modifying the bootloader - and gives you the full 16 MIPS maximum performance.

  [1]: https://github.com/BareConductive/touch-board-ks-edition


body:
Use a TP4056 1A LiPo charger board (it has overdischarge protection) and a boost converter, like the XL6009. It will run you at most 5$ if you are prudent. Overdischarge protection is important.

If you want a port for programming, add a micro-USB breakout board, and if necessary a pushbutton for bringing RST down to GND. I prefer just having GND, TX, RX pins on a 3 pin header, and plugging my cable into that.


message:
Compiling code via terminal

How can I compile my code via terminal? I am working on a Chrome app that allows you to write, compile, and upload code to an Arduino, and I need to know this so I can use the command line compiler on my Linux server. Mac or Linux terminal, it doesn't matter.

body: Check out platformio.org it's the best solution out there for command line compiling.


body:
Assuming an AVR-based Arduino, you would need the avr-gcc compiler, the
avr-libc and the Arduino libraries. Also avrdude if you want to upload.
The only issue is that the commands used for the build process are quite
long (lots of options). You can see them by enabling verbose compilation
in the IDE. Thus you will probably want some way to automate the whole
thing.

There are several options for this. The most straightforward seems to be
the [arduino-builder][] command-line tool. This is part of the Arduino
project and should ensure maximum compatibility. Otherwise you could use
a plain old Makefile. I personally use [Sudar Muthu' Makefile][]. It can
be installed on a Debian-based Linux distribution by:

    sudo apt install arduino-mk

It is not fully compatible with the classic Arduino build process
though: it _does_ automatically include `<Arduino.h>` into your sketch,
but it does _not_ add forward declarations. Some prefer it this way, as
the automatic inclusion of forward declarations is somewhat buggy and
does not play well with some C++ features.

[arduino-builder]: https://github.com/arduino/arduino-builder
[Sudar Muthu' Makefile]: https://github.com/sudar/Arduino-Makefile


body:
There is an Arduino CLI (command line interface):

https://github.com/arduino/arduino-cli

You use commands such as to access Arduino IDE functions:

`arduino-cli compile --fqbn arduino:avr:leonardo sketch`

and

`arduino-cli upload -pCOM14 --fqbn arduino:avr:leonardo sketch`

(obviously port will be different under Linux)


message:
Can the Arduino be hurt by connecting too many LEDs in serial?

Today I learned about Vf for leds, after founding out that 3 leds in series driven by 5 V did not make them light up while 2 did.

However, I also read that it is quite bad for a power source to use more volts (like 3 times 2V) this way than the power source (5V for the Uno).

Can the Arduino be hurt this way?

body:
The forward voltage of an LED or diode is the *applied* voltage of the "knee" in the exponential characteristic at which it starts to substantially conduct, and in the case of an LED, produce light.

It is not, under ordinary circumstances of indicator-type LEDs, a voltage that would be produced internally to the LEDs, at least not with any substantial current capability.

As long as you are supplying the LEDs from a voltage within the Arduino's I/O range, it should not be hurt by a series strings of *too many* LEDs.  However, in theory (if rarely in practice) a series string of *too few* LEDs that did not include a `current limiting resistor` would stress the Arduino beyond its ratings - and possibly (and more commonly) also the LED(s) beyond their current limits.


body:
Placing 3 "typical" LEDs in series and then driving them with the Arduino will not produce any light because the Arduino can only output 5V on any pin.  It would require approx 6 volts to drive current through the LEDs when connected in series.  This is for typical green, yellow, red type LEDs that have a 2 volt or so forward voltage drop. Note: some other colors require more forward voltage.

When you place two of these LEDs in series the forward voltage drop required to light them is only about 4 volts, that's why they light up when 3 in series didn't.  However, since the Arduino outputs 5 volts on its pin and the LEDs only require 4 volts the extra 1 volt can cause more current to flow which, if excessive, can damage the output pin.  Thats why when driving LEDs in this way its usually a good practice to place a current limiting resistor in series with the LED(s).  This resistor limits the current induced by any driving voltage which is over the voltage needed to drive the LEDs to conduction.


message:
Wiring BMP280 to Arduino Uno

I bought a BMP280 and it looks like this:

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

How can I connect BMP280 to Arduino Uno?
I tried the following examples on the web, but they didn't work.
I used  [this library][2], connecting the PINS in this way:

    VCC  ->  3.3V
    GND  ->  GND
    SCL  -> 13
    SDA  -> 12
    SDO  -> 11

But the sensor did not initialize.

  [1]: https://i.stack.imgur.com/c0zuX.jpg
  [2]: https://github.com/adafruit/Adafruit_Sensor

body:
Eventually [as reported here][1], it worked using this pinout:

    VCC --> 3.3V
    GND --> GND
    SCK --> A5
    SDI --> A4

And this code:

    #include <Wire.h>

    #define BME280_ADDRESS 0x76
    unsigned long int hum_raw,temp_raw,pres_raw;
    signed long int t_fine;

    uint16_t dig_T1;
     int16_t dig_T2;
     int16_t dig_T3;
    uint16_t dig_P1;
     int16_t dig_P2;
     int16_t dig_P3;
     int16_t dig_P4;
     int16_t dig_P5;
     int16_t dig_P6;
     int16_t dig_P7;
     int16_t dig_P8;
     int16_t dig_P9;
     int8_t  dig_H1;
     int16_t dig_H2;
     int8_t  dig_H3;
     int16_t dig_H4;
     int16_t dig_H5;
     int8_t  dig_H6;

    void setup()
    {
        uint8_t osrs_t = 1;             //Temperature oversampling x 1
        uint8_t osrs_p = 1;             //Pressure oversampling x 1
        uint8_t osrs_h = 1;             //Humidity oversampling x 1
        uint8_t mode = 3;               //Normal mode
        uint8_t t_sb = 5;               //Tstandby 1000ms
        uint8_t filter = 0;             //Filter off
        uint8_t spi3w_en = 0;           //3-wire SPI Disable

        uint8_t ctrl_meas_reg = (osrs_t << 5) | (osrs_p << 2) | mode;
        uint8_t config_reg    = (t_sb << 5) | (filter << 2) | spi3w_en;
        uint8_t ctrl_hum_reg  = osrs_h;

        Serial.begin(9600);
        Wire.begin();

        writeReg(0xF2,ctrl_hum_reg);
        writeReg(0xF4,ctrl_meas_reg);
        writeReg(0xF5,config_reg);
        readTrim();                    //
    }

    void loop()
    {
        double temp_act = 0.0, press_act = 0.0,hum_act=0.0;
        signed long int temp_cal;
        unsigned long int press_cal,hum_cal;

        readData();

        temp_cal = calibration_T(temp_raw);
        press_cal = calibration_P(pres_raw);
        hum_cal = calibration_H(hum_raw);
        temp_act = (double)temp_cal / 100.0;
        press_act = (double)press_cal / 100.0;
        hum_act = (double)hum_cal / 1024.0;
        Serial.print("TEMP : ");
        Serial.print(temp_act);
        Serial.print(" DegC  PRESS : ");
        Serial.print(press_act);
        Serial.print(" hPa  HUM : ");
        Serial.print(hum_act);
        Serial.println(" %");

        delay(1000);
    }
    void readTrim()
    {
        uint8_t data[32],i=0;                      // Fix 2014/04/06
        Wire.beginTransmission(BME280_ADDRESS);
        Wire.write(0x88);
        Wire.endTransmission();
        Wire.requestFrom(BME280_ADDRESS,24);       // Fix 2014/04/06
        while(Wire.available()){
            data[i] = Wire.read();
            i++;
        }

        Wire.beginTransmission(BME280_ADDRESS);    // Add 2014/04/06
        Wire.write(0xA1);                          // Add 2014/04/06
        Wire.endTransmission();                    // Add 2014/04/06
        Wire.requestFrom(BME280_ADDRESS,1);        // Add 2014/04/06
        data[i] = Wire.read();                     // Add 2014/04/06
        i++;                                       // Add 2014/04/06

        Wire.beginTransmission(BME280_ADDRESS);
        Wire.write(0xE1);
        Wire.endTransmission();
        Wire.requestFrom(BME280_ADDRESS,7);        // Fix 2014/04/06
        while(Wire.available()){
            data[i] = Wire.read();
            i++;
        }
        dig_T1 = (data[1] << 8) | data[0];
        dig_T2 = (data[3] << 8) | data[2];
        dig_T3 = (data[5] << 8) | data[4];
        dig_P1 = (data[7] << 8) | data[6];
        dig_P2 = (data[9] << 8) | data[8];
        dig_P3 = (data[11]<< 8) | data[10];
        dig_P4 = (data[13]<< 8) | data[12];
        dig_P5 = (data[15]<< 8) | data[14];
        dig_P6 = (data[17]<< 8) | data[16];
        dig_P7 = (data[19]<< 8) | data[18];
        dig_P8 = (data[21]<< 8) | data[20];
        dig_P9 = (data[23]<< 8) | data[22];
        dig_H1 = data[24];
        dig_H2 = (data[26]<< 8) | data[25];
        dig_H3 = data[27];
        dig_H4 = (data[28]<< 4) | (0x0F & data[29]);
        dig_H5 = (data[30] << 4) | ((data[29] >> 4) & 0x0F); // Fix 2014/04/06
        dig_H6 = data[31];                                   // Fix 2014/04/06
    }
    void writeReg(uint8_t reg_address, uint8_t data)
    {
        Wire.beginTransmission(BME280_ADDRESS);
        Wire.write(reg_address);
        Wire.write(data);
        Wire.endTransmission();
    }

    void readData()
    {
        int i = 0;
        uint32_t data[8];
        Wire.beginTransmission(BME280_ADDRESS);
        Wire.write(0xF7);
        Wire.endTransmission();
        Wire.requestFrom(BME280_ADDRESS,8);
        while(Wire.available()){
            data[i] = Wire.read();
            i++;
        }
        pres_raw = (data[0] << 12) | (data[1] << 4) | (data[2] >> 4);
        temp_raw = (data[3] << 12) | (data[4] << 4) | (data[5] >> 4);
        hum_raw  = (data[6] << 8) | data[7];
    }

    signed long int calibration_T(signed long int adc_T)
    {

        signed long int var1, var2, T;
        var1 = ((((adc_T >> 3) - ((signed long int)dig_T1<<1))) * ((signed long int)dig_T2)) >> 11;
        var2 = (((((adc_T >> 4) - ((signed long int)dig_T1)) * ((adc_T>>4) - ((signed long int)dig_T1))) >> 12) * ((signed long int)dig_T3)) >> 14;

        t_fine = var1 + var2;
        T = (t_fine * 5 + 128) >> 8;
        return T;
    }

    unsigned long int calibration_P(signed long int adc_P)
    {
        signed long int var1, var2;
        unsigned long int P;
        var1 = (((signed long int)t_fine)>>1) - (signed long int)64000;
        var2 = (((var1>>2) * (var1>>2)) >> 11) * ((signed long int)dig_P6);
        var2 = var2 + ((var1*((signed long int)dig_P5))<<1);
        var2 = (var2>>2)+(((signed long int)dig_P4)<<16);
        var1 = (((dig_P3 * (((var1>>2)*(var1>>2)) >> 13)) >>3) + ((((signed long int)dig_P2) * var1)>>1))>>18;
        var1 = ((((32768+var1))*((signed long int)dig_P1))>>15);
        if (var1 == 0)
        {
            return 0;
        }
        P = (((unsigned long int)(((signed long int)1048576)-adc_P)-(var2>>12)))*3125;
        if(P<0x80000000)
        {
           P = (P << 1) / ((unsigned long int) var1);
        }
        else
        {
            P = (P / (unsigned long int)var1) * 2;
        }
        var1 = (((signed long int)dig_P9) * ((signed long int)(((P>>3) * (P>>3))>>13)))>>12;
        var2 = (((signed long int)(P>>2)) * ((signed long int)dig_P8))>>13;
        P = (unsigned long int)((signed long int)P + ((var1 + var2 + dig_P7) >> 4));
        return P;
    }

    unsigned long int calibration_H(signed long int adc_H)
    {
        signed long int v_x1;

        v_x1 = (t_fine - ((signed long int)76800));
        v_x1 = (((((adc_H << 14) -(((signed long int)dig_H4) << 20) - (((signed long int)dig_H5) * v_x1)) +
                  ((signed long int)16384)) >> 15) * (((((((v_x1 * ((signed long int)dig_H6)) >> 10) *
                  (((v_x1 * ((signed long int)dig_H3)) >> 11) + ((signed long int) 32768))) >> 10) + (( signed long int)2097152)) *
                  ((signed long int) dig_H2) + 8192) >> 14));
       v_x1 = (v_x1 - (((((v_x1 >> 15) * (v_x1 >> 15)) >> 7) * ((signed long int)dig_H1)) >> 4));
       v_x1 = (v_x1 < 0 ? 0 : v_x1);
       v_x1 = (v_x1 > 419430400 ? 419430400 : v_x1);
       return (unsigned long int)(v_x1 >> 12);
    }

Actually, BMP280 doesn't monitor relative humidity so you can delete the part related to the humidity control.

    #include <Wire.h>

    #define BME280_ADDRESS 0x76
    unsigned long int temp_raw,pres_raw;
    signed long int t_fine;

    uint16_t dig_T1;
     int16_t dig_T2;
     int16_t dig_T3;
    uint16_t dig_P1;
     int16_t dig_P2;
     int16_t dig_P3;
     int16_t dig_P4;
     int16_t dig_P5;
     int16_t dig_P6;
     int16_t dig_P7;
     int16_t dig_P8;
     int16_t dig_P9;

    void setup()
    {
        uint8_t osrs_t = 1;             //Temperature oversampling x 1
        uint8_t osrs_p = 1;             //Pressure oversampling x 1
        uint8_t mode = 3;               //Normal mode
        uint8_t t_sb = 5;               //Tstandby 1000ms
        uint8_t filter = 0;             //Filter off
        uint8_t spi3w_en = 0;           //3-wire SPI Disable

        uint8_t ctrl_meas_reg = (osrs_t << 5) | (osrs_p << 2) | mode;
        uint8_t config_reg    = (t_sb << 5) | (filter << 2) | spi3w_en;

        Serial.begin(9600);
        Wire.begin();

        writeReg(0xF4,ctrl_meas_reg);
        writeReg(0xF5,config_reg);
        readTrim();                    //
    }

    void loop()
    {
        double temp_act = 0.0, press_act = 0.0;
        signed long int temp_cal;
        unsigned long int press_cal;

        readData();

        temp_cal = calibration_T(temp_raw);
        press_cal = calibration_P(pres_raw);
        temp_act = (double)temp_cal / 100.0;
        press_act = (double)press_cal / 100.0;
        Serial.print("TEMP : ");
        Serial.print(temp_act);
        Serial.print(" DegC  PRESS : ");
        Serial.println(press_act);
        delay(1000);
    }
    void readTrim()
    {
        uint8_t data[32],i=0;                      // Fix 2014/04/06
        Wire.beginTransmission(BME280_ADDRESS);
        Wire.write(0x88);
        Wire.endTransmission();
        Wire.requestFrom(BME280_ADDRESS,24);       // Fix 2014/04/06
        while(Wire.available()){
            data[i] = Wire.read();
            i++;
        }

        Wire.beginTransmission(BME280_ADDRESS);    // Add 2014/04/06
        Wire.write(0xA1);                          // Add 2014/04/06
        Wire.endTransmission();                    // Add 2014/04/06
        Wire.requestFrom(BME280_ADDRESS,1);        // Add 2014/04/06
        data[i] = Wire.read();                     // Add 2014/04/06
        i++;                                       // Add 2014/04/06

        Wire.beginTransmission(BME280_ADDRESS);
        Wire.write(0xE1);
        Wire.endTransmission();
        Wire.requestFrom(BME280_ADDRESS,7);        // Fix 2014/04/06
        while(Wire.available()){
            data[i] = Wire.read();
            i++;
        }
        dig_T1 = (data[1] << 8) | data[0];
        dig_T2 = (data[3] << 8) | data[2];
        dig_T3 = (data[5] << 8) | data[4];
        dig_P1 = (data[7] << 8) | data[6];
        dig_P2 = (data[9] << 8) | data[8];
        dig_P3 = (data[11]<< 8) | data[10];
        dig_P4 = (data[13]<< 8) | data[12];
        dig_P5 = (data[15]<< 8) | data[14];
        dig_P6 = (data[17]<< 8) | data[16];
        dig_P7 = (data[19]<< 8) | data[18];
        dig_P8 = (data[21]<< 8) | data[20];
        dig_P9 = (data[23]<< 8) | data[22];

    }
    void writeReg(uint8_t reg_address, uint8_t data)
    {
        Wire.beginTransmission(BME280_ADDRESS);
        Wire.write(reg_address);
        Wire.write(data);
        Wire.endTransmission();
    }

    void readData()
    {
        int i = 0;
        uint32_t data[8];
        Wire.beginTransmission(BME280_ADDRESS);
        Wire.write(0xF7);
        Wire.endTransmission();
        Wire.requestFrom(BME280_ADDRESS,8);
        while(Wire.available()){
            data[i] = Wire.read();
            i++;
        }
        pres_raw = (data[0] << 12) | (data[1] << 4) | (data[2] >> 4);
        temp_raw = (data[3] << 12) | (data[4] << 4) | (data[5] >> 4);
    }

    signed long int calibration_T(signed long int adc_T)
    {

        signed long int var1, var2, T;
        var1 = ((((adc_T >> 3) - ((signed long int)dig_T1<<1))) * ((signed long int)dig_T2)) >> 11;
        var2 = (((((adc_T >> 4) - ((signed long int)dig_T1)) * ((adc_T>>4) - ((signed long int)dig_T1))) >> 12) * ((signed long int)dig_T3)) >> 14;

        t_fine = var1 + var2;
        T = (t_fine * 5 + 128) >> 8;
        return T;
    }

    unsigned long int calibration_P(signed long int adc_P)
    {
        signed long int var1, var2;
        unsigned long int P;
        var1 = (((signed long int)t_fine)>>1) - (signed long int)64000;
        var2 = (((var1>>2) * (var1>>2)) >> 11) * ((signed long int)dig_P6);
        var2 = var2 + ((var1*((signed long int)dig_P5))<<1);
        var2 = (var2>>2)+(((signed long int)dig_P4)<<16);
        var1 = (((dig_P3 * (((var1>>2)*(var1>>2)) >> 13)) >>3) + ((((signed long int)dig_P2) * var1)>>1))>>18;
        var1 = ((((32768+var1))*((signed long int)dig_P1))>>15);
        if (var1 == 0)
        {
            return 0;
        }
        P = (((unsigned long int)(((signed long int)1048576)-adc_P)-(var2>>12)))*3125;
        if(P<0x80000000)
        {
           P = (P << 1) / ((unsigned long int) var1);
        }
        else
        {
            P = (P / (unsigned long int)var1) * 2;
        }
        var1 = (((signed long int)dig_P9) * ((signed long int)(((P>>3) * (P>>3))>>13)))>>12;
        var2 = (((signed long int)(P>>2)) * ((signed long int)dig_P8))>>13;
        P = (unsigned long int)((signed long int)P + ((var1 + var2 + dig_P7) >> 4));
        return P;
    }

  [1]: https://forum.arduino.cc/index.php?topic=451402.0


body:
The BMP280 is a sensor that can be used at 3.3V, but not at 5V. The datasheet tells that the interface pins may be maximum 3.6V (when the sensor is powered with 3.3V). That means you may not connect the sensor to an Arduino Uno. Not to the SPI interface and not to the I2C interface. The sensor might already be damaged. This is not a joke. When sensor is still working, the results might be noisy or the values could drift too much.

The easiest solution is a level shifter module for I2C. Another option is to add two extra pullup resistors of 10k from SDA to 3.3V and from SCL to 3.3V and connect the SDA and SCL directly to the Arduino Uno. It will not be reliable, but with some luck it will work. You need some luck, because it will not be okay according to the datasheet of the ATmega328P.

You could also buy a 3.3V Arduino board (Arduino Due, Arduino Zero, Arduino M0, and so on), or buy a BMP280 module that is compatible with 3.3V and 5V signals: [Adafruit BMP280][1]

  [1]: https://www.adafruit.com/product/2651


message:
Square wave based on falling edge of alternative pulse of upcoming RPM square wave

In my recent project, I have RPM Square wave from vehicle. Now, based on that I want square wave based on falling edge but only alternative pulse of RPM square wave.

I think below image clear more properly.

[![Pulse][2]][2]

Upper yellowish square wave which I need. And below pinkish square wave is RPM square wave.

I made a code for that and it's working fine but when RPM is stable. But when RPM change rapidly then it's not working fine.

    const int kPinRPM = 3;        // RPM / Digital Pin 3
    const int RPMInterrupt = 1;   // RPM's interrrupt pin
    byte engineCylinders = 2;         // Engine cylinders = 4;
    byte engineCycles = 4;            // Engine cycle = 2
    int refreshInterval = 750;        // Milliseconds between sensor updates
    unsigned long previousMillis = 0;
    volatile int RPMpulses = 0;
    int RPM, Final_RPM;

    const int kPinInj = 12;

    volatile uint32_t kInjTime = 0;

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

      pinMode(kPinRPM, INPUT_PULLUP); // Enable internal pullup
      attachInterrupt(RPMInterrupt, countRPM, FALLING); //Interrupt for RPM

      pinMode(kPinInj, OUTPUT);
    }

    void loop()
    {
      if(millis() - previousMillis > refreshInterval)
      {
        previousMillis = millis();
        RPM =  getRPM();
      }

      Serial.println(RPM);

      if((kInjTime > 0) && ((millis() - kInjTime) >= 10))
      {
        kInjTime = 0;
        digitalWrite(kPinInj, LOW);
      }
    }

    void countRPM()
    {
      RPMpulses++;

      if(RPMpulses % 2 == 0)           // Skip alternative pulse
      {
        kInjTime = millis();
        digitalWrite(kPinInj, HIGH);
      }
    }

    int getRPM()
    {
      Final_RPM = int(RPMpulses * (60000.0 / float(refreshInterval)) * engineCycles / engineCylinders / 2.0);
      RPMpulses = 0;
      Final_RPM = min(99999, Final_RPM);
    }

After SUGGESTION, updating my codes. But it output waveform has some problem. In white circle, you can see that problem.

[![Waveforms][1]][1]

  [1]: https://i.stack.imgur.com/8tEuN.jpg
  [2]: https://i.stack.imgur.com/d3iXZ.jpg

body:
There are some things you shouldn't be doing within an interrupt service routine (ISR) like `countRPM()`:

 1. Don't call the `millis()` function. It depends on other interrupts which will be disabled during the execution of your ISR.

 2. Don't call `digitalWrite` or any other functions

 3. Don't use execution cycles hungry operators like `%` (modulo). To obtain modulo 2, just use a bit mask for the LSB.

What you should actually be doing within the ISR is just setting/resetting a flag or variable. Then, do all your stuff in the `loop()` function according the value of the flag or variable.


body:
Rather than saying

    if(RPMpulses % 2 == 0)           // Skip alternative pulse
      {
        kInjTime = millis();
        digitalWrite(kPinInj, HIGH);
      }

and later setting `kPinInj` in the main loop, you could act as follows:

    digitalWrite(kPinInj, RPMpulses & 1); // Set or clear kPinInj
    if(RPMpulses & 1)
      kInjTime = millis();  // Store alternate times

This would ensure that your trace 1 toggles properly.  If you want a shorter up-time on that trace, you could treat `CHANGE` interrupts rather than `FALLING`, and maintain `RPMpulses` as a number twice as big as now, ie use 120000 instead of 60000 in the RPM calculation, and could say:

    digitalWrite(kPinInj, (RPMpulses & 3)==1); // Set or clear kPinInj
    if((RPMpulses & 3)==1)
      kInjTime = millis();  // Store alternate fall times

Note, the floating point arithmetic in `getRPM()` is slow.  At a 750 ms refresh interval, that may not matter much.  But you probably can get good enough results rather more quickly using just integer arithmetic, if you parenthesize the expression somewhat as follows:

    Final_RPM = ((RPMpulses * (60000UL / 2) * (engineCycles/engineCylinders)) / refreshInterval;

That is, do any remainderless divisions early; multiply all the remaining numerator terms together into a large number; then divide by the comparatively small `refreshInterval`, ending up with numerous significant digits without the use of floating point arithmetic, which takes many milliseconds on typical Arduino systems.

*Edit 2:* If your modified code still says `RPMpulses = 0;` within `getRPM()`, you may get a glitch at the end or beginning of each   refresh interval.  You may instead need to say `RPMpulses = 1;`, or `RPMpulses &= 1;`, or some such.  Also, to avoid an extra count when the latter expression is 1 instead of 0, say `RPM0 = RPMpulses &= 1;` and use `(RPMpulses-RPM0)` instead of `RPMpulses` in calculating `Final_RPM`.


message:
Arduino to read from RS232 converter to TTL serial module (updated)

Here's the system I want to work on:

 1. The weight controller device detects weight which can transfer data via RS232 serial connection
 2. I used [RS232 converter to TTL serial module][1] to connect the weight controller device to Arduino
 3. The TTL connections were made to respective pins of Arduino UNO Board (GND-GND, VCC-5V, RX-0, TX-1)

**The serial print from serial connection should produce 17 character length string : ST,GS    1.58,kg**

Why am I getting strange results at times?
---

    // Read Serial (RS232) data from Weight Controller Device via RS232 to TTL Converter Module

    // Ignore the include statement, the editor does not allow pasting certain characters

    include SoftwareSerial.h

    int RX_PIN = 2;
    int TX_PIN = 3;
    int BAUD_IDE = 9600;
    int BAUD_WEIGHT_SENSOR = 9600;

    // serial port from weight controller
    SoftwareSerial mySerial = SoftwareSerial(RX_PIN, TX_PIN);

    void setup() {
      mySerial.begin(BAUD_WEIGHT_SENSOR);
      Serial.begin(BAUD_IDE);
    }

    void loop() {
      while (mySerial.available()) {
        int inChar = mySerial.read();
        if (inChar != '\n') {
          serialData += (char)inChar;
        }
        else {
          int dataSize = serialData.length();
          Serial.print(serialData);
          Serial.print(" length:  ");
          Serial.print(dataSize);
          Serial.print("\n");
          delay(3000);
          serialData = "";
        }
      }
      serialData = "";

    }

    // this one works perfectly but i want to store as string to
    process
    // information and use for other functions
    /*void loop() {
    if (mySerial.available()){
      Serial.print((char)mySerial.read());

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

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

body: You need to disconnect the Arduino`s RX and TX pins from any device before trying to upload a sketch via USB, because the Serial data is directly wired from the USB chip to these pins. It's as if you're trying to flash the thing behind your RS232 adapter.


body:
You are attempting to talk to your peripheral via a second serial UART implemented in software on arbitrary pins, which should leave the hardware UART free for uploading and debug or other runtime communication between the Arduino and a PC.

However, the "arbitrary pins" you choose to use to connect the peripheral are *the same* pins as used by the hardware UART.

**Move your peripheral to two other pins**, for example

    int RX_PIN = 2;
    int TX_PIN = 3;

and move the connections accordingly

Also consider if you really want `Serial.println()` which will add a line break after every character in the output, and will also print the received characters as their numeric ASCII codes, one per line, rather than printing the characters themselves.  You probably want `Serial.write()`.


message:
Void value not ignored

Why does this throw the error: "void value not ignored as it ought to be

returning = printTemperature(returnLine);"

    void printTemperature(DeviceAddress deviceAddress)
    {
      float tempC = sensors.getTempC(deviceAddress);
      if (tempC == -127.00) {
        Serial.print("Error getting temperature");
      return 0;
      } else {
        return tempC;
      }
    }

    void loop(){

       delay(2000);
       feeding = printTemperature(feedLine);
       returning = printTemperature(returnLine);
     mySql;
     feeding = 0;
     returning = 0;
    }
Both 'feeding' and 'returning' are declared as a float too.

body: printTemperature() is declared void (i.e., nothing returned) but it contains a return statement, and you've attempted to assign the (void) value. You probably meant to declare the function as 'float'.


body:
First of all: In C/C++ world void means "empty" as in "no value".

As the method is declared void it is saying that it does not return a value.
But the code sets the value and also assigns the return value to a variable.
Logically that does not make sense.

In the old days a void method returned an int (I'm not sure whether that is still the case) but it has never been a good idea to make a value returning method a void returning method.
So technically in the old days it made sense but it still was "not a good idea"

Nowadays compilers will return an error when you return a value in a void method. This can be turned off by using the -fpermissive compiler directive.
This directive might be useful in some template cases. I advice not to use it.


message:
analogRead returning 0 constantly when connected to joystick

What reasons could there be for a joystick to return 0 when using analogRead?

X-pin is connected to AO and y-pin is connected to A1.

VCC is connected to 5V and GRND is connected to GRND.

By default (as in when not using the joystick) the value should be approximately 500, right? Well why is the value then 0? Can this only be a wiring issue?

body:
Adding an answer after clarification:-

Moving the joystick also failed to produce a valid reading which indicated a wiring issue or incorrect configuration of the Analog `pin` in the Arduino code.

Proven to be a wiring problem


body:
Follow these steps to identify the problem.

1. Disconnect A0/A1 from Arduino and use a multimeter to check the voltage coming from the joystick X and Y. If it swings from 0 to 5V....the problem is in the Arduino. Check your code and connections. Maybe your wires are damaged?

2. If the voltage is not changing at X and Y pins, disconnect power from the joystick and use a multimeter to check the joystick potentiometer. Check all three terminals in each axis of the joystick. If R is the measured resistance between the two outer pins, then the resistance between the central pin and each of the outer pins should vary from 0 to R depending on the position of the joystick.

3. If there is no problem at all with the joystick readings by potentiometer then the problem has to be on the Arduino side.


message:
How can I alter my program to read PWM signals from Arduino Mega?

I am new to programming and Arduinos but I've decided to give a go for a project. I'm after a code that will read PWM signals from a RC receiver (Specifically aileron and throttle) and output this as 4 PWM signals to drive two H Bridges (Right motor forward/reverse and left motor forward/reverse).

This is my code that isn't working.

    unsigned long timer[3];
    byte last_channel[2];
    int throttle;
    int aileron;

    void setup() {
    pinMode(8, OUTPUT);//Right motor fowards
    pinMode(9, OUTPUT);//Right motor reverse
    pinMode(10, OUTPUT);//left motor fowards
    pinMode(11, OUTPUT);//left motor reverse

    PCICR |= (1 << PCIE0);  //This enables pin change intterupt enabler

    PCMSK0 |= (1 << PCINT0); // This tells the mask register
    which pins will cause an intterupt (Pin 2)

    PCMSK0 |= (1 << PCINT1); // (Pin 3)

    Serial.begin(9600); //Sets the data rate in bits per second
    }

    void loop() {

    }
    ISR(PCINT0_vect) {

    timer[0] = micros(); // registers intterupt time

    //Throttle_Channel----------------------------------------------------------

    if(last_channel[0] == 0 && PINB & B00000001 ) { // This checks if pin has
    changed from low to high

    last_channel[0] = 1;

    timer[1] = timer[0];
    }

    else if(last_channel[0] == 1 && !(PINB & B00000001)){

    last_channel[0] = 0;

    throttle = timer[0] - timer[1]; //calculates the change in time and sets to

    input[0]
    //--------------------------------------------------------------------------
    }
    //Aileron_Channel-----------------------------------------------------------

    if(last_channel[1] == 0 && PINB & B00000010 ) { // This checks if pin has

    changed from low to high

    last_channel[1] = 1;

    timer[2] = timer[0];
    }

    else if(last_channel[0] == 1 && !(PINB & B00000010)){ //This checks if pin  has

    changed from high to low

    last_channel[1] = 0;

    aileron = timer[0] - timer[2]; //calculates the change in time and sets to i

    input[0]
    //--------------------------------------------------------------------------
    }

    //Calculations to put output in correct form--------------------------------
    int throttle_pwm = (throttle - 1500) / 1000;

    int aileron_pwm = (aileron - 1500) / 1000;

    int v = (0.5 - abs(aileron_pwm)) * (throttle_pwm / 0.5) + throttle_pwm;

    int w = (0.5 - abs(throttle_pwm)) * (aileron_pwm / 0.5) + aileron_pwm;

    int lm = v + (w/2) * 255;

    int rm = v - (w/2) * 255;
    //--------------------------------------------------------------------------

    if (lm > 0 && rm > 0){

    analogWrite(8,rm);

    analogWrite(9,0);

    analogWrite(10,lm);

    analogWrite(11,0);
    }

    else if (lm > 0 && rm <= 0){

    analogWrite(8,0);

    analogWrite(9,abs(rm));

    analogWrite(10,lm);

    analogWrite(11,0);
    }

    else if (lm <= 0 && rm > 0){

    analogWrite(8,rm);

    analogWrite(9,0);

    analogWrite(10,0);

    analogWrite(11,abs(lm));

    }

    else if (lm <= 0 && rm <= 0){

    analogWrite(8,0);

    analogWrite(9,abs(rm));

    analogWrite(10,0);

    analogWrite(11,abs(lm));

    //--------------------------------------------------------------------------
    }
    }

It compiles fine but I've tried measure PWM at the four output and it doesn't work. If anyone could offer advice or guidance it would be greatly appreciated.

body:
See [my page about interrupts](http://www.gammon.com.au/interrupts). Data to be shared between an ISR and the main code should be declared `volatile` which yours isn't.

---

Also see:

https://www.arduino.cc/en/Reference/softwareSerial

> Not all pins on the Mega and Mega 2560 support change interrupts, so only the following can be used for RX: 10, 11, 12, 13, 14, 15, 50, 51, 52, 53, A8 (62), A9 (63), A10 (64), A11 (65), A12 (66), A13 (67), A14 (68), A15 (69).

It's not really clear from your post which pins you are using for the encoder, but you mention pins 2 and 3:

>     PCMSK0 |= (1 << PCINT0); // (Pin 2)
>     PCMSK0 |= (1 << PCINT1); // (Pin 3)

Pins 2 and 3 on the board are not PCINT0 and PCINT1. Also they are not in the list of supported pin-change interrupt pins.

You might be better off using **external** interrupts (see my page above). External interrupts are supported on pin 2 and 3. However your code needs to change a bit.


body:
It looks like the code in the ISR is slow and it may compute incorrect results.

It is slow because of using floating point arithmetic in `throttle_pwm` and `aileron_pwm` calculations.  It may be so slow that the trailing edge of a PWM pulse occurs while the leading edge still is being processed.  This will delay trailing edge processing, and mis-measurement of pulse lengths.

The main thing to do to reduce the amount of code executed in the ISR is separate the input measuring phase from the output actuating phase.  You could compute pulse widths and store them in volatile variables for a loop in main to pick up and use in `analogWrite()` statements there.

---

Note, in 16-bit `int` arithmetic, the value of expression `(t-1500)/1000` is 0 for 500 < t < 2500.   Because `throttle` and `aileron` are supposed to be RC pulse lengths in the range 1000 to 2000 μs, your  `throttle_pwm` and `aileron_pwm` will be zero.  That means you can replace the following code,

    int throttle_pwm = (throttle - 1500) / 1000;
    int aileron_pwm = (aileron - 1500) / 1000;
    int v = (0.5 - abs(aileron_pwm)) * (throttle_pwm / 0.5) + throttle_pwm;
    int w = (0.5 - abs(throttle_pwm)) * (aileron_pwm / 0.5) + aileron_pwm;
    int lm = v + (w/2) * 255;
    int rm = v - (w/2) * 255;

with this code:

    int throttle_pwm=0, aileron_pwm=0, v=0, w=0, lm=0, rm=0;

which should save you several milliseconds of computation!  Also, having `lm` and `rm` as constant zeroes means that you don't need all those lengthy and laborious `if` and `else` blocks.   You can replace those 24 lines of stuff with just the following:

    analogWrite(8,0);
    analogWrite(9,0);
    analogWrite(10,0);
    analogWrite(11,0);

---

Slightly more seriously, it looks like you intended for your arithmetic like `(throttle - 1500) / 1000`, etc. to determine whether to raise or lower the throttle, etc.   Instead of doing that time-consuming division, just say:

    int throttle_pwm = throttle > 1500 ? 1 : -1;  // or whatever values you meant to have
    int aileron_pwm = aileron > 1500 ? 1 : -1;    // ditto

Instead of all those 24 lines of stuff, just say:

    analogWrite(8,  (rm>0) * Level);
    analogWrite(9,  (rm<=0)* Level);
    analogWrite(10, (lm>0) * Level);
    analogWrite(11, (lm<=0)* Level);

where `Level` is some level you want to set the control to.  Note, an expression like `(rm>0)` has a value 1 when it is true and and 0 when it is false.  So when `rm>0`, you have, in effect, `analogWrite(8,Level);` and `analogWrite(9,0);`.

If instead you end up with a calculation where `lm` and `rm` are actually usable PWM levels, ie numbers from 0 to 255, you could instead say:

    analogWrite(8,   (rm>0) * rm);
    analogWrite(9,  -(rm<=0)* rm);
    analogWrite(10,  (lm>0) * lm);
    analogWrite(11, -(lm<=0)* lm);

or could say:

    analogWrite(8,  rm>0  ?  rm : 0);
    analogWrite(9,  rm<=0 ? -rm : 0);
    analogWrite(10, lm>0  ?  lm : 0);
    analogWrite(11, lm<=0 ? -lm : 0);

---

Also see [my answer to](https://arduino.stackexchange.com/a/18221/3917) the question  [Read RC receiver channels using Interrupt instead of PulseIn](https://arduino.stackexchange.com/q/18183/read-rc-receiver-channels-using-interrupt-instead-of-pulsein) and see [my answer to](https://arduino.stackexchange.com/a/33707/3917) the question  [Arduino read PWM duty cycle value with input (analog / digital)](https://arduino.stackexchange.com/q/33689/arduino-read-pwm-duty-cycle-value-with-input-analog-digital).


body:
If you are trying to read a PWM signal, you should try using the [pulseIn][1] function, which reads the length of a pulse signal.

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