body:
I believe there's a simple way to use only n cells and a single dedicated bit pattern to achieve n/2 increase in durability.

The dedicated bit pattern (e.g. 0xffff) is a marker which indicates an unused cell, and in normal operation at most one cell at a time has this value:

    uint16_t readWord (const uint16_t *address);
    void writeWord (uint16_t *address, uint16_t value);

    #define CELL_COUNT   42
    #define BASE_ADDRESS 12
    #define MARKER       0xffff  // Best to use EEPROM default for this

    static uint8_t curCell = 0;

    static void wlInit (void)
    {
      for ( uint8_t ii = 0 ; ii < CELL_COUNT ; ii++ ) {
        if ( readWord (BASE_ADDRESS + ii) != MARKER ) {
          curCell = ii;
          // No early return/break here to keep init() execution time
          // constant.  Could also check for corruption here by checking for
          // > 1 cells with MARKER (see below).
        }
      }
      // If we didn't find a non-marker cell we'll end up with curCell = 0
      // per the initial value of curCell
    }

    static uint16_t wlRead (void)
    {
      return readWord (BASE_ADDRESS + curCell);
    }

    static void wlWrite (uint16_t value)
    {
      assert (value != MARKER);   // Storing marker value is big no-no

      uint8_t nextCell = (curCell + 1) % CELL_COUNT;
      writeWord (BASE_ADDRESS + nextCell, value);
      writeWord (BASE_ADDRESS + curCell, MARKER);
      curCell = nextCell;
    }

The same approach can be used with structured data provided a bit pattern can be reserved (either in a dedicated byte or from some other field that has a spare pattern).

This approach also has a useful property with respect to interrupted (e.g. power drop) writes: if there are ever two cells without the MARKER value an incomplete (i.e. corrupted) write has occurred. This seems useful, because e.g. the ATmega328P datasheet contains the following unclear and not-particularly-reassuring paragraph about using brown-out detection to avoid corruption:

> Keep the AVR RESET active (low) during periods of insufficient power
> supply voltage. This can be done by enabling the internal Brown-out
> Detector (BOD). If the detection level of the internal BOD does not
> match the needed detection level, an external low V CC reset
> Protection circuit can be used. If a reset occurs while a write
> operation is in progress, the write operation will be com- pleted
> provided that the power supply voltage is sufficient.


sender: user

message:
How to connect to pins when using I2C LCD shield?

How are pins used with [this shield][1]? The tutorial says that the header pins are inserted into the Arduino but the guide says they are not used for signals. Is there any way of using the other pins?

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

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

  [1]: https://learn.adafruit.com/rgb-lcd-shield?view=all
  [2]: https://i.stack.imgur.com/o4foB.jpg
  [3]: https://i.stack.imgur.com/ToyG0.jpg

sender: assistant

body:
What it means is although all pins from the Arduino are connected only A4, A5 5V and Gnd are actually used by the shield.  I think that these 4 pins are shared with other shields and all the rest of the pins are available for shields to either share or use exclusively.

So, if you have this shield and an Ethernet shield, which needs exclusive access to pins d7, d8 and d9 then you would be to use both shields at the same time.


message:
WS2812B strip stopped responding to control

I have a [WS2812B LED strip][1] (A clone of the Adafruit one I assume, it's from China via eBay) of 60 LEDs. When I got it, it was all fine - I could load the FastLED examples and they would work perfectly. I then tried to write something more custom, which didn't work for whatever reason. Upon re-loading the FastLED examples, I now get absolutely nothing from the strip.

It's being powered by an ATX computer power supply with ample amperage on 5V, and when I remove and then re-add the power connectors the strip does flash, indicating it's getting power and is capable of lighting up. It just feels like something I have done has caused it to enter a state where it won't respond to control.

I've also made sure my sketches are making it to the arduino by loading the inbuilt LED blink sketch, which works, then trying to switch back to a FastLED example which does nothing.

I'm kind of lost as to what could be wrong here.

  [1]: https://cdn-shop.adafruit.com/datasheets/WS2812B.pdf

body:
Did you follow the [Adafruit NeoPixels best practices guide](https://learn.adafruit.com/adafruit-neopixel-uberguide/best-practices)?

You may have zapped the first NeoPixel in the group. You should be able to, fairly easily, bypass that. Each NeoPixel has to "reshape" the data for the next one along, so if you damage the first one, no data will reach the others.

I strongly suggest you follow the guidelines in the link, including the capacitor and resistor.


message:
Attiny85 DigiSpark: Drive 128X64 OLED screen, no picture problem

**Devices used**
It's about these devices:

[![Devices][1]][1]

------------------

**Quick scheme** (how I connected those)

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

------------------

Got the **wiring info** from the TinyWire library

 [![TinyWire][2]][2]

------------------

**Program I use** (also many different examples tried but no luck):

    #include <Wire.h>

    //~ DEFINES ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    // Some defines for the SSD1306 controller driving a 128x64 resolution OLED display
    // PART     - http://www.simplelabs.co.in/content/96-blue-i2c-oled-module
    // DATASHEET  - https://www.adafruit.com/datasheets/SSD1306.pdf

    // The Slave Address (SLA) of the OLED controller - SSD1306 - is 0x3C
    // The LSB is supposed to be the mode. Since we are only going to WRITE to the OLED, the LSB is going to be 0
    // SLA (0x3C) + WRITE_MODE (0x00) =  0x78 (0b01111000)
    #define OLED_I2C_ADDRESS   0x3C

    // The SSD1306 datasheet (pg.20) says that a control byte has to be sent before sending a command
    // Control byte consists of
    // bit 7    : Co   : Continuation bit - If 0, then it assumes all the next bytes are data (no more control bytes).
    //        :    You can send a stream of data, ie: gRAM dump - if Co=0
    //        :        For Command, you'd prolly wanna set this - one at a time. Hence, Co=1 for commands
    //        :    For Data stream, Co=0 :)
    // bit 6      : D/C# : Data/Command Selection bit, Data=1/Command=0
    // bit [5-0]  : lower 6 bits have to be 0
    #define OLED_CONTROL_BYTE_CMD_SINGLE  0x80
    #define OLED_CONTROL_BYTE_CMD_STREAM  0x00
    #define OLED_CONTROL_BYTE_DATA_STREAM 0x40

    // Fundamental commands (pg.28)
    #define OLED_CMD_SET_CONTRAST     0x81  // follow with 0x7F
    #define OLED_CMD_DISPLAY_RAM      0xA4
    #define OLED_CMD_DISPLAY_ALLON      0xA5
    #define OLED_CMD_DISPLAY_NORMAL     0xA6
    #define OLED_CMD_DISPLAY_INVERTED     0xA7
    #define OLED_CMD_DISPLAY_OFF      0xAE
    #define OLED_CMD_DISPLAY_ON       0xAF

    // Addressing Command Table (pg.30)
    #define OLED_CMD_SET_MEMORY_ADDR_MODE 0x20  // follow with 0x00 = HORZ mode = Behave like a KS108 graphic LCD
    #define OLED_CMD_SET_COLUMN_RANGE   0x21  // can be used only in HORZ/VERT mode - follow with 0x00 + 0x7F = COL127
    #define OLED_CMD_SET_PAGE_RANGE     0x22  // can be used only in HORZ/VERT mode - follow with 0x00 + 0x07 = PAGE7

    // Hardware Config (pg.31)
    #define OLED_CMD_SET_DISPLAY_START_LINE 0x40
    #define OLED_CMD_SET_SEGMENT_REMAP    0xA1
    #define OLED_CMD_SET_MUX_RATIO      0xA8  // follow with 0x3F = 64 MUX
    #define OLED_CMD_SET_COM_SCAN_MODE    0xC8
    #define OLED_CMD_SET_DISPLAY_OFFSET   0xD3  // follow with 0x00
    #define OLED_CMD_SET_COM_PIN_MAP    0xDA  // follow with 0x12

    // Timing and Driving Scheme (pg.32)
    #define OLED_CMD_SET_DISPLAY_CLK_DIV  0xD5  // follow with 0x80
    #define OLED_CMD_SET_PRECHARGE      0xD9  // follow with 0x22
    #define OLED_CMD_SET_VCOMH_DESELCT    0xDB  // follow with 0x30

    // Charge Pump (pg.62)
    #define OLED_CMD_SET_CHARGE_PUMP    0x8D  // follow with 0x14

    // NOP
    #define OLED_CMD_NOP          0xE3

    //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

    // Box pattern
    uint8_t pattern1[] = {
      0x00,0x7E,0x42,0x42,0x42,0x42,0x7E,0x00,
      0x00,0x7E,0x42,0x42,0x42,0x42,0x7E,0x00
      };

    // Cross weave pattern
    uint8_t pattern2[] = {
      0x81,0x42,0x24,0x18,0x18,0x24,0x42,0x81,
      0x81,0x42,0x24,0x18,0x18,0x24,0x42,0x81
      };

    void setup()   {
      // Init the OLED controller
      OLED_init();
    }

    void loop() {
      // I2C
      Wire.beginTransmission(OLED_I2C_ADDRESS);
      Wire.write(OLED_CONTROL_BYTE_CMD_STREAM);
      Wire.write(OLED_CMD_SET_COLUMN_RANGE);
      Wire.write(0x00);
      Wire.write(0x7F);
      Wire.write(OLED_CMD_SET_PAGE_RANGE);
      Wire.write(0);
      Wire.write(0x07);
      Wire.endTransmission();

      for(uint16_t i=0;i<1024;i++){
        Wire.beginTransmission(OLED_I2C_ADDRESS);
        Wire.write(OLED_CONTROL_BYTE_DATA_STREAM);
          for (uint8_t x=0; x<16; x++) {
          // Wire.write(0b11000001);
          // Wire.write(0x81);
          // Wire.write(0x02);
          Wire.write(pattern1[x]);
          // Wire.write(pattern2[x]);
          i++;
          }
          i--;
          Wire.endTransmission();
      }

        delay(5000);

    }

    void OLED_init() {
      // Init the I2C interface (pins A4 and A5 on the Arduino Uno board) in Master Mode.
      Wire.begin();
      // keywords:
      // SEG = COL = segment = column byte data on a page
      // Page = 8 pixel tall row. Has 128 SEGs and 8 COMs
      // COM = row

      // Begin the I2C comm with SSD1306's address (SLA+Write)
      Wire.beginTransmission(OLED_I2C_ADDRESS);

      // Tell the SSD1306 that a command stream is incoming
      Wire.write(OLED_CONTROL_BYTE_CMD_STREAM);

      // Follow instructions on pg.64 of the dataSheet for software configuration of the SSD1306
      // Turn the Display OFF
      Wire.write(OLED_CMD_DISPLAY_OFF);
      // Set mux ration tp select max number of rows - 64
      Wire.write(OLED_CMD_SET_MUX_RATIO);
      Wire.write(0x3F);
      // Set the display offset to 0
      Wire.write(OLED_CMD_SET_DISPLAY_OFFSET);
      Wire.write(0x00);
      // Display start line to 0
      Wire.write(OLED_CMD_SET_DISPLAY_START_LINE);

      // Mirror the x-axis. In case you set it up such that the pins are north.
      // Wire.write(0xA0); - in case pins are south - default
      Wire.write(OLED_CMD_SET_SEGMENT_REMAP);

      // Mirror the y-axis. In case you set it up such that the pins are north.
      // Wire.write(0xC0); - in case pins are south - default
      Wire.write(OLED_CMD_SET_COM_SCAN_MODE);

      // Default - alternate COM pin map
      Wire.write(OLED_CMD_SET_COM_PIN_MAP);
      Wire.write(0x12);
      // set contrast
      Wire.write(OLED_CMD_SET_CONTRAST);
      Wire.write(0x7F);
      // Set display to enable rendering from GDDRAM (Graphic Display Data RAM)
      Wire.write(OLED_CMD_DISPLAY_RAM);
      // Normal mode!
      Wire.write(OLED_CMD_DISPLAY_NORMAL);
      // Default oscillator clock
      Wire.write(OLED_CMD_SET_DISPLAY_CLK_DIV);
      Wire.write(0x80);
      // Enable the charge pump
      Wire.write(OLED_CMD_SET_CHARGE_PUMP);
      Wire.write(0x14);
      // Set precharge cycles to high cap type
      Wire.write(OLED_CMD_SET_PRECHARGE);
      Wire.write(0x22);
      // Set the V_COMH deselect volatage to max
      Wire.write(OLED_CMD_SET_VCOMH_DESELCT);
      Wire.write(0x30);
      // Horizonatal addressing mode - same as the KS108 GLCD
      Wire.write(OLED_CMD_SET_MEMORY_ADDR_MODE);
      Wire.write(0x00);
      // Turn the Display ON
      Wire.write(OLED_CMD_DISPLAY_ON);

      // End the I2C comm with the SSD1306
      Wire.endTransmission();
    }
Source: https://github.com/SonalPinto/Arduino_SSD1306_OLED/blob/master/oled_test/oled_test.ino

------------------

**Other examples** I have been tried:

 - http://www.14core.com/wiring-digispark-attiny85-with-096-oled-screen-display/
 - http://www.instructables.com/id/ATTiny85-connects-to-I2C-OLED-display-Great-Things/

------------------

**Question**

What could be wrong, do I miss something inhere? Wires seems to be OK, do I use the correct pins (sometimes a little confusing on Attiny85, digital versus analog)? Tried also another `OLED_I2C_ADDRESS`, 0x3D instead of 0x3C but no luck at all. Tried both screen and both remain black.

  [1]: https://i.stack.imgur.com/eLoU6.jpg
  [2]: https://i.stack.imgur.com/3WEDy.png
  [3]: https://i.stack.imgur.com/SnFx2.png

body:
With I2C you always need pull up resistors on the data lines, otherwise nothing works.  Normally ones around 4.7K for a Uno, not sure what they should be for a Tiny.

If you are unsure about the I2C address get "I2CScanner" (An Arduino program) and that will tell you.


body:
Hmm not strictly true I've currently got mine working without resistors, and the screens I get often do work without them, for example the Arduino Nano and ESP8266/NodeMCU I have used without resistors.

I had a bit of a pain with this board, the drivers for Windows originaly not working or detecting the board correctly and then the board not seeing the OLED mine is the 128x32 version. I edited the code to reflect the screen size in the DigiSparkOLED.cpp

    0xA8, 0x1F,      // Set multiplex ratio(1 to 64)

And change:

    0xDA, 0x12,      // Set com pins hardware configuration

To:

    0xDA, 0x02,      // Set com pins hardware configuration

Also on several sites it does say to use PINS SCL on P5 and SDA on P2 so if its not working maybe try that pinout. I used the one mentioned above and the I2C scanner is now seeing it on address 0x3C (I wouldn't try changing the address in my experience the pinout will be wrong)

Do your usual checks to see if the screen is drawing power on all lines with a multimeter, also run I2C Scanner program to see if it sees anything and if not then try the alternative pinout.


message:
How to interpret the data from GPS GY-NEO6MV2 using Arduino Uno?

I am trying to get GPS data from my GY-NEO6MV2, but the results are not readable with SoftwareSerial or other libraries. I have used the following code that has worked for others on the net, but I don't get any results from it. The GPS data appears perfectly in the serial monitor, but the interfaces such as SoftwareSerial fail to receive it. Instead, I receive a bunch of `-1`s. Here is the code:

    #include "SoftwareSerial.h"

    // Constants
    #define txPin 1      //tx pin in GPS connection
    #define rxPin 2      //rx pin in GPS connection

    // Set up the GPS serial port
    SoftwareSerial gps = SoftwareSerial(rxPin, txPin);
    // Variables
    byte byteGPS = 0;
    int i = 0;
    int state = 0;
    char dataGPG[100] = "";
    char *pch;
    char *GGA[15];
    int sat = 0;
    void setup() {
      //setup for Serial Port
      Serial.begin(9600);
      Serial.flush();
      //setup for GPS Serial Port
      pinMode(rxPin, INPUT);
      pinMode(txPin, OUTPUT);
      gps.begin(4800);
      gps.flush();
      //setup satellites signal
      pinMode(13, OUTPUT);
      digitalWrite(13, LOW);
      // Turn off the led until a satellite signal
    }

    void loop() {
      gps.flush();
      Serial.flush();
      Serial.println("Waiting GPS data...");
      // Prepare all for reading GPS Serial Port
      memset(dataGPG, 0, sizeof(dataGPG)); // Remove previous readings
      byteGPS = 0; // Remove data
      byteGPS = gps.read(); // Read the byte that is in the GPS serial port
      delay(1000);
      // Find the desired string
      while (byteGPS != '$') {
        byteGPS = gps.read();
       /******* Here I just get -1 *************/
      }
      // Save the string in an array
      i = 1;
      dataGPG[0] = '$';
      while (byteGPS != '*' ) {
        byteGPS = gps.read();
        dataGPG[i] = byteGPS;
        i++;
      }
      dataGPG[i] = '\0';
      string(); // Call to the function that manipulates our string
    }

    /*
      This function will allow us to identify the data we need to get the longitude, latitude ...
    */

    void string() {
      i = 0;
      memset(GGA, 0, sizeof(GGA)); // Remove previous readings
      pch = strtok (dataGPG, ",");
      // Analyze the saved interval in pch to see if it the needed string
      if (strcmp(pch, "$GPGGA") == 0) {
        while (pch != NULL) {
          pch = strtok (NULL, ",");
          GGA[i] = pch;
          i++;
        }
        plot(GGA, "$GPGGA");
        // Call to the function that is going to display the data
      }
    }

    /*
      This function organize the gps data received for printing in the serial monitor.
    */

    void plot(char **GGAPrint, char *trama) {
      state = atoi(GGAPrint[5]);
      sat = atoi(GGAPrint[6]);
      if (trama == "$GPGGA" && state == 1) {
        digitalWrite(13, HIGH);
        // Then there are satellites, the LED switch ON
        Serial.println("");
        Serial.println("----------------------------------------------");
        Serial.print("UTC Hour -> ");
        Serial.println(GGAPrint[0]);
        Serial.print("Latitude -> ");
        Serial.print(GGAPrint[1]);
        Serial.println(GGAPrint[2]);
        Serial.print("Longitude -> ");
        Serial.print(GGAPrint[3]);
        Serial.println(GGAPrint[4]);
        Serial.print("GPS quality: 0=null; 1=GPS fixed -> ");
        Serial.println(GGAPrint[5]);
        Serial.print("Number of satellites -> ");
        Serial.println(sat);
        Serial.print("Horizontal Dilution of Precision -> ");
        Serial.println(GGAPrint[7]);
        Serial.print("Antenna altitude -> ");
        Serial.print(GGAPrint[8]);
        Serial.println(GGAPrint[9]);
        Serial.print("Geoid Separation -> ");
        Serial.print(GGAPrint[10]);
        Serial.println(GGAPrint[11]);
        Serial.println("----------------------------------------------");
        Serial.println("");
      } else {
        // If no satellite connection
        digitalWrite(13, LOW); // Turn off the LED
        Serial.println("");
        Serial.println("-----------------------------");
        Serial.print("|--- Satellites Used -->");
        Serial.print(sat);
        Serial.println(" |");
        Serial.println("|----Waiting location----|");
        Serial.println("-----------------------------");
        Serial.println("");
      }
    }

The result wasn't correct and I only saw this sentence:

>Waiting GPS data...

----------
I updated the code by adding `gps.available()` and `delay(2)` before every `gps.read()` and it worked. I still don't know why, but this worked:

    #include "SoftwareSerial.h"

    // Constants
    #define txPin 2      //tx pin in GPS connection
    #define rxPin 3      //rx pin in GPS connection
    char gps_data[200];

    SoftwareSerial gps = SoftwareSerial(rxPin, txPin);
    char byteGPS = 0;

    void setup() {
      Serial.begin(9600);
      pinMode(rxPin, INPUT);
      pinMode(txPin, OUTPUT);
      gps.begin(9600);
    }

    void loop() {

      byteGPS = '0'; // Remove data
      memset(gps_data, '\0', 200);

      while (gps.available())
      {
        while (gps.available())
        {
          byteGPS = gps.read(); // Read the char that is in the GPS serial port
          if (byteGPS == '$') break;
        }
        int i=0;
        while (gps.available())  // Available3
        {
          delay(1);
          gps_data[i++] = byteGPS;
          byteGPS = gps.read();
          if ((byteGPS == '\n')) break;
        }
        if (i > 1)
        {
          delay(1);
          parse_gps_data();
        }
      }
    }

The code in `parse_gps_data()` parses the data from gps. It works fine.

body:
Your sketch has many problems:

*  The `flush` method waits for everything you have *written* to go out.  You haven't *written* anything to the GPS or `Serial`, so there's no reason to flush the output.  And you don't need to call it at the beginning of `loop`.

*  Calling `delay` is the surest way to lose GPS characters.  Never use `delay` in a GPS sketch.

*  You are calling `read` without calling `available` first.    Because you called `delay`, there are *probably* chars available, but not necessarily, and they will not be a complete sentence.  This explains the partial NMEA data in your question.

*  You are printing too much in the `plot` routine.  After 64 characters are printed (actually *queued* for printing), the `Serial.print` call must wait for some characters to be sent (making room in the output buffer). At 9600, each character takes 1ms to be sent.  During that time, the GPS device is still sending characters.  Eventually, the input buffer overflows and GPS characters are lost.  When properly structured (see below), there is barely enough time to print all those messages.

*  You have connected the GPS to pins 1 & 2, but pins 0 & 1 are the HardwareSerial pins (Rx & Tx), dedicated to `Serial` .  They are conflicting with each other, and may interfere with uploading new sketches via USB.

*  You do not have good satellite reception, according to the GPS data fragments you show.  Check the antenna, get near a window, or go outside.  It may take 10 minutes before a "fix" is acquired.

*  You are using `SoftwareSerial` for the GPS port.  `SoftwareSerial` is very inefficient, because it disables interrupts for long periods of time.  At 4800, the Arduino is dedicated to receiving each char for 2ms, an *eternity* for a 16MHz processor.  This will interfere with other parts of the sketch or other libraries.  [This answer](https://arduino.stackexchange.com/questions/26240#26277) gives several alternatives, like `AltSoftSerial`, on different pins.

### Solutions:

First, you have to get the hardware connections corrected.  The NEO-6M is a 3.3V device, so you shouldn't connect it directly to the 5V Arduino.  You *could* connect just the GPS TX to the Arduino, but you may not receive data reliably. Connecting an Arduino transmit pin to the GPS RX could damage the GPS module, as it is only rated for 3.6V **MAX**.  It is best to "level-shift" between the two devices.  You can use a few discrete parts (resistors + a diode, or resistors + FETs) or a level-shifting module.  I recommend the latter, because they are cheap, and they also work for high-speed interfaces like SPI.

When you have level-shifting ready to add, move the GPS RX & TX connections to Arduino pin 9 (to GPS RX) and 8 (to GPS TX).  This will let you use `AltSoftSerial` instead of `SoftwareSerial`.  If you configure the NEO-6M to run at 9600 (that is the default), you could use [NeoSWSerial](https://github.com/SlashDevin/NeoSWSerial) on any two pins (besides 0 & 1 !!!).  I'm not sure why your NEO-6M is running at 4800, unless you used the u-center utility to configure it permanently.

Finally, I would suggest trying my [NeoGPS](https://github.com/SlashDevin/NeoGPS) library.  It is smaller, faster and more accurate than all other libraries, and it includes distance and bearing calculations that you might eventually need.

The Installation instructions guide you through several examples, after which you should try NMEAloc.  NeoGPS also has a diagnostic program, and lots of tips on the Troubleshooting page.  You can download it from the Arduino IDE Library Manager, under the menu **Sketch -> Include Library -> Manage Libraries**.

After going through those first examples, you should be ready to try your own sketch.  Here is your sketch, modified to use NeoGPS and either `AltSoftSerial`, `NeoSWSerial`, or the built-in `Serial1` on a Mega2560, Leo or Due:

    // Set up the GPS serial port (pick *one* of these choices)

    //#include <AltSoftSerial.h>
    //AltSoftSerial gps_port; // always 8 & 9 on an UNO

    //#include <NeoSWSerial.h>
    //#define rxPin 2
    //#define txPin 3
    //NeoSWSerial gps_port( rxPin, txPin );

    #define gps_port Serial1  // for a Mega2560, Leo or Due

    // Variables
    #include <NMEAGPS.h>
    NMEAGPS gps;
    gps_fix fix;

    #ifndef NMEAGPS_PARSE_GGA
      #error You must uncomment NMEAGPS_PARSE_GGA in NMEAGPS_cfg.h!
    #endif

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

      gps_port.begin(4800); // 9600 is the default for NEO-6M

      //setup satellites signal
      pinMode(13, OUTPUT);

      // Turn off the led until a satellite signal
      digitalWrite(13, LOW);

      Serial.println( F("Waiting GPS data...") );
    }

    void loop() {
      while (gps.available( gps_port )) {
        fix = gps.read();  // a new fix structure has been parsed
        plot();
      }
    }

    /*
      This function organize the gps data received for printing in the serial monitor.
    */

    void plot() {

      if (fix.valid.location) {
      // or if (fix.valid.status && (fix.status >= gps_fix::STATUS_STD)) {

        digitalWrite(13, HIGH); // Then there are satellites, the LED switch ON

        Serial.println();
        Serial.println( F("----------------------------------------------") );
        Serial.print  ( F("UTC Hour -> ") );
        if (fix.valid.time)
          Serial.println( fix.dateTime.hours );
        Serial.print  ( F("Latitude -> ") );
        Serial.println( fix.latitude(), 6 );
        Serial.print  ( F("Longitude -> ") );
        Serial.println( fix.longitude(), 6 );
        Serial.print  ( F("GPS status: 0=NONE; 1=EST, 2=TIME, 3=STD, 4=DGPS -> ") );
        if (fix.valid.status)
          Serial.print( fix.status );
        Serial.println();
        Serial.print  ( F("Number of satellites -> ") );
        if (fix.valid.satellites)
          Serial.print( fix.satellites );
        Serial.println();

        #ifdef GPS_FIX_HDOP
          Serial.print  ( F("Horizontal Dilution of Precision (x1000) -> ") );
          if (fix.valid.hdop)
            Serial.print( fix.hdop );
          Serial.println();
        #else
          #error You must uncomment GPS_FIX_HDOP in GPSfix_cfg.h!
        #endif

        Serial.print  ( F("Antenna altitude (m) -> ") );
        if (fix.valid.altitude)
          Serial.print  ( fix.altitude(), 2 );
        Serial.println();

        #ifdef GPS_FIX_GEOID_HEIGHT
          Serial.print  ( F("Geoid Separation (m) -> ") );
          if (fix.valid.geoidHeight)
            Serial.print  ( fix.geoidHeight(), 2 );
          Serial.println();
        #else
          #error You must uncomment GPS_FIX_GEOID_HEIGHT in GPSfix_cfg.h!
        #endif

        Serial.println( F("----------------------------------------------") );
        Serial.println();

      } else {
        // If no satellite connection
        digitalWrite(13, LOW); // Turn off the LED

        Serial.println();
        Serial.println( F("-----------------------------") );
        Serial.print  ( F("|--- Status -->") );
        if (fix.valid.status)
          Serial.print  ( fix.status );
        Serial.println();
        Serial.println( F(" |") );
        Serial.println( F("|----Waiting location----|") );
        Serial.println( F("-----------------------------") );
        Serial.println();
      }
    }

Note: Using `#if` statements, it verifies the configurations in NMEAGPS_cfg.h and GPSfix_cfg.h.  The Geoid Height field is not enabled in the default NeoGPS configuration.


message:
Am I able to connect an anti static wrist strap to the ground pin on the Arduino uno?

So you have the pin on the arduino uno which is ground, are you able to use a jumper wire to send the ground source out the other end of the wire to the alligator clip for the antistatic wrist strap?

body:
I was about to write that I wouldn't do that, but in view of the [post I linked to](https://electronics.stackexchange.com/questions/238065/connect-anti-static-wrist-strap-to-earth-wire) - I am changing my mind.

The point to the wrist strap it to have you, and the thing you are touching, at the same potential (whatever that is relative to the known Universe). Now if you connected the strap to the earth on your power point, that would not achieve anything unless your Arduino was **also** grounded (eg. via a USB cable).

So using the ground wire on the Arduino sounds sensible enough. Personally I don't usually do that, however if I have moved around (and might have shuffled over some carpet, etc.) I always touch some metal part to ground myself (for example, a metal switch on a lab power supply) and discharge any static that might have built up by moving around on the floor.


message:
Bluetooth signal returns 0

I have started programming Arduino in the last month. Now I'm working with a bluetooth module. But when I send some data from the Android device to the Arduino, it stays for a very short time and after that  immediately it becomes `0`.

Why does it become `0`? And how can I get rid of that problem?

Here is my code:

    int x,y;

    void setup()
    {
      Serial.begin(9600);
    }
    void loop()
    {
      if(Serial.available()>0)
      {
        x=Serial.parseInt();
        y=Serial.parseInt();
        Serial.print("x:");
        Serial.print(x);
        Serial.print("\n");
        Serial.print("y:");
        Serial.print(y);
        Serial.print("\n");
      }
      else
      {
        ;
      }
    }

and here is the result:

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

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

body:
`Serial.parseInt()` has a timeout. If something arrives on the serial, or is left over from a previous transmission and hasn't been read yet, `Serial.parseInt()` will start looking for a number to parse. When that fails it times out (and so does the second one immediately after it). When that timeout occurs `parseInt()` just returns 0.

IMHO the Arduino serial parsing routines are very poorly written and should be avoided. I have some tips on how to properly read serial [here](https://hackingmajenkoblog.wordpress.com/2016/02/01/reading-serial-on-the-arduino/).


message:
Strange power comsuption into sleep mode

I've finished my project and now I'm measuring the current but there is something wrong. I'm using an Arduino Pro Mini board and the [LowPower][1] library but the consumption is about **3.5 - 5 mA** and not less than 500 uA (the board remains into sleep mode almost all the time).

When I began to work with the board its LED was removed but I think that this work was not made correctly. How can I check that LED was removed correctly?

Thanks to all.

**EDIT1:** **The strange power consumption is not associated with board's LED.**

**EDIT2:** [@Gerben][2] has suggested me to review the state of SPI pins connected to the board. I use in this project a SD card module and GSM/GPRS module but the guilty of this excessive power consumption is the first. Then I've disconnected all SD card module's pins and then I get about **60 uA**, so the problem is on those pins but I can't reduce the power consumption. SD card module pins are 10,11,12 and 13 so I've used statements like `digitalWrite(10, LOW)`, `digitalWrite(11, LOW)` and so on after reading/writing on the SD card but it is useless.

**EDIT3:** I've decided to upload a representation of my project using Fritzing. The external modules are not identical but they contain the same pins.

General view of the circuit:[![general view of the circuit][3]][3].

Detail of the connections:

[![more detail][4]][4]

I use these external components:

 - [SD card module](https://www.elecfreaks.com/wiki/index.php?title=SD&MMC_Card_Module_Double_Side)
 - [A6 GPRS/GSM module](http://www.dx.com/es/p/open-smart-gprs-a6-pro-serial-gprs-gsm-module-core-developemnt-board-439972?tc=EUR&gclid=CLnm75W0_tECFYUp0wodeeQD6Q#.WJn2D_Ja3SA)

In my project there are some important details:

 - GPRS module is powered individually. The other battery is dedicated to power on the Arduino board and the SD card module.
 - Batteries are 6v.
 - Transistors base are controlled by 2 and 3 digital pins respectively.
 - The 8 and 9 pins of the Arduino board act like RX and TX pins using `AltSofSerial.h` library.

  [1]: https://github.com/rocketscream/Low-Power
  [2]: https://arduino.stackexchange.com/users/2881/gerben
  [3]: https://i.stack.imgur.com/bBYcx.png
  [4]: https://i.stack.imgur.com/9aEM5.png

body:
If you physically removed the LED make sure the pads for it aren't shorted together by old solder. If they aren't then you removed it correctly.

However: 5mA may be a perfectly reasonable current consumption for your project. Without seeing a full schematic and analysing your code it's impossible to say what kind of current you would expect to see.


body:
**SOLUTION** [by OP]

My problem was that the SD card module was consuming when it was controlled by a transistor and my Arduino board was into the sleep mode. So I wrote into the `void setup()` the `digitalWrite(PIN, HIGH)` statements where PIN represents all pins connected to the board that belong to the SD card module (DI, DO, CS, and CK pins), to enable the internal resistor of that pins. Then, I checked the power consumption and I reached less than 100 uA.


message:
DS18B20 and Arduino - Internall Pull-Up

Can this [DS18B20][1] sensor be used with Arduino internal pull-up or it require exactly 4.7k pull-up resistor?

  [1]: http://www.canadarobotix.com/temperature-sensor/1185-high-temperature-sensor-waterproof-ds18b20-protected

body: If the datasheet specifies a 4.7kΩ resistor then a 4.7kΩ resistor is what you need.


body:
The Arduino internal pull-up is something like 50k. That is a lot different from 4.7k. You would probably find that the pull-up is not strong enough to get clean pulses from the device. Also if you are using it in one-wire (parasitic) mode notice this from the datasheet:

> To assure that the DS18B20 has sufficient
supply current, it is necessary to provide a strong pullup on the 1-Wire bus whenever temperature
conversions are taking place or data is being copied from the scratchpad to EEPROM.

Notice the words 'strong pullup'. The internal pullup is not strong.


message:
Why is the stack pointer out of range?

I have a function that dumps the contents of the arduino's ram, and it works, but I still dont understand why it says my stack pointer is at 0x08C9 If the ram of the arduino is 2kb, or 2048 bytes, shouldent the max addressable size be 0x0800?

    RAM: SP->0x08C9 HP->0x0371 FREE:1368

And the code:

    void printAddress(uint16_t val)
    {
      Serial.print(F("0x"));
      if(val < 16)
    {
     Serial.print(F("0"));
    }
    if(val < 256)
     {
      Serial.print(F("0"));
    }
    if(val < 4096)
    {
      Serial.print(F("0"));
    }
    Serial.print(val,HEX);
    }

    void setup(){
    Serial.begin(115200);
    //0x0800 2048
    uint8_t *heapptr, *stackptr;
    stackptr = (uint8_t *)malloc(4);        // use stackptr temporarily
    heapptr = stackptr;                     // save value of heap pointer
    free(stackptr);                         // free up the memory again (sets stackptr to 0)
    stackptr =  (uint8_t *)(SP);            // save value of stack pointer

    Serial.print(F("RAM: SP->"));
    printAddress(stackptr);
    Serial.print(F(" HP->"));
    printAddress(heapptr);//(int)&__heap_start);
    Serial.print(F(" FREE:"));
    Serial.print(stackptr - heapptr);
    Serial.println();
    }

As a note, Comments are not mine.

body:
Sure... if the RAM started at address 0, which it doesn't.

According to the datasheet the RAM starts at address 0x0100, below which are all the SFRs:

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

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


body:
> free up the memory again (sets stackptr to 0)

Freeing memory alters the **heap**, not the stack. In any case the heap is not like the stack, it is a piece of memory from which memory is allocated, not necessarily contiguously. If you were to allocate A B C from the heap, and then delete B, the heap pointer would be untouched, because it would now have a gap: A ... C

> shouldn't the max addressable size be 0x0800?

As Majenko pointed out, RAM starts past the "internal registers" of the processor, so the maximum RAM would be 0x8FF in this particular case.


message:
Error: request for member 'RGB' in 'redLed' , which is of non-class type 'int'

My 10 year old received great gift from older brother (Crate Creations) and I am trying write the program and getting this error. It looks to me that I matched the required code word for word symbol for symbol but I just can't figure out what I did wrong:

    void loop () {

      for (float x = 0; x < PI; x = x + 0.00001) {
        RGB[0] = power * abs(sin(x * (CommonMathVariable)));
        RGB[1] = power * abs(sin((x + PI/3) * (CommonMathVariable)));
        RGB[2] = power * abs(sin((x + (2 * PI) / 3) * (CommonMathVariable)));
        ambientLight = analogRead(ldrPin);
        if (ambientLight > 600) {

        analogWrite (redLed.RGB[0]);
        analogWrite (greenLed.RGB[1];
        analogWrite (blueLed.RGB[2];

      }

I get this error:

<!-- language: lang-none -->

    request for member 'RGB' in 'redLed' , which is of non-class type 'int'

body:
Probably you didn't spot commas:

        analogWrite (redLed,   RGB[0]);
        analogWrite (greenLed, RGB[1]);
        analogWrite (blueLed,  RGB[2]);

The function `analogWrite` takes two arguments, separated by commas. You were missing some brackets as well.


message:
Optimization Teensy 3.6 Arduino IDE fast I/O Multiplexing Led Matirx

I'm currently working on a 10x10 LED Matrix which is controlled by 5 Shift registers using multiplexing. I've the problem that the Teensy 3.6 is too fast/slow.

One part of my code is the Shiftout function. If I use normal digitalWrite() its working perfectly fine, but its slow. If I use digitalWirteFast() or something like GPIOA_PSOR = (1 << 12); the matrix starts to display crap.

**Teensy 3.6 180MHz**

**74HC595 shift register**

**SS8050 BJT's to protect the whole thing**

scematic here: [circuits.io][1]

    void ShiftOut(uint8_t myDataOut) {
    // This shifts 8 bits out lngMsLoopstartB first,
    //on the rising edge of the clock,
    //clock idles low
    //internal function setup
    uint8_t i = 0;
    //clear everything out just in case to
    //prepare shift register for bit shifting

    //digitalWriteFast(dataPin, LOW);//Data aus
    GPIOA_PCOR = (1 << 12); // Datapin low

    //digitalWriteFast(clockPin, LOW);//Clock aus
    GPIOA_PCOR = (1 << 13); // Clockpin low

    //for each bit in the uint8_t myDataOut
    //This means that 000001 or "1" will go through such
    //that it will be pin Q0 that lights.
    for (i = 0; i <= 7; i++)  {

    //digitalWrite(clockPin, LOW);//Clock aus
    GPIOA_PCOR = (1 << 13); // Clockpin low

    //if the value passed to myDataOut and a bitmask result
    // true then... so if we are at i=6 and our value is
    // 010100 it would the code compares it to 000000
    // and proceeds to set pinState to 1.
    if ( myDataOut & (1 << i) ) {
      //digitalWriteFast(dataPin, HIGH);//Data an
      GPIOA_PSOR = (1 << 12); // Datapin high

    } else {
      digitalWrite(dataPin, LOW);//Data aus
      //GPIOA_PCOR = (1 << 12); // Datapin low
    }

    //register shifts bits on upstroke of clock pin
    digitalWrite(clockPin, HIGH);//Clock an
    //GPIOA_PSOR = (1 << 13); // Clockpin high

    digitalWrite(clockPin, LOW);//Clock aus
    //GPIOA_PCOR = (1 << 13); // Clockpin low

    //zero the data pin after shift to prevent bleed through
    digitalWrite(dataPin, LOW);//Data aus
    //GPIOA_PCOR = (1 << 12); // Datapin low
    }
    }

if somebody needs the **complete** code, please let me know!

1. How it looks like when I use GPIO 2.Picture how it should look like: [Imgur][3]

**Problem**

The thing I want is to make the whole multiplexing faster. Currently 1 Time all 10 rows takes about 480 microseconds. Then add a 4 Bit Bit angle modulation (480*16) its: 7680 microseconds (7.68ms). So if you now divide 1000 by 7.68 = 130,2 Hz refresh rate. Thats ok and Im fine with that.

The main problem is that I want 8 bit. so same thing again 480 * 256 = 112880 (112,88ms). So now divide 1000 by 112,88 = 8,86 Hz refresh rate. That looks really bad. I would like to get about 60-100.

The Problem is **not** the big LED array or setting each value every frame new. This only takes 80 microseconds.

  [1]: https://circuits.io/circuits/2924748#breadboard
  [3]: https://i.stack.imgur.com/t7Zlg.jpg

body:
I have also written a driver for LED matrices based on shift registers. To quickly shift out the bits to the shift registers for each scan update, I used SPI. On the Teensy 3.6, this works quite well.

But what I suspect your issue is (since you didn't post your whole code) is that you are calculating each of the bit updates in between each shifting out. If you are doing this, I suggest that you don't. Instead, buffer the bit calculations, and use a timer interrupt to shift out each row update. This approach takes advantage of the fact that you are likely to recalculate the bit layout for the matrix overall at a much slower frequency than the need to send our row updates to effect the multiplexing of the LED rows. I explain this design in much more detail in [this Instructable][1].

Using the interrupt allows you to cleanly do the heavy lifting of recalculating the bit layout into a buffer while the row updates will consistently go out, creating a very stable image. It's the closest thing you'd to true threading on Arduino-like platforms. Also, this approach will allow a much smaller base interval for row updates. In my code, I use a 5 µs update interval, that gets modulated in order to be able to create a 12-bit color palette. I probably could get a richer color depth on the Teensy 3.6 given it's clock speed, but I wanted my code to be universal, so I am able to get the 12-bit color on 8-bit AVR micro controllers too (e.g., Arduino Mega).

You can study (or use) my code at [this GitHub repository][2], and read more about my LED matrices (hardware and software) at [my website][3].

  [1]: http://www.instructables.com/id/RGB-LED-Matrix-1/
  [2]: https://github.com/michaelkamprath/ShiftRegisterLEDMatrixLib
  [3]: http://kamprath.net/led-matrix/


message:
Weird characters at the end of LCD

I have written a simple sketch that displays temperature and humidity on a 16x2 LCD. Here's its output:

Temp: 28▒▒
Humidity: 68▒▒

The library I used for DHT11 sensor is not from Adafruit. This is the sketch:

    #include <Wire.h>
    #include <LCD.h>
    #include <LiquidCrystal_I2C.h>
    #include<dht.h>

    #define DHT11_PIN 12
    #define I2C_ADDR       0x3F
    #define BACKLIGHT_PIN  3
    #define En_pin         2
    #define Rw_pin         1
    #define Rs_pin         0
    #define D4_pin         4
    #define D5_pin         5
    #define D6_pin         6
    #define D7_pin         7
    #define SCL_PIN        12
    #define SDO_PIN        11

    dht DHT;
    LiquidCrystal_I2C  lcd(I2C_ADDR, En_pin, Rw_pin, Rs_pin, D4_pin, D5_pin, D6_pin, D7_pin);

    void setup() {
      pinMode(SCL_PIN, OUTPUT);
      pinMode(SDO_PIN, INPUT);
      lcd.begin (16, 2);
      lcd.setBacklightPin(BACKLIGHT_PIN, POSITIVE);
      lcd.setBacklight(HIGH);
      lcd.home ();
    }

    void loop() {
      lcd.setCursor(0, 0);
      int chk = DHT.read11(DHT11_PIN);
      lcd.print("Temp: ");
      lcd.println(DHT.temperature,0);
      lcd.setCursor(0, 1);
      lcd.print("Humidity: ");
      lcd.println(DHT.humidity,0);
      delay(2000);
    }

body:
The function `println` usually appends a carriage-return and linefeed to what it prints. It wouldn't surprise me if those two extra characters are its attempt to "render" that.

Try replacing `println` with `print` and see what happens.


message:
Java NetBeans sending value and receiving value from Arduino

This is my Java code to send a value to Arduino and a receiving value from Arduino. Can anyone tell where I made a mistake? I am able to send the value but can't receive a value from Arduino.

    package hell;

    import com.panamahitek.ArduinoException;
    import com.panamahitek.PanamaHitek_Arduino;
    import gnu.io.CommPortIdentifier;
    import gnu.io.SerialPort;
    import gnu.io.SerialPortEvent;
    import gnu.io.SerialPortEventListener;
    import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.InputStreamReader;
    import java.io.OutputStream;
    import java.util.Enumeration;
    import java.util.Scanner;
    import java.util.logging.Level;
    import java.util.logging.Logger;

    public class led extends javax.swing.JFrame
    {
        PanamaHitek_Arduino Arduino  = new PanamaHitek_Arduino();
        private BufferedReader input;
        SerialPort serialPort;

        public led(){
            initComponents();
            try {
                Arduino.arduinoTX("com3", 115200);
            }
            catch (ArduinoException ex) {
                Logger.getLogger(led.class.getName()).log(Level.SEVERE, null, ex);
            }
        }

        public synchronized void close() {
            if (serialPort != null) {
                serialPort.removeEventListener();
                serialPort.close();
            }
        }

        public synchronized void serialEvent(SerialPortEvent oEvent)
        {
            System.out.println("lol 31");
            if (oEvent.getEventType() == SerialPortEvent.DATA_AVAILABLE) {
                try {
                    System.out.println("lol 1.1");
                    Scanner s = new Scanner(serialPort.getInputStream());
                    int mes =Integer.parseInt( s.nextLine());
                    System.out.println(mes);
                    System.out.println("lol 1");
                } catch (Exception e) {
                    System.err.println(e.toString());
                    System.out.println("Syncronice ");
                }
            }
            // Ignore all the other eventTypes, but you should consider the other ones.
        }

        private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
            try{
                Arduino.sendByte(0);
            }
            catch(Exception ex){
                Logger.getLogger(led.class.getName()).log(Level.SEVERE,null, ex);
            }
            System.out.println("led is off");
        }

        private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
            try{
                Arduino.sendByte(1);
            }
            catch(Exception ex){
                Logger.getLogger(led.class.getName()).log(Level.SEVERE,null, ex);
            }
            System.out.println("led is on");
        }

        public static void main(String args[]) {
            java.awt.EventQueue.invokeLater(new Runnable() {
                public void run() {
                    new led().setVisible(true);
                }
            });
        }

        private javax.swing.JButton jButton1;

        try{
            Arduino.sendByte(1);
        }
        catch(Exception ex){
            Logger.getLogger(led.class.getName()).log(Level.SEVERE,null, ex);
        }

        System.out.println("led is on");

        private javax.swing.JButton jButton2;
    }

Here is my Arduino code, which receives a value from Java and prints it accordingly:

    int val = 0;
    int led = 8;

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

    void loop() {
      if (Serial.available()>0) {
        val = Serial.parseInt();
        if(val == 1) {
          //Switch on the LED, if the received value is 1.
          digitalWrite(led, HIGH);
          Serial.println("Succesfully received.");
        } else if(val == 0) {
          //Switch off the LED, if the received value is 1.
          digitalWrite(led, LOW);
        }
      }
    }

EDIT:
There is no problem to controlling arduino via Java code, the problem is that I can't received message from Arduino to display in a Java.

body:
You are writing a number as a single byte and expect it as a string on the other end.

Replace

    val = Serial.parseInt();

with

    val = Serial.read();


message:
Storing data on AT24C02 EEPROM chips with Arduino

I have recently come across some  8-pin 128-byte EEPROM chips. I've seen those USB EEPROM chip programmer units, but I was wondering if there is any way I could manually store data on the chip with my Arduino.

I don't have any application for the chips yet, but I would just like to see if I can read / write data on the chips.

[Here's the data sheet](http://www.atmel.com/Images/doc0180.pdf) for the chips.

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

You wire your chips on a breadboard, with the +/- left rail for Vcc/GND, and the right +/- rail for SCL/SDA, plus a little acrobatics to connect everything.

Your chips can have 8 addresses, 0x50 to 0x57, set up with the A0/1/2 pins: all low = 0x00, all high = 0x07. The you read and write to the EEPROM of your choice with:

    char i2c_eeprom_read_char(int deviceaddress, unsigned int eeaddress) {
      char rdata = 0xFF;
      Wire.beginTransmission(deviceaddress);
      Wire.write((int)(eeaddress >> 8)); // MSB
      Wire.write((int)(eeaddress & 0xFF)); // LSB
      Wire.endTransmission();
      Wire.requestFrom(deviceaddress,1);
      if (Wire.available()) rdata = Wire.read();
      return rdata;
    }

    void i2c_eeprom_write_char(int deviceaddress, unsigned int eeaddress, char data) {
      int rdata = data;
      Wire.beginTransmission(deviceaddress);
      Wire.write((int)(eeaddress >> 8)); // MSB
      Wire.write((int)(eeaddress & 0xFF)); // LSB
      Wire.write(rdata);
      Wire.endTransmission();
    }

If you have more than 8 chips (well throw them away and get larger ones, but anyway, for completeness sake): wire all of them with A1/A2 to GND, and each A0 to a different digital pin. When you need to access a chip, set all A0s to LOW, except the one you want to HIGH, and use 0x51 as the address. By doing this you're setting all chips except the one you want to address 0x50 (which doesn't matter) leaving only one at 0x51. That enables you to have as many chips as you have free digital pins...

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


message:
How should I initialize a RepRap Discount 12864 on u8glib?

I was taking the advantage of an existing piece of hardware (RepRapDiscount Full Graphic Smart Controller) for my present project.

[Here][1] is a link for the RepRap wiki about the controller

    #define LCD_PIN_SCLK   A4
    #define LCD_PIN_MOSI   6
    #define LCD_PIN_CS   8
    U8GLIB_ST7920_128X64_1X u8g(A4,6,8, U8G_PIN_NONE);

But all I got is a blank screen with no light at all. What has happened?

  [1]: http://reprap.org/wiki/RepRapDiscount_Full_Graphic_Smart_Controller

body:
I solved the problem myself. It turns out to be a problem of wrong pinouts.

My PCB of the project was originally designed for the LCD2004 counterpart, and I thought it was a drop-in replacement for 12864. But no, it's not.

[![RAMPS Smart Adaptor 12864 vs 2004][1]][1]
This is the "Smart Adaptors". Notice that the orientation are 180 degree different.

If you have the same problem ***not lighting up a 12864 when switching from 2004***, or vice versa. Check your orientation as above.

My solution will be crimping a different JTAG wire instead.

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


body:
I had a similar issue with figuring out how to get the Zyltech.com RepRapDiscount Full Graphic Smart Controller (with their Mega 2560 clone) to work with u8glib. After some fiddling it looks like the correct settings for me were:

    // SPI Com: SCK = en = 23, MOSI = rw = 17, CS = di = 16
    U8GLIB_ST7920_128X64_1X u8g(23, 17, 16);


message:
What happens if device sends data to arduino over serial port (UART) and arduino is unable to read it

Suppose delay(10000) function is executed, so Arduino cannot do any other work.

> During this time if the other device sends the data to arduino what
> will happen ?

body:
Depending on the memory available, between 16 and 256 bytes will be stored in a ring buffer. Any bytes that arrive after that will be just thrown away.

The reception code in the core is:

    void HardwareSerial::_rx_complete_irq(void)
    {
      if (bit_is_clear(*_ucsra, UPE0)) {
        // No Parity error, read byte and store it in the buffer if there is
        // room
        unsigned char c = *_udr;
        rx_buffer_index_t i = (unsigned int)(_rx_buffer_head + 1) % SERIAL_RX_BUFFER_SIZE;

        // if we should be storing the received character into the location
        // just before the tail (meaning that the head would advance to the
        // current location of the tail), we're about to overflow the buffer
        // and so we don't write the character or advance the head.
        if (i != _rx_buffer_tail) {
          _rx_buffer[_rx_buffer_head] = c;
          _rx_buffer_head = i;
        }
      } else {
        // Parity error, read byte but discard it
        *_udr;
      };
    }


message:
Turning an electric vehicle

I am not sure if what I am asking is possible. I was wondering if I would be able to program my Arduino to have my car go straight until one of the wheels hits a certain amount of wheel rotations then initiating a different code within the same causing that wheel to increase that wheels speed. I have already created a code to make it go and stop in a certain amount of rotations.

    /* motorshield_code
    Pins Utilized
    Digital 2 = encoder0APinA
    Digital 3 (PWM) = MotorASpeed  //motorshield utilized
    Digital 4 = encoder0PinB
    Digital 8 = MotorBBrakePin // motorshield utilized
    Digital 9 = MotorABrakePin // motorshiled utilized
    Digital 11 = MotorBSpeedPin // motorshiled utilized
    Digital 12 = MotorADirectionPin // motorshiled utilized
    Digital 13 = MotorBDirectionPin // motorshiled utilized
    */

    //Encoder values
    const int encoder0PinA = 2;
    const int encoder0PinB = 4;
    const int encoder1PinA = 7;
    const int encoder1PinB = 6;
    int encoder1Pos = 0;
    int encoder0Pos = 0;
    int encoder0PinALast = LOW;
    int encoder1PinALast = LOW;
    int n = LOW;
    int i = 0;

    //Motorshield Pin Values
    const int MotorADirectionPin = 12; //digital pin value for A direction
    const int MotorASpeedPin = 3; //analog pin value for A speed (PWM)
    const int MotorABrakePin = 9; // digital pin value for A brake
    const int MotorBDirectionPin = 13; //digital pin value for A direction
    const int MotorBSpeedPin = 11; //analog pin value for A speed (PWM)
    const int MotorBBrakePin = 8; // digital pin value for A brake
    //Motor Control Values
    int BrakeA = LOW; //Brake for motor A, LOW = motor off, HIGH = motor on
    int BrakeB = LOW;
    int DirectionA = HIGH; //Direction for motor A, LOW/HIGH are opposite (based on wiring) assume Low is forward
    int DirectionB = LOW;
    int SpeedA = 0; //Speed for motor A, PWM value from 0 - 255 (0 is off)
    int SpeedB = 0;
    int encoder0stop = 469.125; //stop value for encoder 0
    int encoder1stop = 469.125; //stop value for encoder 1

    void setup() {
      //Set Digital I/O pins 2 and 4 to inputs for encoder
      pinMode (encoder0PinA, INPUT);
      pinMode (encoder0PinB, INPUT);
      pinMode (encoder1PinA, INPUT);
      pinMode (encoder1PinB, INPUT);
      //Set Digital I/O pins as outputs for motorshield
      //Analog pins are already set so don't have to initialize speed pins
      pinMode(MotorADirectionPin, OUTPUT);
      pinMode(MotorABrakePin, OUTPUT);
      pinMode(MotorBDirectionPin, OUTPUT);
      pinMode(MotorBBrakePin, OUTPUT);
      //Start serial monitor at 9600
      Serial.begin (9600);
      delay (0);
      Serial.print("Last Enc State");
      Serial.print(" ");
      Serial.print("Current Enc State");
      Serial.print(" ");
      Serial.print("Encoder Count");
      Serial.print(" ");
      Serial.print("Speed");
      Serial.print(" ");
      Serial.print("Brake");
      Serial.print(" ");
      Serial.print("Direction");
      delay(2000);
    }

    void loop() {
      if (i == 0) {
        analogWrite(MotorASpeedPin, 255); //set motor A speed
        analogWrite(MotorBSpeedPin, 255); //set motor B speed
        i++;
      }
      //Set values to write to arduino
      if (encoder0Pos < encoder0stop) {
        //if hasn't reached end encoder value
        //Direction Forward, Brake OFF, speed 125
        DirectionA = HIGH;
        DirectionB = LOW;
        BrakeA = LOW;
        BrakeB = LOW;
        SpeedA = 254;
        SpeedB = 253;
      } else {
        //if has reached encoder value
        //Direction Forward, Brake ON, speed 0
        DirectionA = HIGH;
        DirectionB = LOW;
        BrakeA = HIGH;
        BrakeB = HIGH;
        SpeedA = LOW;
        SpeedB = LOW;
      }

      //Write all values to the arduino
      digitalWrite(MotorADirectionPin, DirectionA); //set motor A direction
      digitalWrite(MotorBDirectionPin, DirectionB); //set motor B direction
      digitalWrite(MotorABrakePin, BrakeA); //write motor A brake on/off
      digitalWrite(MotorBBrakePin, BrakeB); // write motor B brake on/off
      analogWrite(MotorASpeedPin, SpeedA); //set motor A speed
      analogWrite(MotorBSpeedPin, SpeedB); //set motor B speed
      //Read Encoder
      //This is reading PinA which should be set to pin 2 and storing it as n
      n = digitalRead(encoder0PinA);
      //Check to see if pin 2 has changed from LOW to HIGH
      if ((encoder0PinALast == LOW) && (n == HIGH)) {
        //Check to see if pin 4 is LOW -> this determines which direction the encoder is going
        if (digitalRead(encoder0PinB) == LOW) {
          //encoder is going "backwards" decrease encoder position
          encoder0Pos--;
        } else {
          //If pin 4 is HIGH
          //encoder is going "forward", increase encoder position
          encoder0Pos++;
        }
        //Tell us what is happening!
        Serial.print (encoder0Pos);
        //go to the next line of code
        Serial.print(" ");
        Serial.print(encoder0PinALast);
        Serial.print(" ");
        Serial.print(n);
        Serial.print(" ");
        Serial.print(encoder0Pos);
        Serial.print(" ");
        Serial.print(SpeedA);
        Serial.print(" ");
        Serial.print(BrakeA);
        Serial.print(" ");
        Serial.print(DirectionA);
        Serial.println();
        encoder0PinALast = n;
      }
      //Set what the last read of pin 2 was so we can compare to see if it changes
      encoder0PinALast = n;
      //End Code for Encoder Reading
    }

body:
I would say that one of the solutions would be to arrange the code in your car into a finite state machine. So your states would be something like:

 1. Start (reset the encoders and set the initial speed)
 2. Go straight (both motors at 100%)
 3. Turn left (left motor at 75%, right at 100%)
 4. Turn right (right motor at 75%, left az 100%)
 5. Stop (stop both motors)

Example code:

    //TODO: Init program and variables
    void go_straight()
    {
        if(number_of_rotations > 10)
        {
            state = TURN_LEFT
        }
        else
        {
            motor_left = 100;
            motor_right = 100;
        }
    }
    void turn_left()
    {
        if(number_of_rotations > 10)
        {
            state = TURN_RIGHT
        }
        else
        {
            motor_left = 100;
            motor_right = 75;
        }
    }
    //TODO: Implement remaining methods

    void loop()
    {
        //Update number of rotations since state change
        update_rotations();
        if(state == START)
            start();
        else if(state == GO_STRAIGHT)
            go_straight();
        else if(state == TURN_LEFT)
            turn_left();
        else if(state == TURN_RIGHT)
            turn_right();
        else
            stop();
        //This code gets executed on every loop cycle and is not dependent on state
        print_status();
        wait(100);
    }


message:
Connect my Arduinos to central server, despite different IP adresses

Community,

A team of friends just built, with an Arduino UNO, a system where one can open a door lock from the internet.
The Arduino UNO has an Ethernet Module (ENC28J60). When the command prompts, the Arduino will let a solenoid receive 5v, which will open it and, therefore, open the door.

The novel thing is, this door-opening-arduino connects via the Internet to a central server, a webpage that 'centralizes' the door-opening process. So, in a certain URL, we'll get a screen which goes:

[![example of the webpage which centralizes door-opening actions][1]][1]

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

All these doors are in remote locations, connected to very different routers. Some of these routers will go **192.168.1.1**, whereas others will go with the **0.1** ending.

So far, my friend has hard-coded the internal IP address 192.168.1.143 for identifying the Arduino, so, he's given up on DHCP.
Afterwards, he's chosen port 6560 to be the open port and connect the door to the Internet. (VPN is not a option).

So the public IP address and port 6560 are our way in into the door. This info is shared with his webpage, where commands can be given: 'open it'.

But with these hard-coding of the 1.143 IP and the router's different default addresses, we've had trouble. You know what I mean: sometimes, the whole code must be changed for our Arduino to connect to the router. Not even close to 'plug-n-play'.

My questions seems natural: how can we ensure the Arduino connects each time to the router, without any problems?
Most devices just connect: an IP camera in these routers will connect, and will never care which IP address the router has given it. If the router resets, things will be fine, and connection will restart.

So, why not DHCP? As far as my understanding goes, a problem my friend mentioned that would happen if he chose to use DHCP would be the communication between his Arduino and his online server: 'how can I know which IP I should speak with in order to open the door? By choosing the .143, I know which would should be'.
Another problem comes in with port forwarding. Apparently, by choosing the .143 and then using port 6560, we ensure that we can access via the Internet, because there's a standarized procedure: 'please open port 6560 for this IP'.

This is a bit cumbersome. Most devices just don't work this way. We want to be able to just plug it in, let our Arduino and the router get any IP, and by just opening port 6560, we're in. Pretty simple.

How can we ensure that:

 - Our Arduino **just connects to the router**, and
 - that **communication between our Arduino and the centralized server
   just flows**?

*Another friend suggested configuring each router so that a device with a certain MAC address (our Arduino) gets* this IP* *and* this port forwarding. *But what if the default address is 192.168.0.1 (instead of 1.1), for example? wouldn't we be facing a problem?*

We're seeking a kind of plug-n-play thing, like most access control systems work. Hardware's ok, it's connection the thing that bugs us.

Any suggestions, advice, or plain responses are really welcome. I think we're just a step away from our commit, which is creating a reliable connection for these doors. It may be just a line of code, or a config trick. Thank you for your time.

**(you'll soon notice we're not that savvy on routing and switching, so If we got our premises completely wrong, don't hesitate to correct us)**

body:
Your problem is two-fold, and neither are easy for an Arduino to overcome.

First you have the problem that the router's internet-facing IP address is (unless you have a special arrangement with your ISP) liable to change at any time. You need to keep your sever up to date at all times with what that IP address is, and the only real way of doing that is for the router, or something behind the router, to connect with your server so it can update its IP address.

Secondly you have the port forwarding. The router has to know where to forward the port to. That means that either the IP address of the Arduino has to be static, or the Arduino has to somehow tell the router to do the port forwarding.  The simplest method is just to allocate a static IP address as you have done. The alternative is to use UPnP to instruct the router "I need you to forward this port through to me" - assuming the router understands UPnP. The hardest part of that though is getting the Arduino to speak UPnP. I am not aware of any UPnP libraries for the Arduino.

So keep the static IP address for the Arduino, it is simplest. One thing to note with manually allocating an IP address though is that it is vitally important you allocate it *outside* the IP address range of the DHCP server. Otherwise it is possible that the DHCP server could then allocate the IP address to someone else, and you'd then get a conflict. Most routers allow you to choose the range of IP addresses so you may want to go in and check that the DHCP server isn't able to clobber the IP address you have chosen.

To help solve the first problem some routers provide a "DDNS" (Dynamic DNS) facility, whereby they will periodically connect to a DDNS service to update a DNS record with the public IP address of the router. Not all provide it and those that do usually only provide access to a couple of DDNS services, so check your router to see if it does support it and if there is a suitable one for your needs there. If there is you can configure that and then, instead of connecting to the IP address of your router for issuing commands you instead connect to the DDNS domain name allocated to your router.

However, there is one much simpler option that solves all the problems in one go: reverse the communications.

Instead of the server connecting to the router to forward the port through to the Arduino to issue a command, it is far simpler (though I will admit not as responsive) for the Arduino, from whatever IP address it happens to be on, to just connect to the server itself and ask it for any pending commands.

If you have the ability to run your own software on the server you could even create your own small TCP server which the Arduino connects permanently to. The server can then send commands down that TCP connection just as if you were working with an Arduino directly connected by serial.

In both those situations it doesn't matter what IP address your router is on. You don't need to do any port forwarding. The Arduino can be on any IP address on your network.

And further more you have more security - no one could connect to your Arduino through the internet and cause havoc.


body:
I would use socket.io for this. Here is a goos presentation on this:

http://www.robojay.us/wp-content/uploads/2016/08/NRB-socket-io.pdf


message:
What is the difference between a 3 pin and 4 pin ultrasonic range sensor?

I am following a tutorial that uses an arduino and ultrasonic range sensor, it calls for a 3 pin module (Paralax 28015-ND) and I have a 4 pin module (http://www.electroschematics.com/wp-content/uploads/2013/07/HCSR04-datasheet-version-1.pdf).  The 3 pin seems to have one signal pin (both input and output) and the 4 pin has two separate signal pins (a trigger and echo).  How would I need to change the code and wiring if I am using the 4 pin?  Here is the code from the tutorial:

         /* Ping))) Sensor

       This sketch reads a PING))) ultrasonic rangefinder and returns the
       distance to the closest object in range. To do this, it sends a pulse
       to the sensor to initiate a reading, then listens for a pulse
       to return.  The length of the returning pulse is proportional to
       the distance of the object from the sensor.

       The circuit:
     * +V connection of the PING))) attached to +5V
     * GND connection of the PING))) attached to ground
     * SIG connection of the PING))) attached to digital pin 7

       http://www.arduino.cc/en/Tutorial/Ping

       created 3 Nov 2008
       by David A. Mellis
       modified 30 Aug 2011
       by Tom Igoe
       modified again 02 Apr 2016
       by Randy Sarafan

       This example code is in the public domain.

     */

    // this constant won't change.  It's the pin number
    // of the sensor's output:
    const int pingPin = 4;

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

    void loop() {
      // establish variables for duration of the ping,
      // and the distance result in inches and centimeters:
      long duration, inches, cm;

      // The PING))) is triggered by a HIGH pulse of 2 or more microseconds.
      // Give a short LOW pulse beforehand to ensure a clean HIGH pulse:
      pinMode(pingPin, OUTPUT);
      digitalWrite(pingPin, LOW);
      delayMicroseconds(2);
      digitalWrite(pingPin, HIGH);
      delayMicroseconds(5);
      digitalWrite(pingPin, LOW);

      // The same pin is used to read the signal from the PING))): a HIGH
      // pulse whose duration is the time (in microseconds) from the sending
      // of the ping to the reception of its echo off of an object.
      pinMode(pingPin, INPUT);
      duration = pulseIn(pingPin, HIGH);

      // convert the time into a distance
      inches = microsecondsToInches(duration);
      cm = microsecondsToCentimeters(duration);

      Serial.print(inches);
      Serial.print("in, ");
      Serial.print(cm);
      Serial.print("cm");
      Serial.println();

body:
It's simple enough... instead of:

    pinMode(pingPin, INPUT);
    duration = pulseIn(pingPin, HIGH);

You would have

    pinMode(echoPin, INPUT);
    duration = pulseIn(echoPin, HIGH);

(of course you have to define `echoPin` to be whatever pin you choose to connect `ECHO` to).

And to save processing time you can have all your `pinMode()` calls in setup since there is no need to change mode on the fly any more.


message:
Showing chronometer on PC controlling the begining and end of time by Arduino

I'm really new on this Arduino thing, so I don't know whether what I'm gona ask is feasible or not.

I'd like to make a chronometer in the computer but the controlling button (beginning and end of count) not to be some computer key. So I was wandering if I could make a button controlled by the arduino - maybe via a piezoelectric element?

Besides the problem of not knowing what to use as a button, I don't really know if it's possible to make a graphical interface (i know how to programme in C, Python, ...) showing the numbers in the screen of the computer and the beginning and end of counting controlled by that button. Is this possible to do?

Thanks for any help to both questions!

body:
It's perfectly possible to do, and the way I would probably do it is to use one of the ATMega32U4 based Arduinos (such as the Arduino Leonardo or the somewhat smaller Arduino Micro) to act like a keyboard. A keyboard with just one key - your chosen button.

Then you program the computer to respond to the keycode the Arduino sends to start and stop the chronometer. You could even use an off the shelf chronometer program that starts and stops with a specific keypress and tell the Arduino to send that keypress. It would probably take about 5 minutes to write the software - if that.


body:
I am already familiarized with the concept of serial communication. I can turn on/off LED via Serial Monitor.

I can also connect it with Python and I've made a small program that makes the LED blink - and this works perfectly.

However I now added a pushbutton to my circuit, so that when it is pressed, the blinking process is interrupted. But this is not working. My attempt was to send a Serial.print when the pushbutton is pressed with the message "Exiting\n".

Part of my Arduino code is:

    if(digitalRead(BUTTON) == HIGH){
    Serial.print("Exiting\n");
    while(1){}
    }

And part of my Python code is:

    while True:
        arduino.write("Y")
        print arduino.readline()
        time.sleep(0.5)
        arduino.write("N")
        time.sleep(0.5)

        try:
           if arduino.readline() == 'Exiting\n':
              print arduino.readline()
              break
        except:
              print("nothing\n")

The problem is that when I run the program, it gets stucked in the line

    if arduino.readline() == 'Exiting\n':

Any help?


message:
Arduino Nano nRF24L01+ DFPlayer Mini SPI Problem

I'm working with an Arduino Nano board clone (CH340) on wireless control of DFPlayer Mini, transceiver sending a Struct variable with MachinePrefix (just in case), sound type (I have more folders by type of machines) and number of sounds.

The transceiver works fine, but the receiver doesn't. If I upload data into the Arduino, the DFPlayer plays the first song once (row 43 - myDFPlayer.play(1)), but after nRF24 init is not working.

After nRF24 init I'm still receiving data in valid format and range. If I comment out the nRF24 part, the DFPlayer is working, but together not. I read about working two devices on one SPI bus but I don't understand what's wrong. I think the problem is the same MOSI pin. In my opinion it should work but did not.

Any suggestions?

**Here is the code of receiver:**

<pre>
#include <SPI.h>
#include "RF24.h"
#include "Arduino.h"
#include "SoftwareSerial.h"
#include "DFRobotDFPlayerMini.h"

RF24 myRadio (8, 9); // CE, CS
byte addresses[][6] = {"Sx001"};

SoftwareSerial mySoftwareSerial(10, 11); // RX, TX
DFRobotDFPlayerMini myDFPlayer;
void printDetail(uint8_t type, int value);

struct dataStruct {
  short machinePrefix;
  short soundType;
  short soundNumber;
} dataReceived;

void setup() {
  mySoftwareSerial.begin(9600);
  Serial.begin(115200);
  delay(1000);
  Serial.println(F("RF24+dfplayermini-recever"));
  Serial.println(F("Initializing DFPlayer ... (May take 3~5 seconds)"));
  if (!myDFPlayer.begin(mySoftwareSerial)) {  //Use softwareSerial to communicate with mp3.
    Serial.println(F("Unable to begin:"));
    Serial.println(F("1.Please recheck the connection!"));
    Serial.println(F("2.Please insert the SD card!"));
    while(true);
  }

  Serial.println(F("DFPlayer Mini online."));
  myDFPlayer.setTimeOut(500);
  myDFPlayer.volume(5);  //Set volume value. From 0 to 30
  myDFPlayer.play(1);  //Play the first mp3
  //----------------------------
  delay(1000);
  myRadio.begin();  // Start up the physical nRF24L01 Radio
  myRadio.setChannel(108);  // Above most Wifi Channels
  // Set the PA Level low to prevent power supply related issues since this is a
  // getting_started sketch, and the likelihood of close proximity of the devices. RF24_PA_MAX is default.
  myRadio.setPALevel(RF24_PA_MAX);
  myRadio.setDataRate(RF24_250KBPS);
  //  myRadio.setPALevel(RF24_PA_MAX);  // Uncomment for more power
  myRadio.openReadingPipe(1, addresses[0]); // Use the first entry in array 'addresses' (Only 1 right now)
  myRadio.startListening();
  Serial.println(F("RF24 online."));
}//--(end setup )---

void loop() {  /****** LOOP ******/
  if (myDFPlayer.available()) {
    printDetail(myDFPlayer.readType(), myDFPlayer.read()); //Print the detail message from DFPlayer to handle different errors and states.
  }
  if (myRadio.available()) { // Check for incoming data from transmitter
    while (myRadio.available()) { // While there is data ready
      myRadio.read( &dataReceived, sizeof(dataReceived) ); // Get the data payload
    }
    Serial.println("loop");
    myDFPlayer.loop(3);
    if (dataReceived.machinePrefix == 11001) {
      Serial.println("same device prefix");
      int playingData = dataReceived.soundNumber;
      if (myDFPlayer.available()) {
        Serial.println("player available");
        Serial.println(myDFPlayer.readType());
        Serial.println(myDFPlayer.read());
      }
      myDFPlayer.play(2);
    }
    Serial.println(dataReceived.machinePrefix);
    Serial.println(dataReceived.soundType);
    Serial.println(dataReceived.soundNumber);
    Serial.println("-----------------------------");
  } //END Radio available
}//--(end main loop )---

/*----------*/
void printDetail(uint8_t type, int value){
  switch (type) {
    case TimeOut:
      Serial.println(F("Time Out!"));
      break;
    case WrongStack:
      Serial.println(F("Stack Wrong!"));
      break;
    case DFPlayerCardInserted:
      Serial.println(F("Card Inserted!"));
      break;
    case DFPlayerCardRemoved:
      Serial.println(F("Card Removed!"));
      break;
    case DFPlayerCardOnline:
      Serial.println(F("Card Online!"));
      break;
    case DFPlayerPlayFinished:
      Serial.print(F("Number:"));
      Serial.print(value);
      Serial.println(F(" Play Finished!"));
      break;
    case DFPlayerError:
      Serial.print(F("DFPlayerError:"));
      switch (value) {
        case Busy:
          Serial.println(F("Card not found"));
          break;
        case Sleeping:
          Serial.println(F("Sleeping"));
          break;
        case SerialWrongStack:
          Serial.println(F("Get Wrong Stack"));
          break;
        case CheckSumNotMatch:
          Serial.println(F("Check Sum Not Match"));
          break;
        case FileIndexOut:
          Serial.println(F("File Index Out of Bound"));
          break;
        case FileMismatch:
          Serial.println(F("Cannot Find File"));
          break;
        case Advertise:
          Serial.println(F("In Advertise"));
          break;
        default:
          break;
      }
      break;
    default:
      break;
  }
}
</pre>

[![Image of circuit][1]][1]

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

body:
When using SPI, pin 10 should never be used as an INPUT. Otherwise the Atmega can go into SPI Slave mode. But you use pin 10 as the RX pin.

Just swap pin 9 and 10, and update your code accordingly.


message:
Avrdude fails at specific baudrates

I'm seeing something very strange. If I run:

    ard-reset-arduino /dev/ttyACM0;
    /usr/share/arduino/hardware/tools/avr/bin/avrdude -C/usr/share/arduino/hardware/tools/avr/etc/avrdude.conf -v -patmega328p -carduino -P/dev/ttyACM0 -b115200 -D -Uflash:w:`pwd`/.build/main.ino.hex:i;

Avrdude uploads my sketch to an Arduino Uno just fine. However, if I change the buadrate to 57600, it fails with the error:

    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x00

I've tried manually pressing the Arduino's reset button just before I upload, but there's no change.

Why is this happening? If I change it back to 115200 baud, it uploads fine...even though the sketch itself initializes the serial port to 57600.

body:
Arduino bootloaders doesn't have any baud rate detection and baud rate is fixed (for the different boards there might be different baud rates)

Only Leonardo (and others with native USB) are almost idependent on baud rate  except for 1200bauds used as "reset". (However it runs at maximum speed that the MCU can handle)


body:
> If I change it back to 115200 baud, it uploads fine...even though the sketch itself initializes the serial port to 57600.

The bootloader is a piece of code designed to work at a specific baud rate. As KIIV said in his answer only the USB-based Arduinos would be relatively immune to changing the rate.

What your own code does, after being uploaded, is completely irrelevant.

> Avrdude fails at specific baudrates

Your title really should be: "Avrdude only **works** at one baudrate (the one it was designed to use for a specific board)"


message:
Multi Level Button Menu

Have been working on a Button Menu for a while now and can't break thru to the 3rd level, which in theory would give access to levels 4/5/6/etc.
It's layed out long hand, I'll neaten the code up after its working.
Could you pls have a look and see if you can access level 3....
Also if there is an alternative for ***multi level menus***, happy to look at those also, just after something that works, have tried dozens that i have found on the web.....either no sketch with the video(how i hate that) or sketch just doesn't work period.
Thanks in advance
Doug

        /*
    Description : Simple Menu function on LCD
              Button Function:
                Up/Down - change Menu Page
                Select - enter page
                Left - Exit

    Link: http://youtu.be/cMqif5ICS5M

    +++++++++++++++++++++++++++++++++++++++++++++++++++*/
    */
    #include <LiquidCrystal_I2C.h> //from newliquidcrystal library
    LiquidCrystal_I2C lcd(0x27, 2, 1, 0, 4, 5, 6, 7, 3, POSITIVE);  // Set the LCD I2C address

    int keypad_pin = A0;
    int keypad_value = 0;
    int keypad_value_old = 0;

    bool menu2 = false;
    char btn_push;

    int selection1 = 0;
    int selection2 = 0;

    int mainMenuPage = 1;
    int mainMenuPageOld = 1;
    int mainMenuTotal = 4;

    int levelMenuPage = 1;
    int levelMenuPageOld = 1;
    int levelMenuTotal = 4;

    void setup()
    {
      Serial.begin(9600);
    lcd.begin(20, 4);  //Initialize a 2x16 type LCD

    MainMenuDisplay();
    delay(1000);

    }
    void loop()
    {
    MainmenuBtn();

    if((btn_push == 'S')&&(menu2 == false))//enter selected menu
    {
      Serial.println("i'm here");
        WaitBtnRelease();
        switch (mainMenuPage)
        {
            case 1:
              MenuA();
              break;
            case 2:
              MenuB();
              break;
            case 3:
              MenuC();
              break;
            case 4:
              MenuD();
              break;
        }

          MainMenuDisplay();
          WaitBtnRelease();
      }
      else
    {
       if((btn_push == 'S')&&(menu2 == true))//enter selected menu
    {
      LevelmenuBtn();
        WaitBtnRelease();
        switch (levelMenuPage)
        {
            case 1:
              MenuA2();
              break;
            case 2:
              MenuB2();
              break;
            case 3:
              MenuC2();
              break;
            case 4:
              MenuD2();
              break;
        }

          LevelMenuDisplay();
          WaitBtnRelease();
      }

      delay(10);
    }
    }
    //--------------- End of loop() loop ---------------------
    void MainmenuBtn()
    {
      btn_push = ReadKeypad();
    WaitBtnRelease();
    if(btn_push == 'U')
    {
        mainMenuPage++;
        if(mainMenuPage > mainMenuTotal)
          mainMenuPage = 1;
          Serial.println(mainMenuPage);
    }
    else if(btn_push == 'D')
    {
        mainMenuPage--;
        Serial.print(mainMenuPage);
        if(mainMenuPage == 0)
          mainMenuPage = mainMenuTotal;
          Serial.println(mainMenuPage);
    }

    if(mainMenuPage != mainMenuPageOld) //only update display when page change
    {
        MainMenuDisplay();
        mainMenuPageOld = mainMenuPage;
    }
    }
    void LevelmenuBtn()
    {
      btn_push = ReadKeypad();
    WaitBtnRelease();
    if(btn_push == 'U')
    {
        mainMenuPage++;
        if(levelMenuPage > levelMenuTotal)
          levelMenuPage = 1;
          Serial.println(levelMenuPage);
    }
    else if(btn_push == 'D')
    {
        levelMenuPage--;
        Serial.print(levelMenuPage);
        if(levelMenuPage == 0)
          levelMenuPage = levelMenuTotal;
          Serial.println(levelMenuPage);
    }

    if(levelMenuPage != levelMenuPageOld) //only update display when page change
    {
        LevelMenuDisplay();
        levelMenuPageOld = levelMenuPage;
    }
    }
    void MainMenuDisplay()
    {
    lcd.clear();
    lcd.setCursor(0,0);
    switch (mainMenuPage)
    {
        case 1:
          lcd.print("1. Menu A");
          break;
        case 2:
          lcd.print("2. Menu B");
          break;
        case 3:
          lcd.print("3. Menu C");
          break;
        case 4:
          lcd.print("4. Menu D");
          break;
    }
    }
    void LevelMenuDisplay()
    {
    lcd.clear();
    lcd.setCursor(0,0);
    switch (levelMenuPage)
    {
        case 1:
          lcd.print("1. Menu A2");
          break;
        case 2:
          lcd.print("2. Menu B2");
          break;
        case 3:
          lcd.print("3. Menu C2");
          break;
        case 4:
          lcd.print("4. Menu D2");
          break;
    }
    }
    void MenuA()
    {
    lcd.clear();
    lcd.setCursor(0,0);
    lcd.print("Inside Menu A");
     menu2 = true;
    while(ReadKeypad()!= 'N')
    {
        //Insert Task for Menu A here
     selection1=1;
     Serial.print("Selection1=");
     Serial.println(selection1);
    }
    }
    void MenuA2()
    {
    lcd.clear();
    lcd.setCursor(0,0);
    lcd.print("Inside Menu A2");
    menu2 = false;
    while(ReadKeypad()!= 'N')
    {
        //Insert Task for Menu A here
     selection2=1;
     Serial.print("Selection2=");
     Serial.println(selection2);
    }
    }
    void MenuB()
    {
    lcd.clear();
    lcd.setCursor(0,0);
    lcd.print("Inside Menu B");
    menu2 = true;
    while(ReadKeypad()!= 'N')
    {
        //Insert Task for Menu B here

     selection1=2;
     Serial.print("Selection1=");
     Serial.println(selection1);
    }
    }
    void MenuB2()
    {
    lcd.clear();
    lcd.setCursor(0,0);
    lcd.print("Inside Menu B2");
    menu2 = false;
    while(ReadKeypad()!= 'N')
    {
        //Insert Task for Menu B here
     selection2=2;
     Serial.print("Selection2=");
     Serial.println(selection2);
    }
    }
    void MenuC()
    {
    lcd.clear();
    lcd.setCursor(0,0);
    lcd.print("Inside Menu C");
    menu2 = true;
    while(ReadKeypad()!= 'N')
    {
        //Insert Task for Menu C here
     selection1=3;
     Serial.print("Selection1=");
     Serial.println(selection1);
    }
    }
    void MenuC2()
    {
    lcd.clear();
    lcd.setCursor(0,0);
    lcd.print("Inside Menu C2");
    menu2 = false;
    while(ReadKeypad()!= 'N')
    {
        //Insert Task for Menu C here
     selection2=3;
     Serial.print("Selection2=");
     Serial.println(selection2);
    }
    }
    void MenuD()
    {
    lcd.clear();
    lcd.setCursor(0,0);
    lcd.print("Inside Menu D");
    menu2 = true;
    while(ReadKeypad()!= 'N')
    {
        //Insert Task for Menu D here
     selection1=4;
     Serial.print("Selection1=");
     Serial.println(selection1);
    }
    }
    void MenuD2()
    {
    lcd.clear();
    lcd.setCursor(0,0);
    lcd.print("Inside Menu D2");
    menu2 = false;
    while(ReadKeypad()!= 'N')
    {
        //Insert Task for Menu D here
     selection2=4;
     Serial.print("Selection2=");
     Serial.println(selection2);
    }
    }

    char ReadKeypad()
    {
    /* Keypad button analog Value
    no button pressed 1023
    nul     <450
    select  <400
    left    <350
    down    <290
    up      <190
    right   <50
    */
    keypad_value = analogRead(keypad_pin);

    if(keypad_value < 50)
    return 'R';
    else if(keypad_value < 190)
    return 'U';
    else if(keypad_value < 290)
    return 'D';
    else if(keypad_value < 350)
    return 'L';
    else if(keypad_value < 400)
    return 'S';
    else if(keypad_value < 450)
    return 'N';

    }

    void WaitBtnRelease()
    {
      while( analogRead(keypad_pin) < 600){}
    }

body:
Ok...nobody bought into this and I understand why...menus have been done to death, but not being one to quite I have answered my own question.
Here is a simple, fool proof button menu, that i think has NO limit in depth.
I have just tested this before posting, so if you don't get it to work, check your wiring. instructions at the bottom of the sketch.

        /* Rebuilt by Doug 07/02/2017 Australia.
     * This is a bare bones menu using buttons to navigate and select, there are no special libraries,
     * I am using an I2C LCD2004, but any display will work with minor mods. This has been translated from,
     * I believe Slovakian, that was fun, stripped down and modified for button control, I have found that
     * buttons are less picky than rotary encoders, even the good ones, just my experience.
     * I believe that I have removed all unnecessary script, but I may have missed some.
     * look at the last 2 --page()-- sections for instruction on extending down even further, I don't think
     * that there is a limit to how many levels you can have, how many do you really need.
     * The original sketch is from: Stanislav Petrek of Slovakia, you can find sketch on YouTube comments.
     * https://www.youtube.com/watch?v=gIP29m12wjQ&t=41s
     * Have fun with the translation  ;-}
     * The last thing I did before posting was to relaod and test this sketch, so it works.
     */
    #include <LiquidCrystal_I2C.h> //from newliquidcrystal library
    LiquidCrystal_I2C lcd(0x27, 2, 1, 0, 4, 5, 6, 7, 3, POSITIVE);  // Set the LCD I2C address

    // menu system
    int poz = 0; //  cursor position on actual page
    int poz_max = 1;
    int poz_min = 0;

    int pozOld = 0;
    int pozNew = 0;

    int page = 0; //  actual page
    int page_max = 1;
    int page_min = 0;

    int press = 0;
    int press_max = 1;

    int keypad_pin = A0;                      //analoge A0 to sense button values.
    int keypad_value = 0;
    int keypad_value_old = 0;

    //bool menu2 = false;
    char btn_push;
    //****************************************************************setup*****************************************
    void setup() {
    Serial.begin(9600);
    lcd.begin(20, 4);
    lcd.clear();
    lcd.home();
    }
    //************************************************************loop************************************************
    void loop() {
    MainmenuBtn();
    if (btn_push == 'S') //enter selected menu
    {
    press++;
    delay(250);
    if (press > press_max) {
      press = 0;
    }
    }
    // page select
    switch (page) {

    case 0:
      page0();
      break;
    case 1:
      page1();
      break;
    case 2:
      page2();
      break;
    case 3:
      page3();
      break;
    case 4:
      page4();
      break;
    case 5:
      page5();
      break;
    }
    }
    //****************************************************up/down************************************************
    void MainmenuBtn()
    {
    btn_push = ReadKeypad();
    WaitBtnRelease();
    if (btn_push == 'U')
    {
    poz++;
    if (poz > poz_max) {
      poz = poz_max;
    }
    }
    else if (btn_push == 'D')
    {
    poz--;
    if (poz < poz_min) {
      poz = poz_min;
    }
    }
    pozNew = poz;
    if (pozNew != pozOld) { //only update display when page change
    pozOld = pozNew;
    }
    }
    //*************************************************************read buttons***********************************
    char ReadKeypad()
    {
    /* Keypad button analog Value
    no button pressed 1023
    *********************adjust these values to suit your keypad***********************
    nul     >400
    select  <400
    left    <350
    down    <290
    up      <190
    right   <50
    */
    keypad_value = analogRead(keypad_pin);
    if (keypad_value < 50)
    return 'R';
    else if (keypad_value < 190)
    return 'D';
    else if (keypad_value < 290)
    return 'U';
    else if (keypad_value < 350)
    return 'L';
    else if (keypad_value < 400)
    return 'S';
    else if (keypad_value > 400)
    return 'N';
    }
    //********************************************************button release*************************************
    void WaitBtnRelease()
    {
    while ( analogRead(keypad_pin) < 600) {}
    }
    //*******************************************************Front Page 0*******************************************
    void page0() {
    poz_min = 0;
    poz_max = 3;
    press_max = 1;

    lcd.setCursor(0, 0);
    lcd.print("Pg1 Pg2 Pg3 Pg4     ");
    lcd.setCursor(0, 2);
    lcd.print("                    ");
    lcd.setCursor(0, 3);
    lcd.print("                    ");

    switch (poz)
    {
    case 0:
      lcd.setCursor(0, 1);
      lcd.print("---                 ");
      if (press == 1) {
        press = 0;
        poz = 0;
        page = 1;
      }
      break;
    case 1:
      lcd.setCursor(0, 1);
      lcd.print("    ---             ");
      if (press == 1) {
        press = 0;
        poz = 0;
        page = 2;
      }
      break;
    case 2:
      lcd.setCursor(0, 1);
      lcd.print("        ---         ");
      if (press == 1) {
        press = 0;
        poz = 0;
        page = 3;
      }
      break;
    case 3:
      lcd.setCursor(0, 1);
      lcd.print("            ---     ");
      if (press == 1) {
        press = 0;
        poz = 0;
        page = 4;
      }
      break;
    }
    }
    //*************************************************Pages 1*****************************************
    void page1() {
    poz_min = 0;
    poz_max = 2;
    press_max = 1;

    lcd.setCursor(0, 0);
    lcd.print("Page1               ");
    lcd.setCursor(0, 1);
    switch (poz) {

    case 0:
      lcd.print("Page1 Case0         ");
      if (press == 1) {
        press = 0;
      }
      break;
    case 1:
      lcd.print("Page1 Case1         ");
      if (press == 1) {
        press = 0;
      }
      break;

    case 2:
      lcd.print("Page1 Case2    exit ");
      if (press == 1) {
        press = 0;
        page = 0;
        poz = 0;
      }
      break;
    }
    }
    //*************************************************Pages 2*****************************************
    void page2() {
    poz_min = 0;
    poz_max = 2;
    press_max = 1;

    lcd.setCursor(0, 0);
    lcd.print("Page2               ");
    lcd.setCursor(0, 1);
    switch (poz) {

    case 0:
      lcd.print("Page2 Case0         ");
      if (press == 1) {
        press = 0;
      }
      break;
    case 1:
      lcd.print("Page2 Case1         ");
      if (press == 1) {
        press = 0;
      }
      break;

    case 2:
      lcd.print("Page2 Case2  exit   ");
      if (press == 1) {
        press = 0;
        page = 0;
        poz = 1;
      }
      break;
    }
    }
    //*************************************************Pages 3*****************************************
    void page3() {
    poz_min = 0;
    poz_max = 2;
    press_max = 1;
    lcd.setCursor(0, 0);
    lcd.print("Page3               ");

    switch (poz)
    {
    case 0:
      lcd.setCursor(0, 1);
      lcd.print("Page3 Case0         ");
      if (press == 1) {
        lcd.setCursor(0, 1);
        lcd.print("                    ");
        //navi();
      }
      break;

    case 1:
      lcd.setCursor(0, 1);
      lcd.print("Page3 Case1         ");
      if (press == 1) {
        press = 0;
      }
      break;

    case 2:
      lcd.setCursor(0, 1);
      lcd.print("Page3 Case2  exit   ");
      if (press == 1) {
        press = 0;
        page = 0;
        poz = 2;
      }
      break;
    }
    }
    //*************************************************Pages 4*****************************************
    void page4() {
    poz_min = 0;
    poz_max = 1;
    press_max = 1;

    lcd.setCursor(0, 0);
    lcd.print("Page4               ");
    lcd.setCursor(0, 1);
    switch (poz) {

    case 0:
      lcd.print("Page4 Case0  branch ");
      if (press == 1) {
        press = 0;
        page = 5;                                   //branches to page5() menu
        poz = 0;                                    //at position 0 on button 'S' press
        break;

      case 1:
        lcd.setCursor(0, 1);
        lcd.print("Page4 Case1  exit   ");
        if (press == 1) {
          press = 0;
          page = 0;
          poz = 3;
        }
        break;
      }
      }
    }
    //*************************************************Pages 5*****************************************
    void page5() {
    poz_min = 0;                      //see void MainmenuBtn()
    poz_max = 1;                      //see void MainmenuBtn()
    press_max = 1;                    //used when you have multiple selection within a section-increase number
                                      //see  original script for example
    lcd.setCursor(0, 0);
    lcd.print("Page5               ");
    lcd.setCursor(0, 1);
    switch (poz) {

    case 0:
      lcd.print("Page5 Case0         ");
      break;

    case 1:
      lcd.setCursor(0, 1);
      lcd.print("Page5 Case1  exit   ");
      if (press == 1) {                 //variable set to '1' when the 'S' key is pressed
        press = 0;
        page = 4;                         //this is the page() that you return to after the 'S' button is pressed
        poz = 1;                          //this is the 'case' number that you will return to for that page
      }
      break;
    }
    }

I have only inserted print statements where operational code can be placed, to keep it universally open. To reduce the size of the Global variables use the >>lcd.print(F("TEXT"));<< method, it works really well. Also works on Serial.print....Something for you to fiddle with.


message:
What is the opposite of this data operation?

If I store in an array a double-value in this format, in which format I should be able to read the same double out?

    double myDouble = 12.123456;
    byte myArray[] = {0x00, 0x00, 0x00, 0x00};

    myArray[0] = (myDouble >> 0);
    myArray[1] = (myDouble >> 8);
    myArray[2] = (myDouble >> 16);
    myArray[3] = (myDouble >> 24);

body: in the simplest form (compiler dependent however), a pointer will do.


body:
You are better off making a union, that will be compiler independent, and won't give you the (possibly) odd results that trying to shift a double would give.

Example:

      union
        {
        byte myArray [4];
        double myDouble;
        } foo;

       foo.myArray [0] = Serial.read ();
       foo.myArray [1] = Serial.read ();
       foo.myArray [2] = Serial.read ();
       foo.myArray [3] = Serial.read ();

       double f = foo.myDouble;

Even then be cautious that whatever is sending you this double in 4 bytes is using the same encoding for doubles that the Arduino does. For one thing, **double** and **float** are the same on the 8-bit Arduinos (they are only 4 bytes).