message:
Why sensor acts erratically?

I am trying to connect an [ADXL355][1] digital sensor to an Arduino. The wiring and the code I think are OK because the system returns the correct values sometimes and partly correct answers mostly. The code checks the device register, and the correct data is printed to serial most of the time. The code also checks for temperature but only returns the correct value occasionally. The values are polled every few seconds. The values are correct all of the time if they are correct the first time after restart but never if they are incorrect on restart. I thought it might help to unplug the sensor when uploading the program or powering up the Arduino through USB to the computer but there is no clear pattern.

It is not a defective sensor because I have 2 that behave the same way. What could be the problem? Is this a problem with the Arduino?

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

I only wire VDD, VDDIO, ground,chip select, sclk, MOSI and MISO.

code:

    #include <SPI.h>

        const int ID = 0x00;
        const int FIFO = 0x11;
        const int TEMP = 0x06;
        const int TEMP1 = 0x07;
        const byte FIFO_WATERMARK = 0x29;
        const int chipSelectPin = 7;

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

            SPI.begin();

            pinMode(dataReadyPin, INPUT);
            pinMode(chipSelectPin, OUTPUT);

            // writing 0 to to enable sensor
            writeRegister(0x2D, 0x00);

            delay(100);

            Serial.println(readRegister(ID));
            Serial.println(readRegister(FIFO_WATERMARK));
        }

        void loop() {
            int temp = (readRegister(TEMP)); // << 8) | (readRegister(TEMP1))) ;
            temp = (temp<<8)|(readRegister(TEMP1));
            Serial.println(((1852 - temp)/9.05) + 19.21);
            Serial.println(readRegister(ID));

            delay(1000);
        }

        byte readRegister (byte thisRegister){
            byte inByte = 0 ;
            SPI.beginTransaction(SPISettings(500000, MSBFIRST, SPI_MODE0)); // 500khz clock
            digitalWrite(chipSelectPin, LOW);
            SPI.transfer((thisRegister << 1) | 1);
            inByte = SPI.transfer(0x00);
            digitalWrite(chipSelectPin, HIGH);
            return inByte;
        }
        void writeRegister (byte thisRegister, byte value){
            SPI.beginTransaction(SPISettings(500000, MSBFIRST, SPI_MODE0)); // 500khz clock
            digitalWrite(chipSelectPin, LOW);
            SPI.transfer(thisRegister << 1);
            SPI.transfer(value);
            digitalWrite(chipSelectPin, HIGH);
        }

Some one suggested it might be signal bounce on the SPI and the clock rate was set to 500kHz but it didn't work.

Update:
Not long ago, the correct device ID would be read consistently (173 for 0xAD); now that returns 0. The temperature would either return 0 from the register or changing values between -1 and -5 that may have been wrongly calibrated temperature. But sometimes the correct temperature would return. Now it also only returns 0 from the registers.

  [1]: http://www.analog.com/media/en/technical-documentation/data-sheets/ADXL354_355.pdf
  [2]: https://i.stack.imgur.com/0gpi1.png

body:
Per your post looks like you have not wired any grounds. Consider wiring Analog and Digital grounds.

[![ADXL355 Grounds][1]][1]

Here are excerpts from the datasheet

[![ADXL355 Ground Pins][2]][2]

  [1]: https://i.stack.imgur.com/1HIg7.jpg
  [2]: https://i.stack.imgur.com/u8I6n.jpg


sender: user

sender: assistant

body:
This is a poor product, look at [this](https://ez.analog.com/mems/f/q-a/109925/adxl355-latch-up-condition): that describes exactly the problems you (and me) are experiencing. Correct me if you've found any solutions so far.

## edit
Try looking at description of regster 0x2f in datasheet and to [this question](https://electronics.stackexchange.com/questions/532331/why-is-the-only-way-to-make-this-device-work-to-manually-unplug-and-re-plug-the/532373#532373).
I think that the first problem you describe can be solved this way, the second behaviour sounds like you fried the device.


message:
I2C MCP4725 DAC connection speed

I'm trying to use the MCP4725 DAC from Adafruit (https://www.adafruit.com/product/935) to output some waveforms over a frequency range up to about 50kHz. At the moment, I'm simply sending values to the DAC via the Wire library and through the DAC's onboard library. It appears that the values are only being sent at 7kHz. Is this due to the added weight of the libraries I'm using? Is there some way I can increase the transmission speed?

body:
You cannot get 50kYz from a DAC running on I2C on an Arduino.

The maximum rate for I2C (if you select fast mode) is 400kbps. Setting the DAC takes three bytes plus start/stop/ack bits (total 29 bits).

At 400kbps that equates to (400000/29) 13793 settings per second.

Add to that the time taken to actually create and process the data, running the instructions to do everything, you can expect about half that - which is the 7kHz you're getting.

To get 50kHz from a DAC you really need a CODEC and run something like I2S, which you are never going to do on an Arduino.


message:
Better cycling through the RGB colors

I have been trying to achieve a way to tap into the 16 million colors RGB provides for this LED strip. I thought of using `LEDS.setBrightness();` but I have not been successful in my attempts. I have read [the documentation on color fading][1], but I have not been able to write this to my Arduino Leonardo. Here is my code below, which cycles through the initial rainbow of 0-255. I was wondering how to get more than 0-255 if not all the colors.

    #include <FastLED.h>

    #define LED_COUNT 60
    #define LED_OUT       13
    #define BUTTON_IN     10
    #define ANALOG_INPUT  A9
    #define EXTRA_PIN_A    7
    #define EXTRA_PIN_B   11

    struct CRGB leds[LED_COUNT];
    int wait_time = 5;

    void setup() {
      Serial.begin(57600);
      LEDS.addLeds<WS2812B, LED_OUT, GRB>(leds, LED_COUNT);
      LEDS.show();
    }

    void loop() {
      //start from red
      for(int colorStep=0; colorStep <= 255; colorStep++) {
        int r = 255;
        int g = 0;
        int b = colorStep;
        // Now loop though each of the LEDs and set each one to the current color
        for(int x = 0; x < LED_COUNT; x++) {
          leds[x] = CRGB(r,g,b);
        }
        // Display the colors we just set on the actual LEDs
        delay(wait_time);
        LEDS.show();
      }

      //into blue
      for(int colorStep=255; colorStep >= 0; colorStep--) {
        int r = colorStep;
        int g = 0;
        int b = 255;
        // Now loop though each of the LEDs and set each one to the current color
        for(int x = 0; x < LED_COUNT; x++) {
          leds[x] = CRGB(r,g,b);
        }
        // Display the colors we just set on the actual LEDs
        delay(wait_time);
        LEDS.show();
      }
      //start from blue
      for(int colorStep=0; colorStep <= 255; colorStep++) {
        int r = 0;
        int g = colorStep;
        int b = 255;
        // Now loop though each of the LEDs and set each one to the current color
        for(int x = 0; x < LED_COUNT; x++) {
          leds[x] = CRGB(r,g,b);
        }
        // Display the colors we just set on the actual LEDs
        delay(wait_time);
        LEDS.show();
      }
      //into green
      for(int colorStep=255; colorStep >= 0; colorStep--) {
        int r = 0;
        int g = 255;
        int b = colorStep;
        // Now loop though each of the LEDs and set each one to the current color
        for(int x = 0; x < LED_COUNT; x++) {
          leds[x] = CRGB(r,g,b);
        }
        // Display the colors we just set on the actual LEDs
        delay(wait_time);
        LEDS.show();
      }
      //start from green
      for(int colorStep=0; colorStep <= 255; colorStep++) {
        int r = colorStep;
        int g = 255;
        int b = 0;
        // Now loop though each of the LEDs and set each one to the current color
        for(int x = 0; x < LED_COUNT; x++) {
          leds[x] = CRGB(r,g,b);
        }
        // Display the colors we just set on the actual LEDs
        delay(wait_time);
        LEDS.show();
      }
      //into yellow
      for(int colorStep=255; colorStep >= 0; colorStep--) {
        int r = 255;
        int g = colorStep;
        int b = 0;
        // Now loop though each of the LEDs and set each one to the current color
        for(int x = 0; x < LED_COUNT; x++) {
          leds[x] = CRGB(r,g,b);
        }
        // Display the colors we just set on the actual LEDs
        delay(wait_time);
        LEDS.show();
      }
    } //end main loop

  [1]: https://www.arduino.cc/en/Tutorial/ColorCrossfader

body:
If you want to display every one of the about 16 million possible colours, you will have to nest your for loops like in this example:

    x = 1 ;  // only for testing
    for ( int redx = 0 ; redx <= 255 ; redx ++ ) {
        for ( int greenx = 0 ; greenx <= 255 ; greenx ++ ) {
            for ( int bluex = 0 ; bluex <= 255 ; bluex ++ ) {
                 leds[ x ] = CRGB(redx,greenx,bluex);
                 delay(wait_time);
                 LEDS.show();
            }
        }
    }


body:
You should consider making it non-blocking :)

    loop(){
       //if(millis() > previous+100){//uncomment this part to only do a step of the rainbow effect every 100ms
       rainbowEffect();
       //previous = millis();
       //}

       //you can do other stuff, like check a buttons' state here.
       //using the same structure as above, you can choose to give it a higher or lower priority.
    }

    unsigned char r,g,b;
    void rainbowEffect(){
       if(r>254){
          r=0;
          g++;
       }
       if(g>254){
          g=0;
          b++;
       }
       if(b>254){
          b=0;
       }
       r++;
       ledStrip.set(r,g,b);
    }


body:
I've included a simple sketch that will cycle a single RGB led using the sine fade technique

    // Cycle a single RGB led using the sine fade technique
    // For common cathode led

    const uint8_t lights[360]={
      0, 0, 0, 0, 0, 1, 1, 2, 2, 3, 4, 5, 6, 7, 8, 9, 11, 12, 13, 15, 17, 18, 20, 22, 24, 26, 28, 30, 32, 35, 37, 39,
     42, 44, 47, 49, 52, 55, 58, 60, 63, 66, 69, 72, 75, 78, 81, 85, 88, 91, 94, 97, 101, 104, 107, 111, 114, 117, 121, 124, 127, 131, 134, 137,
    141, 144, 147, 150, 154, 157, 160, 163, 167, 170, 173, 176, 179, 182, 185, 188, 191, 194, 197, 200, 202, 205, 208, 210, 213, 215, 217, 220, 222, 224, 226, 229,
    231, 232, 234, 236, 238, 239, 241, 242, 244, 245, 246, 248, 249, 250, 251, 251, 252, 253, 253, 254, 254, 255, 255, 255, 255, 255, 255, 255, 254, 254, 253, 253,
    252, 251, 251, 250, 249, 248, 246, 245, 244, 242, 241, 239, 238, 236, 234, 232, 231, 229, 226, 224, 222, 220, 217, 215, 213, 210, 208, 205, 202, 200, 197, 194,
    191, 188, 185, 182, 179, 176, 173, 170, 167, 163, 160, 157, 154, 150, 147, 144, 141, 137, 134, 131, 127, 124, 121, 117, 114, 111, 107, 104, 101, 97, 94, 91,
     88, 85, 81, 78, 75, 72, 69, 66, 63, 60, 58, 55, 52, 49, 47, 44, 42, 39, 37, 35, 32, 30, 28, 26, 24, 22, 20, 18, 17, 15, 13, 12,
     11, 9, 8, 7, 6, 5, 4, 3, 2, 2, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
      0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
      0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
      0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};

    const byte redpin = 3;
    const byte greenpin = 5;
    const byte bluepin = 6;
    int loopdelay = 5000; // ms
    int displaylength = 50; // ms

    boolean showiterations = false;

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

    void loop() {
    for (int k=0; k<360; k++)
    {
        if (showiterations) {
        Serial.print(k);
        Serial.print(F(","));
        }
    analogWrite(redpin, lights[(k+120)60]);
    analogWrite(greenpin, lights[k]);
    analogWrite(bluepin, lights[(k+240)60]);
    delay(displaylength);
    }
    if (showiterations) {
    Serial.println("  ");
    }
    delay(loopdelay);
    }

This sketch is derived from an Instructables posting entitled "How to Make Proper Rainbow and Random Colors With the RGB Color Model", http://www.instructables.com/id/How-to-Make-Proper-Rainbow-and-Random-Colors-With-/
It additionally provides information and rationale behind different techniques for cycling colours.

____________________________________________

If you are trying to stagger the colours along the strip whilst creating a rainbow effect,  I have another sketch [from Adafruit, I believe] that will do this.  I've used it effectively with different Neopixel ring configurations.  The sketch demonstrates a number of different techniques. I have currently commented out the invocations of all but the theaterChaseRainbow, but you may wish to explore them all.

    #include <Adafruit_NeoPixel.h>
    // following atatement should be wrapped with an ifdef for __AVR__, but this facility botches it up.
    // As it is, formatting for the sketch is not quite right, and I do not have a solution for that.
      #include <avr/power.h>

    const  byte PIN = 7;

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

    // IMPORTANT: To reduce NeoPixel burnout risk, add 1000 uF capacitor across
    // pixel power leads, add 300 - 500 Ohm resistor on first pixel's data input
    // and minimize distance between Arduino and first pixel.  Avoid connecting
    // on a live circuit...if you must, connect GND first.

    void setup() {
      // This is for Trinket 5V 16MHz, you can remove these three lines if you are not using a Trinket
      #if defined (__AVR_ATtiny85__)
        if (F_CPU == 16000000) clock_prescale_set(clock_div_1);
      #endif
      // End of trinket special code

      strip.begin();
       colorWipe(strip.Color(0, 0, 0), 50); // blank
      strip.show(); // Initialize all pixels to 'off'
    }

    void loop() {
      // Some example procedures showing how to display to the pixels:
    //  colorWipe(strip.Color(255, 0, 0), 50); // Red
    //  colorWipe(strip.Color(0, 255, 0), 50); // Green
    //  colorWipe(strip.Color(0, 0, 255), 50); // Blue
    //colorWipe(strip.Color(0, 0, 0, 255), 50); // White RGBW
      // Send a theater pixel chase in...
    //  theaterChase(strip.Color(127, 127, 127), 50); // White
    //  theaterChase(strip.Color(127, 0, 0), 50); // Red
    //  theaterChase(strip.Color(0, 0, 127), 50); // Blue

    //  rainbow(20);
    //  delay(50000);
    //  colorWipe(strip.Color(0, 0, 0), 50); // blank
    //  rainbowCycle(10);
    //  delay(5000);
    //    colorWipe(strip.Color(0, 0, 0), 50); // blank
    //   delay(5000);
      theaterChaseRainbow(50);
    //  delay(5000);
    //    colorWipe(strip.Color(0, 0, 0), 50); // blank
    //   delay(5000);
    }

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

    void rainbow(uint8_t wait) {
      uint16_t i, j;

      for(j=0; j<256; j++) {
        for(i=0; i<strip.numPixels(); i++) {
          strip.setPixelColor(i, Wheel((i+j) & 255));
        }
        strip.show();
        delay(wait);
      }
    }

    // Slightly different, this makes the rainbow equally distributed throughout
    void rainbowCycle(uint8_t wait) {
      uint16_t i, j;

      for(j=0; j<256*5; j++) { // 5 cycles of all colors on wheel
        for(i=0; i< strip.numPixels(); i++) {
          strip.setPixelColor(i, Wheel(((i * 256 / strip.numPixels()) + j) & 255));
        }
        strip.show();
        delay(wait);
      }
    }

    //Theatre-style crawling lights.
    void theaterChase(uint32_t c, uint8_t wait) {
      for (int j=0; j<10; j++) {  //do 10 cycles of chasing
        for (int q=0; q < 3; q++) {
          for (uint16_t i=0; i < strip.numPixels(); i=i+3) {
            strip.setPixelColor(i+q, c);    //turn every third pixel on
          }
          strip.show();

          delay(wait);

          for (uint16_t i=0; i < strip.numPixels(); i=i+3) {
            strip.setPixelColor(i+q, 0);        //turn every third pixel off
          }
        }
      }
    }

    //Theatre-style crawling lights with rainbow effect
    void theaterChaseRainbow(uint8_t wait) {
      for (int j=0; j < 256; j++) {     // cycle all 256 colors in the wheel
        for (int q=0; q < 3; q++) {
          for (uint16_t i=0; i < strip.numPixels(); i=i+3) {
            strip.setPixelColor(i+q, Wheel( (i+j) % 255));    //turn every third pixel on
          }
          strip.show();

          delay(wait);

          for (uint16_t i=0; i < strip.numPixels(); i=i+3) {
            strip.setPixelColor(i+q, 0);        //turn every third pixel off
          }
        }
      }
    }

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


body:
I think it's worth noting that the three 255 values for RGB colour space is just one way to encode the 255^3 (16,581,375) colours. These include each and every brightness level too.

If you are trying to get a rainbow effect, you may have more success or find it easier to use a HSL or HSV colour space.

HSV uses Hue, Saturation and Value instead of RGB. FastLED has optimized it's implementation of HSV to use a 0-255 addressing for Hue (instead of 360), keeping it fast for animations run on microcontrollers:

https://github.com/FastLED/FastLED/wiki/FastLED-HSV-Colors


body:
I think @Mazaryk was correct, HSV is the way to go for this.  RGB's 16+ million colors include brightness, and some of them just won't display on the strip, so I found a way to at least better fade thru:

    int thissat = 255;           //- LOOPS DELAY VAR
    int idex = 0;                //-LED INDEX
    int ihue = 0;                //-hue (0-255)

    void rainbow_fade() {
        ihue++;
        if (ihue > 255) {ihue = 0;}
        for(int idex = 0 ; idex < LED_COUNT; idex++ ) {
          leds[idex] = CHSV(ihue, thissat, 255);
        }
        LEDS.show();
        delay(wait_time);
    }


body:
You could take advantage that the rgb color could be represented in a unsigned long. And use a counter.
But have patience looping through 16 mio colors with 1ms at iteration take some time :-). (around 4-5 hours:  16581375/(1000[ms] * 60[m] * 60[h]) = 4,6 )

    void loopThrougAllColors(){
      // The trick here is to use a unsigned long value as the color representation.
      // Each byte represent a color (except the first)
      //          none, R  G  B
      //          0x00 00 00 00
      // Note: static means it is a global variable - but only seen in thisfunction.
      static unsigned long ledColor = 0;
      static int ledIndex = 0;

      ledColor++;
      ledColor &= 0x00FFFFFF; /* Overflow preventing (instead of if sentence checking the boundaries). */

      leds[0] = ledColor;

      FastLED.show();
      FastLED.delay(1);
      //delay(10);
    }


body:
You can make a smooth transition/sliding rainbow effect by using a sine wave lookup table, then phase shifting green and blue by 120 and 240 degrees.

```
#define RED 9
#define GREEN 10
#define BLUE 11

uint8_t sins[360] = {
  127,129,131,134,136,138,140,143,145,147,149,151,154,156,158,160,162,164,166,169,171,173,175,177,179,181,183,185,187,189,191,193,195,196,198,200,
  202,204,205,207,209,211,212,214,216,217,219,220,222,223,225,226,227,229,230,231,233,234,235,236,237,239,240,241,242,243,243,244,245,246,247,248,
  248,249,250,250,251,251,252,252,253,253,253,254,254,254,254,254,254,254,255,254,254,254,254,254,254,254,253,253,253,252,252,251,251,250,250,249,
  248,248,247,246,245,244,243,243,242,241,240,239,237,236,235,234,233,231,230,229,227,226,225,223,222,220,219,217,216,214,212,211,209,207,205,204,
  202,200,198,196,195,193,191,189,187,185,183,181,179,177,175,173,171,169,166,164,162,160,158,156,154,151,149,147,145,143,140,138,136,134,131,129,
  127,125,123,120,118,116,114,111,109,107,105,103,100,98,96,94,92,90,88,85,83,81,79,77,75,73,71,69,67,65,63,61,59,58,56,54,
  52,50,49,47,45,43,42,40,38,37,35,34,32,31,29,28,27,25,24,23,21,20,19,18,17,15,14,13,12,11,11,10,9,8,7,6,
  6,5,4,4,3,3,2,2,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,2,2,3,3,4,4,5,
  6,6,7,8,9,10,11,11,12,13,14,15,17,18,19,20,21,23,24,25,27,28,29,31,32,34,35,37,38,40,42,43,45,47,49,50,
  52,54,56,58,59,61,63,65,67,69,71,73,75,77,79,81,83,85,88,90,92,94,96,98,100,103,105,107,109,111,114,116,118,120,123,125
};

void setup() {
  pinMode(RED, OUTPUT);
  pinMode(GREEN, OUTPUT);
  pinMode(BLUE, OUTPUT);
}

void loop() {
  for (int i = 0; i < 360; ++i)
  {
    analogWrite(RED, sins[i]);
    analogWrite(GREEN, sins[(i+120)60]);
    analogWrite(BLUE, sins[(i+240)60]);
    delay(2);
  }
}
```


message:
HELP with, I think, are wrongly placed Interrupts

I am still struggling to get this sketch functional. The problem seems to lie with the interrupts, and relying on them to turn on and off the PIRtrigger when needed. Everything else seems to be OK. This is a slightly modified sketch from what I had uploaded earlier, with some changes that I thought would fix the problem. In general, a "correct" PIN disables the alarm from firing as it sets the "away" flag to "false", which works. An "incorrect" PIN sets "away" to "true" which, when a trigger is activated via an Interrupt, sounds the alarm. The program should then go to readKeypad for further function, which it appears to do. The following shows the result after an incorrect PIN:

    Key_input[0] = #
    @ checkPIN
    @ incorrect PIN
    away=1 PIRtrigger=0
    at Alarm
    after alarm

The trigger then doesn't seem to get activated. Can anyone HELP!? Thanks.

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

    ///////////////////////// initialize & includes //////////////////////////
    #include "SIM900.h"
    #include "sms.h"
    #include "Keypad.h"
    #include <GSM.h>
    SMSGSM sms;

    //To change pins for Software Serial, use the two lines in GSM.cpp.
    int PIR_SensorPin = 2;
    int LED_OutPin = 11; //green
    int Alarm_OutPin = 12; //red
    int alarm_count;
    volatile boolean PIRtrigger = false;
    boolean away = false;
    const byte interruptPin = 2;
    int z = 0;
    int i = 0;
    int timeout = 10000;
    unsigned long time = millis();

    //////////////////////////// setup keyPad //////////////////////////
    const byte ROWS = 4; //four rows
    const byte COLS = 4; //four columns
    char keys[ROWS][COLS] =
    {
      {
        '1', '2', '3', 'A'
      }
      ,
      {
        '4', '5', '6', 'B'
      }
      ,
      {
        '7', '8', '9', 'C'
      }
      ,
      {
        '*', '0', '#', 'D'
      }
    };
    byte rowPins[ROWS] = {
      6, 7, A2, A3 // row pin# on keypad to Arduino pin#, ie Row Pin #1 goes to Arduino Pin #6, etc.
    }; // connect to the row pinouts of the keypad
    byte colPins[COLS] = {
      3, A0, A1, A4
    }; // connect to the column pinouts of the keypad
    Keypad keypad = Keypad(makeKeymap(keys), rowPins, colPins, ROWS, COLS );
    const char PIN[5] = {
      '9', '6', '7', '9', '#'
    }; // PIN number
    char key_input[5] = {
      0, 0, 0, 0, 0
    }; // used for comparison

    //////////////////////////////// setup ///////////////////////////////////
    void setup() {
      Serial.begin (9600);  // Establish Serial connection;
      pinMode (LED_OutPin, OUTPUT);   // Set pinMode.
      pinMode (Alarm_OutPin, OUTPUT);   // Set pinMode.
      pinMode (PIR_SensorPin, INPUT);   // Set pinMode.
      digitalWrite (LED_OutPin, LOW); // Set output pins to LOW for start.
      digitalWrite (Alarm_OutPin, LOW); // Set output pins to LOW for start.
      digitalWrite (PIR_SensorPin, LOW);
      Serial.println ("Studio Alarm starting up."); // Serial message that GSM shield is starting up
      if (gsm.begin(4800)) {    // Set GSM shield to recommended 4800 baud rate.
        Serial.println ("Status = Network READY");
        digitalWrite (LED_OutPin, HIGH);
      }
      attachInterrupt (digitalPinToInterrupt (2), trigger, HIGH); // PIR as interrupt
      Serial.println ("System Ready");
    }

    //////////////////////////////// void loop ///////////////////////////////////
    void loop()
    {
      interrupts();
      readKeypad(); Serial.println ("at keypad");
      alarm();
    }

    ////////////////////////// void trigger ///////////////////////////////////
    void trigger() {
      PIRtrigger = true;
      // alarm();
    }

    ///////////////////////////// void alarm ///////////////////////////////////
    void alarm() {
    //  PIRtrigger = false;
      time = millis(); // reset time.
      interrupts();
      Serial.print ("away="); Serial.print (away); Serial.print (" "); Serial.print ("PIRtrigger="); Serial.println (PIRtrigger);
      Serial.println ("at Alarm");
      if (away == true && PIRtrigger == true) {
        // (sms.SendSMS("**********", "***Motion Detected in Studio!***"));
        Serial.println ("MOTION detected: SMS Sent");
        for (alarm_count = 0; alarm_count <= 5; alarm_count++) { // Cycle outputs if triggered
          digitalWrite (Alarm_OutPin, HIGH); delay (1000); // On/Off/On/Off/Off
          digitalWrite (Alarm_OutPin, LOW); delay (500);
          digitalWrite (LED_OutPin, HIGH); // delay (1000);
          Serial.println (alarm_count);
        }
      }
      PIRtrigger = false;
      //  away = false;
      Serial.println ("after alarm");
      Serial.print ("away="); Serial.print (away); Serial.print (" "); Serial.print ("PIRtrigger="); Serial.println (PIRtrigger);
      noInterrupts(); /////////////////////////////////
      readKeypad();
    }

    ///////////////////////////// read Keypad ///////////////////////////////////
    void readKeypad() {
      char key = keypad.getKey();
      if (key != NO_KEY) { // if a keypad input
        key_input[z] = key;
        tone(10, 900, 100);
        Serial.print ("Key_input["); Serial.print(z); Serial.print ("] = "); Serial.println(key);
        z++;
        if (z >= sizeof(key_input)) {
          z = 0;
        }
        switch (key) {
          case '*': // resets key_inputs to "0"
            z = 0;
            break;
          case '#': // pressed to "enter"
            z = 0;
            for ( i = 0;   i < 4 ;  i++ ) {
              //        Serial.print(key_input[i]);
            }
            //      Serial.println ("-------");
            delay(100); // for extra de-bounce
            checkPIN();
            break;
        }
      }
    }

    ///////////////////////////// check PIN ///////////////////////////////////
    void checkPIN() {
      Serial.println ("@ checkPIN ");
      int correct = 0;
      int i;
      for ( i = 0;   i < (sizeof(PIN) - 1) ;  i++ ) {
        if (key_input[i] == PIN[i]) {
          correct++;
        }
      }
      if (correct >= sizeof(PIN) - 1) {
        //   Serial.print ("# correct = "); Serial.println (correct); Serial.println (sizeof(PIN) - 1);
        correctPIN();// go to correct PIN instructions
      }
      else {
        incorrectPIN(); // go to incorrect PIN instructions
      }
    }

    ///////////////////////////// correct PIN ///////////////////////////////////
    void correctPIN() {              // do this if correct PIN entered
      Serial.println ("@ correct PIN ");
      // digitalWrite (LED_OutPin, HIGH);
      digitalWrite (LED_OutPin, LOW); // on-board LED to show the status of alarm
      PIRtrigger = false; // turn the PIR state to off
      away = false; // turn the away state to off
      noInterrupts();
      readKeypad();
    }

    ///////////////////////// incorrect PIN ///////////////////////////////////
    void incorrectPIN() {           // do this if incorrect PIN entered
     //  noInterrupts(); // Serial.println ("interrupt off 1");
      Serial.println ("@ incorrect PIN ");
      away = true;
      digitalWrite (LED_OutPin, HIGH); // tied to Alarm output level
      //Has time passed? delay(timeout) - allow time to leave premises
      PIRtrigger = false;
        alarm();
      }

body:
Most [Arduinos][1] don't support interrupting when a pin is HIGH. Try changing `attachInterrupt (digitalPinToInterrupt (2), trigger, HIGH)` to `attachInterrupt (digitalPinToInterrupt (2), trigger, RISING)`.

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


body:
First, as AH L said, there is no HIGH interrupt on a Uno. Looking at Arduino.h we see:

    #define HIGH 0x1
    #define LOW  0x0

    ...

    #define CHANGE 1
    #define FALLING 2
    #define RISING 3

Thus your HIGH interrupt (which doesn't exist) is really a CHANGE interrupt.

Next, you seem to be recursively calling stuff.

* `loop` calls `readKeypad`.
* `readKeypad` calls `checkPIN`
* `checkPIN` calls `correctPIN`
* `correctPIN` calls `readKeypad`

So this code is digging itself deeper and deeper into function calls. It will eventually run out of stack.

i.e.

    readKeypad -> checkPIN -> correctPIN -> readKeypad -> checkPIN ...

You need to restructure.

See [my page about interrupts](http://www.gammon.com.au/interrupts).

Also see [my page about state machines](http://www.gammon.com.au/statemachine).


message:
Easy way to upload sketches using MIDI (without RX pin removed)

I noticed when I use sketches with MIDI (using RX/TX), before uploading I have to remove every time the RX wire ... is there an easy way to prevent this?

(I'm thinking about making a push button/toogle for this to prevent it, but maybe there is an easier way).

Update: I use an Arduino Uno

body:
To allow the bootloader on the Arduino MCU to communicate with the USB chip, the TXD/RXD pins are connected:

![Arduino bootloader serial connections](https://i.stack.imgur.com/vaVbr.png)

These connections have 1 kΩ resistors so that the signals of the USB chip do not interfere with your own hardware too much. However, this means that your own hardware can easily override those signals.

In this case, your MIDI hardware actively drives the RXD line to a high level.

You is no way to work around this in software.
You could try to replace the optocoupler's pull-up resistor (270 Ω) with a 10 kΩ resistor, which would make the USB controller's signals ten times stronger than the MIDI ones, but this might make the signal edges too slow.
To reliably prevent conflicts, you have to add a disable function to the MIDI receiver, or power it down, or disconnect it.


message:
Generating random pattern on startup

I'm trying to get an arduino to generate a random pattern in a neopixel grid every time you restart it. But I only get the same number sequence generated each time. What I'm doing wrong?

Here's the sequence that keeps happening: 1110 0000 1101 0011

Here's the code I have so far:

    /* ========================== INCLUDES ================================= */
    #include "RGB.h"

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

    /* ========================== NEOPIXELS SETTINGS ================================= */
    #define NEOPIN 6
    #define MATRIX_W 4
    #define MATRIX_H 4

    Adafruit_NeoMatrix matrix = Adafruit_NeoMatrix(MATRIX_W, MATRIX_H, NEOPIN,
      NEO_MATRIX_BOTTOM + NEO_MATRIX_LEFT +
      NEO_MATRIX_ROWS + NEO_MATRIX_ZIGZAG,
      NEO_GRB + NEO_KHZ800);

    /* ========================== BOARD / GRID STUFF ================================= */

    /* coordinates for a 4 x 4 grid
    00,10,20,30
    01,11,21,31
    02,12,22,32
    03,13,23,33,
    04,14,24,34
    */

    int land[4][4] = {};

    /* ========================== SETUP AND LOOP ================================= */

    void setup(){

      Serial.begin(9600);

      matrix.begin();
      matrix.setBrightness(60);
      matrix.fillScreen(matrix.Color(off.r,off.g,off.b));
      crossFade(off, white, 50, 5);
      drawLand();
    }

    void loop(){
      matrix.show();
    }

    /* ========================== FUNCTIONS ================================= */

      void drawLand() {
      for(int row = 0; row < MATRIX_W; row++) {
        for(int column = 0; column < MATRIX_H; column++) {

         land[row][column] = random(0,2);

         Serial.println(land[row][column]);
         if(land[row][column] == 1) {
           matrix.drawPixel(column, row, matrix.Color(red.r,red.g,red.b));
         }
       }
      }
    }

body:
It's because an machine running the same program on the same data will calculate the same result. rand() is a _pseudo_-random generator for that reason. With the same starting value it will create the same sequence of numbers. The only way to get different outputs is to provide different inputs: You have to start rand with a different value each run. You can set initialize rand() by supplying an unsigned int to randomSeed(). But it still needs to be different from run to run for you get different outputs from those runs.

Some devices do this by reading a real-time clock on startup and hashing the result in some way. Another method is to ask the user to press a button or a key and using the response time (and possibly the key, if it's a keyboard) to generate the seed. Counting non-repeating events, like electrical noise or background radiation is another way.

But bottom line: you need different inputs to get different outputs.


body:
> randomSeed(analogRead(A0)); does the trick well

Better yet, use the lsb of analogreads to seed the random number generator. No repeat patterns any more.


body: Re: previous comments.  You can use a product, sum, and modulus/LSB of analogRead's to make it unpredictable and give somewhat equally probable outcomes.  The timing of multiple analogRead's could potentially affect the randomness.


message:
Serial not displaying sketch for MPU6050

I followed this tutorial on youtube: https://www.youtube.com/watch?v=M9lZ5Qy5S2s

Where he provided the code below. The problem I'm having is the serial monitor shows nothing. I tried changing the baud to 115200 and still nothing showed up. I'm using an Arduino nano.

Update: I wrote a Serial.print in each function (printing the name of the function), and I found it just printed up to "recordAccelRegisters" then stopped. Then I put a Serial.print after each line in the function, and it prints until the line
`while(Wire.available() < 6);`
Is this a problem with the while function or I2C?

Ok, so I reinstalled Arduino and got this message on the serial print with the I2C test:

"Scanning... I2C device found at address 0x69  ! done."

    #include <Wire.h>

    long accelX, accelY, accelZ;
    float gForceX, gForceY, gForceZ;

    long gyroX, gyroY, gyroZ;
    float rotX, rotY, rotZ;

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

    void loop() {
      recordAccelRegisters();
      recordGyroRegisters();
      printData();
      delay(100);
    }

    void setupMPU(){
      Wire.beginTransmission(0b1101000); //This is the I2C address of the MPU (b1101000/b1101001 for AC0 low/high datasheet sec. 9.2)
      Wire.write(0x6B); //Accessing the register 6B - Power Management (Sec. 4.28)
      Wire.write(0b00000000); //Setting SLEEP register to 0. (Required; see Note on p. 9)
      Wire.endTransmission();
      Wire.beginTransmission(0b1101000); //I2C address of the MPU
      Wire.write(0x1B); //Accessing the register 1B - Gyroscope Configuration (Sec. 4.4)
      Wire.write(0x00000000); //Setting the gyro to full scale +/- 250deg./s
      Wire.endTransmission();
      Wire.beginTransmission(0b1101000); //I2C address of the MPU
      Wire.write(0x1C); //Accessing the register 1C - Acccelerometer Configuration (Sec. 4.5)
      Wire.write(0b00000000); //Setting the accel to +/- 2g
      Wire.endTransmission();
    }

    void recordAccelRegisters() {
      Wire.beginTransmission(0b1101000); //I2C address of the MPU
      Wire.write(0x3B); //Starting register for Accel Readings
      Wire.endTransmission();
      Wire.requestFrom(0b1101000,6); //Request Accel Registers (3B - 40)
      while(Wire.available() < 6);
      accelX = Wire.read()<<8|Wire.read(); //Store first two bytes into accelX
      accelY = Wire.read()<<8|Wire.read(); //Store middle two bytes into accelY
      accelZ = Wire.read()<<8|Wire.read(); //Store last two bytes into accelZ
      processAccelData();
    }

    void processAccelData(){
      gForceX = accelX / 16384.0;
      gForceY = accelY / 16384.0;
      gForceZ = accelZ / 16384.0;
    }

    void recordGyroRegisters() {
      Wire.beginTransmission(0b1101000); //I2C address of the MPU
      Wire.write(0x43); //Starting register for Gyro Readings
      Wire.endTransmission();
      Wire.requestFrom(0b1101000,6); //Request Gyro Registers (43 - 48)
      while(Wire.available() < 6);
      gyroX = Wire.read()<<8|Wire.read(); //Store first two bytes into accelX
      gyroY = Wire.read()<<8|Wire.read(); //Store middle two bytes into accelY
      gyroZ = Wire.read()<<8|Wire.read(); //Store last two bytes into accelZ
      processGyroData();
    }

    void processGyroData() {
      rotX = gyroX / 131.0;
      rotY = gyroY / 131.0;
      rotZ = gyroZ / 131.0;
    }

    void printData() {
      Serial.print("Gyro (deg)");
      Serial.print(" X=");
      Serial.print(rotX);
      Serial.print(" Y=");
      Serial.print(rotY);
      Serial.print(" Z=");
      Serial.print(rotZ);
      Serial.print(" Accel (g)");
      Serial.print(" X=");
      Serial.print(gForceX);
      Serial.print(" Y=");
      Serial.print(gForceY);
      Serial.print(" Z=");
      Serial.println(gForceZ);
    }

https://github.com/VRomanov89/EEEnthusiast/blob/master/MPU-6050 Implementation/MPU6050_Implementation/MPU6050_Implementation.ino

body:
Ground the AD0 pin. I thought the address should be set to 0x68 without this, but from what I've seen it fluctuates between 0x68 and 0x69. If you want the address to be 0x69 short the AD0 pin to 5V. I guess this would be useful if you need to use 2 MPU6050s with different I2C addresses without doing something in software. Haven't looked into that yet

Still, the I2C scanner for arduino may be useful for detecting the address/debugging: http://playground.arduino.cc/Main/I2cScanner


message:
47Effects MIDI Library and serial debugging

I noticed that since I use the MIDI library from 47effects, I cannot use the print(ln) for the serial port for debugging purposes, neither I can find it in the documentation.

It states that the MIDI library uses the serial port, but I really miss the serial port now for debugging.

Update: so my question: The MIDI library uses the RX (pin 0) and TX (pin 1) on my Arduino One. However, I think the internal Serial.print/println also uses these same pins, so I was wondering how I can use Serial.print and Serial.println statements being visible on the Arduino IDE Terminal (emulator) while using the MIDI library.

body:
 I assume you have one or more Arduinos, are trying to do MIDI control, and want to know how to debug with the MIDI library having commandeered the hardware serial port.

One approach is to use I2C or SPI to communicate with a second Arduino, which uses its serial port to deliver debugging data to a host system.  See Nick Gammon's excellent page [ Debugging using SPI/I2C and a second processor (gammon.com.au forum id=11329)](http://www.gammon.com.au/forum/?id=11329), which illustrates communication between two Arduinos, using one of them as a slave to forward information sent by I2C or SPI from a system being debugged.

Another approach might be to use a *serial bridge*.  I don't know the ins and outs of this or exactly what it does but have read that, for example, the [Hairless](http://projectgus.github.io/hairless-midiserial/) bridge (which is an open-sourced software package) can display both sides of MIDI communication, possibly depending on use of `Serial.write` vs `Serial.print`.  You could designate certain note sequences as standing for various debugging cases.

A third approach is use of Arduino [software serial](https://www.arduino.cc/en/Reference/softwareSerial) to send debugging data to a serial port on your host system.  This would use some Arduino pins other than the hardware Rx, Tx pins.

*Edit 1:  Pin Usage –*

For approach 1, using I2C ties up two specific pins, SDA and SCK.  These are shared with other I2C devices, if any.  SPI typically shares three signals – SCLK, MOSI, and MISO – among all SPI devices, and generates one SS signal per device.  For pinout and protocol details, see Nick Gammon's well-organized and clearly-illustrated [I2C](http://www.gammon.com.au/i2c) and [SPI](http://www.gammon.com.au/spi) pages.

Approach 2 would use no extra pins.

Approach 3 would use one or two extra pins:  one for half-duplex or output-only communication (which may be adequate for debugging), two for separate Rx, Tx lines.  Compared to hardware serial, [software serial](https://www.arduino.cc/en/Reference/softwareSerial) is CPU-intensive, does not support as-high data rates, and has a higher error rate.  It should work ok for light-weight debugging output, such as occasional text to show what tests succeeded or failed or what branch was taken, or values of a few variables.


message:
74HC595 with 4 digit 7 segment display. Any way to get rid of leading zeros?

I am working on an Arduino based temperature reader using a DS18B20 temperature IC. The display is a 4 digit 7 segment LED common anode display driven by a single 74HC595 shift register. Currently, it is setup to read a variable assigned with a number to test the display portion. It displays to the tenths decimal place I am having troubles trying to get rid of the leading zeros. When the variable 'tempF' is assigned a number such as 12.3, the display yields 012.3 and if the variable is assigned a number such as 1.2, the display will yield 001.2. At the same time, I was wanting to have it place a minus (-) sign when the number is less than zero. So far, the examples I'm finding on the web don't seem to match into the code I'm currently working with or don't work at all. I haven't been able to locate a sketch that seems to work for this type of setup. I have posted below, the code I am working with. The original code was obtained from the link provided in the sketch.

The sketch there does not provide the means of reading negative temps or suppress leading zeros.

**********

       /*
     * www.pial.net/arduino-controlling-a-4-digit-seven-segment-display/
     */

    //#include <OneWire.h>
    //#include <DallasTemperature.h>

    //#define ONE_WIRE_BUS 2

    //OneWire oneWire(ONE_WIRE_BUS);
    //DallasTemperature sensors(&oneWire);
    //DeviceAddress insideThermometer;

    const int ledPin =  13;// LED connected to digital pin 13
    const int latchPin = 8;//Pin connected to ST_CP of 74HC595
    const int clockPin = 9;//Pin connected to SH_CP of 74HC595
    const int dataPin = 10;//Pin connected to DS of 74HC595

    const int digitPins[4] = {
      3,4,5,6}; //pins to control the 4 common anode pins of the display

    const byte digit[10] = //seven segment digit bits
    {
      B00111111, //0
      B00000110, //1
      B01011011, //2
      B01001111, //3
      B01100110, //4
      B01101101, //5
      B01111101, //6
      B00000111, //7
      B01111111, //8
      B01101111, //9
    //  B00000000, //all segments off
    //  B01000000 //-
    };

    int digitBuffer[4] = {
      1};
    int digitScan = 0;
    int soft_scaler = 0;
    float tempC, tempF;
    int tmp;

    void setup()   {
      TCCR2A = 0;
      TCCR2B = (1<<CS21);
      TIMSK2 = (1<<TOIE2);
      TCNT2 = 0;
      Serial.begin(9600);

      pinMode(ledPin, OUTPUT);
      for(int i=0;i<4;i++)
      {
        pinMode(digitPins[i],OUTPUT);
      }
      pinMode(latchPin, OUTPUT);
      pinMode(clockPin, OUTPUT);
      pinMode(dataPin, OUTPUT);

    //  sensors.begin();
    //  sensors.getAddress(insideThermometer, 0);
    }

    ISR(TIMER2_OVF_vect) {
      soft_scaler++;
      if(soft_scaler==15)
      {
        refreshDisplay();
        soft_scaler = 0;
      }
    };

    void refreshDisplay()
    {
      for(byte k=0;k<4;k++)
      {
        digitalWrite(digitPins[k], LOW);
      }
      digitalWrite(latchPin, LOW);
      shiftOut(dataPin, clockPin, MSBFIRST, B11111111);
      digitalWrite(latchPin, HIGH);
      delayMicroseconds(50);
      digitalWrite(digitPins[digitScan], HIGH);

      digitalWrite(latchPin, LOW);
    //  if (digitScan==3)
    //  {
    //    shiftOut(dataPin, clockPin, MSBFIRST, ~(digit[digitBuffer[digitScan]] | B00000000)); //inserting the blank
    //    }
    //    else
    //  {
    //    shiftOut(dataPin, clockPin, MSBFIRST, digit[digitBuffer[digitScan]]);
    //  }

      if(digitScan==1)
      {
        shiftOut(dataPin, clockPin, MSBFIRST, ~(digit[digitBuffer[digitScan]] | B10000000)); //inserting the dot
      }
      else
      {
        shiftOut(dataPin, clockPin, MSBFIRST, ~digit[digitBuffer[digitScan]]);
      }
      digitalWrite(latchPin, HIGH);
      digitScan++;
      if(digitScan>3) digitScan=0;
    }

    void loop()
    {
      digitalWrite(ledPin, HIGH);
      boolean sign = false;
      //sensors.requestTemperatures();
      //tempC = sensors.getTempC(insideThermometer);
      //tempF = DallasTemperature::toFahrenheit(tempC);
      //tmp = int(tempF*100);
      tempF = 0.2;
      tmp = int(tempF*10);

    //   if (digitScan == 4 ){
    //    shiftOut(dataPin, clockPin, MSBFIRST, ~(digit[digitScan] | B00000000)); //inserting the blank
    //    }
    //    else
    //  {
    //    shiftOut(dataPin, clockPin, MSBFIRST, digit[digitBuffer[digitScan]]);
    //  }

    //if (tmp < 0){
    //sign = true;
    //tmp = abs(tmp);
    //}

    //if (digitScan == 3) {
    //  if (tmp < 0){
    //    shiftOut(dataPin, clockPin, MSBFIRST, ~(digit[digitBuffer[digitScan]] | B01000000)); // outputs minus sign
    //  }
    //  else {
    //    shiftOut(dataPin, clockPin, MSBFIRST, ~(digit[digitBuffer[digitScan]] | B00000000));
    //   }

    //  tmp = abs(tmp);
    // }
    //  else if (digitScan == 3 && digit[digitScan-1] == 0) { // writing on the second display (tens; if there are none, outputs nothing)
    //     shiftOut(dataPin, clockPin, MSBFIRST, ~(digit[digitBuffer[digitScan]] | B00000000));
    //   }
    //   else if (i == 2) { // writing on the third display, where decimal point is needed
    //     shiftOut(data_pin, clk_pin, MSBFIRST, digit[digitBuffer[i-1]]);
    //   }
    //   else { // writing on "other" displays (in fact fourth display AND seecond display only if there are some tens)
    //     shiftOut(data_pin, clk_pin, MSBFIRST, digit[digitBuffer[i-1]]);
    //   }

      digitBuffer[3] = int(tmp)/1000;
      digitBuffer[2] = (int(tmp)00)/100;
      digitBuffer[1] = (int(tmp)0)/10;
      digitBuffer[0] = (int(tmp)0);
      Serial.print("number assigned to the variable 'tmp' = ");
      Serial.println(tmp);
      Serial.print("number assigned to the variable 'tempF' = ");
      Serial.println(tempF);
      digitalWrite(ledPin, LOW);
      delay(500);
    }

**********

The commented out commands in the sketch were attempts to remove leading zeros and add a minus sign when needed but failed. I have also posted a schematic of the project as well. A 74HC595 was used in this manner to free up pins to be used later in a deep freezer project.

I am by no means an expert programmer but if anyone could help me out or provide some insight on how to solve this problem, it would be most appreciated.

[![Arduino temp reader][1]][1]

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

body:
> Any way to get rid of leading zeros?

Sure but two conditions have to be true:

1) you have the font information for "blank"; you need to un-comment it in your code for that.

2) you need to get rid of leading zeros, after having calculated the display buffer.

      displayBuffer[0]=(displayBuffer[0]==0)?FONT_BUFFER:displayBuffer[0]; //eliminate leading zero for displayBuffer[0]
      displayBuffer[1]=((displayBuffer[1]==0) && (displayBuffer[0]==FONT_BUFFER))?FONT_BUFFER:displayBuffer[1];
      ...

edit:

here is an example implementation of the concept from above, on a PIC12F675 driving two HC595. The number to be displayed is "12" on a 4-digit display. Blanking done on the first three digits -> you can confirm that by looking at the value of the display buffer lRAM[4]. 0x11 is my blank designator.

The partial display of '1' is due to multiplexing. Code largely based on what I wrote here: https://dannyelectronics.wordpress.com/2017/03/03/driving-7-segment-leds/, modified to drive over HC595s.

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

it should work on any mcu with minimum changes.

edit 2: here is your code driving a CC display directly. the number to be displayed is 1.23, with the leading zeros in the most significant 2 digits taken out.

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

  [1]: https://i.stack.imgur.com/ZkrUL.png
  [2]: https://i.stack.imgur.com/rGnIq.png


message:
Virtual analog inputs? Possible?

Just wondering whether it is possible to create 'virtual analog' signals, I am designign a system that uses a tank level sensor (pressure transducer); the component has not yet arrived and I am expecting it in a few weeks.

Is there any way to simulate the signals it would spit out, using some sort of GUI where I can physically control the 'virtual' tank level?

I'm thinking something along the lines of Wonderware's Intouch?

Would appreciate the help! Thanks

body:
You don't specify the sensor you're trying to emulate, so we can't tell you exactly how to do it.

The obvious hardware approach would be a potentiometer.

You could also do it in software by writing a function to get the value, and temporarily replacing its implementation with one which generates random values, or reads values from a serial port, or reads them in order from a hard-coded array, or calculates them according to the time, or whatever you want.


body: If you just want different values on an analog port then you could use a potentiometer, or a second Arduino the reads a value from its serial port and sets the value of its analog port connected to your first Arduino.  Just remember to have a common ground if you do this.


message:
Connecting ACS 712 30A to my Solar Panel with Arduino

I am trying to connect my Solar Panel (array of 2 x 265Wp 24v panels connected in series) to my Arduino UNO R3/Nano so that I can make a current/voltage measurement system that can be connected to the internet for remote data access.

I am not sure if an Allegro ACS712 30Amp chip could handle the voltage/current of my system which is usually over 60v dc and 4-5 amps. I can relate the ACS712 to a simple ammeter which is connected in series of the load where a shunt resistance is used between the two connecting ends of the ammeter.

The confusing part here for me is that the solar panel is connected via an MPPT charge controller to my 1.5 KVA inverter which in turn powers my house equipment, and I am not sure if the two connecting ends of the ACS712 can handle this load (which sometime exceeds to over 450 Wh) if connected in between the wire connecting the panel and charge controller.

Can anyone help me with a suggestion or better with a diagram showing the suggested system.

body:
> I am not sure if an Allegro ACS712 30Amp chip could handle the voltage/current of my system which is usually over 60v dc and 4-5 amps.

Easily. It's designed for mains voltages up to 30A. You're using a fraction of that. You could even use the 20A version to get more accuracy and resolution.

> The confusing part here for me is that the solar panel is connected via an MPPT charge controller to my 1.5 KVA inverter which in turn powers my house equipment, and I am not sure if the two connecting ends of the ACS712 can handle this load (which sometime exceeds to over 450 Wh) if connected in between the wire connecting the panel and charge controller.

Why is that confusing? If you're monitoring the feed between the solar panel and the charge controller what comes out of that system at the other end is of no concern. Just because you are drawing a larger current from the output doesn't mean that the solar panels are providing that current - that comes from the batteries. Now if you were monitoring the current to/from the batteries that would be a different matter. You'd need to calculate the peak current that your house would draw at mains voltage then convert that to the current at the battery voltage (converting to watts in between is a good step. Note that Wh is meaningless when you want a peak value - Wh is a total power over a period of time ["area under a curve"], but you don't care about time, only peak ["maximum value of curve"]).


body:
I know what you mean.
It can read it, but sure the terminals and the power going though it are tiny and therefore have to take a current at the terminals.

Try a ASC758LCB-100U-PFF-T.

You say your 60V 5 Amps. therefore for I will say "yes" this is 300 watts
There are two terminals per side for the connection
1-2 and 3-4.. I would Solder Join them to enure it can hold the current.
 Im looking at this issue and I have made the suggestion above on what you could use as a alternative. it has been used for more powerful systems, in a 30 amp MPPT charge controller.

The area of each terminal is 0.51x0.25x1.27 (0.6477mm2) AWG puts it as a 1.8 amp current area or AWG 19

At worst case, the chip legs will be like a fuse and it will just "pop". so dont go to the fuse box first. they are also internally fused.


message:
How to stop transmission i2c on LCD 16x4 i2c

i want to try to stop communicaton I2C between arduino and lcd I2C but i don't see any command to stop this communication. I try with Wire.endTransmission or Wire.end but the transmission to the LCD continue without problem. I'm using this library NewliquidCrystal and inside no command for end transmission. I need to interupt that communicaton for have a good management of lcd or if know a new library with best features. Thank's for help

body:
> I need to interupt that communicaton for have a good management of lcd or if know a new library with best features. Thank's for help

This sounds like a classical [X-Y problem][1]. You have decided on a solution and asking about some "magic" functionality without understanding the library or how the I2C bus works.

It would be better to try to describe the original issue, investigate, propose and discuss solutions. Basically better understand the original issue.

Back to your question:

> Wire.endTransmission()

 does not really do what you think. It marks the end of a block to be transmitted (previous Wire.write()) and starts the actual transmission to the slave.

This is what the [manual][2] says:

> **Wire.endTransmission()**
>
> Description
>
> Ends a transmission to a slave device that was begun by beginTransmission() and transmits the bytes that were queued by write().

  [1]: http://xyproblem.info/
  [2]: https://www.arduino.cc/en/Reference/WireEndTransmission


message:
Light up more than one LED connected to 74HC595 Shift Register

I have a 74HC595 Shift Register with a LED (and resistor) on each of the 8 output pins.
I can light them all up
I can light one up

How do I light two up?
For example the one on pin 2 and the one on pin 7

I used this a my starting point.
https://learn.adafruit.com/adafruit-arduino-lesson-5-the-serial-monitor?view=all

Is 74HC595 Shift Register  the correct componet to use?

body:
You don't mention if you are using and Arduino, but I will assume that is the case.

Using the shift register to light up LEDs is fairly straight forward.

You can use the ShiftOut() function to send out an 8bit binary value to the register. https://www.arduino.cc/en/Reference/ShiftOut

In summary however, if you want to light up the LEDs on the output pins 2 and 7 you would shift out b01000010 to the shift register. If you wanted pins 4, 5 and 7 to light up, you shift out b01011000. These assume the least significant bit is sent first.

Here's an example:

    // set shift register output pins 2 and 7 to high
    uint8_t data = 1<<2 | 1<<7; // use bit shifting

    digitalWrite(latchPin, LOW);
    shiftOut(dataPin, clockPin, LSBFIRST, data); // send the data
    digitalWrite(latchPin, HIGH);


body:
> How do I light two up? For example the one on pin 2 and the one on pin 7

If the LEDs are active high, sending 0x82 lights up the two LEDs.

If they are active low, sending ~0x82 lights up the same LEDs


message:
Can't send SoftwareSerial to Class Object

I have a problem when I try to use SoftwareSerial in a class..

**Here my detail** My class

    class MyEsp8266
    {
     protected:
         SoftwareSerial *esp8266;
     public:
         MyEsp8266(SoftwareSerial *_esp8266){
               esp8266 = _esp8266;
         }
         void begin(int baud){
            esp8266->begin(baud);
         }
         String testAT(){
              esp8266->println("AT");
              return esp8266->readString();
         }
    }

**My Arduino code**

    #include <SoftwareSerial.h>
    #include "MyEsp8266.h"
    // the setup function runs once when you press reset or power the board

    SoftwareSerial _esp(10, 11);
    MyEsp8266 wifi(&_esp);

    void setup() {
        Serial.begin(9600);
     wifi.begin(115200);
     Serial.println(wifi.testAT());
    }

It doesn't log anything **But** when I have used all code in Arduino code it worked.

    #include <SoftwareSerial.h>
    // the setup function runs once when you press reset or power the board

    SoftwareSerial _esp(10, 11);

    void setup() {
     Serial.begin(9600);
     _esp.begin(115200);
     _esp.println("AT");
     Serial.println(_esp.readString());
    }

Thank any tips.
Regards.

body:
This is more of a work-around than a solution, but the code you're trying to get to work, worked for me once I changed

    wifi.begin(115200);

to

    wifi.begin(9600);

(sorry I don't have enough karma to just comment)


message:
What difference between readString and while loop read

From Arduino code, I have a question for SoftwareSerial Class

First: when I use more example for Esp8266 those functions use while loop to read response string from Esp when we send AT_Command to ESP.

    getResponse(const uint32_t  wait) {
     String tmpData = "";
     long int time = millis();
     while ((time + wait) > millis()) {
      while (esp8266->available() > 0) {
       char c = esp8266->read();
       if (c == '\0') continue;
       tmpData += c;
      }
     }
     tmpData.trim();
     return tmpData;
    }
I know that SoftwareSerial Class have a public method is **readString()** then I'm tried to use that and it return same result returned by while loop read:

    getResponse(const uint32_t  wait) {
     String tmpData = "";
     tmpData = esp8266->readString();
     return tmpData;
    }

Thanks for any. I'm working on improving my Eng.
Regards

body:
Your `while` loop reads all the characters up until it reaches character 0 (it also has a timeout, although the timeout has been coded wrong since it can't deal with clock rollover). The `.readString()` method reads characters until no characters arrive within a timeout period (1s if memory serves me correctly).

Your `while` loop is the more reliable method since it uses a specific delimiter to identify blocks of data (strings) rather than assuming that:

1. The string will all arrive with no delays greater than the timeout
2. The strings will be sent with a gap of at least the timeout length between them.

Personally I would never recommend using any of the "helpful" functions provided for reading from a `Stream` object other than the basic `.read()` function.


message:
Using an esp8266, how can I create a circuit to measure 2 different analog inputs (not simultaneously) with only one ADC pin available (A0)

I'm currently using a circuit with 2 separate transistors that can be switched on or off to measure 2 separate voltage inputs.

The reason for this is because I'm using an esp8266 which has only one ADC input at pin A0 and I need to measure light intensity from an LDR as well as voltage from a solar panel.

The LDR is wired with a voltage divider. The voltage input from the solar panel is 0 - 5v, so I have that wired with a voltage divider to output a max of 3.3v (pin A0 is 0 - 3.3v). The problem is that in complete darkness, the ADC is still reading the LDR with a value of around 260 (should be close to zero) and with bright light reading around 850 (should be close to 1023). Also, the voltage measured from the solar panel (divided to 3.3v) is returning anywhere from 600 (0v) to around 840 (3.3v).

I've tried these input measurements separately with expected results. It's having the option to switch inputs is what is tripping me up.

So, is my approach correct or is there another way to do this?

Note: I would have included a circuit diagram if I knew anything about circuits and making diagrams.

body:
There's two basic solutions, both of which require the addition of an external chip:

1. Use an analog multiplexer to select the different devices to connect to the ADC input
2. Use an external (I2C or SPI) ADC chip. These can give you higher resolutions than the internal ADC and many more inputs (depending on the chip you choose).

My recommended solution would be to get an external ADC chip.


message:
Instance does not name a type, in function void loop (8x8 matrix)

Hey guys I'm doing a beginners project 8x8 matrix and I have some errors when compiling

The Errors are;

 - MyBlink:0: error: 'Instance' does not name a type
 - MyBlink.cpp: In function 'void loop()':

-MyBlink:40: error: 'row1' was not declared in this scope

     Instance code:
    //the pin to control ROW
    const int row1 = 2; // the number of the row pin 9
    const int row2 = 3; // the number of the row pin 14
    const int row3 = 4; // the number of the row pin 8
    const int row4 = 5; // the number of the row pin 12
    const int row5 = 17; // the number of the row pin 1
    const int row6 = 16; // the number of the row pin 7
    const int row7 = 15; // the number of the row pin 2
    const int row8 = 14; // the number of the row pin 5
    //the pin to control COl
    const int col1 = 6; // the number of the col pin 13
    const int col2 = 7; // the number of the col pin 3
    const int col3 = 8; // the number of the col pin 4
    const int col4 = 9; // the number of the col pin 10
    const int col5 = 10; // the number of the col pin 6
    const int col6 = 11; // the number of the col pin 11
    const int col7 = 12; // the number of the col pin 15
    const int col8 = 13; // the number of the col pin 16
    void setup(){
    int i = 0 ;
    for(i=2;i<18;i++)
    {
    pinMode(i, OUTPUT);
    }
    pinMode(row5, OUTPUT);
    pinMode(row6, OUTPUT);
    pinMode(row7, OUTPUT);
    pinMode(row8, OUTPUT);
    for(i=2;i<18;i++) {
    digitalWrite(i, LOW);
    }
    digitalWrite(row5, LOW);
    digitalWrite(row6, LOW);
    digitalWrite(row7, LOW);
    digitalWrite(row8, LOW);
    }
    void loop(){
    int i;
    //the row # 1 and col # 1 of the LEDs turn on
    digitalWrite(row1, HIGH);
    digitalWrite(row2, LOW);
    digitalWrite(row3, LOW);
    digitalWrite(row4, LOW);
    digitalWrite(row5, LOW);
    digitalWrite(row6, LOW);
    digitalWrite(row7, LOW);
    digitalWrite(row8, LOW);
    digitalWrite(col1, LOW);
    digitalWrite(col2, HIGH);
    digitalWrite(col3, HIGH);
    digitalWrite(col4, HIGH);
    digitalWrite(col5, HIGH);
    digitalWrite(col6, HIGH);
    digitalWrite(col7, HIGH);
    digitalWrite(col8, HIGH);
    delay(1000);
    //turn off all
    for(i=2;i<18;i++) {
    digitalWrite(i, LOW);
    }
    delay(1000);
    }

body:
> MyBlink:0: error: 'Instance' does not name a type

Once I deleted the line `Instance code:` on the first line both errors went away.

Cheers


body:
There is typo in your program. Exactly you should comment out the first line of your code. Adding two slashes at the beginning of the first lines.

    Instance code:

As this is not a valid syntax for your code. The compiler is not recognizing what are you trying to do. So it generates a second error because everything that comes after may generate an unknown error.
Next time try to solve these kind of problems by reading your console log as it describes exactly at which lines the compiler has found an error. You can see that it generates an error at line 0:

> Myblink:0:error....

You have multiples errors on this program because as i said before sometimes they are generated as a consequence of your previous error. So you should also try to fix your errors from top to bottom.


body:
The colon is a bit misleading, it is used in C++ to denote inheritance like this:

E.g.

    class Form
    {
      int _area;

      public Form(area)
      {
        _area = area;
      }
    }

    class Circle : class Form
    ...

However, this is not your intention probably.

Also the colon is used for calling base constructors and for labels to go to (goto, never use this).


message:
Arduino Uno with ESP8266

#include <stdlib.h>
    #include <SoftwareSerial.h>

    #define SSID "name-of-my-network" //replace XXXXX by your router SSID
    #define PASS "password-of-network" //replace YYYYY by your router password
    #define IP "184.106.153.149" //thingspeak.com IP

    const int tempPin = A0; //configure Arduino pins
    String GET = "GET /update?key=thingspeak-api-key&field1=";
    SoftwareSerial mySerial(10,11); //Serial communication to ESP8266 module(RX, TX)
    unsigned long starttime;
    unsigned long sampletime_ms = 30000;
    unsigned long delay_time = 60000;

    void setup() {
      Serial.begin(57600);
      while(!Serial) {
        ;
      }
      mySerial.begin(115200);
      Serial.println("Initializing...");
      //communication with wifi module
      mySerial.flush();
      mySerial.println("AT");
      delay(2000);
      if(mySerial.find("OK")) {
         Serial.println("Communication with ESP8266 module: OK");
       } else {
         Serial.println("ESP8266 module ERROR");
       }
       connectWiFi();
       //initialize timer
       starttime = millis();
    }

    void loop() {
      // put your main code here, to run repeatedly:
      if ((millis() - starttime) >= sampletime_ms) {
        char buffer[10];
        int analogReading = analogRead(tempPin);
        String temperatureStr = dtostrf(analogReading, 4, 1, buffer);
        temperatureStr.replace(" ","");
        updateSensors(temperatureStr);
        //wait next sampling cycle
        Serial.print("Wait ");
        Serial.print(delay_time/1000);
        Serial.println("s for next sampling");
        Serial.println();
        delay(delay_time);
        //initialize new cycle
        Serial.println();
        Serial.print("Sampling (");
        Serial.print(sampletime_ms/1000);
        Serial.println("s)...");
        starttime = millis();
      }
    }

    void updateSensors(String tempStr){
      String cmd = "AT+CIPSTART=\"TCP\",\"";
      cmd += IP;
      cmd += "\",80";
      mySerial.println(cmd);
      delay(2000);
      cmd = GET;
      cmd += tempStr;
      cmd += "\r\n";
      delay(1000);
      int strsize = cmd.length();
      mySerial.println("AT+CIPSEND=" + String(strsize));
      delay(2000);
      mySerial.print(cmd);
      if(mySerial.find("OK")) {
        Serial.println("Transmission completed with success");
      } else {
        Serial.println("Transmission failed!");
      }
    }

    boolean connectWiFi(){
      Serial.println("Connecting wi-fi...");
      String cmd ="AT+CWMODE=1";
      mySerial.println(cmd);
      delay(2000);
      mySerial.flush(); //clear buffer
      cmd="AT+CWJAP=\"";
      cmd+=SSID;
      cmd+="\",\"";
      cmd+=PASS;
      cmd+="\"";
      mySerial.println(cmd);
      delay(5000);
      if(mySerial.find("OK")) {
        Serial.println("Connection succeeded!");
        return true;
      } else {
        Serial.println("Connection failed!");
        return false;
      }
      Serial.println();
    }

I am using the above code and have connected the ESP8266 to the Arduino as follows:

>TX of ESP8266 to pin number 11 of Arduino
Rx of ESP8266 to pin number 10 of Arduino
Vcc of ESP8266 to 3.3V power supply taken from Arduino
GND of ESP8266 to GND taken from Arduino
CH_PD of ESP8266 to GND

It seems that I can't get the ESP8266 working. Could anyone could help me? I would really appreciate any help since I cannot continue my project.

body:
This code is used to upload temperature data on pin A0 to things speak
Create thingspeak account and create channel you get api key it seems that this code uses field1 to upload data upload this code to arduino the change ssid and password


body: Often the issue with this module is that the 3.3v of Arduino is unable to maintain enough current for the ESP8266 to work properly. I assume you have the proper firmware flashed to the wifi module


message:
Cutting off OneWire/SDA line with transistors

I am developing a pcb for a design I am working on and I need to share a pin to be used by a ds18b20 (onewire) and some possible I2C sensors. There would be just one of each at a time.

I was thinking about using a couple of transistors. One would cut or enable ds18b20 data line and the other one, the same for SDA line. So I would enable the first one and disable the second one or viceversa.

Do you think this is possible? I don't have transistors right now to test it. I have to order some of them. I was thinking about a bd228. Would this add some errors/delays/whatever in signal information? A kind of distorsion I mean. Or should it work?

EDIT: I will try to explain a bit my project.

My idea is to have a box with 5 sockets. Each one of them will be a different data input. They should be able to use a wide variety of sensors, ds18b20, dht22, open/close door (1 or 0 signal)... Also I would want to include some I2C sensors.

I was thinking about BME280 for example.

My idea is that the user could set which sensor is connected each time so the arduino can switch transistor behaviour to allow the connectivity to the digital pin or the I2C SDA (or SCL) pin.

I was thinking about using an I2C multiplexer to allow multiple BME280 to be at the same time so the first line would go to the socket1, second line socket 2...

body:
For multiple I2C busses, it is allowed to share a single SCL and have a separate SDA line for each I2C bus. That means that as long as the SDA is inactive (high), you can do with the SCL whatever you want.

It might even be possible to share the SCL signal for I2C and 1-Wire, and use both. The SCL signal would then also be the 1-Wire signal. The I2C pulses are probably shorter than the start pulse of the 1-Wire. You would also have to do it right in the software to switch the function of the pins. As far as I know that has never been done, so you might get into a lot of trouble.

Transistors are not the right choice to multiplex signals, and the BD228 is definitely not okay. The I2C bus is a open-collector or open-drain bus with a current of maximum 3mA. The 1-Wire bus is roughly the same. It is possible with mosfets or with multiplexers (see: [Nick Gammon about multiplexers][1]). However, if you are going to add extra hardware there are probably better solution than combining I2C with 1-Wire.

Have you thought about the voltage levels ? Are you using a 5V Arduino board ? Most sensors are 3.3V. The DS18B20 will work with voltages as low as 3.0V, so 3.3V is no problem for the DS18B20.

Tell us what else is connected to your Arduino board. I'm sure there are better solutions.

Could you better specifiy what it is that you want to achieve ? When there is only I2C sensors or only 1-Wire sensors connected, you could run a i2c-scanner to check for I2C sensors. If nothing is found, do a Wire.end() and start the OneWire using the SCL pin. That could be done during startup and then you don't need extra hardware.

How long are the wires ? The 1-Wire bus can have long wires, but the I2C bus can only have short wires.

  [1]: https://www.gammon.com.au/forum/?id=11976


message:
Arduino String memory allocation

When a String variable is declared and modified inside a function, where does it go? To the **heap**(as string declaration is a part of dynamic memory allocation) or to the **stack**(as it is a part of function)? And is the space regained after the function goes out of the scope?
For example

    void loop()
    {
      Serial.println(foo("def"));
      while(1);
    }

    String foo(String arg1)
    {
     String test = "abc";
     test = test + arg1;
     return test;
    }

So, in this case, the variable "test" is declared in stack or heap? And this space is regained at the end or not?

**Modified:**
What if inside loop variable is declared like below?

    String foo_test = F("def");
    Serial.println(foo(foo_test));
In this case what will be the status of variables?

body:
The string is an instance of an object, high likely keeping the administration like the offset and size (unless it is implemented as a 0-delimited string).
This is a local variable and will be stored on the stack and will be nicely removed after finishing the function.

The characters itself ("abc" ...) will be stored on the heap since this needs to be dynamic. This data will be freed by the string object after returning from the function and possibly when needed to relocate the string.

Normally a string instance will keep some memory allocated, when it is increased (or increased too much) the string content will be copied. This all happens in heap and 'holes' in the heap can occur by this.

That's why in a memory/time critical process it's best to allocate the string before hand, of course this is only possible if you know the (maximum) string size.


body:
This is an excellent question to illustrate the amount of string copying and heap operations (malloc/free) going on when using the Arduino String class.

    void loop()
    {
      Serial.println(foo("def"));
      while(1);
    }

The compiler will generate loop() something like this:

    void loop()
    {
      // String literal is stored in program memory. Needs to be copied
      // to temporary variable. This is done before main() is called.
      static const char temp0[4] PROGMEM = "def";
      static const char temp1[4];
      copy_from_program_memory(temp1, temp0);

      // The parameter to the call to foo() is actually a temporary String
      // variable constructed from the string literal. Storage is allocated
      // on the heap and the assigned from the value of the string literal.
      String temp2;
      temp2.constructor(temp1);

      // The return value of the call to foo() is a String that is passed
      // to Serial.println(). This is also a temporary String variable.
      String temp3;
      temp3.constructor(foo(temp2));
      Serial.println(temp3);

      // The String class destructor has to be called for the temporary
      // String variable so that the string values on heap are deallocated.
      temp2.destructor();
      temp3.destructor();
    }

Note that each call to the constructor involves allocating and copying data to the heap.

    String foo(String arg1)
    {
     String test = "abc";
     test = test + arg1;
     return test;
    }

The function foo() needs to copy strings several times to perform the string concatenation. The operator+ will require an intermediate String copy.

Cheers!

PS: For more details please see the assembly listing below with the calls to String member functions. The compiler reduces inline member functions and reuses temporary local variables. Also the call to foo() is inlined. The member function reserve() is part of the constructor.

    00000198 <main>:
     1de: 60 df        rcall .-320     ; 0xa0 <String::reserve(unsigned int)>
     1fc: 50 d2        rcall .+1184    ; 0x69e <strcpy>
     212: 46 df        rcall .-372     ; 0xa0 <String::reserve(unsigned int)>
     230: 36 d2        rcall .+1132    ; 0x69e <strcpy>
     248: 62 df        rcall .-316     ; 0x10e <String::operator=(String const&)>
     26a: 1a df        rcall .-460     ; 0xa0 <String::reserve(unsigned int)>
     27e: 0f d2        rcall .+1054    ; 0x69e <strcpy>
     28e: 3f df        rcall .-386     ; 0x10e <String::operator=(String const&)>
     294: 60 df        rcall .-320     ; 0x156 <String::~String()>
     29a: 5d df        rcall .-326     ; 0x156 <String::~String()>
     2a0: 5a df        rcall .-332     ; 0x156 <String::~String()>

Bottom-line is that the String class uses a lot of instruction cycles and memory, and there is a potential risk of heap fragmentation and allocation failure.


body:
The truth here turns out to be a bit more complicated than the other answers express. **There's more than one implementation of the Arduino String library, and some are better than others.** Which one you get depends on which board you deploy to.

The newer code handles strings a whole lot more efficiently, particularly in terms of memory usage, and changes the whole dynamic around the answer to this question.

Compare the _original_ version of the Arduino String library, [the one for AVR][1], to [the version for the ESP8266][2].
_(As of writing this answer, these were [this snapshot][3] and [this snapshot][4], respectively.)_

Looking in particular at the functions like `changeBuffer` you can see that the ESP version contains something called "SSO" ("Small String Optimization") added with [this PR here][5]. Basically, for small strings—small enough to fit in the structure would otherwise be used to track the string buffer on the heap—it'll just store the string in that space (in the String object itself) instead.

In practice, this means strings smaller than 12 characters don't require memory allocation; they're stored on the stack inside the String object.

This is a pretty huge deal if you push around a lot of tiny strings, like in the example listed in the question. It means that the code works about as efficiently as you might hope, without problematic side-effects.

  [1]: https://github.com/arduino/ArduinoCore-avr/blob/master/cores/arduino/WString.cpp
  [2]: https://github.com/esp8266/Arduino/blob/master/cores/esp8266/WString.cpp
  [3]: https://github.com/arduino/ArduinoCore-avr/blob/c270eaabf4b7e85b0cfbb96c57817af5995b5ad8/cores/arduino/WString.cpp
  [4]: https://github.com/esp8266/Arduino/blob/698ffc34980191ab422918e3aa22ea90b6596766/cores/esp8266/WString.cpp
  [5]: https://github.com/esp8266/Arduino/pull/5690


message:
Possible error in CAN-Bus shield schematic?

This is a part of SeeedStudio CAN-Bus shield schematic. The vertical green line on the left seems suspicious to me. Am I missing something?

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

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

body:
No, it's not a mistake. It's related to this statement on their Wiki:

> When you use more than two CAN Bus Shield in one net, you should take the impedance into consideration. You should either cut P1 in the PCB with a knife, or just remove R3 on the PCB.

If you look closely at the pads of P1 you will see a small trace joining them together. That is the "rogue" green line you found. By cutting that trace you disconnect the termination resistor. You can then re-connect the termination resistor by soldering the pads together again.


message:
What Are The Differences Between Arduino Language and Standard C for MCU?

What the differences between Arduino language and standard C used for MCU programming (like AVR).I heard Arduino language is C.What happen if i use Arduino language with bare-bones AVR chips.Or with PIC mcu.Will it work?
And, if i use just use AVR chip without arduino, will it work with sensor that designed for Arduino (lets say HC-SR04 ultrasonic sensor).And will sensor designed for arduino work with PIC mcu or other non AVR mcu?
I'm a beginner mcu programmer and currenly learning Arduino.Which is good starting point learning Arduino first or just go straight to MCU programming (without Arduino, just bare bones chip)?
Thank you

body:
There's no "Arduino language", it is C++ with some pre-written libraries to provide an abstraction layer on top of the hardware. You cannot use that library on other microcontrollers because it was designed for the specific MCU (AVR).

Pretty much all microcontrollers on the market have compiler support for the C language, which is similar to C++. There is also often C++ compilers available. But overall, C is by far the most popular language to use when programming embedded systems, with the best tool support.

I would probably avoid spending too much time learning about the Arduino library, since that is not useful knowledge for other platforms. Focus on learning C and study at least one assembler (to grasp what happens underneath the hood of C).


message:
How to detect if the arduino wire is still connected

I have hall sensors connected to an arduino, because of mechanical movements there is some possibility that the input wire may accidentally slip out of the arduino analogin sockets. Is there any way I can detect if the wire is still connected to hall sensor  ? I don't want to solder the cables yet.

body:
You can maybe try to see if the value on analog pins when sensors are connected (while not sensing anything) is different when not connected.
Depending on your sensors and schematic, if analog input is fluctuating, you can use this command to use pull resistor to avoid this fluctuation.

    digitalWrite(Ax, INPUT_PULLUP);

If the above gets true, then you can set up a threshold for detection. Below or beside threshold value, sensor is unplugged.

Otherwise, use some vinyl duct tape.... this would securize the thing a bit!


message:
The working of a MFRC522 and its Interface protocols?

I've actually messed up and posted into the stackoverflow site, even though I'm probably not meant to. I've been given [this][2] datasheet, but even though it does explain somewhat how each host interfaces works, it does not fully answer the questions I have at the moment and I probably don't even know what I'm doing in the first place, hence I'm giving this question another shot in the right place.

I've enrolled recently into a programming course, and one of the subject seems to be embedded software development revolving around an Arduino. Now, I'm tasked with explaining to the class how the MFRC522 works and where it might be applicable, but before all that, I probably am lacking the basic knowledge before I can proceed with my work.

I have [here][1] the image of the pinout from a MFRC522 and I have the following questions:

 - Theres UART, I2C and SPI. Are they all separate communication protocols or are they all involved somehow with each other on this device? If I plan to use only UART for example, is it possible that I just only use the RX and TX?
 - Are there restrictions as to which pins on the Arduino or the MFRC522 I could possibly use, depending on the protocol or circumstances? I can see in the datasheet the pins D1 to D7 being referenced, but I cannot find it anywhere on the MFRC522 itself.
 - In case they are separate protocols, I would like to know how each protocol is applicable for this specific device? Like a general idea as to why a protocol is suited for a certain every day device we have been using.
 - The device itself uses only 3.3V, but is it also 5V resistant? Like, will plugging it into a 5V fry the circuit board or will it work just as fine?

Thanks everyone for your time.

  [1]: https://i.stack.imgur.com/Bnpew.png
  [2]: https://www.nxp.com/documents/data_sheet/MFRC522.pdf

body:
Let's have a look at [the datasheet of that chip](https://www.nxp.com/documents/data_sheet/MFRC522.pdf):

Paragraph 8.1 says

> The MFRC522 supports direct interfacing of hosts using SPI, I2C-bus or serial UART interfaces. The MFRC522 resets its interface and checks the current host interface type automatically after performing a power-on or hard reset. The MFRC522 identifies the host interface by sensing the logic levels on the control pins after the reset phase. This is done using a combination of fixed pin connections.

But it seems that on **this specific board** the control pins are preconfigured for SPI. But, the [supporting library only supports SPI](http://playground.arduino.cc/Learning/MFRC522) so I guess that's OK. For other applications the control pins will be connected differently, and the pins will take up an i2c or serial async role. Applications for the other interfaces include microcontrollers without an SPI interface but with an i2c interface, or eg general purpose computers that have easy access to serial async interfaces, like PC's

 - the pin names D1-D7 in the datasheet are not related to the Arduino's pins with the same names, that's just a coincidence. If you use the aforementioned library, the Arduino pins to use are documented:

<pre>
     * Pin layout should be as follows:
     * Signal     Pin              Pin               Pin
     *            Arduino Uno      Arduino Mega      MFRC522 board
     * ------------------------------------------------------------
     * Reset      9                5                 RST
     * SPI SS     10               53                SDA
     * SPI MOSI   11               51                MOSI
     * SPI MISO   12               50                MISO
     * SPI SCK    13               52                SCK
</pre>

 - what the device will tolerate in terms of voltage on its pins is documented in chapter 11. Absolute max on most pins is 4.5 V, so the chance that 5V will fry the component is so high you probably don't want to try.

---
I think [this](http://www.sunrom.com/p/mifare-rfid-readerwriter-1356mhz-rc522) is your board, and luckily they include a schematic on that page:

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

Here's it clearly visible that pin 1 is connected to ground, and pin 32 is connected to 3.3V, which shows that it's indeed hardcoded to SPI mode.

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


message:
Having some trouble incrementing counters

So, I have some simple code here. I'll just try and explain what I am trying to have my code do here.

I am trying to rotate my stepper motor by half a turn, and then move it back and forth by 200 steps or so.

The problem I have is in my loop function, where I have a variable called ctr. I am trying to increment this ctr when I execute an if statement. The ctr increments inside the if statement and I can see the result when I do Serial.println as it changes to 1. However, when I Serial.println(ctr) right below the if statement, it prints out as 0 even after the previous print statement prints out 1.

Why is this happening? I am a C/C++ noob, so is there something I am missing about variable scoping or pointers?

    void loop()
    {
        stepper1.run();
        int ctr = 0; //counter value to store how many times the back and forth motion has occured
        if(stepper1.currentPosition() == 1024){
          backMotion(stepper1.currentPosition());
          ctr++;
          Serial.println(ctr);
        }
        Serial.println(ctr);
        if(stepper1.currentPosition() == 824 && ctr > 0){
          forthMotion(stepper1.currentPosition());
        }
    }

    void backMotion(int value){
        int current = value;
        int back_distance = current - 200; //distance to move back by
        stepper1.moveTo(back_distance);
    }

    void forthMotion(int value) {
      int current = value;
      int forth_distance = current+200;
      stepper1.moveTo(forth_distance);
    }

body:
Make CTR static or place it in the global scope. As it stands you set it to 0 every time you go through loop.

The line:

    int ctr = 0;

literally means "Create a new variable on the stack called 'ctr' and give it the value 0", and that happens *every time `loop()` is executed*.

Instead making it *static* will change it so that it only happens *the first time `loop()` is executed* so it retains its value across successive executions of `loop()`.

    static int ctr = 0;


body:
loop() != main()

when declaring a variable inside a function, it is cleaned up when returning from the function.

if cnt was in a main() function, it would have worked (as it's the only function that may have an infinite loop in a program. In the arduino world, it's not the case. The main() function is hidden, but loop calls the loop() function.

Workaround is to use the static quelifier when you declare variables inside loop() (or in any other function if you want the variable to remain inside the function scope, but don't want it to be initialized each time you enter the function).


message:
POE with Arduino Leonardo Eth

I recently purchased a [Leonardo Eth][1] and a [5v POE module][2] in an attempt to have a POE micro-controller.  I installed the module in the holes closest to the Ethernet jack side of the board, but when I apply power, the green power light turns on every second or so, but never fully turns on.

What am I doing wrong? Did I install the module wrong? Is it the wrong module?

  [1]: https://www.amazon.com/gp/product/B013PUTJYO/ref=oh_aui_detailpage_o02_s00?ie=UTF8&psc=1
  [2]: https://www.amazon.com/gp/product/B01AMBBJJW/ref=oh_aui_detailpage_o02_s01?ie=UTF8&psc=1

body:
From the arduino.cc website.

"The optional PoE module is designed to extract power from a conventional twisted pair Category 5 Ethernet cable. PoE module features are as follows: IEEE802.3af compliant Input voltage range 36V to 57V Overload and short-circuit protection 12V Output High efficiency DC/DC converter: typ 85% @ 80% load 1500V isolation (input to output)"

It sounds like you need the 12V PoE module


message:
Control a motor with a button

Code:

    int motorPin = 9;  // the pin the motor is connected to

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

    void loop()
    {
     motorOnThenOff(); //motorAcceleration
    }

    void motorOnThenOff(){
      int onTime = 2500;  //the number of milliseconds for the motor to turn on for
      int offTime = 1000; //the number of milliseconds for the motor to turn off for

      digitalWrite(motorPin, HIGH); // turns the motor On
      delay(onTime);                // waits for onTime milliseconds
      digitalWrite(motorPin, LOW);  // turns the motor Off
      delay(offTime);               // waits for offTime milliseconds
    }

    void motorOnThenOffWithSpeed(){

      int onSpeed = 200;  // a number between 0 (stopped) and 255 (full speed)
      int onTime = 2500;  //the number of milliseconds for the motor to turn on for

      int offSpeed = 50;  // a number between 0 (stopped) and 255 (full speed)
      int offTime = 1000; //the number of milliseconds for the motor to turn off for

      analogWrite(motorPin, onSpeed);   // turns the motor On
      delay(onTime);                    // waits for onTime milliseconds
      analogWrite(motorPin, offSpeed);  // turns the motor Off
      delay(offTime);                   // waits for offTime milliseconds
    }

    void motorAcceleration(){
      int delayTime = 50; //milliseconds between each speed step

      //Accelerates the motor
      for(int i = 0; i < 256; i++){ //goes through each speed from 0 to 255
        analogWrite(motorPin, i);   //sets the new speed
        delay(delayTime);           // waits for delayTime milliseconds
      }

      //Decelerates the motor
      for(int i = 255; i >= 0; i--){ //goes through each speed from 255 to 0
        analogWrite(motorPin, i);   //sets the new speed
        delay(delayTime);           // waits for delayTime milliseconds
      }
    }

This code spins the motor. In the circuit, I have a button which I want to toggle the spinning of the motor.

This is the circuit:

https://circuits.io/circuits/4267039-spin-motor-spin/edit

How would I make it so that the button toggles the spinning of the motor? like a fan and its switch?

body:
add this variable at the top of your program:

    const int buttonPin = XX; // the pin for the button
    bool bState = false;

in the setup() function:

    pinMode(buttonPin, INPUT_PULLUP);
    // in case INPUT_PULLUP is not defined, comment the above line and uncomment below
    //pinMode(buttonPin, INPUT);
    //digitalWrite (buttonPin, HIGH);  // enable internal pull-up

in the loop() function, change your code with this:

    update_bState();

    if (bState) { digitalWrite(motorPin, HIGH); }
    else        { digitalWrite(motorPin, LOW); }

then, at the end of your program, add the getButton function:

 void update_bState(void)
 {
  static bool buttonDone = false;
  static uint16_t timeButton;

  if (!digitalRead(buttonPin))
  {
   if ((!buttonDone) && ((uint16_t) (millis() - timeButton) > 100))
   { // Do once when button is pressed for at least 100ms (debounce)
    bState ^= true;  // Toggle button state
    buttonDone = true;
   }
  }
  else
  {
   buttonDone = false;
   timeButton = millis();
  }
 }

Now that all the work is done, you should add acceleration when launching and deceleration when launching and stopping :D

By the way, I did not tested any code, so there may be some typo errors...


message:
Servos stop after a while in case of 8 servo motor control

I recently purchased 10 units of MG996R servo motor and the 16 channel 12-bit PWM/Servo driver from Adafruit for a small project. I confirmed that all of my servos are functional and that my code is correct. My issue is that there seems to be a limit on the number of servos I can run. With 4AA batteries, I can power about 3 of the MG996R servos. Starting with the 4th one, they stop moving. I supposed that the current drawn from the servos is high, so I tried powering the servos by providing two 4AA batteries in parallel (8AA). This appeared to have increased the number of servos I can run. But after a few minutes, the servos stop responding and I have to disconnect the power for a while before the servos respond again. I read on Adafruit that I may need to add a capacitor to the PWM/servo drive if I have multiple servos. Is this my problem or I just need to provide more power? Why do the servos seem to respond initially but stop moving after a while? Thanks in advance.

body:
If Adafruit say to use the kit to drive multiple servos you need to add a cap and without the cap you can't drive multiple servos, then yes your first port of call should be to add the cap.

However that's probably not all that's wrong.  If it runs for a bit before dying then it could be a number of causes.

 1. Not enough power.
 2. Something is overheating.
 3. Code problem.

1.  Use a decent transformer with more than enough amps to power your motors.
2. Use your nose, does something smell hot?  If you use your fingers you will get burnt!
3. We can't fix invisible code.


message:
Why the command noDisplay() clear all LCD screen?

i want to preserve video information for long time without communicating with arduino on lcd 1602, i'm tryng to use the command of liquidCrystal library `noDisplay()` but when i use it,this clear all display. On arduino website here is the description of this command "Turns off the LCD display, without losing the text currently shown on it." but i lose all on screen. Thanks for reply

there is my test code

    #include <LiquidCrystal.h>

    // initialize the library with the numbers of the interface pins
    LiquidCrystal lcd(12, 11, 5, 4, 3, 2);

    void setup() {
      // set up the LCD's number of columns and rows:
      lcd.begin(16, 2);
      // Print a message to the LCD.
      lcd.print("hello, world!");
    }

    void loop() {
      // Turn off the display:
      lcd.noDisplay();
      delay(500);
      // Turn on the display:
      lcd.display();
      delay(500);
    }

with this code display blinking and don't show continuos "hello word".

body:
I tried out your code. It's working absolutely fine.

Whenever `lcd.noDisplay()` executes then LCD not displaying `hello, word!`...
And whenever `lcd.display()` executes then LCD displaying `hello, word!`...

So, that's why "hello word" not continuously displaying.

And you can also find `the display() and noDisplay() functions to turn on and off
the display` comment on top of arduino sketch.


body:
> I tried out your code. It's working absolutely fine.
>
> Whenever lcd.noDisplay() executes then LCD not displaying hello,
> word!... And whenever lcd.display() executes then LCD displaying
> hello, word!...
>
> So, that's why "hello word" not continuously displaying.
>
> And you can also find the display() and noDisplay() functions to turn
> on and off the display comment on top of arduino sketch.

To follow on @Hasan's answer:
noDisplay() doesn't clear the previous displayed stuff, it just inhibits it, all displayed pixels are latched in the chip while it remains powered on.

In case you need to clear the display, you can use lcd.clear() function.


message:
Using two MIDI inputs with Arduino UNO (with one serial)

Would it be possible to use TWO MIDI inputs (and a MIDI output) on an Arduino having only one RX/TX serial port? Timing will be somewhat critical so a software serial port is not usable probably. I need to listen continuously to both MIDI (in) ports not to miss messages.

Or is it better to use an Arduino Mega having 4 serial ports?

body:
Use a Mega. SoftwareSerial is shaky at best and cripples everything else while it runs, and there really is no substitute for real hardware UARTs.

Alternatively look around and see if you can find a board based around the ATMega328-PB (note the "B") which has a second UART built in.