text:
C++ State Machine / Wpmf-convesion
I'm quite a newbie using C ++. I am trying to implement in C ++, the state machine described in this link for C language:
https://barrgroup.com/Embedded-Systems/How-To/Coding-State-Machines.
I have created an Fsm class, which implements the behavior of the state machine, and a Machine class, whose methods will be the states.
The code works, but it generates a warning (-Wpmf-conversions) when I try to save the memory address of a Machine method, in State state__
class Fsm
{
public:
    typedef void (*State)();
private:
    State state__;
public:
    Fsm(State state);
    void dispatch();
};

Fsm::Fsm(State state)
{
    state__ = state ;
} //Fsm

void Fsm::dispatch()
{
    (*state__)() ;
}

class Machine : public Fsm
{
public:
    Machine() : Fsm((State)&Machine::initial) {}       // ctor
};

I'm using an Atmega2560, with AVR-GCC compiler.

For what line of code is the warning generated? Also, why does your Fsm class have two "public" access specifiers. And why type-def (*State)() as void? It could be that I'm forgetting my C++, but I don't see what you're trying  to do here.

@Paul typedef void (*State)(); is a typedef for a function pointer to a function with no parameters and a void return type.  It is perfectly normal to have multiple public, protected or private sections in a class.

A "PMF" is a Pointer to a Member Function. In C++ this is not allowed.

A pointer to a member function is not allowed in C++. GCC can allow it, but moans at you because it's non-standard.
In C++ the normal way of dealing with the kind of thing you want is through class inheritance.
Typically you would create your base Fsm class that implements the basic functionality of your state machine control, then overlay over the top of that (create a new class that inherits the Fsm class) another class that implements your specific machine functionality.  You can declare functions in your base Fsm class that are pure virtual - that is, they exist, but have no body. It's then the job of the child class to actually implement that functionality.  The parent Fsm class then knows about those functions and can call them.
So you would have something like:
class Fsm {
    public:
        void dispatch();
    protected:
        virtual void initial() = 0;
};

void Fsm::dispatch() {
    initial() ;
}

class Machine : public Fsm {
    protected:
        void initial() {
             Serial.println("Here");
        }
};

Machine mach;

mach.dispatch(); // --> "Here"

Fsm knows about initial(), but the function hasn't been further defined.  Machine implements initial().  You then create an instance of Machine which contains everything needed.  Calling dispatch() runs the function in the Fsm parent class which then calls initial() in the child Machine class.


text:
Header file or library to test i2c FRAM?
I found a header file to test a i2c eeprom 24LC256, but I used this to test my eeprom CAT24C32.The test sketch works fine. I modified the line BLOCKSIZE 8 because my eeprom have 32byte page write only.
I have also a FRAM MB85RC256V, I am wondering if can I use the same header to test the FRAM. I saw the command byte write are same like eeprom, but the page write have a different side of buffer, it says have 32Kbytes. Can I use it?
If I made a mistake please help me. Thanks very much!
Here the .h

#ifndef  EEPROM_ROUTINES
#define  EEPROM_ROUTINES

#if defined(ARDUINO) && ARDUINO >= 100
  #include "Arduino.h"
#else
  #include "WProgram.h"
#endif
#include <Wire.h>

#define BLOCKSIZE 8
#define I2CADDR 0x57
#define BLOCKSIZE_READ 30

template <class T>
uint16_t writeObjectSimple(uint8_t i2cAddr, uint16_t addr, const T& value){

      const uint8_t* p = (const uint8_t*)(const void*)&value;
      uint16_t i;
      for (i = 0; i < sizeof(value); i++){
            Wire.beginTransmission(i2cAddr);
                  Wire.write((uint16_t)(addr >> 8));  // MSB
                  Wire.write((uint16_t)(addr & 0xFF));// LSB
                  Wire.write(*p++);
            Wire.endTransmission();
            addr++;
            delay(5);  //max time for writing in 24LC256
      }
      return i;
}

template <class T>
uint16_t readObjectSimple(uint8_t i2cAddr, uint16_t addr, T& value){

            uint8_t* p = (uint8_t*)(void*)&value;
            uint8_t objSize = sizeof(value);
            uint16_t i;
            for (i = 0; i < objSize; i++){
                  Wire.beginTransmission (i2cAddr);
                        Wire.write((uint16_t)(addr >> 8));  // MSB
                        Wire.write((uint16_t)(addr & 0xFF));// LSB
                  Wire.endTransmission();
                  Wire.requestFrom(i2cAddr, (uint8_t)1);
                  if(Wire.available()){
                        *p++ = Wire.read();
                  }
                  addr++;
            }
            return i;
}

template <class T>
uint16_t writeObject(uint16_t addr, const T& value){
      const uint8_t* p = (const uint8_t*)(const void*)&value;

      Wire.beginTransmission(I2CADDR);
      Wire.write((uint16_t)(addr >> 8));        // MSB
      Wire.write((uint16_t)(addr & 0xFF));      // LSB

      //in the loop: counts the bytes we may send before
      //our block becomes full
      //but initialise it to the number of bytes up to the
      //next 16-byte aligned address
      uint8_t blockBytes = (addr/BLOCKSIZE + 1)*BLOCKSIZE - addr;
      uint16_t i;
      for (i = 0; i < sizeof(value); i++){
            if (blockBytes == 0){
                  //block is full;
                  Wire.endTransmission(); //dispatch the buffer
                  delay(5);
                  //restart new block
                  addr = (addr/BLOCKSIZE + 1)*BLOCKSIZE;
                  blockBytes = BLOCKSIZE;
                  Wire.beginTransmission(I2CADDR);
                  Wire.write((uint16_t)(addr >> 8));  // MSB
                  Wire.write((uint16_t)(addr & 0xFF));// LSB
            }
            Wire.write(*p++); //dispatch the data byte
            blockBytes--;     //decrement the block space
      }
      Wire.endTransmission();
      delay(5);   //required write delay 5ms
      return i;
}

template <class T>
uint16_t readObject(uint16_t addr, T& value){
      uint8_t* p = (uint8_t*)(void*)&value;

      Wire.beginTransmission(I2CADDR);
            Wire.write((uint16_t)(addr >> 8));        // MSB
            Wire.write((uint16_t)(addr & 0xFF));      // LSB
      Wire.endTransmission();

      //counts the bytes we may read before buffer is depleted
      uint8_t   blockBytes = 0;
      uint16_t  objSize = sizeof(value);
      uint16_t  i;
      for (i = 0; i < objSize; i++){
            if (blockBytes==0){
               //we need a new block
               blockBytes = BLOCKSIZE_READ;
               if (objSize < blockBytes) blockBytes = objSize;
               //get the new block
                Wire.requestFrom((uint8_t)I2CADDR, blockBytes);
            }
            if(Wire.available()){
                  //read a byte from buffer
                  *p++ = Wire.read();
                  blockBytes--;
            }
      }
      return i;
}

#endif

Here the skecth to test eeprom
#include <Wire.h>
#include "eeprom_routines.h" //definitions of the functions:
                             //writeObject, readObject,
                             //writeObjectSimple, readObjectSimple
#define BLOCK_OPERATIONS 0

#if BLOCK_OPERATIONS>0
  #define __WRITE__(ad, obj) writeObject(ad,(obj))
  #define __READ__(ad, obj) readObject(ad,(obj))
#else
  #define __WRITE__(ad, obj) writeObjectSimple(0x57,ad,(obj))
  #define __READ__(ad, obj)  readObjectSimple(0x57,ad,(obj))
#endif
#define MEM_ADDR_MULTI 3458

//This is the structure we write and read from EEPROM
class MyData{
      long result;
public:
      float  f1;
      float  f2;
      double f3;
      int    i1;
      long   i2;
      long   i3;
      bool  negative;

      long getResult(){
            return result;
      }
      long calcResult(){
            //makes a calculation with its data
            //and stores the result to a private variable
            long    i = (i2+i3)/i1;
            double  f = f3/(f1+f2);
            result = f/i;
            //round off
            result += result>0 ? 0.5 : -0.5;
            if (negative) result=-result;
            return result;
      }
      MyData() : result(0){   }
};

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

      MyData data[5];

      //data[0] - result should be 20
      data[0].i1 = 10;
      data[0].i2 = 150000;
      data[0].i3 = 350000;
      data[0].f1 = 0.5;
      data[0].f2 = 2.5;
      data[0].f3 = 3.0E+6;
      data[0].negative = false;

      //data[1] - result should be -40
      data[1].i1 = data[0].i1;
      data[1].i2 = data[0].i2;
      data[1].i3 = data[0].i3;
      data[1].f1 = data[0].f1;
      data[1].f2 = data[0].f2;
      data[1].f3 = 2*data[0].f3;
      data[1].negative = true;

      //data[2] - result should be 80
      data[2].i1 = data[0].i1;
      data[2].i2 = data[0].i2;
      data[2].i3 = data[0].i3;
      data[2].f1 = data[0].f1;
      data[2].f2 = data[0].f2;
      data[2].f3 = 4*data[0].f3;
      data[2].negative = false;

      //data[3] - result should be -20
      data[3].i1 = data[0].i1;
      data[3].i2 = -data[0].i2;
      data[3].i3 = -data[0].i3;
      data[3].f1 = data[0].f1;
      data[3].f2 = data[0].f2;
      data[3].f3 = data[0].f3;
      data[3].negative = false;

      //data[4] - result should be -2
      data[4].i1 = data[0].i1;
      data[4].i2 = -data[0].i2;
      data[4].i3 = -data[0].i3;
      data[4].f1 = data[0].f1*10;
      data[4].f2 = data[0].f2*10;
      data[4].f3 = -data[0].f3;
      data[4].negative = true;

      Serial.println ("Data before writing to eeprom");
      for (int i=0; i<5; i++){
            data[i].calcResult();
            Serial.print("data-"); Serial.print(i);
            Serial.print(": result = ");
            Serial.println(data[i].getResult());
      }
      Serial.print("Size of each object: ");
      Serial.println(sizeof(MyData)) ;

      Serial.println ("Writing data to eeprom");
      int memaddr = MEM_ADDR_MULTI;
      long t0 = millis();
      for (int i=0; i<5; i++){
            memaddr += __WRITE__(memaddr, data[i]);
      }
      long t1 = millis();
      Serial.print ("...writing finished. Elapsed time: ");
      Serial.println(t1-t0);
      delay(1000);

      Serial.println ("Reading data from eeprom");
      MyData read[5];
      t0 = millis();
      memaddr = MEM_ADDR_MULTI;
      for (int i=0; i<5; i++){
            memaddr += __READ__(memaddr, read[i]);
      }
      t1 = millis();
      Serial.print ("Time to read: "); Serial.println(t1-t0);

      for (int i=0; i<5; i++){
            Serial.print ("Read object: #");
            Serial.println(i);
            long storedResult = read[i].getResult();
            Serial.print ("  >stored result = ");
            Serial.println(storedResult);
            long newResult = read[i].calcResult();
            Serial.print ("  >recalculated result = ");
            Serial.println(newResult);
            if (storedResult== newResult &&
                  storedResult==data[i].getResult() )
                  Serial.println ("SUCCESS");
            else  Serial.println ("FAIL");
      }
}

void loop() {
}

Here the serial output of eeprom CAT24C32 test
Data before writing to eeprom
data-0: result = 20
data-1: result = -40
data-2: result = 80
data-3: result = -20
data-4: result = -2
Size of each object: 27
Writing data to eeprom
...writing finished. Elapsed time: 126
Reading data from eeprom
Time to read: 15
Read object: #0
  >stored result = 20
  >recalculated result = 20
SUCCESS
Read object: #1
  >stored result = -40
  >recalculated result = -40
SUCCESS
Read object: #2
  >stored result = 80
  >recalculated result = 80
SUCCESS
Read object: #3
  >stored result = -20
  >recalculated result = -20
SUCCESS
Read object: #4
  >stored result = -2
  >recalculated result = -2
SUCCESS

At Fujitsu's site is said

Furthermore, applications that have used other products with I2C interfaces, such as EEPROMs and microcontrollers, can now replace EEPROMs, with the new FRAM products

So you can use it without any modifications in your code.

source: Stack Exchange

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/

sort: votes


text:
Arduino not responding to macbook pro
When I try to upload my code onto the Arduino it just gives me the error message: "avrdude: ser_open(): can't open device "/dev/cu.usbmodem14201": No such file or directory
Problem uploading to board.  See http://www.arduino.cc/en/Guide/Troubleshooting#upload for suggestions."
My Arduino used to function just fine. Now when a plug it in, the lights on the Arduino do not blink like they used to, and the only pins that do anything are the ones to power. It also said something like: Arduino is not optimized for mac os. It seems that the Arduino is taking in the power but not the code. here's the code:
int led = 13; // the pin the LED is connected to
void setup() {
  pinMode(led, OUTPUT); // Declare the LED as an output
}

void loop() {
  digitalWrite(led, HIGH); // Turn the LED on
}

Is there a power LED? Is that lit? The lights for the serial connection are only going to blink if there is a program on the board that is sending serial data. I would try it on a different computer and see if its the Mac or the arduino causing issues.

Genuine Arduino or cheap Chinese clone?

While having your Arduino connected try pushing the reset button and report us if there is anything blinking.

Make sure you have a USB cable with data lines - I spent a couple of hours trying to debug a similar problem  because of a "Charging Only" cable.

I had this issue and it was because the port was not set in my Arduino IDE.
I fixed it by going to Tools -> Port, and selecting my usb device.  In my case it was called /dev/cu.SLAB_USBtoUART

I fixed it by plugging it into my other USB port (which I had previously been using)
So possibly this is caused by switching USB ports

Whoever voted this down didn't bother to say why, so I'll take a guess: They probably saw it was short and what looks like a duplicate of an existing answer. You're new here, so sorry for the crappy reception, but I figured I'd at least be able to give you some insight on what the downvote may mean.

Thanks, I appreciate making you making up for it. I debated putting an answer since its short and not expert insight. But I figured I wish someone put it for me since its super fast to attempt and hints at a possible cause.

This sounds so silly, but honestly was the just the ticket that got me to be able to finally flash via UART to my device. I had this issue both in Arduino IDE as well as VSCode ESP-IDF extension. On a MacBook Pro, ls /dev/cu.* listed /dev/cu.Bluetooth-Incoming-Port /dev/cu.SLAB_USBtoUART  /dev/cu.usbserial-XXXX and I set the PORT /dev/cu.SLAB_USBtoUART, flash method to UART, and it didn't work. Unplugging the cable from the top USB near the MacBook screen to the one right below it did work.

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/


text:
ESP8266 Webserver not reachable after 2 minutes from reset
I have a Keyes Espressif ESP8266 NodeMCU, I have two LEDs that I want to control which are connected to the ESP. When I open the webpage http://10.0.0.5/5 after uploading the sketch it works fine. If I don't open and close the website before ~ 02:30[mm:ss] the server becomes unreachable even if I close the existing connection and open a new connection in a new tab the same error yields: ERR_CONNECTION_TIMED_OUT
If I don't open a web page before ~ 02:30[mm:ss] I also receive error ERR_CONNECTION_TIMED_OUT
The web server is only made available when I hard reset the board then the same rules apply as above.
ESP.getFullVersion() outputs:
SDK:2.2.1(cfd48f3)/Core:2.5.1=20501000/lwIP:STABLE-2_1_2_RELEASE/glue:1.1-7-g82abda3/BearSSL:a143020

Question:
How can I make the web server accessible constantly?
With the help of @Juraj I tried changing to SDK V3 which made no difference I also tried:

All lwip variants

My Code:

// Load Wi-Fi library
#include <ESP8266WiFi.h>

// Replace with your network credentials
const char* ssid     = "DO_231455";
const char* password = "0828842107";

// Set web server port number to 80
WiFiServer server(80);

// Variable to store the HTTP request
String header;

// Auxiliar variables to store the current output state
String output5State = "off";
String output4State = "off";

// Assign output variables to GPIO pins
const int output5 = 16;
const int output4 = 4;

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

  // Initialize the output variables as outputs
  pinMode(output5, OUTPUT);
  pinMode(output4, OUTPUT);
  // Set outputs to LOW
  digitalWrite(output5, LOW);
  digitalWrite(output4, LOW);

  Serial.print(ESP.getFullVersion());
  //WiFi.disconnect() ;
  //WiFi.persistent(false);
  //WiFi.setSleepMode(WIFI_NONE_SLEEP);
  // Connect to Wi-Fi network with SSID and password
  Serial.print("Connecting to ");
  Serial.println(ssid);
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  // Print local IP address and start web server
  Serial.println("");
  Serial.println("WiFi connected.");
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());
  server.begin();
}

void loop(){
  WiFiClient client = server.available();   // Listen for incoming clients
  if (client) {                             // If a new client connects,
    Serial.println("New Client.");          // print a message out in the serial port
    String currentLine = "";                // make a String to hold incoming data from the client
    while (client.connected()) {            // loop while the client's connected
      if (client.available()) {             // if there's bytes to read from the client,
        char c = client.read();             // read a byte, then
        Serial.write(c);                    // print it out the serial monitor
        header += c;
        if (c == '\n') {                    // if the byte is a newline character
          // if the current line is blank, you got two newline characters in a row.
          // that's the end of the client HTTP request, so send a response:
          if (currentLine.length() == 0) {
            // HTTP headers always start with a response code (e.g. HTTP/1.1 200 OK)
            // and a content-type so the client knows what's coming, then a blank line:
            client.println("HTTP/1.1 200 OK");
            client.println("Content-type:text/html");
            client.println("Connection: close");
            client.println();

            // turns the GPIOs on and off
            if (header.indexOf("GET /5/on") >= 0) {
              Serial.println("GPIO 5 on");
              output5State = "on";
              digitalWrite(output5, HIGH);
            } else if (header.indexOf("GET /5/off") >= 0) {
              Serial.println("GPIO 5 off");
              output5State = "off";
              digitalWrite(output5, LOW);
            } else if (header.indexOf("GET /4/on") >= 0) {
              Serial.println("GPIO 4 on");
              output4State = "on";
              digitalWrite(output4, HIGH);
            } else if (header.indexOf("GET /4/off") >= 0) {
              Serial.println("GPIO 4 off");
              output4State = "off";
              digitalWrite(output4, LOW);
            }

            // Display the HTML web page
            client.println("<!DOCTYPE html>");
            client.println("<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">");
            client.println("<link rel=\"icon\" href=\"data:,\">");
            // CSS to style the on/off buttons
            // Feel free to change the background-color and font-size attributes to fit your preferences
            client.println("");

            // Web Page Heading
            client.println("
ESP8266 Web Server
");

            // Display current state, and ON/OFF buttons for GPIO 5
            client.println("
GPIO 5 - State " + output5State + "
");
            // If the output5State is off, it displays the ON button
            if (output5State=="off") {
              client.println("
<button class=\"button\">ON</button>
");
            } else {
              client.println("
<button class=\"button button2\">OFF</button>
");
            }

            // Display current state, and ON/OFF buttons for GPIO 4
            client.println("
GPIO 4 - State " + output4State + "
");
            // If the output4State is off, it displays the ON button
            if (output4State=="off") {
              client.println("
<button class=\"button\">ON</button>
");
            } else {
              client.println("
<button class=\"button button2\">OFF</button>
");
            }
            client.println("");

            // The HTTP response ends with another blank line
            client.println();
            // Break out of the while loop
            break;
          } else { // if you got a newline, then clear currentLine
            currentLine = "";
          }
        } else if (c != '\r') {  // if you got anything else but a carriage return character,
          currentLine += c;      // add it to the end of the currentLine
        }
      }
    }
    // Clear the header variable
    header = "";
    // Close the connection
    client.stop();
    Serial.println("Client disconnected.");
    Serial.println("");
  }
}

Worth noting (while debugging):
The new client disconnects.

if a client is returned from server, then the problem is in sketch

What resources would you suggest I look at to learn how to fix this problem?

does it help if you restart the WiFi router/AP?

No effect, the site still drops if not requested from my W8.1 Chrome browser within 2 minutes of resetting or uploading.

does it stop working after two minutes - even if you do not make any requests to it until 2 minutes has passed? Or, does it stop after a certain number of requests that happen to take about 2 minutes to execute?? The point is, does it fail after a certain number of requests, or does it fail after a period of operation - irrespective of the workload???

I tested this by resetting then opening and closing a connection in my browser every minute  - I could do this for 30 minutes and continue to do it thereafter but if I don't make a new connection within ~2 minutes 35 seconds the server times out. It's as if the ESP goes into sleep mode after no requests.

it prints "New client" so it doesn't sleep

Yes, the ESP times out only if a new request not made. I'm trying to find a method to prevent webserver from timing out.

it doesn't time out. it returns a client. the sketch prints  "New client"

That's only if I send a request to the web server and not if it's left idle. If it's left idle it times out.

and the next client after that time is returned by the server. only not handled in your sketch

Is there a better way of solving this problem than how I dealt with it in my answer below?

I need to .stop() the older(first) client!

you stop() the client

in my case, I was reaching through http://esp8266.local/ I noticed that still can reach through ip but mdns failed i guess

The short answer: Config a static IP!
After looking at Git Issue #2371 I found out that I need to create a static IP address to fix this issue. I can do this by inserting WiFi.config(ip, gateway, subnet) just before WiFi.mode(WIFI_STA) in the code above.

First I found the information gateway & subnet I needed by opening the command prompt on a computer that's connected to the access point(router) as the one connected to the ESP8266 which functions in station mode. I did this on Windows by searching Command Prompt then typing ipconfig to obtain the following information:

Replace the points with commas! See this references for more information regarding other parameters and DNS.

To create an IP address you need to see your IP address in the red square in the picture above taken from the command prompt. The first three octects (numbers) of your router IP (probably 10.0.0.x, 192.168.0.x, or 192.168.1.x) must match your chosen static IP. For my example the numbers to match would be 10.0.0.
Next, I needed to obtain the DCHP range for my router. My router is a Netgear Wireless ADSL2+ Modem Router DG834Gv5. To obtain the range I needed to access my router settings. To access this I looked for an HTTP link under the router. For my router it was http://10.0.0.2 along with the username and password which was admin, admin respectively. This is what it looks like:

This will vary according to your router - Then I went into Advanced settings and saw the DHCP range. This is an error on my part noted by @djsfantasi. Please see his answer regarding DHCP range selection.The new static IP needs to be within the DHCP range According to one of the comments brendanmatkin made in Git Issue #2371 the last number of my static IP (which is ZZ in WW.XX.YY.ZZ) needs to be outside of this range. For me it didn't work, it worked when I used a value inside this range but brendanmatkin knows much more than me, I'm just a novice. There might be implications that I am not aware of so I think it's worth looking into. A DHCP range looks like this below:

My inserted code looks like this below:
void setup(void) {
  .
  .
  .
  Serial.begin(115200);
  //WiFi.disconnect();  //Prevent connecting to wifi based on previous configuration
  IPAddress ip(10,0,0,15); // this 3 lines for a fix IP-address
  IPAddress gateway(10,0,0,2);
  IPAddress subnet(255,255,255,0);
  //WiFi.hostname("ESP8266");      // DHCP Hostname (useful for finding device for static lease)
  WiFi.config(ip, gateway, subnet);
  //Station mode:
  WiFi.mode(WIFI_STA);
  .
  .
  .
}

Please comment for more info :)
Additional information and changes I've made to IDE:
OS : Windows 8.1
IDE : Arduino IDE V1.9.8
Board : Keyes ESP8266
Arduino IDE > Tools >Board (in boards manager) : Generic ESP8266 Board
Arduino IDE > Tools >lwip : V2 Low Memory
Arduino IDE > Tools >Esp FW:"nonos.." : nonos-sdk pr-3(known issues)*
Power Supply : USB COM from 300Watt desktop power supply. ~ 1.5A current output.
Much appreciation to @Juraj.  Juraj

It worked when the IP was in the range because there are no valid IP addresses outside the range.
WW.XX.YY.0 and WW.XX.YY.255 are reserved. The router is using the .1 and .2 addresses. That leaves 3-254 available, which as we see are the addresses within the DHCP range.
You can assign a static IP address within the DHCP range, but you run the risk of disabling 1 or 2 devices. DHCP doesn’t know you’ve used one of it's addresses, so can assign it to another device. Boom! Two devices with the same address and both will not function.
The correct way to resolve this is to log into the router and change the DHCP range. For example, increase the lower limit of 3 to (random pick) 20. Now, DHCP won’t be disturbed and will happily give out addresses to your devices. But if you need a static IP address, you’ve defined a pool, from WW.XX.YY.3 to WW.XX.YY.19


text:
How can I connect an arduino to a raspberry pi via an HC 05 bluetooth module and transmit data?
I am currently undertaking a project where I am attempting to build a bluetooth thermometer using an arduino.
I have the temperature sensor working and returning temperature readings via a usb connection to the serial monitor in the Arduino IDE using the following code.
#include <OneWire.h>
#include <DallasTemperature.h>
#include "Timer.h"

Timer t;

// Data wire is plugged into pin 10 on the Arduino
#define ONE_WIRE_BUS 10

// Setup a oneWire instance to communicate with any OneWire devices
OneWire oneWire(ONE_WIRE_BUS);

DallasTemperature sensors(&oneWire);

DeviceAddress insideThermometer = { 0x28, 0x94, 0xE2, 0xDF, 0x02, 0x00, 0x00, 0xFE };

void setup(void)
{
  // start serial port
  Serial.begin(9600);
  // Start up the library
  sensors.begin();
  // set the resolution to 10 bit (good enough?)
  sensors.setResolution(insideThermometer, 10);
  int tickEvent = t.every(3000,doTempReading);

}

void loop()
{
    t.update();
}

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

void doTempReading()
{
  delay(2000);
  Serial.print("Getting temperatures...\n\r");
  sensors.requestTemperatures();

  Serial.print("Inside temperature is: ");
  printTemperature(insideThermometer);
  Serial.print("\n\r");
}

I now want to try and transmit the readings via a bluetooth connection using the HC 05 module to a raspberry pi which will record the data.
I have done a lot of research and tried several different techniques and can't understand how to go about it.
What mode does the HC 05 need to be in? (Command AT/slave/data/etc.)
How should it be wired (I have found several different methods using various resistors and capacitors and unsure which to follow).
How should I pair it with the Raspberry pi?
Thanks in advance for any help.

have you tried searching "Arduino HC05" in google?

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/


text:
How to convert USB to PS/2?
Objective: To get my USB keyboard to interface with an Arduino Uno board.
Constraints: I can't afford a USB host shield for now for Arduino. Currently available is a keyboard with PS/2 connector. That example is available here. However, it is silly going for such a keyboard, or, buy a USB to PS/2 converter at the moment.
Challenge: USB has VCC, GND, RX/TX. (Rx/Tx also labelled D+/D- respectively). The parallel port connector has the following:

Where will the D- pin go?

USB doesn't have RX/TX.

Is there a reason that you think an USB keyboard would work with a PS2 library? These are not the same but two very different means of communication. When wanting to interface an USB slave, you simply have (!) to implement some kind of an USB master. Thats how USB works.

@chrisl Many USB keyboards can also work as PS/2 keyboards. Plug them into one of those green USB to PS/2 converters and it becomes a PS/2 keyboard. There's no electronics in those converters, it's just a plug. It's down to the keyboard to recognise it's plugged into PS/2 not USB and change its behaviour. Not all keyboards can do it, but certainly most older ones can. I doubt wireless ones would work.

@IgnacioVazquez-Abrams I thought the green/white wires correspond to TX/RX respectively...

@chrisl heard keyboard MCUs do support both protocols...so I have to discover for myself what is the case with my keyboard... :(

@deostroll USB uses "low voltage differential signals". It is half duplex (only sends or receives, never both at once) and sends the signal twice - once normally (D+) and once inverted (D-). At the receiver the two signals are combined (D- is inverted, then added to D+) to cancel out any common mode (inducted) noise. This allows higher speeds over longer distances. RS-485 uses the same technique for traditional UART communications over very long distances.

Many USB keyboards (certainly older ones, though almost certainly not wireless ones) are also PS/2 keyboards.  The wiring of the cable is all that differs, and the chip in the keyboard changes its behaviour depending on how it's wired.
A simple USB to PS/2 adaptor is merely a USB socket and PS/2 plug wired together in a certain way:

So that's:

5V to 5V
D- to Data
D+ to Clock
GND to GND

It may work with your keyboard, or it may not. All you can do is try it and see.


text:
Servo causes disconnection
I've only started using Arduino in the last week, and I'm having a problem with the servo supplied with the kit I purchased. It's a SG90 microservo. I'm trying to connect the servo as shown on the Arduino tutorial site:

But when I connect the power and ground pins to the board, the board powers down and disconnects from the USB. I've had the servo working before without a problem.
Yesterday I was trying out another tutorial without any luck, and I noticed the servo getting hot (not too hot to touch though).
Could I have accidentally fried the control board in the servo?

Probably. It sounds like it's causing the power to short.

Never run power to a servo or other motor through an Arduino or from its regulator.  Also do not power servos from USB.

@ChrisStratton Nice information. I think I do that mistake for several times. Cares to elaborate?

@ChrisStratton I don’t think I did. What would that look like?

@Jim421616 It would look like your schematic.

Oh! But that schematic is from the tutorial!

Have a look at the current requirements of the SG90 and compare this to the maximum current available from an Arduino Uno.

Another thing to look at is how much current your computer's USB port can supply. My laptop, for example, can only supply 500mA per USB port.
My advise is to use a separate 5V power supply for the servo.

So the technique I used should be ok if I power the board with a 9V battery rather than through the USB?

There's a couple of problems with that idea. If you are talking about an everyday alkaline 9V battery with an approximate mA hour rating of 580, and you draw the SG90's "running current" of approximately 270mA from it, how long do you think the battery will last?

If your Arduino has a AMS1117 voltage regulator, then it's maximum power dissipation specification is 1.2W. Supplying 9V at the power input jack will give you a maximum output current of approximately 360mA. (9 - .7 - 5) * .360 = 1.19W. The "stall current" of the SG90 is up to 730mA, more than double the current you have available. A separate, 1A, 5V power supply is what I would use.

I'm sorry to harp on about it, but pretty much all of the tutorials I've been able to find online suggest hooking up the servo in the way I originally posted about. I guess maybe I hooked it up incorrectly, but as far as I can tell, you're all advising against this method anyway. So I'm confused; is this a good way to hook up the servo, or not? And if not, what would the best way look like in a schematic?

Unfortunately, there are several tutorials on the internet showing the servo connected directly to an Arduino Uno, which is incorrect. Here is a tutorial with a connection diagram showing a separate power supply for the servo in Step 3: http://www.instructables.com/id/Arduino-How-to-Use-a-Servo-Motor-With-an-External-/

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/


text:
Storing byte array from serial and converting to a floating point number
I have tried getting my Arduino to communicate with another device, to no avail. The command A, when sent via serial to the device, triggers it to respond with 8 binary bytes with the first 4 representing a floating point number, and the final 4 representing a floating point number. The command only has to be sent once a second, and the aim is to store the 8 incoming bytes in an array, and convert them into their respective floats.
unsigned long previousMillis = 0;
const long interval = 1000;
char incomingByteA[8];

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

void loop() {
  unsigned long currentMillis = millis();
  if(currentMillis - previousMillis >= interval){
    //1 second timer
    previousMillis = currentMillis;
    Serial1.write('O');
    //Send command 'A' to device *noting Serial1 not Serial
    for(int n = 0; Serial1.available() < 8; n++) {
    incomingByteA[n] = Serial1.read();
    //Add each consecutive byte to an array until all 8 bytes have been added
  }
  float x;
  float y;
  ((byte*)&x)[3] = incomingByteA[0];
  //Convert first four bytes into a float
  ((byte*)&x)[2] = incomingByteA[1];
  ((byte*)&x)[1] = incomingByteA[2];
  ((byte*)&x)[0] = incomingByteA[3];
  ((byte*)&y)[3] = incomingByteA[4];
  //Convert final four bytes into a float
  ((byte*)&y)[2] = incomingByteA[5];
  ((byte*)&y)[1] = incomingByteA[6];
  ((byte*)&y)[0] = incomingByteA[7];
  Serial.println(x, 4);
}
}

However, when I do Serial.println(x);, it returns "nan". And if I try to do Serial.println(incomingByteA[2]);, it returns "?".
The following is the floating point format as per the device protocol:
31: sign of mantissa, 1=negative.
30-23: exponent, biased by 128.
22-0: mantissa, 24 bits, MSB hidden and always=1.
The mantissa is normalized, 24 bits with the MSB hidden. The MSB is always
assumed to be 1, therefore only 23 bits are needed to store the mantissa. The exponent is biased by 128; i.e. a 128 value represents an exponent of zero. A 129 value is an exponent of 1. Example: if the exponent has a 131 value (+3), the number is 2^3 * (mantissa). The mantissa is always less than one, and greater than or equal to 1/2. The number zero is stored as four zero bytes.
I am confident that it is not a fault with the hardware and for what it's worth, I am using a Leonardo. I would like to get the code down pat before I stress about hardware issues. What is this code not doing properly, if at all?
Thanks in advance.

Why not read directly into the float's address?

Two things I see wrong:

Serial1.write('O');                                            //Send command 'A' to device *noting Serial1 not Serial

No, you send O not A... ???

for(int n = 0; Serial1.available() < 8; n++)

While there are less than 8 bytes available in the buffer read one.
Erm...  The buffer starts off empty - empty is less than 8. It remains empty (always less than 8) until a byte finally arrives. Then it's still less than 8. I can't really see this ever working, and your array will overflow instantly and clobber the entirety of the rest of your RAM. I guess it finally finished when the serial object itself gets clobbered and available() returns some garbage number. In the meantime your array is just full of nothingness.
You need to completely rewrite that whole section. The simplest way is to wait until there are 8 bytes in the buffer (which will take some time - serial is slooooow):
while (Serial1.available() < 8);

You now have 8 bytes available to read, so you can go ahead and read them.
A better way is to look to see if there is at least one byte available, then read it into the right place in your array - and keep count of how many bytes you have read:
int n = 0;
while (n < 8) {
    if (Serial1.available()) {
        incomingByteA[n++] = Serial1.read();
    }
}

Of course, it's better to add some form of timeout in there too - so if nothing arrives soon enough your program doesn't lock up - or if you miss a byte it doesn't get completely out of sync. Also purging your read buffer before sending the command can help to prevent sync issues:
// Purge any old data
while (Serial1.available()) {
    Serial1.read();
}

Serial1.write('A');

int n = 0;
uint32_t start = millis();
while (n < 8) {
    // 1 second timeout
    if (millis() - start > 1000) {
        break;
    }
    if (Serial1.available()) {
        incomingByteA[n++] = Serial1.read();
    }
}

if (n == 8) {
    // We got the data - do something with it
} else {
    // It timed out
}

Now when it comes to converting to a pair of floats there's better ways than your byte-wise manipulation.  For instance, you could use a union:
union FloatPair {
    struct {
        float a;
        float b;
    };
    char bytes[8];
} __attribute__((packed));

FloatPair data;

Now you can use:
data.bytes[n]

to access the memory directly, and
data.a;
data.b;

to access the float values.
You can also do something similar with casting:
struct FloatPair {
    float a;
    float b;
};

FloatPair data;

char *bytes = (char *)&data;

bytes is now a byte-wise view of the memory used by a pair of floats.
You can even work the other way around:
char data[8] __attribute__((aligned(4)));

The aligned attribute will force the address of the array to be on a 4-byte boundary. Not important for a little 8-bitter, but vital if you ever port to a 32-bit MCU since a float always has to be on a 4-byte boundary, so a good habit to get into.
Now you can map floats into that memory space:
float *a = (float *)(&data[0]);
float *b = (float *)(&data[4]);

and access the floats as *a and *b. The * dereferences the pointers back into real numbers.
One thing to note: these methods all depend on the endianness of your data matching the endianness of your MCU - if they differ then you will have no choice but to do it all with manual byte-wise mapping.

Thanks for the quick reply! I typoed 'O' I did mean to write 'A', I will implement your technique for obtaining and storing the bytes. Could you please elaborate on "endianness"? As far as I know, isn't it just the order in which the most significant bits are arranged? If so, as per the protocol manual, then it's are ordered from left to right as most significant,  to least significant. Cheers

That sounds like big-endian. I think the AVR CPU is little-endian. If they don't match then you will have to manually swap the bytes around and make sure they get in the right places in your floats.

This thread may help you understand.

Thanks again for the reply. I tried comprehending that thread. If the CPU is little-endian, doesn't that mean I just work from least significant to most significant instead?

Yep. That's right. 0->3, 1->2, 2->1 and 3->0 byte mapping

Does that mean I should keep my current code for that process so I can simply reverse the order?

Yes, your current code for the assigning of the values looks reasonable for swapping the bytes around (which it looks like it may already do). You can still use the union method though, since that gives you access to the individual bytes - just write them in reverse order (7-0 instead of 0-7).

Thank you Majenko for your fast help!
I believe that the code is now alright. I will look at using the union method this weekend. For now, however, this is the final code.
 byte incomingByteA[8];

 void setup() {
 // put your setup code here, to run once:

 Serial.begin(9600);
 while(!Serial);
 Serial1.begin(9600);
 while(!Serial1);

 }

 void loop() {

 // Purge any old data
 while (Serial1.available()) {
 Serial1.read();
 }

 Serial1.write('A');

 int n = 0;
 uint32_t start = millis();
 while (n < 8) {
 // 1 second timeout
 if (millis() - start > 1000) {
    break;
 }
 if (Serial1.available()) {
    incomingByteA[n++] = Serial1.read();
 }
 }
 float x;
 float y;
 if (n == 8) {
 ((byte*)&x)[3] = incomingByteA[0];                             //Convert first four bytes into a float
 ((byte*)&x)[2] = incomingByteA[1];
 ((byte*)&x)[1] = incomingByteA[2];
 ((byte*)&x)[0] = incomingByteA[3];

 ((byte*)&y)[3] = incomingByteA[4];                             //Convert final four bytes into a float
 ((byte*)&y)[2] = incomingByteA[5];
 ((byte*)&y)[1] = incomingByteA[6];
 ((byte*)&y)[0] = incomingByteA[7];

 Serial.println(x);
 } else {
 // Some timeout response
 }

 }

What I find odd, is that Serial.println(x); returns "8.00" followed by several, random lines of "0.00". Yet Serial.println(x); returns just "0.00". I am simply putting this down to the device I am trying to communicate with though.
Harry


text:
serial communication dead slow after a while
I'm workin on a node for blender to control an arduino. I notice it goes really slow after a while so I isolated the problem.
It is good in maintaining 60 frames a second, then after around 40 seconds (pretty exact), it drops to a pretty exact 1 fps for some reason.
What could be going on?
import serial
import time

ser = serial.Serial('COM3', 115200)

c = 0

while True:
    c+=1
    print("ok ", c)
    numIn = "100n"
    ser.write(numIn.encode('ascii'))
    time.sleep(1./60)

arduino code:
// special thx to  Nick Gammon
const unsigned int MAX_INPUT = 50;

unsigned long delay_time = 300;
unsigned long last_toggle_time = 0;
int current_state = LOW;

void setup () {
  Serial.begin (115200);
  pinMode(12, OUTPUT);

}

void process_data (const char * data) {
  Serial.println (data);
  delay_time = atoi(data);
}

void processIncomingByte (const byte inByte) {
  static char input_line [MAX_INPUT];
  static unsigned int input_pos = 0;

  switch (inByte) {

    case 'n':   // end of text
      input_line [input_pos] = 0;  // terminating null byte
      process_data (input_line);
      input_pos = 0;
      break;

    case 'r':
      break;

    default:
      if (input_pos < (MAX_INPUT - 1))
        input_line [input_pos++] = inByte;
      break;

  }
}

void loop() {

  while (Serial.available () > 0) {
    processIncomingByte (Serial.read ());
  }

  unsigned long m  = millis();

  if (m > last_toggle_time + delay_time) {
      current_state = current_state == HIGH ? LOW : HIGH;
      digitalWrite(12, current_state);
      last_toggle_time = m;
  }

}

Hint: Check "if (m > last_toggle_time + delay_time)" and what happens when millis() as int wraps?

I changed it to unsigned long now and it's still the case.

Also, the blinking is not the problem, that keeps going well. It's the serial communication that slows down.

What happens if you remove the Serial.print() from process_data()? What does your Python script do with serial input?

Cool, if I remove the print then the problem is gone. However, eventually I want python to read the input. Now python hangs on ser.readLine(). Maybe a new topic for the hanging?

Now we need an explanation not dive directly into the next issue :) What was the problem, really? The Arduino prints. The host (Python) script does not read and internal USB/USART buffers are filled. And what happens on the Arduino side when the Serial output buffer is filled? Check the code - it is open-source :)

BW: Be a good stackexchange user and write an answer and mark this question as answered.

I guess it goes in a second delay :)

@MikaelPatel "Serial" output data unclaimed by the host could only potentially be a cause for slowdown in the case for a Leonardo board or something else where the USB is implemented directly in the application processor, and even there it is a bit uncertain.  It is definitely not the case for an Uno or something where the application processor has a UART connection to a USB converter, as in such case the UART data is blindly transmitted, regardless if the receiver is able to handle it or not.

Please state which Arduino you are using. There is some confusion by responders as to whether outgoing communications would block if you fill up the buffer.

I just want to point out that you are using n as a delimiter in a rather unusual way. In my code it was \n and \r (newline and carriage return). When you do Serial.println (data); you are adding two more bytes (println adds a carriage-return and linefeed) so you are printing 6 bytes for every four you receive. It doesn't totally surprise me that something fills up after 40 seconds, however at 115200 baud that shouldn't really be an issue for 60 x 6 bytes.

Bit bang it with a delay loop before the next bit gets sent.
Delay loop variable will have to be tested to not be too quick. Sync it with baud rate. I developed a product which was trademarked as "Bit Banger" which was a serial I/O controller before you were mostly born back in 1997.
Then again it may help that My 1st real job was peripheral controller tech for a 16 bit computer company in the early 70's. Intel had jusr released the 4004 4 bit slicer. By 74 they came out with tge 8080.
Harry

If you print from arduino to serial and you don't read it then the buffer gets full. Causing it to go in a second delay. So make sure you read as well when you send data over.
A short sleep is required between the sleep and the read for some reason. Else it hangs.
import serial
from time import sleep

ser = serial.Serial('COM3', 115200)
sleep(1)

c = 0

while True:
    c+=1
    print("ok ", c)
    numIn = "100"
    ser.write((numIn + '\r\n').encode())
    sleep(1./120)

    inp = ser.readline()
    print(inp.decode("utf-8"))
    sleep(1./120)

The theory behind this answer is quite dubious, and if you have a conventional Uno type Arduino or something with a distinct USB-serial converter, impossible.


text:
warning: variable 'b' set but not used
I got the following error:
warning: variable 'b' set but not used.
I think I do a really small thing wrong but I can't figure out what it is.
#define array_size(array) ((int)(sizeof(array) / sizeof((array)[0])))

typedef struct Boid {
  unsigned long start_animate_time;
} Boid;

Boid boids[4];

Boid create_boid() {
  unsigned long start_animate_time = 0L;
  Boid b = {start_animate_time};
  return b;
}

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

  boids[0] = create_boid();
  boids[1] = create_boid();
  boids[2] = create_boid();
  boids[3] = create_boid();

  for (int i = 0; i < array_size(boids); i++) {
    Boid b = boids[i]; // <<<<<<<<<<<<< this line!
    b.start_animate_time = 456;
  }

  for (int i = 0; i < array_size(boids); i++) {
    Boid b = boids[i];
    Serial.println(b.start_animate_time); // BUG always 0
  }
}

void loop() {

}

flock_01_ino_debug.ino:28:10: warning: variable 'b' set but not used
  [-Wunused-but-set-variable]
       Boid b = boids[i];
            ^

I get Symbol 'I' could not be resolved. Change I to i.

@Jurai No idea how that became a capital since I copied pasted all code. I guess it is a safari auto correct that happened after I added // <<<<<<<<<<<<< this line! Since that is the only thing I added in the browser.

C++ is not Java. You can't just assign structs like that - it copies them (if anything).
Boid b = boids[I]; // <<<<<<<<<<<<< this line!
b.start_animate_time = 456;

Instead just access the array slice directly:
boids[i].start_animate_time = 456;

And later on as well:
Serial.println(boids[i].start_animate_time);

Basically, you create a "Boid" variable called "b", copy the content of boids[i] to it, set a value in that variable, and then throw it away. Hence the "not used". If you want to reference a specific array slice as a separate variable either get a pointer to it:
Boid *b = &boids[i];
b->start_animate_time = 456;

Or use a reference:
Boid &b = boids[i];
b.start_animate_time = 456;

Of the two I prefer using a pointer, but I come from a C background and understand pointers, but it took me many years of trial and error to get to that point...

Thanks, I always struggle with references and pointers since my lack of experience with them.

Or you can use some C++11 features:  for (auto & boid : boids) { boid.start_animate_time = 456; Serial.println(boid.start_animate_time); }  (two loops are not needed here at all)

@KIIV Indeed - though be careful using auto - the meaning seems to change from C++ version to C++ version. Like they can't make their mind up what it's for.


text:
Crash when datalogging MPU-6050 to SD card
On an Arduino Pro Mini, I'm using Jeff Rowberg's stuff in i2cdevlib to read from the MPU6050, and using SdFat to write data to an SD card. Each part in isolation is fine, but when both DAQ and logging are in use the Arduino locks up after a few minutes, then happily restarts when reset is pressed.
I've tried disabling the interrupt and manually polling mpu.getIntStatus() in loop(), and I've also dropped the FIFO rate from 100Hz to 10Hz by changing the config in MPU6050_6Axis_MotionApps20.h (and confirmed that it has actually dropped) along with changing the SPI speed from SPI_FULL_SPEED to SPI_SIXTEENTH_SPEED and changing the I2C wire speed from 400kHz to 50kHz. All of these were done progressively and showed no significant change in the run times, which are scattered pretty randomly between <1 and 20 minutes. I also changed the datalogging to doing a filesystem flush on every cycle from doing it every 100 cycles, which helped performance but might have meant lots of internal buffer allocation/deallocation and memory leak risk.
I've tried putting a watchdog in but have encountered a widely known issue with this board that the watchdog is useless with the stock bootloader. I'm now working on that so I can try and use it to debug where in code the hang is, but I suspect it's going to be deep in one of the two third party libraries and I'm not going to be able to do much with it. I've attached the present iteration of code below. Does anyone have thoughts on where to go from here? Has anyone done similar with this kit?

#include "I2Cdev.h"

//#include <helper_3dmath.h>
//#include <MPU6050.h>
#include <MPU6050_6Axis_MotionApps20.h>
//#include <MPU6050_9Axis_MotionApps41.h>

// Arduino Wire library is required if I2Cdev I2CDEV_ARDUINO_WIRE implementation
// is used in I2Cdev.h
#if I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE
    #include "Wire.h"
#endif

//Includes for SdFat

#include <FreeStack.h>
#include <MinimumSerial.h>
#include <SdFat.h>
#include <SdFatConfig.h>
#include <SdFatUtil.h>
#include <SystemInclude.h>

//Includes for watchdog
#include <avr/wdt.h>

// ************* Defines for MPU6050 *****************
#define INTERRUPT_PIN 2  // use pin 2 on Arduino Uno & most boards

// ************* Variables for MPU6050 *****************

// class default I2C address is 0x68
// specific I2C addresses may be passed as a parameter here
// AD0 low = 0x68 (default for SparkFun breakout and InvenSense evaluation board)
// AD0 high = 0x69
MPU6050 mpu;
//MPU6050 mpu(0x69); // <-- use for AD0 high

// MPU control/status vars
bool dmpReady = false;  // set true if DMP init was successful
uint8_t mpuIntStatus;   // holds actual interrupt status byte from MPU
uint8_t devStatus;      // return status after each device operation (0 = success, !0 = error)
uint16_t packetSize;    // expected DMP packet size (default is 42 bytes)
uint16_t fifoCount;     // count of all bytes currently in FIFO
uint8_t fifoBuffer[64]; // FIFO storage buffer

// orientation/motion vars
//Quaternion q;           // [w, x, y, z]         quaternion container
VectorInt16 aa;         // [x, y, z]            accel sensor measurements
VectorInt16 gyro;       // [x, y, z]            gyro measurements

//VectorInt16 aaReal;     // [x, y, z]            gravity-free accel sensor measurements
//VectorInt16 aaWorld;    // [x, y, z]            world-frame accel sensor measurements
//VectorFloat gravity;    // [x, y, z]            gravity vector
//float euler[3];         // [psi, theta, phi]    Euler angle container
//float ypr[3];           // [yaw, pitch, roll]   yaw/pitch/roll container and gravity vector

// ************* Defines for SdFat *******************

// The chip select line for the SD card
#define SD_CHIP_SELECT 4
// Log file base name.  Must be six characters or less.
#define FILE_BASE_NAME "Data"

// ************ Variables for SdFat *******************
//
// Set DISABLE_CHIP_SELECT to disable a second SPI device.
// For example, with the Ethernet shield, set DISABLE_CHIP_SELECT
// to 10 to disable the Ethernet controller.
const int8_t DISABLE_CHIP_SELECT = -1;
//
// Test with reduced SPI speed for breadboards.
// Change spiSpeed to SPI_FULL_SPEED for better performance
// Use SPI_QUARTER_SPEED for even slower SPI bus speed
const uint8_t spiSpeed = SPI_SIXTEENTH_SPEED;
// File system object.
SdFat sd;
// Log file.
SdFile file;

int sd_writes_since_flush = 0;

// Serial streams
ArduinoOutStream cout(Serial);

// input buffer for line
char cinBuf[40];
ArduinoInStream cin(Serial, cinBuf, sizeof(cinBuf));

// ******************************* Misc *******************************
int crash_timer = 0;

// ================================================================
// ===               INTERRUPT DETECTION ROUTINE                ===
// ================================================================

volatile bool mpuInterrupt = false;     // indicates whether MPU interrupt pin has gone high
void dmpDataReady() {
    mpuInterrupt = true;
}

//******************* Setup ***************************

void setup() {
  // put your setup code here, to run once:

  // Set up serial comms
  Serial.begin(250000);
  while (!Serial); // wait for Leonardo enumeration, others continue immediately
  Serial.println(F("Serial initialised"));

  // initialize device
  Serial.println(F("Initializing MPU.."));

  // Set up comms to the MPU6050
  Wire.begin();
  Wire.setClock(50000); //400000= 400kHz I2C clock. Comment this line if having compilation difficulties

  mpu.initialize();

  pinMode(INTERRUPT_PIN, INPUT);
  Serial.println(F("Initializing DMP.."));

  devStatus = mpu.dmpInitialize();

    // make sure it worked (returns 0 if so)
    if (devStatus == 0) {
        // turn on the DMP, now that it's ready
        Serial.println(F("Enabling DMP..."));
        mpu.setDMPEnabled(true);

        // enable Arduino interrupt detection
        Serial.println(F("Enabling interrupt detection (Arduino external interrupt 0)..."));
        attachInterrupt(digitalPinToInterrupt(INTERRUPT_PIN), dmpDataReady, RISING);
        mpuIntStatus = mpu.getIntStatus();

        // set our DMP Ready flag so the main loop() function knows it's okay to use it
        Serial.println(F("DMP ready! Waiting for first interrupt..."));
        dmpReady = true;

        // get expected DMP packet size for later comparison
        packetSize = mpu.dmpGetFIFOPacketSize();
    } else {
        // ERROR!
        // 1 = initial memory load failed
        // 2 = DMP configuration updates failed
        // (if it's going to break, usually the code will be 1)
        Serial.print(F("DMP Initialization failed (code "));
        Serial.print(devStatus);
        Serial.println(F(")"));
    }

  // verify connection
  Serial.println(F("Testing device connections..."));
  Serial.println(mpu.testConnection() ? F("MPU6050 connection successful") : F("MPU6050 connection failed"));

  Serial.println(F("Initialising SD card.."));
  if (!sd.begin(SD_CHIP_SELECT, spiSpeed)) {
    if (sd.card()->errorCode()) {
      Serial.println (F(
             "\nSD initialization failed.\n"
             "Do not reformat the card!\n"
             "Is the card correctly inserted?\n"
             "Is chipSelect set to the correct value?\n"
             "Does another SPI device need to be disabled?\n"
             "Is there a wiring/soldering problem?\n"));
      //Serial.println(F("\nerrorCode: ") << hex << showbase);
      //Serial.println(sd.card()->errorCode());
      //Serial.println(F(", errorData: ") << int(sd.card()->errorData());
      //Serial.println(noshowbase);
      sd.initErrorHalt();
    }
    Serial.println(F("\nCard successfully initialized.\n"));
    if (sd.vol()->fatType() == 0) {
      Serial.println(F("Can't find a valid FAT16/FAT32 partition.\n"));
      sd.initErrorHalt();
    }
    if (!sd.vwd()->isOpen()) {
      Serial.println(F("Can't open root directory.\n"));
      sd.initErrorHalt();
    }
    Serial.println(F("Can't determine error type\n"));
    sd.initErrorHalt();
  }
  Serial.println(F("Card successfully initialized."));

  getFile();

  //Serial.println(F("Enabling 2s watchdog"));
  /* Watchdog is set to 2s.
   *  We tick every 10ms so initially it was set to 60ms, however the watchdog stays enabled
   *  after reboot, and since the code takes more than 60ms to come back up we ended up in a boot loop.
   */
  //wdt_enable(WDTO_2S);

}

void getFile()
{
    const uint8_t BASE_NAME_SIZE = sizeof(FILE_BASE_NAME) - 1;
    char fileName[13] = FILE_BASE_NAME "00.csv";

    // Find an unused file name.
  if (BASE_NAME_SIZE > 6) {
    sd.errorHalt(F("FILE_BASE_NAME too long"));
  }
  while (sd.exists(fileName)) {
    if (fileName[BASE_NAME_SIZE + 1] != '9') {
      fileName[BASE_NAME_SIZE + 1]++;
    } else if (fileName[BASE_NAME_SIZE] != '9') {
      fileName[BASE_NAME_SIZE + 1] = '0';
      fileName[BASE_NAME_SIZE]++;
    } else {
      sd.errorHalt(F("Can't create file name. May have used them all."));
    }
  }

  Serial.print(F("Trying to create file "));
  Serial.println(fileName);

  if (!file.open(fileName, O_CREAT | O_WRITE | O_EXCL)) {
      sd.errorHalt(F("file.open failed"));
    }

  file.println(F("Time/ms,acc_x,acc_y,acc_z,gyr_x,gyr_y,gyr_z"));

    // Force data to SD and update the directory entry to avoid data loss.
  if (!file.sync() || file.getWriteError()) {
    sd.errorHalt(F("write error"));
  }
  Serial.print(F("File opened; "));
  Serial.println(fileName);

}

void loop() {
  // put your main code here, to run repeatedly:
 // wdt_reset(); //reset watchdog
  // wait for MPU interrupt or extra packet(s) available

    int loopTO = 0;

    while (!mpuInterrupt && fifoCount < packetSize) {
        if (loopTO++ > 100000)
        {
          Serial.println(F("mpuInterrupt died?"));
          loopTO=0;
        }
    }

    // reset interrupt flag and get INT_STATUS byte
    mpuInterrupt = false;
    mpuIntStatus = mpu.getIntStatus();

    // get current FIFO count
    fifoCount = mpu.getFIFOCount();

    // check for overflow (this should never happen unless our code is too inefficient)
    if ((mpuIntStatus & 0x10) || fifoCount == 1024) {
        // reset so we can continue cleanly
        mpu.resetFIFO();
        Serial.println(F("FIFO overflow!"));

    // otherwise, check for DMP data ready interrupt (this should happen frequently)
    } else if (mpuIntStatus & 0x02) {
        // wait for correct available data length, should be a VERY short wait
        loopTO=0;
        while (fifoCount < packetSize)
        {
          fifoCount = mpu.getFIFOCount();
          if (loopTO++ > 100000)
          {
            Serial.println(F("fifo no longer getting data?"));
            loopTO=0;
          }
        }

        // read a packet from FIFO
        mpu.getFIFOBytes(fifoBuffer, packetSize);

        // track FIFO count here in case there is > 1 packet available
        // (this lets us immediately read more without waiting for an interrupt)
        fifoCount -= packetSize;

        mpu.dmpGetAccel(&aa, fifoBuffer);

        //Gyro data is in the packet that comes back. More easily obtained using
        //dmpGetGyro(int32_t *data, const uint8_t* packet)
        //or dmpGetGyro(VectorInt16 *v, const uint8_t* packet)
        //These take the same parameters as the two versions of dmpGetAccel
        mpu.dmpGetGyro(&gyro, fifoBuffer);

        file.print(millis());
        file.print(",");
        file.print(aa.x);
        file.print(",");
        file.print(aa.y);
        file.print(",");
        file.print(aa.z);
        file.print(",");
        file.print(gyro.x);
        file.print(",");
        file.print(gyro.y);
        file.print(",");
        file.println(gyro.z);

        //Either sync here or in the 100th iteration bit.
        if (!file.sync() || file.getWriteError()) {
          sd.errorHalt(F("write error"));
        }

        if (sd_writes_since_flush++ > 10) //was 100 at 100Hz but at 10Hz that gets silly
        {
           // Force data to SD and update the directory entry to avoid data loss.
           sd_writes_since_flush = 0;
          /*
          if (!file.sync() || file.getWriteError()) {
            sd.errorHalt(F("write error"));
          }
          */
          //Also output so we know something's happening
          Serial.print(millis());

        Serial.print("\t");
        Serial.print(aa.x);
        Serial.print("\t");
        Serial.print(aa.y);
        Serial.print("\t");
        Serial.print(aa.z);
        Serial.print("\t");
        Serial.print(gyro.x);
        Serial.print("\t");
        Serial.print(gyro.y);
        Serial.print("\t");
        Serial.println(gyro.z);

        //Force a crash after 10s to test the watchdog
        //if (crash_timer++>10) while(1);

        }
        /*
        Serial.print(millis());

        Serial.print("\t");
        Serial.print(aa.x);
        Serial.print("\t");
        Serial.print(aa.y);
        Serial.print("\t");
        Serial.print(aa.z);
        Serial.print("\t");
        Serial.print(gyro.x);
        Serial.print("\t");
        Serial.print(gyro.y);
        Serial.print("\t");
        Serial.println(gyro.z);
*/
        // blink LED to indicate activity
        //blinkState = !blinkState;
        //digitalWrite(LED_PIN, blinkState);
    }

}

A SD memory card is 3.3V and the MPU-6050 is 3.3V. If your Pro Mini runs at 5V and 16MHz, you need levels shifters for the SD and for I2C.

Ta. Yeah it is a 5V board. I've confirmed the SD card module does have level shifters. Can't confirm it with the MPU-6050 module. However, now I've got the watchdog working I can see where it's crashing- it's in the guts of the SdFat library, "bool SdSpiCard::writeBlock(uint32_t blockNumber, const uint8_t* src)" so it doesn't look like a 3.3V/5V issue

Not every SD memory card is compatible. At least use the SD formatter: https://forum.arduino.cc/index.php?topic=228201.0 If that doesn't help, try another SD memory card. Could you return the the Arduino default SD library ? It is a slower, but it is reliable. If you use a breadboard, there might be bad connections. It is better to use a level shifter for the I2C bus and, if possible, exchange the outdated MPU-6050 for a MPU-9250.

Yeah I used the recommended format utility- given each test successfully records hundreds of thousands of lines of data to the card there doesn't seem a fundamental incompatibility. Also the hangs are only happening when both I2C and SPI comms are in use- each bit in isolation is fine. Re libraries, I was given to understand the standard lib is a fork of SdFat that's several years old and has a number of bugs that've since been resolved in the master?

The Arduino SD library is made by Bill Greiman https://github.com/greiman and he has continued to work on it which is now his SdFat library. However, I just want to get rid of everything unknown. When you have a I2C level shifter and everything is connected properly, there is no conflict between I2C and the SPI bus. At this moment I can only see troubles with 3.3V or 5V or voltage drops, but I don't know which modules you have and how you have connected it. Could you do a test by lowering the 5V for the Pro Mini to about 3.5V ?

Difficult because I'm running through an FTDI cable and looking at the output on a PC to see if it's rebooted at any point. However I seem to have resolved it- made another set of modules with soldered links and that's just run for 18 hours before I stopped the test. So even slowing SPI and I2C right down, the breadboard was still doing something that caused hangs- even though there was no obvious data corruption while running.

This seems to be fixed. I've connected the modules together using short soldered leads rather than the breadboard and it's just run for 18 and a half hours before I decided to stop the test. Previously the maximum run time was less than an hour. So even with SPI at sixteenth speed and I2C at 50kHz instead of 400kHz, it seems a breadboard is too flaky when both comms mechanisms are in use. I note I didn't actually say I was on breadboard- in hindsight maybe that would've prompted immediate comment but I thought at slow data rates I'd be ruling out such things.

It seems that, from my experiments, this has something more to do with the serial buffer. If you print more than 55 characters in Serial.print (); using the MPU6050 and the SDCard, stack overflow errors occur. Try limit the buffer to 55 using the snprintf(); function; instead of Serial.print(); directly. Or make the serial output divided by 55 if your serial output is more than 55 per line.

I had a similar problem with an SD-Card and CAN-BUS Module on an Arduino Mega Pro Mini.
My solution was to add a 470uF capacitor between VCC and GND. Problem solved!
That was the only capacitor I tried, maybe a smaller value would have done the job.
My project used about 200mA.
What I found surprising was that I had to add this capacitor when I used the USB from my PC for the power supply. The PC power supply and motherboard are high quality.
When I powered my project with a linear regulator (12V to 5V) and a switching converter all worked fine. But both had already a 470uF capacitor on the 5V side.
It's obvious that this won't be the answer in all scenarios. But it might be one of the possible answers for a system which hangs for no obvious reason.


text:
Do prototypes need to follow the order of the functions?
I define prototypes prior to calling the functions.
Does the order of the prototypes have to match the order of the functions in the code?
I'd like to sort the prototypes alphabetically, while I wouldn't care in which order they appear in the code.
I am after common or best practice.

Why don't you try it and find out?

I am after common or best practice... and what a lame/flippant way to reply (and with a down vote)... I can try a lot of things, but would rather stick to what is considered good practice.

Your question as you originally posted it, with no mention of best practice, deserved the down vote, in my opinion: you could have tested whether the order mattered very easily, and prior research is expected here. With your edits there's now a sensible question, and I'll remove my downvote. You shouldn't take this personally - it's about the quality of the question, not a slight on your character.

how is this C question arduino related? you don't need function forward declaration in ino files (unless you use a pointer to function before setup()).

@Juraj: "unless"... and then you need to. The Arduino is programmed in C, hence it is Arduino related (so I thought).

@MarkSmith: fair enough... I have tried quite a few things as novice to C, and see how I have evolved to doing things I can share with others than rather the strange ways a newbie comes up with. It were also questions like these, that helped me to write better code... and also code, that compiles in IDEs other than the standard Arduino IDE.

There is no specific best practice in this regard.
The rest of this answer is primarily opinion based, and hence off topic for this site.
If you have classes it's common, but in no way required, universal or "bad" not to do, to group the public, private and protected methods together.
Really, group them in a way which makes sense for your program - related functions together. If you have so many methods / functions that they need a lot of organizing, split them into groups of related functionality - using classes or whatever.

It is sometimes a catch 22 to determine, whether a question will have a sort of standard answer or only an 'opinion'ated one. :)

Does the order of the prototypes have to match the order of the functions in the code?

No.

I'd like to sort the prototypes alphabetically, while I wouldn't care in which order they appear in the code.

You can do that. It would make the prototype easier to find, I suppose, however most editors these days have search functions.

I am after common or best practice.

Because the Arduino IDE automatically generates function prototypes the common practice is not to use them at all.
If you want to know best practice in general I suggest you ask on Stack Overflow.

Years ago I programmed Burroughs Medium Systems in BPL (Burroughs Programming Language), a language similar to Algol (which Pascal looks a bit like).
In BPL you could not use a function or variable which had not been previously defined. Thus, the "main" function would always appear at the end of the source file. Major functions (called by the main function) would therefore precede it, and minor functions would appear earlier again. Thus you could tell the hierarchy of function calls, roughly, by the order in which the functions appeared.
In C (and C++) you don't need function prototypes if you have all your code in a single file, and if you follow that convention. Put the main code at the end and the things it calls before them. You only need function prototypes then in unusual cases where A might call B but B might call A.


text:
Why serial communication does not work on atmega168/328p?
I expect from the following program serial.c to light the led on if I send key 1 from terminal, and light the led off when I send key 0 from terminal:
#define F_CPU 16000000UL
#define BAUD 9600
#include <avr/io.h>
char data;
void main(void) {
  #include <util/setbaud.h>
  UBRR0H = UBRRH_VALUE;
  UBRR0L = UBRRL_VALUE;
  UCSR0B |= (1<<RXEN0);
  UCSR0C |= (1<<UCSZ01)|(1<<UCSZ00);
  DDRB |= (1<<PB1);
  while(1) {
    while(!(UCSR0A&(1<<RXC0)));
    data = UDR0;
    if (data=='0') PORTB &= ~(1<<PB1);
    if (data=='1') PORTB |= (1<<PB1);
  }
}

I use the following commands to compile and burn all the programs:
avr-gcc -Os -mmcu=atmega328p -c -o serial.o serial.c
avr-ld -o serial.elf serial.o
avr-objcopy -O ihex serial.elf serial.hex
avrdude -c usbasp -p atmega328p -U flash:w:serial.hex

The output of avrdude is the following:
$ avrdude -c usbasp -p atmega328p -U flash:w:serial.hex

avrdude: AVR device initialized and ready to accept instructions

Reading | ################################################## | 100% 0.00s

avrdude: Device signature = 0x1e950f
avrdude: NOTE: "flash" memory has been specified, an erase cycle will be performed
         To disable this feature, specify the -D option.
avrdude: erasing chip
avrdude: reading input file "serial.hex"
avrdude: input file serial.hex auto detected as Intel Hex
avrdude: writing flash (12 bytes):

Writing | ################################################## | 100% 0.03s

avrdude: 12 bytes of flash written
avrdude: verifying flash memory against serial.hex:
avrdude: load data flash data from input file serial.hex:
avrdude: input file serial.hex auto detected as Intel Hex
avrdude: input file serial.hex contains 12 bytes
avrdude: reading on-chip flash data:

Reading | ################################################## | 100% 0.02s

avrdude: verifying ...
avrdude: 12 bytes of flash verified

avrdude: safemode: Fuses OK (E:07, H:DE, L:FF)

avrdude done.  Thank you.

For serial connection I tried PL2302 and FT232RL usb-com adapters - the effect is always the same.
Terminal settings on the computer are correct (9600,8N1).
avr-gcc version 4.8.1
avrdude version 6.1
Why the very first program in this question does not work as needed and what should be changed in it to achieve the desired behavior?

How is the LED wired to the ATMega?

@Majenko: one led is built-in from the arduino duemilanove board (PB5), another is an ordinary led directly connected to GND and PB1.

So no resistor on the PB1 LED then?

@Majenko: no resistor. I'll try with 270 ohm between GND and led (right?) and report in a minute....

Yes, you do that.  270Ω should be OK.

Also, do you have an Arduino bootloader installed on this chip?

@Majenko: No, as in fuse settings I have BOOTRST enabled.

@Majenko: With the resistor the strange blinking disappeared.

Ok, so forst problem solved: the one LED was most likely causing the Brownout detector to kick in and reset the chip.  Now we can tackle the problem with your code.  I suggest you update your question now the blinking is no longer an issue so the answers can focus on the software problem.

@Majenko: I'll update the question in a moment... It is not clear about Brownout detector - I have it totally disabled in fuses. And where could this problem with voltage appear from anyway? 5V is provided by the PC.

But an LED has a fixed forward voltage of say 2V.  With no resistance the current drawn by the LED is theoretically infinite. That can cause all sorts of issues, including power supply droop and general crashes and resets even with brownout disabled. With it enabled it just reboots cleanly. With it disabled it just crashes messily.  The good news is I can replicate the symptoms of your first bit of code on my Uno quite happily, so I can diagnose the problem now.

The problem you have is that your baud rate is not being set right.
You only have part of the settings you need.  There is a third macro in the setbaud.h file that you need to take account of:  USE_U2X.
That defines whether or not you need to set or clear the U2X0 bit of UCSRA0.  If that is set wrong then your baud rate will be either twice or half what you want it to be - in this case it's coming out as twice.
Modify your code to assign the baud rate like this:
#include <util/setbaud.h>
UBRR0H = UBRRH_VALUE;
UBRR0L = UBRRL_VALUE;
#if USE_U2X
UCSR0A |= (1<<U2X0);
#else
UCSR0A &= ~(1<<U2X0);
#endif
UCSR0B |= (1<<RXEN0);
UCSR0C |= (1<<UCSZ01)|(1<<UCSZ00);

Then you should be able to receive characters.
In the actual header file in question there is a large number of comments and instructions, including this:

Assuming that the requested BAUD is valid for the given F_CPU then
     the macro UBRR_VALUE is set to the required prescaler value.  Two
     additional macros are provided for the low and high bytes of the
     prescaler, respectively: UBRRL_VALUE is set to the lower byte of
     the UBRR_VALUE and UBRRH_VALUE is set to the upper byte.  An
     additional macro USE_2X will be defined.  Its value is set to 1 if
     the desired BAUD rate within the given tolerance could only be
     achieved by setting the U2X bit in the UART configuration.  It will
     be defined to 0 if U2X is not needed.

My resulting UART configuration, which may be being affected by the bootloader, is:
UBRR0H: 0x00
UBRR0L: 0x67
UCSR0A: 0x20
UCSR0B: 0x10
UCSR0C: 0x06

That equates to data register empty, RX enabled, 8-bit.
To my mind that is equal to the values being manually set in the code, so shouldn't be a problem.

No, it changes anything - still the program does not work as needed. With F_CPU = 16MHz and BAUD = 9600 it leaves U2X0 setting in the default value (I already checked this before).

Then there must be something else unrelated that is stopping it from working. This code works, I tested it on an Uno.

What could this be? I've been fighting with this all the week...

By the way, did you say you didn't have a bootloader installed, because you had BOOTRST enabled? With BOOTRST turned on (hf=0xDE) you boot into the bootloader. With it turned off (hf=0xDF) you boot into your code.

With it "enabled" (=0) you boot the bootloader. With it "disabled" (=1) you boot your code. Make sure you have it set right if you don't have a bootloader installed.

Oh, and on my Uno, which is like your setup 16MHz, I had to add the U2X code to make it work - the bit defaulted to the wrong state for 9600 baud.

Of course, BOOTRST must be disabled. Their enabled/disabled = 0/1 terminology is totally confusing... I'll change the fuse and report in a minute...

It's not their "convention" - it's normal. It's all to do with the fact that an un-programmed flash cell is 0xFF not 0x00, so they map the default values to be 1 and the non-default to be 0. That way it can operate direct from the factory without needing to have any fuse bits manually changed.

Maybe the fact that I am using a bootloader is leaving some value in a different state that you would need to change.  I will just print out my register values... one sec...

I'm very curious what is the problem ... Still nothing makes sense to me ...

@IgorLiferenko You need to disable the watchdog timer, and the only way I have found to do that reliably is using the functions in avr/wdt.h - the watchdog is a right pain and can be hard to get rid of when you don't want it - the bootloader disables it for you normally which is why I wasn't seeing a problem before.

I cannot disable it by any means - in fuses it is disabled and wdt_disable(); does not help. I would like to use the bootloader so that it will do necessary resets. Will anything change in my compile-burn workflow described above if I will use bootloader? (for example, burn my programs via ICSP, not via bootloader). The answer should be edited with this info, as it relates to the core problem.

Once the WDT has fired it's almost impossible to turn it off short of removing the power.  Once it is turned off though it won't fire again so won't get stuck in that condition.  The only difference for using the bootloader with ICSP is to make sure you don't wipe the bootloader when you program the chip, which means making sure you use the -D flag to disable chip erase.

I found the solution - see http://arduino.stackexchange.com/questions/17585/what-makes-the-watchdog-timer-start-on-atmega168-328p/17614#17614


text:
Where in datasheet is the warning about unreliability of reading PINxn?
I use atmega32u4 (but believe it applies to all models). Here is the datasheet.
Consider the following C program (I use AVR-GCC 5.4.0):
#include <avr/io.h>
int main(void)
{
  PORTB |= 1 << PB5; /* pullup */
  DDRB |= 1 << PB0; /* LED */
  if (!(PINB & 1 << PB5))
    PORTB |= 1 << PB0; /* turn on LED */
  while (1) ;
}

There are two situations:

connect a 10cm wire to PB5 pin (the other end of the wire is in the air): the result is that sometimes after poweron the led is on, sometimes the led is not on.
do not connect anything to PB5 pin: the result is that after poweron led is never on.

I have a standard setup. Nothing tricky. If it does not work reliably, this gotcha MUST be documented in datasheet. This setup is supposed to deal with a stupid button. But sometimes it detects a keypress while there is no keypress.
The question is: where in datasheet there is a warning about this gotcha?
And did somebody come across such case, or I'm the first in the world?
EDIT See also this question.

the internal pullup is pretty weak ... there may be too much radio interference in your area .... try using an external 1k resistor for pullup .... increase the value until failure occurs again, then use the largest value resistor that provides correct functionality

@jsotola ok, but I need to know where it is mentioned in datasheet (remember: it is a standard button, and I doubt that a 10 cm wire can have any influence even if "there may be too much radio interference in my area")

It's not in the datasheet because it's a basic characteristic of all CMOS circuits, and should have been covered in Digital Electronics 101.

@jsotola OK, put it in the answer please. Now (as a newbie) I know that internal pullup is not useful for anything. Good to know this.

I know that internal pullup is not useful for anything ... that is not true ... it works great for switches .... also you abused the intended usage of the chip .... you should not have an antenna connected to the input pin

did somebody come across such case, or I'm the first in the world?

You are not the first. I recently got bitten by the very same issue.
However, unless you are close to an unusually strong radio source, I do
not think it has anything to do with electromagnetic interference. In my
experience, the internal pullup is perfectly reliable for reading
switches and push buttons, even on a breadboard with jumper wires acting
as antennas. If you use pinMode() and digitalRead() instead of
direct port access, you too will find the internal pullup is perfectly
fine.
Before I give you the answer (suspense...), let's look closely at what
your code does. The disassembly looks like this:
main:
    sbi  PORTB, PB5 ; turn on pullup on PB5
    sbi  DDRB,  PB0 ; set LED pin as output
    sbis PINB,  PB5 ; read PB5, if it is LOW then:
    sbi  PORTB, PB0 ;   turn on LED
0:  rjmp 0b         ; hang in an infinite loop

In the situation when the LED turns on, every instruction there executes
in two CPU cycles, save for sbis, which takes a single cycle in this
case. Now, let's look at the timings, and specifically at the states of
the pullup and the input circuitry during each of the first seven CPU
cycles:
cycle   instruction   pullup latch PINB5
----------------------------------------
   1   sbi PORTB, PB5   off    X     X
   2      cont.         off    X     X
   3   sbi DDRB,  PB0   on     X     X
   4      cont.         on    LOW    X
   5   sbis PINB, PB5   on     X    LOW
   6   sbi PORTB, PB0   on     X     X
   7      cont.         on     X     X

In the table above, “X” means “don't care”. Each instruction takes
effect at the beginning of the next CPU cycle, when the clock's rising
edge commits the result of the instruction to the affected flip-flops.
That's why the pullup turns on only at the beginning of cycle 3.
Now, since the pin did read LOW, that means the PB5 flip-flop was LOW
while the CPU was reading it, during cycle 5. This in turn means
that the synchronizing latch before that flip-flop was LOW during
cycle 4.
Your expectation was for the pin to read HIGH. So let's see: how fast
should the pin voltage have risen in order for the pin to indeed read
HIGH? Since the input latch is transparent during the first half of each
cycle, this means that the voltage should raise past the Schmitt
trigger's threshold during cycle 3 and the first half cycle 4.
So the rise time should be less than 1.5 cycles. Or rather
1.5 cycles minus the combined propagation delay of the PORTB5
flip-flop and the logic that controls the pullup from that flip-flop's
output. Probably around 90 ns. That's short!
By now you have probably guessed: the culprit is not electromagnetic
interference, it's stray capacitance. A simple calculation will show you
that about three picofarads is enough to produce the effect you are
seeing. This is the kind of stray capacitance you will find everywhere,
even between the PCB traces of your Arduino board. Note that
electromagnetic noise can add some unpredictability to what you see, as
the pin is susceptible to it when it's completely floating, i.e.
before you turn on the pullup, which makes the initial voltage (at the
beginning of cycle 3) unpredictable. But once the pullup is on and
the pin has settled, you won't care about noise anymore, unless it's
unusually strong.
The solution to your problem is simply to wait for the pullup to charge
the stray capacitance. A microsecond delay should be enough to fix the
issue. Alternatively, use the Arduino functions instead of direct port
access: they are so slow that you will not need any extra delay.

where in datasheet there is a warning about this gotcha?

In section 18.2.4 – Reading the Pin Value: “[The synchronizing latch] is
needed to avoid metastability if the physical pin changes value near the
edge of the internal clock, but it also introduces a delay.”
(emphasis mine).
Edit: In a previous version of this answer, I incorrectly stated
that sbi is a single cycle instruction, which required the voltage to
rise in half a cycle instead of 1.5 cycles. The corrected timing is
still short enough for stray capacitance to be a valid explanation of
the observed behavior.

In summary:

The stray capacitance attached to the pin, together with the pullup
resistor, for an RC circuit.
As the pin is initially floating, it's initial voltage is
unpredictable.
When the pullup is turned on, the voltage starts to rise from whatever
initial value it had to 5 V.
After some time, which can be typically of the order of the RC time
constant, the input Schmitt trigger turns HIGH.
After some extra delay introduced by the synchronizer, the PINxn
flip-flop turns HIGH.
If the CPU reads the PINx register before that happens, it gets a LOW
reading.

Could you explain in a couple of words what this "latch" and "synchronizer" stuff is all about? Or recommend a resource which explains it in a more understandable way than the datasheet?

@IgorLiferenko: This is common electronics knowledge. The latch is a D latch, similar to a D flip-flop, but sensitive to clock levels instead of clock edges. The synchronizer synchronizes the input signal with the internal clock in order to prevent metastability, i.e. the “undecided” states in between LOW and HIGH. It's a non-trivial topic. You can try a Web search or this in depth tutorial (warning: not a light reading).

To sum it up: the delay from metastability synchronization input circuit sometimes is enough for the
stray capacitance to settle, and sometimes not. And the stray capacitance has more chance (with other conditions being equal) to affect the input pin when reading of pin is delayed by 1/2 cycle than
when by 1.5 cycles. Is it correct?

@IgorLiferenko: I couldn't understand your summary, so I added my own.

A test with an Arduino Uno.
I used the usb connector to power-on the arduino uno. The led is at PB5, so I have exchanged PB0 and PB5. My test is therefor not the same.
#define LED_PB  PB5   // pin 13, onboard led
#define INP_PB  PB0   // pin 8, antenna

void setup(void)
{
  noInterrupts();
  PORTB |= 1 << INP_PB; /* pullup */
  DDRB |= 1 << LED_PB; /* LED */
  if (!(PINB & 1 << INP_PB))
    PORTB |= 1 << LED_PB; /* turn on LED */
  while (1) ;
}

void loop()
{
}

Using it next to my computer and phone, sometimes the led stays on. I can even find a spot behind my computer monitor (with CCFL backlight) where the led always turns on.
Then I went outside, away from metals, wifi, and so on. The air humidity outside is 70% at the moment, which is high. I put it on a wooden table, so there is no charge by plastic. I used a battery to power the arduino uno. Then the led never turns on.
In such a clean environment, the internal pullup resistor was probably strong enough to pull the pin high during that very short time.
@IgorLiferenko, @sa_leinad gave the right answer. What you noticed is normal. It is totally normal. That behaviour can be expected. It will be worse when your circuit is not well designed.
A oscilloscope will not help. As soon as you connect a oscilloscope, you have changed something. It will also be very hard to detect that very short time (less than a microsecond).
In my opinion the influence by radio waves is only half of the problem. I think the electrical charge of the air, and the capacitive coupling of the wire with the air might have a larger effect.

You have made an antenna with the 10cm wire and are receiving radio waves which is translating to voltages on your input pin. This is why you don't have the same trouble when the wire is not connected.
According to www.csgnetwork.com/freqwavelengthcalc.html your 10cm wire is picking up frequencies of 750 MHz based on a quarter wavelength calculation.
The datasheet states that the internal pull up resistance is roughly between 20K - 50K ohms. As mentioned in the comments, this is quite weak.
There are two things that you can do that I can see:

Add a stronger pull up resistor (a value between 1K and 5K ohms should do)
Add a decoupling/bypass capacitor.

The reason that this is not in the datasheet is because this is a general electronics/physics knowledge, not a characteristic of the micro-controller itself.

Is there any explanation to the fact that this effect manifests itself only right after enabling pullup, never after a delay (I used 10ms to check)?

@IgorLiferenko, how many explanations do you want? The radiowaves are reflected by metals and can be unpredictable. Perhaps the air is dry and is charged. The internal multiplexer might have influence. How scientific was your test? Did you try it with an other computer and other arduino board in another location? Have you made your own circuit with a atmega32u4, did you forget to decouple the vcc or are the crystal and 22pf capacitors not close to the atmega? Maybe the voltage is too low or there is a grounding error. I can think of about 20 explanations, and others perhaps another 80.

@Jot If you are interested, try the simple setup as I described in OP - I'm sure you will get the same results. I just thought somebody came across such problem before... Now I'm sure that the only way for me to find out what is going on, is to get an oscilloscope...

@IgorLiferenko I did, see my answer.

This actually is documented in the datasheet and illustrated by the logic diagram of the typical GPIO, to see what is really going on behind your compiled code you need to look at the generated assembly code and which registers are being accessed:

When you change one bit of an IO port, you are either modifying the 8 bit register on which that bit is mapped using the WRx signal or just the 1 bit register for the pin alone using the WPx signal.  When you use the WPx signal to set or clear the bit, you don't need to know the states of the other pins so the discussion ends here.  However, when you use the WRx signal to MODIFY a single bit, you need to know the states of the other 7 bits which means that your need to read the 8 bit port.  You can either read the port LATCH using the RRx signal or you can read the actual physical pins using the RPx signal.  Now when using the RRx signal, no amount of loading or noise on the pins themselves will affect what is read from the output of the port latch but when using the RPx signal, if a previous write to the port is followed by a read of the port, any parasitics or noise on the OUTPUT pins may cause a pin that you think that you just set to a one suddenly becomes a zero.
The reason this happens is because of how opcodes are pipelined.  Writes to ports happen at the end of the last instruction clock but reads happen at the beginning so that there is essentially zero time between when you set that bit to a 1 and when you change some other bit (Read-modify-write fashion) so that bit is still a zero when it is read and then immediately written as a zero.
As illustrated below, this can be rectified by inserting a delay between write and read-modify-write opcodes to let the pin states stabilize.  The delay must take into account the capacitive loading and noise environment

The WRx vs WPx distinction has nothing to do with whether you are writing a single bit or the whole register: WRx is the signal for writing the PORTxn flip-flop, whereas WPx is for writing PINxn (which is actually used to toggle PORTxn). And note that the OP did include a two-cycle delay between writing and reading.

You have apparently missed the entire point:  When read-modify-write reads from the pins and then writes the latch, noise or delay on outputs can be re-written to the output and possibly changing the output's state unintentionally.  Adding one cycle, tow cycles or a thousand cycles of delay may not be sufficient and understanding the mechanism of this uncertainty is the only way to build robust platforms that operate predictably under ALL circumstances.

You also missed my point. I told you about a factual error in your answer. The appropriate response in this case is to edit the answer and fix the error. Your point that I still don't get is the one about “When read-modify-write reads from the pins and then writes the latch [...]”. Do you actually mean “reads from PINx and writes to PORTx”? If so, it's irrelevant. Nobody does that. Certainly not the OP.


text:
Am I multiplexing my LEDs correctly?
I am new to electronics. I have a good amount of programming under my belt however.
I want to know if I am multiplexing correctly or not. My intended output is how I want it, but I am not sure if I implemented it how it's supposed to be, i.e. am I potentially damaging my equipment.
I have 6 RGB LEDs hooked up to my arduino, let's called them L1 - L6.
I have each R, G, and B pin on L1 - L3 connected in parallel, and the same for L4 - L6. Then I have ground on L1 and L4 connected in parallel, and the same for L2 to L5, and L3 to L6.
So this gives me 6 pins to supply voltage to, to which I put a 220 ohm resistor in each one. Then it gives me 3 different spots for ground.
My question is about the ground. How should I control the different 'pins' for ground.
This is what I have right now, and it works, but I don't know if this is dangerous to my equipment for some reason.
I have the 3 ground pins connected to the Arduino in 3 different pins, 7, 4, and 2.
In Setup() I configure these 3 pins as outputs, and I later found out in order to keep them all 'off' I need to set them all to high.
So then in order to turn L1 on to red, I need to turn its red pin to high, but turn its ground pin to low, then L1 turns on.
Using this same technique, I am able to get every LED to every desired color. So I mean it works. But why is this? Is this how I should be doing it? I understand LEDs polarity matters, but why would supplying its cathode with voltage make it turn off? That's the part I'm worried about, am I destroying my LEDs by doing this?
Any and all help much appreciated!
Here is how I have it all wired up for clarity.

So I mean it works. But why is this?

It works because the LED inside the RGB LED, all three of the LEDs inside have the characteristic of a diode, this means it will allow current flow in one direction, but will stop, or restrict it in the opposite direction. Also are you asking why it works because of your specific wiring?

Is this how I should be doing it?

Yes, how you are doing it is fine. Although I would suggest you use NPN transistors to drive your cathodes of the LEDs.

This will at least remove any worry of applying 5v to the cathode.
It will also reduce the amount of current your I/O pins have to handle.
You should also move the resistors from the cathodes to the anodes as this is more reliable and pretty much the norm.

I understand LEDs polarity matters, but why would supplying its cathode with voltage make it turn off?

This works because of the theory of the p-n junction, (inside construction of a diode), this means that because of the construction of the diode it requires the voltage on the Cathode to be at a lower potential. So that means when you set the output HIGH the 5v on the anode and the 5v on the cathode "stop" current flow because it stops the breakdown within the p-n junction.

That's the part I'm worried about, am I destroying my LEDs by doing this?

No you are not, the LED acts as a diode and when the potentials are the same, current doesn't really flow and thus doesn't do anything to the LED.

LEDs are not powered by a particular voltage level, but by the voltage difference between anode and cathode. That's why you need to drive cathode pins (7, 4, and 2) LOW to switch the LEDs ON and HIGH to switch them off. A truth table could help:
╔═══════╦═════════╦══════════════════════════╦═══════════╗
║ anode ║ cathode ║ voltage anode to cathode ║ led state ║
╠═══════╬═════════╬══════════════════════════╬═══════════╣
║ LOW   ║ LOW     ║ 0V                       ║ OFF       ║
╠═══════╬═════════╬══════════════════════════╬═══════════╣
║ LOW   ║ HIGH    ║ - 3.3V                   ║ OFF       ║
╠═══════╬═════════╬══════════════════════════╬═══════════╣
║ HIGH  ║ LOW     ║ + 3.3V                   ║ ON        ║
╠═══════╬═════════╬══════════════════════════╬═══════════╣
║ HIGH  ║ HIGH    ║ 0V                       ║ OFF       ║
╚═══════╩═════════╩══════════════════════════╩═══════════╝

Your schematic looks safe to me, but be aware that if you decide to illuminate L1, L2 and L3 to the same color simultaneously (e.g drive red line HIGH and pins 7, 4, and 2 LOW), your LEDs will not have uniform brightness. Only one of the cathode pins should be LOW at a time, otherwise you will end up in the situation described here.

I see what you mean. I'm having trouble trying to figure out PWM now and I don't know how to make L2 @ 255 red while keeping L1 @ 127 red - because they use the same red pin (11).

first drive cathode L2 low, L1 high, and PWM @255. Then drive cathode L1 low, L2 high, and PWM @ 127. repeat about 100 times per second so both LEDs appear lit simultaneously.