text:
Need help shrinking a code
I'am new to Arduino and c++
i get his code from the INTERNET
void setup() {
    Serial.begin(57600);
    pinMode(13, OUTPUT);
}
int f = 0, pos;
void loop() {
    boolean has_request = false;
    String in = "";
    if (Serial.available()) {
        in = "";
        while (true) {  // should add time out here
            while (Serial.available() == false) {}
            in += (char)(Serial.read());
            if (in.endsWith("\r\n\r\n")) {
                has_request = true;  break;
            }
        }
    }
    if (has_request) {
        int i1 = in.indexOf("GET /blink?f="), i2;
        if (i1 != -1) {
            i2 = in.indexOf(" ", i1+13);
            f = in.substring(i1+13, i2).toInt();
        }
        Serial.println("HTTP/1.1 200 OK\nContent-Type: text/html\nConnection: close");
        String sr = "<!DOCTYPE HTML>\n";
        sr += "\n";
        sr += "LED frequency: ";
        sr += f;
        sr += "Hz.";
        Serial.print("Content-Length: ");
        Serial.print(sr.length());
        Serial.print("\r\n\r\n");
        Serial.print(sr);
        has_request = false;
    }
    if (f>0) {
        static unsigned long t = millis();
        if (millis() > t + 1000/f) {
            digitalWrite(13, 1-digitalRead(13));
            t = millis();
        }
    }
}

see this link if you cant see the code formated here in the site
this code is used for the Arduino uno wifi shield
it is working perfectly except it is too complicated for me
while loop inside a while loop
and i don't want to do frequency i only need to send turn on or off
without any complexity
anyone could help me ?

The test if (millis() > t + 1000/f) will not work properly close to the millis() rollover. It should rewritten as if (millis() - t > 1000/f). See this answer to How can I handle the millis() rollover? for an extended discussion.

I would recommend starting out with some easy stuff you understand or making code yourself... Starting out with code you don't understand will backfire you.
I'll explain the code for you anyway.
This part will "set everything up". The serial connection and the direction (in/output) of the pin(s).
void setup() {
    Serial.begin(57600);
    pinMode(13, OUTPUT);
}

Somehow did the person who made this think it was logical to put this here instead of on the very top of code. There are 2 integer variables declared here of which one is initialized with 0. (f).
int f = 0, pos;

This part of the code (untill the very last bracket) will be ran continiously, in a "loop". Many, if not all, embedded systems will run "forever".
void loop() {

This is basically a "flag", it indicates if something has, or has not happened. At this point it's only initialized.
    boolean has_request = false;

Also we're keeping a buffer (text string) of the characters we receive.
    String in = "";

Check if there are characters in our serial buffer.
    if (Serial.available()) {

If so, we empty our own buffer.
        in = "";

And keep doing this code.
        while (true) {  // should add time out here

We wait until the next character is ready.
            while (Serial.available() == false) {}

And add it to our buffer.
            in += (char)(Serial.read());

But when we see our buffer ends with \r\n\r\n (carriage return, line break x2).
            if (in.endsWith("\r\n\r\n")) {

We're going to set te flag, indicating that we have received a message.
And we stop the: "Keep doing this code".
                has_request = true;  break;
            }
        }//(this is actually the parenthesis of the while(true) which we break out.

    }

So we had this message, right? Let's do the following:
    if (has_request) {

Parse the variable in the GET request (f=??) to an int.
        int i1 = in.indexOf("GET /blink?f="), i2;
        if (i1 != -1) {
            i2 = in.indexOf(" ", i1+13);
            f = in.substring(i1+13, i2).toInt();
        }

Send a 200OK (with body) back to the thing that sent the http request (actually pretty neat to do so.)
        Serial.println("HTTP/1.1 200 OK\nContent-Type: text/html\nConnection: close");
        String sr = "<!DOCTYPE HTML>\n";
        sr += "\n";
        sr += "LED frequency: ";
        sr += f;
        sr += "Hz.";
        Serial.print("Content-Length: ");
        Serial.print(sr.length());
        Serial.print("\r\n\r\n");
        Serial.print(sr);
        has_request = false;
    }

We also keep doing this blinking. (Fun fact: While receiving/sending stuff, your blinking will stop/desync. This is because the receive/send code is blocking the blinking code. Making the blinking hardware and/or receive/send interrupt based will improve the systems reaction time and efficiency.)
    if (f>0) {
        static unsigned long t = millis();
        if (millis() > t + 1000/f) {
            digitalWrite(13, 1-digitalRead(13));
            t = millis();
        }
    }
}

But how will we make this better? Or atleast easier to read?
By using functions, you can split up the code, and giving the functions a logic name, it all becomes quite obvious. The whole thing is doing 3 jobs:
Blinking a led on a given frequency.
Receiving requests/commands through serial (handling serial).
And handling these requests afterwards.
void BlinkLed(int f);
void HandleRequest();
void HandleSerial();

int f = 0, pos;//Pos doesn't have to be a global variable...

void setup() {
    Serial.begin(57600);
    pinMode(13, OUTPUT);
}

void loop() {
    boolean has_request = false;//Reset the flag every loop.
    String in = "";//Clear the string every new loop.
    if (Serial.available()) {
        HandleSerial();
    }
    if (has_request) {
        HandleRequest();
    }
    BlinkLed(f);
}

void BlinkLed(int f){
if (f>0) {
        static unsigned long t = millis();
        if (millis() > t + 1000/f) {
            digitalWrite(13, 1-digitalRead(13));
            t = millis();
        }
    }
}

void HandleSerial(){
        in = "";
        while (true) {  // should add time out here
            while (Serial.available() == false) {}
            in += (char)(Serial.read());
            if (in.endsWith("\r\n\r\n")) {
                has_request = true;  break;
            }
        }
}

void HandleRequest(void){

        int i1 = in.indexOf("GET /blink?f="), i2;
        if (i1 != -1) {
            i2 = in.indexOf(" ", i1+13);
            f = in.substring(i1+13, i2).toInt();
        }
        Serial.println("HTTP/1.1 200 OK\nContent-Type: text/html\nConnection: close");
        String sr = "<!DOCTYPE HTML>\n";
        sr += "\n";
        sr += "LED frequency: ";
        sr += f;
        sr += "Hz.";
        Serial.print("Content-Length: ");
        Serial.print(sr.length());
        Serial.print("\r\n\r\n");
        Serial.print(sr);
        has_request = false;
}

V2 (more likely to compile, but kinda changes the structure):
void BlinkLed(int f);
void HandleRequest();
boolean HandleSerial();

int f = 0;//Frequency of the led (blinking)

void setup() {
    Serial.begin(57600);
    pinMode(13, OUTPUT);
}

void loop() {
    String in = "";//Clear the string every new loop.
    if (Serial.available()) {
        if(HandleSerial()){
            HandleRequest();
        }
    }
    BlinkLed(f);
}

void BlinkLed(int f){
if (f>0) {
        static unsigned long t = millis();
        if (millis() > t + 1000/f) {
            digitalWrite(13, 1-digitalRead(13));
            t = millis();
        }
    }
}

boolean HandleSerial(){
        in = "";
        while (true) {  // should add time out here
            while (Serial.available() == false) {}
            in += (char)(Serial.read());
            if (in.endsWith("\r\n\r\n")) {
                return true;
            }
        }
        return false;
}

void HandleRequest(void){
    int i1 = in.indexOf("GET /blink?f="), i2;
    if (i1 != -1) {
        i2 = in.indexOf(" ", i1+13);
        f = in.substring(i1+13, i2).toInt();
    }
    Serial.println("HTTP/1.1 200 OK\nContent-Type: text/html\nConnection: close");
    String sr = "<!DOCTYPE HTML>\n";
    sr += "\n";
    sr += "LED frequency: ";
    sr += f;
    sr += "Hz.";
    Serial.print("Content-Length: ");
    Serial.print(sr.length());
    Serial.print("\r\n\r\n");
    Serial.print(sr);
}

We can even make it more nicer by:

using hardware (PWM) to toggle/time the led.
rewriting the serial handling code... (https://www.arduino.cc/en/Serial/ReadStringUntil)
Using printf() to format the serial.prints on one line...
Make the receive/send code interrupt based, so that it will only take short amounts of time of your code, instead of continously waiting in a while, you can do stuff in the meanwhile ;)
using classes.

The variable pos is not used at all.

In your “better” version, line 35: “error: ‘in’ was not declared in this scope”. Same for has_request (lines 40 and 62), in (line 47) and i2 (line 49).

Haha, indeed, edited the code on "answer" itself. And copied from the original code.
Pos indeed doesn't seem to do anything.
And yeah, by putting stuff in functions you're going to need to transfer the variables from one to another, or make them global :)
not sure about the  i2 though, it's in: int i1 = in.indexOf("GET /blink?f="), i2;?
I'll be editing the code (this time in Notepad++, don't have access to a compiler at the moment :l).

The syntax highlighting is actually very nice!
And you should consider the code in my answer as an example. With the explanation on the code it'd be fairly easy to roll your own (better) version of it (that will actually compile and work as you want ;) )
I believe that in V2 it's better, but I'm not sure if it still works as intended.

Just one compilation error remaining: in is declared in loop(), and used in HandleSerial() and HandleRequest(). Simplest solution would be to make it global.

You are awesome , appreciate your help bro !

There is only one "while loop inside a while loop" and that is hardly complex:
while (Serial.available() == false) {}

All that means is "Wait for something to become available on the serial".  That is ALL it does.
There is nothing even remotely complex there.  True, it may not be very well written (as is the case with lots of code on t'interwebs).  It's time to start learning how the code works so you can write your own.

+1, that code is extremely straightforward. Written like crap, but straightforward nonetheless.

Here is my take at this. I realize that I did not really make the
program simpler, but hopefully better in some respects, as it avoids
blocking reads and heap memory allocation. Be warned however that I did
not test it. It compiles fine though.
Preamble, hopefully simple enough that it requires no comments:
const uint8_t led_pin = 13;

void setup() {
    Serial.begin(57600);
    pinMode(led_pin, OUTPUT);
}

Next, here is a function to read the HTTP request. A few things are
worth noting in this function:

It is non-blocking: if there is not data in the serial buffer, it will
return NULL immediately. This is to prevent the whole program from
hanging if the client does not terminate its request.
It only saves the first 31 bytes of the request. This is because
browsers tend to add lots of useless headers, which can be unfriendly
to the memory of a small Arduino. And the only interesting piece of
data is at the very beginning anyway.
The request terminating sequence (CR LF CR LF) is detected without
having to store it in the buffer, just by counting how many
consecutive bytes of that sequence we have already received.
Declaring the function as static makes it possible for the compiler
to inline it, which it does as it is only called from one place. This
makes for a smaller executable.

/*
 * Non-blocking read. Returns the first bytes of the request in a static
 * buffer, or NULL if we do not have a complete request yet.
 */
static char * read_request() {
    static char buffer[32];
    static uint8_t pos;
    static uint8_t crlf_bytes;  // bytes of "\r\n\r\n" received

    while (Serial.available()) {
        char c = Serial.read();

        // Store the received byte if there is enough room.
        if (pos < sizeof buffer - 1)
            buffer[pos++] = c;

        // Update the count of consecutive CRLF bytes received.
        if ((c == '\r' && crlf_bytes % 2 == 0)
         || (c == '\n' && crlf_bytes % 2 == 1))
            crlf_bytes++;
        else
            crlf_bytes = 0;

        // Return the buffer if we have a complete request.
        if (crlf_bytes == 4) {
            buffer[pos] = '\0';  // terminate the string
            pos = 0;
            crlf_bytes = 0;
            return buffer;
        }
    }
    return NULL;
}

Parsing the request is done by a different function. Here, I do not
search for the "GET /blink?f=" string, because it must be at the very
beginning for the request to be valid.
/*
 * Returns the requested frequency, or 0 if nothing valid is found.
 */
static int parse_request(char *request) {

    /* The "GET" should be at the very beginning. */
    if (strncmp(request, "GET /blink?f=", 13) != 0)
        return 0;

    return atoi(request + 13);
}

Now we can send the response to the client, telling it how we parsed the
frequency. I avoid using String, as it involves heap allocation, and I
put the bulk of the response in PROGMEM (F() macro) to save RAM. I
also added a <title> to make it valid HTML.
/*
 * Tell the client how we understood the requested frequency.
 */
static void send_response(int freq) {
    char freq_str[12];
    itoa(freq, freq_str, 10);
    Serial.print(F("HTTP/1.1 200 OK\r\n"
                   "Content-Type: text/html\r\n"
                   "Content-Length: "));
    Serial.print(84 + strlen(freq_str));
    Serial.print(F("\r\nConnection: close\r\n\r\n"
                   "<!DOCTYPE html>\n"
                   "<title>Blink</title>\n"
                   "LED frequency: "));
    Serial.print(freq_str);
    Serial.print(F(" Hz.\n\n"));
}

The next function blinks the LED in a rollover-safe fashion. Storing the
current LED state in a static variable avoids a call to digitalRead().
static void blink_led(unsigned long toggle_time) {
    static uint8_t led_state;
    static unsigned long last_toggle;
    unsigned long now = millis();
    if (now - last_toggle > toggle_time) {
        led_state = !led_state;
        digitalWrite(led_pin, led_state);
        last_toggle = now;
    }
}

Putting it all together, the main loop() ends up being quite straight
forward:
void loop() {
    static unsigned long period = 1000;
    char * request = read_request();
    if (request) {
        int freq = parse_request(request);
        if (freq > 0) period = 1000 / freq;
        send_response(freq);
    }
    blink_led(period);
}

PS: My version is significantly larger than the original at the
source level (66 v.s. 44 source lines of code), but the compiled program
is smaller in both flash and RAM usage:
text    data     bss     version
5646     168     197     original
3316      40     218     my version

Hmm, I agree this code is probably way faster and better optimized. Though the variable last_toggle is only known in the "blink_led" function. And that basically means that in the if-statement (in blink_led function), you're testing the toggle_time against an uninitialized variable?

No, last_toggle is a local static variable. This means that, although it is only “locally visible”, it has “global duration”: it is initialized at program startup by the C runtime (in __do_clear_bss), before main() is called, and it keeps its value between successive calls to blink_led(). Static variables are always initialized. If not explicitly, they are implicitly initialized to zero. And this is the right initialization for this variable, just like blink_led(unsigned long)::led_state, read_request()::pos and read_request()::crlf_bytes.

Ah, yea, static in a function means something completely different as static in a variable?
Thanks for the extensive argumentation!
I just saw that indeed, it makes more sense to make it a static variable as global variable. As you won't need/want to access it anywhere, but you do want the "global" duration. It'll also be more efficient as just making it global?

@FuaZe: Yes, “static” has different meanings depending on whether it is used inside a function or in global scope. And no, it is not more efficient than a global variable, it's the same. You would not be able to tell the difference by disassembling the compiled program, except for the symbol table.


text:
Do I need to supply the 12V connection to an HDD
I'm working on trying to control a hard drive with an Arduino Uno, but I'm having trouble with the power supply. From what I know, both the Molex Mate-n-Lok and the new SATA connectors both have 2 grounds, a 5V and a 12V power in. I'm wondering what the purpose of the 12V power supply is. I suspect it's used to drive the motor but I'm not sure.

Which hard drive? Are you planning to use it as a mechanical device, or to actually read/write to the disk?

@NickGammon Any ATA Compliant HDD, I plan to use the hdd as an hdd, but currently am having issues with power supply. At the moment, I'm working with an IDE, but may move to a SATA if I don't have enough pins

The hard drive lists what voltages and currents it needs on the casing.

@IgnacioVazquez-Abrams Yes, the standards indicate that there will be a 5V supply needed and a 12v. What I want to know is whether the 12v supply is crucial

Have you looked at the hard drive? On its casing?

Yes, it says 12v and 5V. The ATA standard has two inputs for power, one at 5V one at 12V. I'm not asking what the voltages are, I'm asking what the 12v supply is for, and whether I need to power it

This would depend on the drive.  Since you won't state a specific one, it is off topic as too broad.  But regardless, it is off topic because this is the Arduino site, not the hard disk drive site.  Also, you aren't going to talk SATA with an Arduino.  But you can get away with using only 8 of the 16 bits on the IDE bus, if you are willing to waste half the capacity, as the commands are only 8-bit.  For anything practical, SD cards will probably serve you better, if not you should probably look at something better than an Arduino.

but may move to a SATA if I don't have enough pins That's a laugh for a start...  Do you even have the slightest clue about hard-drive interfacing and protocols?

I would love to see you try and generate a 1.5Gbps LVDS signal from an Arduino... and that's just for the old-fashioned SATA-1.  It's 6Gbps these days...

The "sensible" option would be to get a USB Host Shield and a USB to SATA adapter cable.

An SD card is much more practical if you just want to store lots of data. With a $15 (or so) interface board you can connect the card to your Arduino using SPI and have gigabytes of storage space.

@Majenko Not much, but I'm reading the ATA standards at the mo

Also, the point of this is not using the HDD as such, it's the challenge of interfacing with it. If it's difficult, all the better

Judging by my old copy of "Upgrading and repairing PCs" - which I found a quote for on Google Books - the 12V supply is for the spindle motor, and it says:

Spindle motors, particularly on the larger form-factor drivers, can consume a great deal of 12V power.

Thanks, answered the question clearly and succinctly. Without casting aspersions on the idea itself

3.5" hard drives require 12V and 5V for the motor and logic respectively. SATA ones may also require 3.3V for the logic.  Most smaller laptop drives (2.5") only require 5V and 3.3V.  Some 2.5" drives also require 12V.
You will not be able to interface a SATA hard drive to an Arduino without some kind of SATA hard drive controller, which you could possibly build using a fast FPGA (in which case why would you bother with an Arduino?). For SATA-I (way out of date now) you need to generate a 1.5Gbps LVDS (Low-Voltage Differential Signal) data stream. For SATA-3.2 that is now 16Gbps. Impossible on an Arduino.
PATA (Parallel ATA) is more realistic, although you need a lot of pins since it is a 16-bit parallel interface. Timing is less critical since it is synchronous with the read / write strobes.

Yes, I'm currently working with an IDE HDD, which is PATA.

source: Stack Exchange

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

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

sort: votes


text:
Nano onboard "test" LED blinks when powered via 5V pin
I have a Nano (clone) that I am powering from a regulated supply via the 5V pin; I have checked this at the board and my multimeter reads 4.92V, which seems close enough (?). The main reason I don't use the microUSB jack is a space constraint. In any case, thus far it does work fine.
Except the leftmost (considered with the microUSB jack as "top") of the four onboard LEDs, on the opposite side from the rx/tx lights, blinks at a steady one second interval.  Searching around, the only association I've found for that LED is that it is connected to D13, which I'm not using for anything.
What does this indicate?  I have not tried disabling it (by setting 13 low) but I am hoping to do so if it is a benign issue.

Do you have the Blink sketch loaded by any chance?

@Majenko No, I've never used that.  To double check it wasn't something I'd done though, I took it out to reflash it and noticed it did the same thing w/ the USB power :\ When I reflashed it it stopped, and it doesn't do it anymore via the 5V pin either.  I just assembled this one, and D13 is attached, but the only thing it might conceivably have been used for would be driving a servo or reset.  Since there was a pin connected to reset, I tried that driven low instead of high and guess what?

So, as per the comments on the question here's what I think happened:
That "test" LED lights briefly when the board is first powered on, indicating I suppose that it's booted and setup() is either complete or about to run.
It also lights briefly when the reset button is released.
In the sketch I'm using one of the digital pins is connected to RST -- the arduino is being controlled via UART.  I have swapped some of the pin numbers and wiring around, so I tried leaving the one driving RST low instead of high and indeed, this seems to be the issue: It's resetting at ~1s intervals.
(I honestly believe I checked this before by removing all connections, but since I did not note that in the question, perhaps I never did...)

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


text:
I2C / TWI: set up atmega328p as slave
I try to run an atmega328p as a i2c slave. even with the bare minimum the slave acts as its not wired at all: NACK is transmitted after request (see logic analyzer).
The master should read a constant value in this example. iam using the wire.h lib. pullup resistors on SDA, SCL 4.7kOhm.
master.ino: esp8266 (working, sends requests)
#include <Wire.h>
#define DEFAULT_SLAVE_ADDRESS 0x0A
void setup()
{
  Wire.begin(); // join i2c bus as master
  Serial.begin(9600);
  Serial.println("\n Hello");
  delay(2000);
}
void loop()
{
  //Wire.beginTransmission(DEFAULT_SLAVE_ADDRESS);
  //Wire.write(0);
  //Wire.endTransmission();
  //delay(10);
  Wire.requestFrom(DEFAULT_SLAVE_ADDRESS, 1);
  Serial.println(Wire.read());
  delay(1000);
}

slave.ino: atmega328p
#include <Wire.h>
#define F_CPU 8000000UL
volatile uint8_t nr;
void setup()
{
  Wire.begin(0x0A);                // join i2c bus with address #4
  //Wire.onReceive(receiveEvent); // register event
  Wire.onRequest(requestEvent);
}
void loop()
{
}
//void receiveEvent(int howMany)
//{
//  while(0 < Wire.available()) // loop through all but the last
//  {
//  int x = Wire.read();    // receive byte as an integer
//  }
//}
void requestEvent()
{
  nr = 99;
  Wire.write(nr);
}

Serial output from master: (got no val)
-1
-1
...

Logic analizer output:

Wiring on atmega:
VALUE-PIN

VCC 7
GND 8
SCL 28
SDA 27

anyone got an idea whats missing?
Edit: removed receiveEvent(), added CPU speed and it worked

You seem to have a problem only with the read operation at the moment. I would remove the onReceive part to troubleshoot the problem and test if the example code works (https://www.arduino.cc/en/Tutorial/LibraryExamples/MasterReader).

esp8266 is usually 3.3V while atmega328p is 5V - do your hardware setup take it in account? And have the voltage on SDA,SCL the right values for HIGH and LOW on BOTH master and slave?

Can you make your 328P's loop() do something, like blink an led so that you know the 328P is operational and at the correct frequency?

@SimSon thanks for your reply. when i removed the receiveEvent it worked. i figured out the the problem is the Wire.available() function on the atmega.

@gilhad the ATmega can be operated at 3.3V, I guess that's the case here. The ATmega also NACKs the read header, which means the address has been transmitted successfully. That doesn't make it look like a hardware issue.

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


text:
sizeof tm struct (datetime) different on ESP32 vs linux64x
I am logging binary data to my SD. I log a datetime object of type 'tm', which is 36 bytes on ESP32.
When I create a datetime of type 'tm' on linux it is 56 bytes.
ESP32 write tm to SD:
[tm datetime = 36 bytes]
time_t t = std::time(nullptr);
tm datetime = *std::localtime(&t);
uint16_t t = file.write((const uint8_t *)&datetime, sizeof(datetime)); // ==36 bytes.

PC
[tm datetime = 56 bytes] (compiled using g++ on linux 64)
tm datetime;
std::ifstream fileStream(filename, std::ios::binary);
fileStream.read((char *)&datetime, sizeof(datetime));

tm is defined in time.h:
struct tm
{
  int   tm_sec;
  int   tm_min;
  int   tm_hour;
  int   tm_mday;
  int   tm_mon;
  int   tm_year;
  int   tm_wday;
  int   tm_yday;
  int   tm_isdst;
#ifdef __TM_GMTOFF
  long  __TM_GMTOFF;
#endif
#ifdef __TM_ZONE
  const char *__TM_ZONE;
#endif
};

My tm struct doesn't have the 'tm_gmtoff' or 'tm_zone', even if it had it wont add up to 56 bytes.
How can my tm be 56 bytes on my PC?
If someone has a better way to log a datetime object, without this issue, let me know.

sizeof(int) on arduino (AVR) is 2, on most other platforms its 4.

Why log in binary? Log as text, in the format of date +'%FT%T%:z'. If you really need binary, log time_t rather than strcut tm.

@PMF I'm using ESP32, didn't specify, my bad!

@EdgarBonet logging to text is too slow, I log at 100hz using sd.h lib. why is logging time_t better in binary?

Then don't write the entire struct but by elements, making your own data structure.

The layout of strcut tm is implementation dependent. In contrast, time_t is usually a simple integer, with very little variations across implementations: either 32 or 64 bits, and maybe a different epoch (which is fixed by simply adding a constant).

On top of that you have the problems of alignment and data access sizes. The entries in a struct will be aligned to addresses that will be dictated by what the underlying architecture is able to access (if it can only read/write whole words every byte will be aligned on a word boundary bloating your struct). You should never use system level structs in data storage or transmission (unless they're designed specifically for that). Instead define your own and pack them to remove any alignment and padding issues.

You can not trust system-level structs for data storage or transfer between different systems. The main reasons are:

Different data type sizes (16 / 32 / 64 bit ints, floats vs doubles, etc)
Struct element alignment differences owing to underlying architecture optimizations and limitations

Unless you are working with a system struct that is specifically designed for cross-system communication you must define your own and pay special attention to the layout.

Always use explicitly sized variable types (uint8_t, int32_t, etc for example) to ensure both ends always agree on data storage sizes
Always "pack" your struct (__attribute__((packed))) to collapse any specially aligned variables into just the room needed to store those variables

Point 2 requires special attention if you're doing much more than filling the struct and saving / transmitting it. It's advisable to never do more than create the struct instance, fill it, save it, then throw it away. If you start doing advanced operations with pointers to the struct you risk corrupting the packing code if the alignment changes. Also packed structs are often slightly slower to access owing to more complex code usually needed to be used to read / write the individual fields within them (especially if there are no byte-wise operations in the underlying architecture).

Thank you! multiple people commented solutions, but you gave the reason why. Also thanks for your blogpost, very helpful!


text:
Failure using references variables in classes
Theoretical Q
I'm having some trouble when using a referenced variable in a class.
Class A have an int a=0. Class B has an instance of Class A, and referencing int &a=A.a, and in the same manner Class C has an instance of Class B and int &a=B.a. Code crashed when trying to update a variable when using C instance.
Relvant Example
I'm creating a library for TFT+Touch 2.4 screen, to handle buttons more easily.
Libraries XPT2046_Touchscreen and Adafruit_ILI9341 are included here, but initiated in main .ino file for easier handling in loop and more control in main code.
1) MessageTFT
A "basic" class was created, called MessageTFT. This class creates the graphics, and stores its geometrical properties and color as shown below.
2) ButtonTFT
ButtonTFT based on MessageTFT adding touch capabilities to it. Its geometrical and color parameters are referenced to MessageTFT. When creating a button instance, user defines its properties but, actually it is referenced to MessageTFT.
ButtonTFT and MessagesTFT works as expected. For example a button is defined in .ino:
ButtonTFT butt;

and defined in void setup():
  butt.a = 200;
  butt.b = 60;
  butt.xc = tft.width() / 2;
  butt.yc = tft.height() - butt.b / 2;
  butt.txt_size = 1;
  butt.face_color = ILI9341_CASET;
  butt.txt_color = ILI9341_DARKGREY;
  butt.border_color = ILI9341_MAGENTA;
  butt.roundRect = false;
  butt.createButton("Press!");

and in void loop():
  if (ts.touched())
  {
    TS_Point p = ts.getPoint();
    if (butt.checkPress(p))
      {
        Serial.print("Pressed");
      }
  }

3) buttonArrayTFT
Evolving to buttonArrayTFT, which spreads up to 8 buttons x and y centered on screen. Here again using same way to reference relevant properties (in buttonArrayTFT each button's size and position are not defined by user, but calculated to optimize size and position). Now variable are referenced to a ButtonTFT instance, for example &txt_size = _button0.txt_size as shown below.
Since txt_size is common for all button members in that array of buttons, it is referenced for all buttons later in code.
Also buttonArrayTFT works as expected, when defining its instance as:
char *a[] = {"All Windows", "Saloon", "Room", "Specific"};
buttonArrayTFT mainWindows;

and created:
  mainWindows.create_array(4, 1, a);

as a 4X1 button array with text for each button as in a.
The Problem (code crashes)
when trying to pass a value for any of referenced parameter ( taking txt_size as an example ):
mainWindows.txt_size = 3;          // <----- This
mainWindows.create_array(4, 1, a);

While when doing same thing when initiating a button (see up ), I use same way to update button's text size (which is refenced to MessageTFT ).
What may be the reason for that ??
Guy
.h file:
#ifndef TFT_GUI_h
#define TFT_GUI_h

#include <SPI.h>
#include <Adafruit_GFX.h>
#include <Adafruit_ILI9341.h>
#include <XPT2046_Touchscreen.h>

/* Screen calibration */
#define TS_MIN_X 350
#define TS_MIN_Y 350
#define TS_MAX_X 3800
#define TS_MAX_Y 3800
/* ~~~~~~~~~~~~~~~~~ */

/* For Wemos Mini and TFT screen 2.4" */
#define TFT_CS D0
#define TFT_DC D8
#define TFT_RST -1
#define TS_CS D3
/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */

const uint8_t _pos_corr_factor_x = 3;
const uint8_t _pos_corr_factor_y = 4;

extern XPT2046_Touchscreen ts; /* Touch screen */
extern Adafruit_ILI9341 tft;   /* Graphics */

class MessageTFT
{
public:
  int xc = 0;
  int yc = 0;
  uint8_t a = 0;
  uint8_t b = 0;
  uint8_t txt_size = 3;
  uint8_t border_thickness = 1;
  char txt_buf[20];
  bool roundRect = true;
  uint8_t screen_rotation = 0;
  uint16_t face_color = ILI9341_GREENYELLOW;
  uint16_t txt_color = ILI9341_BLACK;
  uint16_t border_color = ILI9341_RED;
  Adafruit_ILI9341 *TFT[1];

public:
  MessageTFT(Adafruit_ILI9341 &_tft = tft);
  void createMSG(char *txt);
  void clear_screen(uint8_t c = 0);

private:
  void _put_text(char *txt);
  void _drawFace();
  void _drawBorder();
};

class ButtonTFT
{
public:
  /* Following vars belong to MSG class*/
  MessageTFT MSGwindow;
  int &xc = MSGwindow.xc;
  int &yc = MSGwindow.yc;
  uint8_t &a = MSGwindow.a;
  uint8_t &b = MSGwindow.b;
  uint8_t &txt_size = MSGwindow.txt_size;
  uint8_t &screen_rotation = MSGwindow.screen_rotation;
  uint16_t &face_color = MSGwindow.face_color;
  uint16_t &txt_color = MSGwindow.txt_color;
  uint16_t &border_color = MSGwindow.border_color;
  bool &roundRect = MSGwindow.roundRect;
  char *txt_buf = MSGwindow.txt_buf;
  /* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */

  XPT2046_Touchscreen *TS[1];

public:
  ButtonTFT(XPT2046_Touchscreen &_ts = ts, Adafruit_ILI9341 &_tft = tft);
  void createButton(char *txt);
  bool wait4press();
  bool checkPress(TS_Point &p);

private:
  int _tft_x, _tft_y;

private:
  void _put_text();
  void _press_cb();
  /* fucntions below converts touchscreen values to TFT coordinates */
  void _conv_ts_tft(TS_Point &p);
  bool _check_press_geometry(TS_Point &p);
  int _TS2TFT_x(int px);
  int _TS2TFT_y(int py);
};

class buttonArrayTFT
{
public:
  buttonArrayTFT(XPT2046_Touchscreen &_ts = ts, Adafruit_ILI9341 &_tft = tft);
  void create_array(uint8_t R, uint8_t C, char *but_txt[]);
  uint8_t checkPress(TS_Point &p);

public:
  uint8_t &txt_size = _button0.txt_size;
  uint16_t &txt_color = _button0.txt_color;
  uint16_t &border_color = _button0.border_color;
  bool &roundRect = _button0.roundRect;
  int shift_array = 0;

private:
  ButtonTFT _button0;
  ButtonTFT _button1;
  ButtonTFT _button2;
  ButtonTFT _button3;
  ButtonTFT _button4;
  ButtonTFT _button5;
  ButtonTFT _button6;
  ButtonTFT _button7;
  ButtonTFT *_buttons[8] = {&_button0, &_button1, &_button2, &_button3,
                            &_button4, &_button5, &_button6, &_button7};

private:
  uint8_t _num_items = 0;
};

#endif

Edit1: How Constructors are defined in .cpp file
MessageTFT::MessageTFT(Adafruit_ILI9341 &_tft)
{
  TFT[0] = &_tft; // <--- stored in a pointer
}

and
ButtonTFT::ButtonTFT(XPT2046_Touchscreen &_ts, Adafruit_ILI9341 &_tft) : MSGwindow(_tft)
{
  MSGwindow.TFT[0] = &_tft;
  TS[0] = &_ts;
}

and
buttonArrayTFT::buttonArrayTFT(XPT2046_Touchscreen &_ts, Adafruit_ILI9341 &_tft)
    : _button0(_ts, _tft), _button1(_ts, _tft), _button2(_ts, _tft),
      _button3(_ts, _tft), _button4(_ts, _tft), _button5(_ts, _tft),
      _button6(_ts, _tft), _button7(_ts, _tft)
{
  _button0.MSGwindow.TFT[0] = &_tft;
  _button0.TS[0] = &_ts;
}

Sounds like you should actually be using inheritance and polymorphism for this task.

For example in my display library twButton inherits from Widget which itself is a form of Image that is then a virtual Cariad display device.

@Majenko can you please tell what is wrong in my code?

I'm not sure what value this is going to have for Arduino users, but here goes. Your question seem to be an over-complicated form of this the following:
My code:
struct MessageTFT {uint8_t txt_size = 3;};

struct ButtonTFT {
  MessageTFT MSGwindow;
  uint8_t &txt_size = MSGwindow.txt_size;
};

struct buttonArrayTFT {
  uint8_t &txt_size = _button0.txt_size;
  ButtonTFT _button0;
};

buttonArrayTFT bat;

void setup() {
  Serial.begin(9600);
  Serial.println(F("\n\n\nStart."));
}

void loop() {
  Serial.println(bat.txt_size++, DEC);
  delay(1000);
}

My question:
Why does this crash? ...or not print the correct value? or whatever.
I don't think I'm straw-manning (for lack of better term) your question.  But, the question is kind of a mess, so this a best-effort response to it.
If I've clarified the question to the point of being off-topic, so be it. If I do have the correct distillation, if nothing else what people can get out of this is that your questions here can usually be made simpler.
The declared order of members in a class is relevant to the order of initialization; there's more to it than just that. In any case, _button0 has not been initialized prior to your uint8_t &txt_size = _button0.txt_size; The mechanism underlying a member reference in a class is basically that of a pointer.  You are essentially copying an uninitialized pointer out of _button0 and into the txt_size member of buttonArrayTFT; that is the uint8_t &txt_size = MSGwindow.txt_size has not yet been executed.
You can fix this by doing nothing more than reordering the members like so:
struct buttonArrayTFT {
  ButtonTFT _button0;
  uint8_t &txt_size = _button0.txt_size;
};

Now uint8_t &txt_size = MSGwindow.txt_size; in ButtonTFT executes prior to uint8_t &txt_size = _button0.txt_size; in buttonArrayTFT.
This will fix the problem as I've presented. Should you do this? I'm not sure. But then that's not what was asked anyway. Still, you may be better served by getting rid reference members or converting them to inline functions that return a reference type. Or any number of other strategies.
At a minimum this is a problem your code has.

Re “You are essentially copying an uninitialized pointer”: My understanding is that, even though _button0 has not been initialized at this point, it has already been allocated. He is thus copying a pointer to uninitialized data, not an uninitialized pointer. Did I miss something?

The mechanism underlying  uint8_t &txt_size in ButtonTFT is roughly speaking a pointer. When the reference in ButtonTFT is bound to  the txt_size field in MSGwindow, it is initing two bytes of ButtonTFT with the address of the field in MSGwindow. Those two bytes (which are basically a pointer) have not be initialized prior to uint8_t &txt_size = _button0.txt_size; The uint8_t &txt_size = _button0.txt_size;  is binding the txt_size reference of buttonArrayTFT to its counterpart in the ButtonTFT member.This binding is effectively the copying of an (unitialized) pointer.

I'm not sure I do it justice in a comment, I mangled the above pretty bad trying to make it fit. If you want you can find me on libera.chat and I'll explain there.  Or spend some time with it and if it's still not making sense, I will try to update the answer later. The "pointers" I'm speaking of are only to illustrate what's happening underneath the references in terms of something that may already be understood.

Now it is clearer in my mind, thanks!

@timemage I don't understand why did you assume _button0 is not initiaed correctly. please see EDIT 1 in my question

In buttonArrayTFT you have uint8_t &txt_size = _button0.txt_size; and seven lines later you have: ButtonTFT _button0;  If that is in your code as you've shown it, irrespective of what else is in your code, then what I've said the answer applies.


text:
DS1820 bad reading from 4th sensor
I am very new to Arduino. I want to add about 50 sensors to Arduino R3. I get good readings from 3 sensors, but when I connect 4th one, I get 'No devices found'.
Here is a diagram:

and here is the code I use:
#include <OneWire.h>
#include <DallasTemperature.h>

// Data wire is plugged into port 2 on the Arduino
#define ONE_WIRE_BUS 2
#define TEMPERATURE_PRECISION 8
#define BAUD_RATE 9600

// Setup a oneWire instance to communicate with any OneWire devices (not just Maxim/Dallas temperature ICs)
OneWire oneWire(ONE_WIRE_BUS);

// Pass our oneWire reference to Dallas Temperature.
DallasTemperature sensors(&oneWire);

// arrays to hold device addresses
DeviceAddress devices[10];
int devicesFound = 0;

void setup(void)
{
  // start serial port
  Serial.begin(BAUD_RATE);

  sensors.begin();

  devicesFound = sensors.getDeviceCount();

  // locate devices on the bus
  Serial.print("Locating devices...");
  Serial.print("Found ");
  Serial.print(devicesFound, DEC);
  Serial.println(" devices.");

  // report parasite power requirements
  Serial.print("Parasite power is: ");
  if (sensors.isParasitePowerMode()) Serial.println("ON");
  else Serial.println("OFF");

  for (int i = 0; i < devicesFound; i++)
    if (!sensors.getAddress(devices[i], i))
      Serial.println("Unable to find address for Device" + i);

  // show the addresses we found on the bus
  for (int i = 0; i < devicesFound; i++)
  {
    Serial.print("Device " + (String)i + " Address: ");
    printAddress(devices[i]);
    Serial.println();
  }

  for (int i = 0; i < devicesFound; i++)
    sensors.setResolution(devices[i], TEMPERATURE_PRECISION);
}

// function to print a device address
void printAddress(DeviceAddress deviceAddress)
{
  for (uint8_t i = 0; i < 8; i++)
  {
    // zero pad the address if necessary
    if (deviceAddress[i] < 16) Serial.print("0");
    Serial.print(deviceAddress[i], HEX);
  }
}

// function to print the temperature for a device
void printTemperature(DeviceAddress deviceAddress)
{
  float tempC = sensors.getTempC(deviceAddress);
  if (tempC < 10)
    Serial.print("0");

  Serial.print(tempC);
}

// function to print a device's resolution
void printResolution(DeviceAddress deviceAddress)
{
  Serial.print("Resolution: ");
  Serial.print(sensors.getResolution(deviceAddress));
  Serial.println();
}

// main function to print information about a device
void printData(DeviceAddress deviceAddress)
{
  Serial.print("Device Address: ");
  printAddress(deviceAddress);
  Serial.print(" ");
  printTemperature(deviceAddress);
  Serial.println();
}

void loop(void)
{
  if (devicesFound == 0)
  {
     Serial.println("No devices found.");
     return;
  }

  int start=millis();
  sensors.requestTemperatures();

  // print the device information
  for (int i = 0; i < devicesFound; i++)
  {
    printTemperature(devices[i]);
    if (i != devicesFound - 1)
      Serial.print(" ");
  }

  Serial.println();

  Serial.print(millis() - start);
  Serial.println(" ms passed.");
}

The resistor I use is 4.7 kΩ. What should I change to get good readings? And is it a problem to get reading from about 50 sensors?
UPDATE
So after a few trials, I managed to get readings for 18 sensors. I managed to have a mixed topology. What I did is I added close to sensors I didn't get reading a resistor (mainly 4.7k, but also few 100, 1k). At the moment I get occasionally -127 reading from some sensors, but I think I will fix that with CRC check in the program. Thanks for your help! –

Thanks for the advice. I changed the diagram. Hope it makes more sense now. I will check with external power supply (now I am on usb power).

I've connected external power supply. Output 9V 2000mA. But I get the same result. I swapped sensors, so I exclude faulty one. I have connected power supply and USB at the same time because I need to see readings.

First check the sensors
To check that the fourth sensor isn't broken and causing everything to fail, swap them around and then see if it still fails when adding the fourth sensor (although this time it will be a different fourth sensor).
That is to say, if your current fourth sensor becomes the second (and the second becomes the fourth), does it now fail on two sensors..? Or does it still fail on four?
If two (and three) work then the (previously) fourth sensor isn't broken.
Current supply issues
In that case, it could be that your power supply from the Arduino lacks sufficient current and you need to power the sensors with a separate external power supply - separate to the Arduino external PSU (especially when you start to use 50 sensors)1. If you do, don't forget to connect the GND of the Arduino (i.e. the GND of the Arduino PSU) to the external PSU for the sensors. However, for four sensors the current required would only be 4 x 4 mA = 16 mA so it shouldn't be a problem.
If you are using the USB port as your only power supply, then that will most likely cause problems. Make sure that you have an external power supply for the Arduino other than relying only on the USB. Also, again, 16 mA draw for 4 sensors should not be a problem.
Addtional links
There is a similar link to Michel's link to SE.Electronics, on SE.RPi: What is the maximum number of DS18B20 probes that can attached to one input port?
On the Arduino forum, there is this thread, Problem with DS18B20 OneWire and long cables:

I've done more with 1-Wire using dedicated interfaces rather than
connecting the device to my Arduino, but I suspect the same principles
will apply....
a) You are better off NOT using parasitic mode. The modest extra
"trouble" is well worth it.
b) Use cat-5 cable
c) The "magic resistor" (mentioned above) often helps. The right
value? Use a little trial and error!
d) Be sure to put multiple 1-Wire chips in a daisy chain, not a
"star"... i.e. ONE run of two wires, with 1-wire chips across it, like
the rungs of a ladder.... do NOT have several wires leading out from
where your Arduino is, with 1-Wire chips on each of the several "rays"
of the "star".
I have tested strings of three or four 1-Wire temperature sensors on
cat-5 cables of up to... umm, from memory... 40m? They WILL work! But
as I said... this was with 1-Wire adapters.

But cable length does not seem to be your problem, if your Fritzing diagram is an accurate portrayal...
In this long thread, someone has issues with over seven sensors, which seems similar to your issue, see Multiple DS18B20 reading isues. In summary, cable length and quality is important, and avoid a star topology.

1 To clarify, you will need two PSU. One for the Arduino, and one for the 50 sensors.

I have connected USB, and PSU to Arduino. I still can get only reading from 3 sensors. And I am stuck at 4 sensors. Long way to 50...

Hmmm, if all of the sensors are working correctly, and as Michel implies, only 16 mA are being drawn with 4 sensors, then there must be something else that is causing the failure. Not sure. Sorry. But the link to SE.Electronics in Michel's answer looks interesting.

I've connected power to 3.3V on Arduino board and I got reading from 4th sensor. But now more. Tomorrow I am going to connect another psu for sensors only. As I read 5V is good for that, am I wrong? I should connect also GND from that PSU to GND on Arduino, right?

Yes, the grounds must be connected. What cable are you using from breadboard to Arduino and how long is it? Avoid a star topology. Are the sensors all on the same breadboard (this seems to be good idea to test with)  Here is another link (someone has issues with over 7 sensors), https://www.raspberrypi.org/forums/viewtopic.php?t=64477. Good luck. I would like to know what the solution is to your problem

Thanks for link. Interesting reading. I use generic jumper wires bought on ebay, on the same breadboard. DS1820 sensors are on about 1m long cable. So distance from Arduino to sensor is max 1.4m. After test I need to connect that snesors with 3core cable 0.5mm2.

I connected external PSU to sensors but with no change. Still max 3 sensors were visible. I also have this DS18B20 Adapter Module for Arduino (https://www.amazon.co.uk/Waterproof-DS18B20-Digital-Temperature-Adapter/dp/B06XJH5HLB/ref=sr_1_1?ie=UTF8&qid=1534371709&sr=8-1&keywords=ds18b20+adapter) and when i use this I can see new sensor. I have 3 sensors connected without that adapter and 2 sensors with those adapters. Do I need that adapter for every sensor? Is there any chance I can do this myself? They are quite expensive

That is interesting to know. So now you have 5 devices visible to the Arduino? As to whether you can make the adapter yourself, possibly probably, you'd have to look for a schematic. But whether it is worth doing so, you'll only know once you find the schematic. I may have a fish about for you tomorrow. Keep on plugging away, and keep us posted :-)

I found that link https://info.kmtronic.com/lan-ds18b20-temperature-monitor-resistors-scheme.html , from your experience, do you think that can solve my issues? There is also some link with more details but as I said, I am very newbie and cannot understand that technical language.

That appears to be compensation for very long wires, but you aren't using very long wires (currently) are you? So, that may not be the current problem.  Also, note Gerben's comment below - the additional power supply for the sensors may not be relevant/necessary. I see that you have accepted my answer, does that mean that you have solved the problem?

It's definitely not software issue. It's some wiring problem I have. I don't know where. I got from this question a lot of material I can learn from, and I am quite sure if I study it I can find what I am missing.  I ordered more ds1820 terminal adapters, hoping that can solve the issue. But connecting more sensors with that adapter allowed me to see them, so I think the problem is with the wiring. I don't know where, but I will find out :)

So after a few trials, I managed to get readings for 18 sensors. I managed to have a mixed topology. What I did is I added close to sensors I didn't get reading a resistor (mainly 4.7k, but also few 100, 1k). At the moment I get occasionally -127 reading from some sensors, but I think I will fix that with CRC check in the program. Thanks for your help!

@gerpaick that is great that you got it working and thanks for letting us know. You really should post your comment above as a separate answer as then it will be searchable (the comments aren't searchable). Also, the comments tend to get cleared up eventually, so it would be safer to write it all in an answer :-).

Max current
For 4 sensors I wouldn't expect problem, however, for 50 it will.
The VCC/GND pin has a maximum of 200 mA, see Arduino Pin Current Limitations.
(Update after remark of Gerben, thanks!):
However, these are for the ATMega, not the Arduino R3. See Arduino Voltage and Current. It's not an official document, but made by Gabriel Staples). It contains a lot of references. But the VCC can handle 0.5 or 1A depending on USB or battery power.
This means:
The DS1820 uses 4 mA (checking a random datasheet), so 50 * 4 = 200 mA, which is way within 500 mA/1000 mA).
Non one wire sensors (not your case)
Since you have one wire sensors the following is not applicable (just leave it here for others):
None one-wire sensors use their own GPIO pin mostly. Since the Arduino doesn't have 50 GPIO pins, especially not for analog input, you need to have external IC(s), ADCs (Analog Digital Converters) or analog multiplexers, see also connecting more than 6 analog input pins to Arduino.
One wire sensors (your case)
You might find how many ds18b20 temperature sensors can I connect to one bus interesting.

Thanks for the answer. As far as I read about oneWire, I can connect many sensors to one digital pin. For this reason I use DS1820.

@gerpaick yes I just see it (and learnt something), and found a link you might interesting, see end of answer.

That 200mA limit is for the ATMega328. This doesn’t apply to the UNOs power pins, as the current going though the Vcc and GND pins of the UNO never goes through the ATMega.

@Gerben thanks, I didn't know about this, I added a reference to a source that looks ok.


text:
Nokia32/RCMM IR decoding issues
I am trying to decode the IR signals from a remote. I'm using an Arduino Pro Micro, and a TSOP38238 IR receiver.
I found out that the remote uses the Nokia32(RCMM) protocol, and I have been able to partially decode it using cyborg5/IRLib (specifically this one: rcmm.ino). I tweaked the values of the example using the LIRC file corresponding to my remote, mainly the absolute error tolerance (Freebox_V5.lircd.conf).
Compared to other remotes I tried (with different protocols) the RCMM algorithm doesn't manage to decode the signal every time. Around 40% of the time when I press a button I got an "Unknown type received" output from the decoder.
The following is three outputs (for the same button) of the algorithm for a successful decoding and below two other outputs corresponding to two failures. Could anyone tell me what could be done to increase the success of the decoding algorithm?
Successful
Decoded RCMM: Value:2400A601 (32 bits)
Raw samples(36): Gap:63264
  Head: m410  s290
0:m160 s290 1:m160 s590      2:m210 s390    3:m210 s240
4:m210 s240 5:m210 s240      6:m210 s240    7:m210 s240
8:m210 s540 9:m210 s590      10:m210 s390   11:m210 s590
12:m160 s290    13:m160 s290         14:m160 s240   15:m210 s440

16:m160
Extent=9810
Mark  min:160    max:210
Space min:240    max:590

Failure 1
Unknown type received. Ignoring.
Decoded Unknown(0): Value:0 (0 bits)
Raw samples(36): Gap:3148
  Head: m410  s290
0:m160 s240 1:m210 s590      2:m210 s390    3:m210 s240
4:m210 s240 5:m210 s240      6:m160 s290    7:m160 s290
8:m160 s590 9:m210 s590      10:m160 s440   11:m210 s590
12:m160 s240    13:m210 s240         14:m210 s240   15:m210 s390

16:m210
Extent=9810
Mark  min:160    max:210
Space min:240    max:590

Failure 2
Unknown type received. Ignoring.
Decoded Unknown(0): Value:0 (0 bits)
Raw samples(32): Gap:27904
  Head: m410  s290
0:m160 s290 1:m160 s590      2:m160 s490    3:m160 s240
4:m210 s240 5:m160 s290      6:m160 s290    7:m160 s290
8:m160 s290 9:m160 s590      10:m160 s490   11:m160 s590
12:m160 s1190   13:m160 s440         14:m160
Extent=9460
Mark  min:160    max:210
Space min:240    max:1190

Are all three of those for the same button?

yes, my bad I edited the text to be more clear

I can see where the third one went wrong (not why, only where so far), but just correlating them all together at the moment in a spreadsheet. Manually decoding :)

the timings are left unchanged from the original file (https://github.com/cyborg5/IRLib/blob/master/examples/rcmm/rcmm.ino line 35). The tolerance line 60 is set to 100.

The problem is very much with the timing. I don't yet know whether that is the reception timing or the transmission timing, but there are some big errors in the numbers.

Hmmm... Manually decoding the values - the second one should have worked (better than the first one actually). The third is a complete failure of course.

Incidentally, from those figures, a tolerance of 75 should be good to use.

Sorry not to have been able to answer earlier. Here is the output of 10 clicks on one button with a tolerance of 75 : http://pastebin.com/jrZaDQty. What is quite wierd is the decoding value when there is a success (it's either 2400A601 or 24002601). I'm a bit lost ...

I'm unable to provide a complete answer yet but my research so far into a similar quest to use a similar remote can at least answer why you are getting two values for the same button on the remote. This is by design: the Nokia-32 RCMM protocol of this remote uses toggling codes that flip between one value and another on alternating presses of the same button.
My quest and the challenges of decoding this remote are documented in this thread: https://github.com/bengtmartensson/harctoolboxbundle/issues/97 where I discover that my IR remote uses Nokia 32 protocol but with mark and space timings slightly different from what most Arduino libraries are programmed for requiring a tweak to the signal in order to enable other libraries to decode it successfully.
Further information here: http://www.avsforum.com/forum/93-remote-control-area/1517341-theater-master-mx-500-remote-won-t-learn-bell-fibe-remote-any-help.html#post24345872 where we learn:

it is different from most IR signals, because it has 4 different off durations, denoting zero, one, two , or three, while traditionally IR protocols have used just two off durations signifying zero or one.

Could you please highlight the most important parts of the websites you've linked? If at one point those links break this answer will be unfortunately useless and we'd like to avoid that.

done... an upvote would be encouraging


text:
SD print in script works in setup but not loop
I am a bit of a novice with the Arduino, and have had to learn a lot for my High Altitude balloon launch. I am getting ready to launch this, but for some reason, my datalogger, printing to an SD card, will work in the setup function but not the loop.
If someone could explain what is wrong with my code, and any improvements that could be made to it, it would be very helpful. I am using SPI, SD, I2C, Wire, Sparkfun BMP, and MPU6050 library.
    #include <SPI.h>
    #include <SD.h>
    #include <math.h>
    #define thermoPin 0

    #include <SFE_BMP180.h>
    SFE_BMP180 pressure;

    #define ALTITUDE 87.8
    #include "I2Cdev.h"

    #include "MPU6050_6Axis_MotionApps20.h"
    #include <Wire.h>

    MPU6050 mpu;
    #define OUTPUT_READABLE_YAWPITCHROLL

    #define OUTPUT_READABLE_REALACCEL

    #define analogInPin 3  // Analog input pin that the potentiometer is attached to

    int sensorValue = 0;        // value read from the sensor

    // 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 aaReal;     // [x, y, z]            gravity-free accel sensor measurements
    VectorFloat gravity;    // [x, y, z]            gravity vector
    float ypr[3];           // [yaw, pitch, roll]   yaw/pitch/roll container and gravity vector

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

    #define photocellPin 2
    // the cell and 10K pulldown are connected to a9
    int photocellReading;     // the analog reading from the analog resistor divider

    #define chipSelect 4

    void setup() {
      pinMode(A5, OUTPUT);
      pinMode(A4, OUTPUT);
      // Open dataFile communications and wait for port to open:
      if (!SD.begin(chipSelect)) {
        // don't do anything more:
        return;
      }
        File dataFile = SD.open("datalog.txt", FILE_WRITE);
      if(dataFile) {

      // Initialize the sensor (it is important to get calibration values stored on the device).

      if (pressure.begin())
        dataFile.println("BMP180 init success");
      else
      {
        dataFile.println("BMP180 init fail\n\n");
        while(1); // Pause forever.
      }
      // join I2C bus (I2Cdev library doesn't do this automatically)
        #if I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE
            Wire.begin();
            TWBR = 24; // 400kHz I2C clock (200kHz if CPU is 8MHz)
        #elif I2CDEV_IMPLEMENTATION == I2CDEV_BUILTIN_FASTWIRE
            Fastwire::setup(400, true);
        #endif
        dataFile.println(F("Initializing I2C devices..."));
        mpu.initialize();

        dataFile.println(F("Testing device connections..."));
        dataFile.println(mpu.testConnection() ? F("MPU6050 connection successful") : F("MPU6050 connection failed"));
        // load and configure the DMP
        dataFile.println(F("Initializing DMP..."));
        devStatus = mpu.dmpInitialize();

        mpu.setXGyroOffset(220);
        mpu.setYGyroOffset(76);
        mpu.setZGyroOffset(-85);
        mpu.setZAccelOffset(1788); // 1688 factory default for my test chip
    mpu.setDMPEnabled(true);
    mpuIntStatus = mpu.getIntStatus();
    dmpReady = true;
    packetSize = mpu.dmpGetFIFOPacketSize();
    dataFile.close();
      }

    }

    void loop() {
      // make a string for assembling the data to log:
      int valF, valC;
      valF = analogRead(thermoPin);
      valC = analogRead(thermoPin);
      File dataFile = SD.open("datalog.txt", FILE_WRITE);

      // if the file is available, write to it:
      if (dataFile) {

        dataFile.print(F("Millis since Launch"));
        dataFile.println(millis());
        dataFile.print(F(", Analog Val."));
        dataFile.print(valF);

        photocellReading = analogRead(photocellPin);

        dataFile.print(F("  Analog reading = "));
        dataFile.println(photocellReading);     // the raw analog reading
                                          // We'll have a few threshholds, qualitatively determined
      dataFile.println();
      char status;
      double T,P,p0,a;

        dataFile.print(F("provided altitude: "));
      dataFile.print(ALTITUDE,0);
      dataFile.println(F(" meters, "));

      status = pressure.startTemperature();
      if (status != 0)
      {
        // Wait for the measurement to complete:
        delay(status);

        status = pressure.getTemperature(T);
        if (status != 0)
        {
          // Print out the measurement:
          dataFile.print(F("temperature: "));
          dataFile.print(T,2);
          dataFile.println(" deg F");

          status = pressure.startPressure(3);
          if (status != 0)
          {
            // Wait for the measurement to complete:
            delay(status);

            status = pressure.getPressure(P,T);
            if (status != 0)
            {
              // Print out the measurement:
              dataFile.print(F("absolute pressure: "));
              dataFile.print(P,2);
              dataFile.print(F(" mb, "));

              p0 = pressure.sealevel(P,ALTITUDE); // we're at 87.08 meters (Home)
              dataFile.print(F("relative (sea-level) pressure: "));
              dataFile.print(p0,2);
              dataFile.print(F(" mb, "));
              dataFile.print(p0*0.0295333727,2);
              dataFile.println(" inHg");

              a = pressure.altitude(P,p0);
              dataFile.print(F("computed altitude: "));
              dataFile.print(a,0);
              dataFile.print(F(" meters, "));
            }
            else dataFile.println("error retrieving pressure measurement\n");
          }
          else dataFile.println("error starting pressure measurement\n");
        }
        else dataFile.println("error retrieving temperature measurement\n");
      }
      else dataFile.println("error starting temperature measurement\n");
      // if programming failed, don't try to do anything
        if (!dmpReady) return;

        // wait for MPU interrupt or extra packet(s) available
        while (!mpuInterrupt && fifoCount < packetSize) {
        }

        // 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();
            dataFile.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
            while (fifoCount < packetSize) fifoCount = mpu.getFIFOCount();

            // 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;

            #ifdef OUTPUT_READABLE_YAWPITCHROLL
                // display Euler angles in degrees
                mpu.dmpGetQuaternion(&q, fifoBuffer);
                mpu.dmpGetGravity(&gravity, &q);
                mpu.dmpGetYawPitchRoll(ypr, &q, &gravity);
                dataFile.print(F("ypr\t"));
                dataFile.print(ypr[0] * 180/M_PI);
                dataFile.print(F("\t"));
                dataFile.print(ypr[1] * 180/M_PI);
                dataFile.print(F("\t"));
                dataFile.println(ypr[2] * 180/M_PI);
            #endif

            #ifdef OUTPUT_READABLE_REALACCEL
                // display real acceleration, adjusted to remove gravity
                mpu.dmpGetQuaternion(&q, fifoBuffer);
                mpu.dmpGetAccel(&aa, fifoBuffer);
                mpu.dmpGetGravity(&gravity, &q);
                mpu.dmpGetLinearAccel(&aaReal, &aa, &gravity);
                dataFile.print(F("areal\t"));
                dataFile.print(aaReal.x);
                dataFile.print(F("\t"));
                dataFile.print(aaReal.y);
                dataFile.print(F("\t"));
                dataFile.println(aaReal.z);
            #endif
        }
        // read the analog in value:
      sensorValue = analogRead(analogInPin);
      // print the results to the dataFile monitor:
      dataFile.print(F("  analog Val of OZONE= " ));
      dataFile.println(sensorValue);
      dataFile.close();
      }
      analogWrite(A4, 168);
      delay(3000);
      analogWrite(A4, 0);
      delay(750);
      analogWrite(A5, 0);
      delay(250);
      analogWrite(A5, 168);
      delay(3000);
        analogWrite(A4, 168);
      delay(2000);
      analogWrite(A4, 0);
      delay(1000);
    }

Possible problems (correct me if I'm wrong):

I noticed that the MPU6050 stops transmitting if delays are put into it

EDIT:
I have now tried the script but commented out the accelerometer (MPU6050) portion,  and it successfully writes to the SD card. could someone explain why the accelerometer portion messes up the rest of the code?

I haven't followed all the details of your code, nor looked into all of the libraries being used, so you may need to ignore some of the following comments.

You write “my datalogger, printing to an sd card, will work in the setup function but not the loop”.  However, you don't say what you mean by “work”, nor how you tell if it works.
It looks like your code in loop() uses the same filename as in setup().  If so, there's no reason to write a file insetup() because it will just be overwritten later.  (If you have a reason, use a different file name.)
Sequences like status = pressure.startTemperature(); if (status != 0) {... delay(status); ... } look suspect.  The parameter to Arduino's delay() function is a number of milliseconds, in an unsigned long; is your startTemperature() supposed to return a status that's usable as the number of milliseconds to delay?
Your status is declared via char status; and  char is a signed type.  If status is negative, the call delay(status); will first convert status to a signed long by sign-extension.  Then it will convert the signed long to an unsigned long with the same bit pattern.  This will ensure a delay of at least 7 weeks, which presumably is longer than you mean to wait.
[Ref: See the “Conversions from Signed Integral Types” table in microsoft.com/en-us/library's Conversions from Signed Integral Types webpage.]
To avoid those long and tedious sequences of dataFile.print(...); statements, you can #include Streaming.h, which is a contributed library that adds some “syntactic sugar” to Arduino C.  At compile time it converts C++-like << stream operators to .print() calls, without increasing code size.  If you don't have Streaming.h installed, install it via Streaming5.zip from arduiniana.org.  Then, for example, in place of
dataFile.print(F("areal\t"));
  dataFile.print(aaReal.x);
  dataFile.print(F("\t"));
  dataFile.print(aaReal.y);
  dataFile.print(F("\t"));
  dataFile.println(aaReal.z);

write
  dataFile << F("areal\t") << aaReal.x << '\t' << aaReal.y << '\t' << aaReal.z << endl;

Whether using Streaming.h or not, writing F("\t") instead of '\t' uses half a dozen bytes of program memory where one will do, and uses the same amount or more of RAM.  That is, while F() saves on RAM usage for long strings, it's of negative value for single characters and short strings.


text:
How can I use a BlueSMIRF Silver (RN-42) as a HID Keyboard (on IOS)?
I've got a BlueSMIRF Silver (RN-42) Bluetooth module.
I am trying to create a basic keyboard I can play with on an iPad Air.
At the moment barely manage to get the module to pair with OSX
but only through using Bluetooth Setup Assistant and using "Passcode Options...use a specific code".
With this option, the module pairs, but the connection resets about every 5 seconds.
On iPad it tries to use a generate number really fast and fails straight away, being unable to connect.
I noticed there is a BlueSMIRF HID version, but from what I can tell, the hardware is the same,
just the firmware is different. I've gone through the whole Bluetooth Data Module Command Reference & Advanced Information User’s Guide(pdf link) manual and from what I can gather,
even though I have Silver firmware burned onto my module, I should be able to set and use the HID profile
(from the default SPP):

Roving Networks modules shipped with firmware version 6.11 and higher
  support the HID profile. You do not need special firmware if your
  module is running firmware 6.11 or higher.

and my module reports version as:
Ver 6.15 04/26/2013
(c) Roving Networks

I've also gone through the Bluetooth HID Profile(pdf link) guide from Roving Networks, but the same information is present in Chapter 5 of the advanced user's guide mentioned above.
I've setup the following settings (with commands used):

HID Profile (S~,6)
Device discovery and pairing is set to automatic, without using GPIO6(SM,6)
HID Flag is set to Keyboard (SH,0000)
Authentication is set to open (SA,0)

I've also tried the inquiry scan(SI,0800)  and page scan(SJ,0800)  windows to maximum
in the hope it would increase the odds of successful pairing and made sure I rebooted the module and checked the settings again.
I have used the same module with the SPP profile just fine, but I'm still fairly new to Bluetooth
and this is the first time I try to use the HID profile.
How can I use the BlueSMIRF Silver as a basic Bluetooth Keyboard for an iPad Air ?

I should be able to set and use the HID profile (from the default SPP)

Unfortunately, your assumption is incorrect. From the same documentation you quoted, the previous sentence says:

To use Roving Networks’ Bluetooth HID profile, you must use a special
  build of firmware, version 6.03 or later.

Poorly phrased, this does mean that you need to have two things:

A special HID firmware
Version 6.03 or later

Your BlueSmirf Silver only complies with the second condition; it does not have the special HID firmware (also note that the Rovnix command reference does not address a specific variant of the BlueSmirf, but speaks generally about all of the variants).
The SPP protocol (Serial Port Profile) is used for emulating a serial cable, and functions as a substitute for the physical RS-232 connection, but cannot stack pure HID profile on top of it. In order for you do talk HID, you will need the HID firmware.
As a side note, the HID version comes with SPP and you can switch between the two modes interchangeably, I have been using the HID version for a while now and it works fine (including the pairing with iOS).
Another misfortune is that it does not appear that Roving Networks officially support any re-flashing of the BlueSmirf firmware, so unless you are willing to reverse the hardware, this is off the table as well.

Thanks Omer, very helpful(+1). I thought that I can get away just because the firmware is version 6.15, which is greater than 6.11 although I don't have the HID firmware. I found a blog post explaining how to capture and rewrite firmware, but I'm not experienced enough to risk it. I'm returning the Silver and getting an HID replacement (same price, same hardware, different firmware)

Happy to hear. Can you please post the link? might help others.

No worries, here what I found on Byron's Blog on flashing a new firmware and I got there from this post. I haven't tried this myself though, but it looks good

In the comments on SparkFun's product page for RN-42, gskelly indicates there is a flag in the v6.15 firmware that allows you to switch back and forth easily:

Actually, since this includes the v6.15 firmware, you don’t need to
  re-flash the module to switch between HID and SPP. It can now be done
  using AT commands as follows:
S~,6    // Enable HID on reboot
R,1     // Reboot
S~,0    // Enable SPP on reboot
R,1     // Reboot

I will try this again when I get my hands on another module. I do clearly remember trying the HID flag (S~,6) as I mentioned in question and it didn't work in my case.

I would be interested to know if it works. I found your question and this answer while I was looking for someone else, so I thought I'd try to connect the dots.

I know I am late to the party but for others searching this topic:
"S~,6" command does work for switching to HID profile but it requires the reboot command "R,1" otherwise it won't take.
I send these commands from the microcontroller to RN42 whilst the RN42 is in command mode, just to be clear.


text:
Conflict between UART serial transmission and timer interrupt Arduino MEGA
I have a small problem with collision between handling serial transmission and executing things in timer interrupt.
I'm doing program which communicates with PC. It transmits and receives as well and received values are computed in timer interrupt and then transmitted to PC. I have also a LCD for simple debugging state of variables.
My question is generally about influancing uart transmision and timer interrupts each other, but I paste part of my code to  better discribing my issue:
float Kr;
float Tp=0.05;
float Ti;
float Td;
float yref;

void setup() {
lcd.begin(16,2);
 Serial.begin(115200);
lcd.clear();

 analogReference(DEFAULT);

   Timer1.initialize(50000);
   Timer1.attachInterrupt(Myfunction);

 }

  void loop() {

  while(1)
  {

if(Serial.available() > 0)
{
 received = (char)Serial.read();
  if(received== 'a')
  {
    Serial.print(y);  // Here uC transmits to PC
    Serial.print('b');
  }
  if(received == 'w')
  {
    yref_str = Serial.readStringUntil(';');  //uC receives datas from PC
   // yref = yref_str.toFloat();
  }
  if(received == 'x')
  {
    Kr_str = Serial.readStringUntil(';');  //uC receives datas from PC
    //Kr = Kr_str.toFloat();
  }
  if(received == 'y')
  {
    Ti_str = Serial.readStringUntil(';');  //uC receives datas from PC
    //Ti = Ti_str.toFloat();
  }
  if(received == 'z')
  {
    Td_str = Serial.readStringUntil(';');  //uC receives datas from PC
    //Td = Td_str.toFloat();
  }

}

 //Conversion string to float
 yref = yref_str.toFloat();
 Kr = Kr_str.toFloat();
 Ti = Ti_str.toFloat();
 Td = Td_str.toFloat();

//Simple displaying some of  variables values
  lcd.home();
  lcd.print("Process ");
 lcd.setCursor(0,1);
 lcd.print("yref=");
 lcd.print(yref);
 lcd.setCursor(9,1);
 lcd.print(" ");
 lcd.setCursor(10,1);
 lcd.print("Kr=");
 lcd.print("    ");
 lcd.setCursor(12,1);
 lcd.print(Kr);
 }
 }

  void Myfunction()
  {
     //here the datas are computed
  }

Transmition bases on kind of frame. When it gets from PC proper char sign it sends datas or receives datas. The frame has ';' sign at the end.
The main thing is that when I set values of variables: float Kr, Ti, Td at the beginning of program, in declaration section (not by serial port) it works perfectly. problem appears when I don't set value at the beginning (just declare likes above) and try to set it via serial port the situation is following:
I can see correct values of those variables on LCD (exactly what I send from PC to arduino) but they don't get to Myfunction (function which is executed within timer interrupt) so actually they are 0 continually.
I don't give whole code for "Myfunction" because this function works properly, for sure. I don't change anything since good working program version. Change is only adding serial transmission.
I tried to declare variables as volatile but it didn't solve the problem.
Anyone did have any experience with such problems??
Update:
I paste code of whole program, as you asked me for:
It looks like below
#include<LiquidCrystal.h>
#include<TimerOne.h>

LiquidCrystal lcd(52, 50, 48, 46, 44, 42, 40);

#define Max 127
#define Min -128

/*float Kr;
float Tp=0.05;
float Ti;
float Td; */
/*float Kr = 0.19;
float Tp=0.05;
float Ti = 0.91;
float Td = 0.19;*/
volatile float Kr;
volatile float Tp=0.05;
volatile float Ti;
volatile float Td;
float yref= -50;
float y;
float ep_p, ep_i, ep_d, u_b;
float U_pr, U_int, U_intp, U_ip;
float U_d, Ui_d, Ui_d_pop, U_d_pop;
int Upwm;
float u_b_OGR;
float b=1;
float c=0;
float Tdf;

float ep_a;
float Tt;
float U_a;
int out=11;
int inp=A7;
int x;
boolean state;

 String Kr_str, Ti_str, Td_str, yref_str;
 char received;

void setup() {
lcd.begin(16,2);
Serial.begin(115200);
lcd.clear();
pinMode(out,OUTPUT);
pinMode(inp,INPUT);

analogReference(DEFAULT);
Timer1.initialize(50000);
Timer1.attachInterrupt(Myfunction);

U_int=0;
U_intp=0;
Ui_d_pop=0;
U_d_pop=0;
y=0;
U_a=0;

 state=0;

}

void loop() {

if(Serial.available() > 0)
{
  received = (char)Serial.read();
  if(received == 'a')
  {
    Serial.print(y);
    Serial.print('b');
  }
  if(received == 'w')
  {
    yref_str = Serial.readStringUntil(';');
   // yref = yref_str.toFloat();
  }
  if(received == 'x')
  {
    Kr_str = Serial.readStringUntil(';');
    //Kr = Kr_str.toFloat();
  }
  if(received == 'y')
  {
    Ti_str = Serial.readStringUntil(';');
    //Ti = Ti_str.toFloat();
  }
  if(received == 'z')
  {
    Td_str = Serial.readStringUntil(';');
    //Td = Td_str.toFloat();
  }

}
yref = yref_str.toFloat();
Kr = Kr_str.toFloat();
Ti = Ti_str.toFloat();
Td = Td_str.toFloat();

lcd.home();
lcd.print("Process");
lcd.setCursor(0,1);
lcd.print("yref=");
lcd.print(yref);
lcd.setCursor(9,1);
lcd.print(" ");
lcd.setCursor(10,1);
lcd.print("y=");
lcd.print("    ");
lcd.setCursor(12,1);
lcd.print(y);

}

void Myfunction()
{

Tt=0.3*Ti;
Tdf=Td/10;

y=analogRead(inp);
y=y/4;
y=y-128;

ep_p=b*yref-y;
ep_i=yref-y;
ep_d=c*yref-y;
U_pr=Kr*ep_p;
U_int=U_ip*Tp+U_intp;
U_ip=ep_i*(Kr/Ti)+U_a;
U_intp=U_int;
Ui_d=ep_d*Kr;
U_d=(Td/Tdf)*Ui_d-(Td/Tdf)*Ui_d_pop-U_d_pop*exp(-Td/Tdf);
Ui_d_pop=Ui_d;
U_d_pop=U_d;
u_b=U_pr+U_int+U_d;

if (u_b > Max)
 {
 u_b_OGR=Max;
}
else if (u_b < Min)
{
  u_b_OGR=Min;
}
else if (u_b>=Min && u_b<=Max)
{
u_b_OGR=u_b;
}

ep_a=u_b-u_b_OGR;
U_a=ep_a*(1/Tt);

Upwm=(int)u_b_OGR+128;
analogWrite(out,Upwm);

}

Could you please add to the question a Minimal, Complete, and Verifiable example showing your problem? As it stands, your question is unanswerable without a crystal ball.

Interrupts are for short pieces of code that do not block or cause interrupts.  You can't call Serial functions and you shouldn't be performing computations.  What you should do it toggle a volatile global bool and then exit the interrupt.  Next time loop() is executed check to see if the bool has been set and if so doStuff()

I've updated my question and gave whole code of my program. Please look at it and advise what can be wrong

I have added a 'Update' section to my answer.

You wrote: “analogRead(inp)”. This alone is a no-no in an ISR: it takes about 110 µs, enough to loose incoming serial data. And also: “exp(-Td/Tdf)”. Since Tdf=Td/10, this is exp(−10) ≈ 4.5399930e-5. You should declare it as a constant, rather than repeating the (very expensive) calculation each time. Seriously: forget about interrupts and manage your timings with micros() instead.

@Edgar Bonet, Ok, because I have strict recruiments for this project to read ADC once per every 50 ms, what do you advise me, how and where can I read ADC without blocking datas from UART??

50 ms ± how much? 50 ms is forever as far as the Arduino is concerned. If your loop is not overly inefficient, something like if (micros() - lastReading >= PERIOD) { lastReading += PERIOD; doSomethingWith(analogRead(pin)); } in loop() should be OK. If you really need to minimize jitter, forget analogRead(), read the ATmega2560 datasheet, and trigger the ADC from Timer 1.

When you say that something is working for sure, then there is a big chance that the problem is in that part. If the problem was somewhere else, then perhaps you could find the problem yourself.
Interrupts are executed one after another (with a few exceptions). Things run smooth when all interrupt routines are as short and as fast as possible. You have no control over the interrupt routine of the serial communication in the Serial library, but at least your own interrupt function should be as short as possible.
Please show us a sketch that has the problem. You have removed the most important part.
If for example your interrupt function calls a Serial function, then it can go wrong because the Serial library uses interrupts itself. If your interrupt function takes longer than the interrupts from receiving data at 115200 baud, then characters could be missed. The keyword 'volatile' should be used in a proper way. The Arduino Mega has a 8-bit microcontroller, that means that when handling an 16-bit or 32-bit variable an interrupt could occur while that variable is read or writting only halfway. And so on, and so on.
Update
You have shown the complete sketch, and the interrupt function 'myFunction'  takes a very long time to do all those calculations.
The 'Kr', 'Ti' and 'Td' are written in the loop, and used in 'Myfunction' which is an interrupt routine. They are float variables that are 4 bytes long. That means that 'Myfunction' could be executed when one of those variables are written only halfway. It is better to disable interrupts when writing those variables. To keep disabling the interrupts short, don't disable interrupts when calling .toFloat(). Use temperary variables.
float yref_temporary = yref_str.toFloat();
float Kr_temporary = Kr_str.toFloat();
float Ti_temporary = Ti_str.toFloat();
float Td_temporary = Td_str.toFloat();

noInterrupts();
yref = yref_temporary;
Kr = Kr_temporary;
Ti = Ti_temporary;
Td = Td_temporary;
interrupts();

I think you have to make 'yref' volatile as well.
The Serial input is 115200 baud, that can be an interrupt every 87µs.
The Timer1 Myfunction runs every 50ms.
The Myfunction takes more than 600µs.
I did not measure the timing of 'Myfunction'. I calculated it for a rough number. 5 float divisions = 5*70µs. 11 float multiply = 11*7µs. 10 float substractions or additions = 10*7µs. Plus analogRead of 112µs. Plus a few more, that adds up to at least 600µs. It could be about 1ms.
There might be more conflicts.
The baudrate is high, and the Serial.readStringUntil is slow because it uses a String object.
There is no error checking for the received values.
The four .toFloat are always called, even when there was no serial data received.
Printing to the lcd display is also done every time the loop runs. There is no need to update the slow LCD display hundreds of times per second. That could be slowed down with millis.
Conclusion: Your 'Myfunction' is a real interrupt routine. When that is busy, the other interrupts have to wait. Since it takes more than 600µs, the Serial interrupts could be missed.
Perhaps a software timer with millis is accurate enough for the calculations. To be able to use millis, the Serial.readStringUntil can no longer be used.

Unless the function called from the ISR is itself producing serial output, the problem is most likely going to be the lack of a volatile declaration and atomic access.  The simplest solution may be to disable the interrupt while updating the variables; another option is to write to a holding set, and set a flag requesting the ISR to copy them to the operational one.

@Jot, thank you for this answer, you suggest that timer interrupt routine takes too much time to the serial receiving interrupt can be called at all. But the situation is strange a bit because datas are being received and displayed on LCD so they really arrive to uC but they don't get to timer interrupt routine.

@M_K, I thought about that. But in the sketch that you show, only yref and y are printed, not the others. It is hard to tell what is going on in the interrupt routine and I don't know why you conclude that the variables don't reach the interrupt routine. The same global volatile variables are used, so they definitely are available in the interrupt routine, it must be something else. It would be better to declare locally used variables only locally to make the code better readable. The analogWrite to pin 11 uses Timer2, that should be okay.


text:
MIDI output circuit behaving incorrectly when not connecting with USB
I recreated this circuit to send MIDI notes to my MIDI-USB adapter to my computer.

It works fine when the Arduino is powered via USB. When I power the Arduino Nano with 9v on Vin however, the output is gibberish. It just spams the input monitor on my computer with random midi commands. For testing I used this code:
    #include <MIDI.h>

    MIDI_CREATE_DEFAULT_INSTANCE();

    static const unsigned ledPin = 13;
    bool on = false;
    void setup()
    {
        pinMode(ledPin, OUTPUT);
        MIDI.begin(MIDI_CHANNEL_OFF);
    }

    void loop()
    {
        digitalWrite(ledPin, on);
        on = !on;
        MIDI.sendControlChange(12, 127, 1);
        delay(1000);
    }

The Arduino itself seems to be working fine when powered with 9v (note that I tested with both a wall power supply as well as a 9v battery) as the TX-led still  flashes briefly and the built-in led also toggles nicely.
At first I blamed my power supply and/or my power supply, but both work fine on my MIDI-keyboard so I don't think they are to blame.
Worth mentioning: When the Arduino was powered by Vin, I also as a test plugged in the USB-cable in the Arduino, But only touched the connector on the USB-port on my computer. I then received the correct notes.
Because of this I think it is an issue with the grounding. What am I doing wrong?
EDIT: Thanks for the response guys. I think I diagnosed my problem incorrectly. I'm using a cheap Chinese MIDI-adapter which I pried open, and it lacks an optocoupler. I'm getting a decent MIDI adapter now. Thanks!

What USB MIDI adapter are you using? That one? https://i.sstatic.net/yA3dT.jpg

Do you really need to use port 1?

@CL. Yup, that was the one I was using. After some after some googling on it I found out that it could lack an optocoupler, and after opening it confirmed that mine didn't have one as well. I ordered a good adapter now! Thanks!

If you are connecting multiple devices then they have to share a common ground.
I only know about British mains sockets, they all have an earth pin connecting to a common ground, so usually you are OK.
Plug in transformers 'wall warts' sometimes don't connect to ground, the give away is the plastic pin.  In this case you need to provides a separate earth and connect it to the rest of the equipment.
PCs normally have a good earth and this is passed by the USB to connected devices.  So "the Arduino always works when it is connected to the PC" is usually a good indicator of an earthing issue.
I think your keyboard uses a wall wart and therefore when you remove the USB they both float.  Touching the USB lead to the Arduinos USB socket grounds it all again.
So it looks like you diagnosed the fault correctly :)


text:
Unable to load programs onto Arduino Pro Mini Using FTDI?
I'm pretty new to this, so forgive me if I get some things wrong. I am working with a piece of equipment that uses an Arduino Pro Mini. When I first got to it, I realized that some of the code was incorrect and wanted to fix it. Unfortunately, my Pro Mini is soldered into the board with the labels and pins down, so the only accessible pins are the top six, and even those aren't labeled. The reset button is also upside down. I tried using a FT232H FTDI
hooked up (using a pinout because of the aforementioned no labels)
D0-> TX
D1-> RX
which I was told should work, but when I plug in the micro-usb into the FT232H and try to upload the sketch, it gives me the error
avrdude: stk500_getsync(): not in sync: resp=0x00

and also blinks green but has a constant red light (from what I can see from looking under the board). Because this Pro Mini controls my equipment, I'm wary of doing anything too intense. Any ideas of how to fix this without breaking my apparatus?
Update!
I changed the pinning, and the IDE told me that it uploaded, but it still won't run the program! Help!

An FTDI breakout should use more than two pins, check the Pro Mini datasheet for the correct pins to connect through a breakout. You might also benefit from looking up an Arduino FTDI tutorial on YouTube. Just make sure to check the simple things first :)

Please edit your question to include a list of exactly which pins you can connect to.  “The top six” is too vague.   Eg, are the ISP pins accessible? Also please edit your question to  make a list of unused pins

If you want to know which pins are which, Google search for "arduino pro mini pinout diagram". You will find lots of them.

"IDE told me that it uploaded, but it still won't run the program". It's likely the problem is with your code. Try uploading a minimal known-working sketch to see if it will run. The obvious choice would be File > Examples > 01.Basics > Blink but first you should make sure that the pin being blinked (13 by default) won't have any harmful effect on your equipment.

On some pro-minis, such as the one I got off Amazon, the FTDI header pins are mirrored. You may not be able to go by a downloaded pinout diagram without verifying the pins.

Same problem faced. Try out many times with proper connection but no success. After that, I found one unique and simple solution. I use Arduino Uno instead of FTDI. Follow below step, your problem will definitely solve.

First, remove Arduino Uno's IC means ATMEGA 328P-PU.
Now, do connection as shown in below figure.

Connections are like:
Arduino Uno(Without Chip)     Arduino Mini Pro

          RX                         RX
          TX                         TX
          +5V                        Vcc
          GND                        GND
         RESET                  RST(RESET PIN)

Now, plug your Arduino Uno to your computer and open your Arduino IDE.
Now, an open sketch which one you want to upload. Now, go to Tools and select board in which you want to upload code. Below, show in the figure.

Now, upload your program. It will definitely work.

I hope it will help you.

Could you possibly provide a reference link to some relevant documentation that explains this type of configuration please?

This should not be necessary.  Uploading via an FTDI does work.

@stevieb There is no proper documentation about this but I read out this thing in the forum. Prefer this link https://stackoverflow.com/questions/18362942/how-to-use-an-arduino-uno-as-an-ftdi-programmer

@ChrisStratton But FTDI not worked for me. That's why I found out this solution.

Then you did not use the FTDI correctly.  It will work for someone who does.  Postings here are not only for the benefit of the asker, but for that of future readers too.  Using an Arduino as a serial adapter is a possibility, but the traditional method of using an FTDI is a fine solution too, if that is what is on hand.

@ChrisStratton Hii buddy you  are right but if some alternatives are available and that  worked too so it is good to share and research is the field where you have to have different ways to find solution.