text:
How to determine the source of constants in libraries?
Preamble:
I am trying to figure out how to program and use the timers in the Feather M0 using the Arduino IDE. I have seen a number of examples published, but I'm not one to just blindly copy some code and expect it to work. The issue that I'm having (and it seems to be ubiquitous in Arduino) is that there does not seem to be a concept of dependencies. In order to reference constants, they have to be defined somewhere.
Question:
How can I find the source of the definition of the constants that people keep referring to in their code? For example, in this code a Arduino Zero, M0 timer example, reference is made to TC_CTRLA_PRESCALER_DIV1 among other constants. Where is this constant defined?
Efforts:
I've searched generally and specifically for these constants. But, as you would imagine in C, it's difficult to find the actual source versus a simple reference to the constant.
I've also tried a search in the installed Arduino IDE with SAMD and Adafruit SAMD libraries installed. For example
~/Arduino$ grep -r --include=*.h --include=*.cpp "TC.*_PRESCALER_DIV"

Did not yield anything. I apologize if this is a naive question, but I haven't been able to find a simple, obvious answer. Actually, I haven't been able to find any answer.

in Eclipse I use 'go to definition' with F3 key

The name TC_CTRLA_PRESCALER_DIV1 indicates this is a macro. A trick for quickly finding the exact location of a macro definition is:

File > Preferences > Compiler Warnings > All > OK
In your sketch, add a #define directive for the macro name that definitely changes the definition:

#define TC_CTRLA_PRESCALER_DIV1 foobar

Sketch > Verify/Compile
After the compilation finishes, examine the compiler output in the black console window at the bottom of the Arduino IDE window (you will need to scroll up to see it all) for a "redefined" warning. The warning will state the path of the original definition:

    C:\Users\per\AppData\Local\Temp\arduino_modified_sketch_804921\sketch_aug05a.ino:1:0: warning: "TC_CTRLA_PRESCALER_DIV1" redefined [enabled by default]

   #define TC_CTRLA_PRESCALER_DIV1 foobar

   ^

  In file included from C:\Users\per\AppData\Local\Arduino15\packages\arduino\tools\CMSIS-Atmel\1.1.0/CMSIS/Device/ATMEL/samd21/include/samd21g18a.h:268:0,

                   from C:\Users\per\AppData\Local\Arduino15\packages\arduino\tools\CMSIS-Atmel\1.1.0/CMSIS/Device/ATMEL/samd21/include/samd21.h:69,

                   from C:\Users\per\AppData\Local\Arduino15\packages\arduino\tools\CMSIS-Atmel\1.1.0/CMSIS/Device/ATMEL/samd.h:105,

                   from C:\Users\per\AppData\Local\Arduino15\packages\arduino\tools\CMSIS-Atmel\1.1.0/CMSIS/Device/ATMEL/sam.h:470,

                   from C:\Users\per\AppData\Local\Arduino15\packages\arduino\hardware\samd\1.6.19\cores\arduino/Arduino.h:48,

                   from C:\Users\per\AppData\Local\Temp\arduino_build_309126\sketch\sketch_aug05a.ino.cpp:1:

  C:\Users\per\AppData\Local\Arduino15\packages\arduino\tools\CMSIS-Atmel\1.1.0/CMSIS/Device/ATMEL/samd21/include/component/tc.h:113:0: note: this is the location of the previous definition

   #define TC_CTRLA_PRESCALER_DIV1     (TC_CTRLA_PRESCALER_DIV1_Val   << TC_CTRLA_PRESCALER_Pos)

   ^

in Eclipse F3 shortcut key opens the definition source code on the value. end if it is a redefinition of some lower level macro, I drill down with next F3. And the value of a macro is displayed in tooltip bubble too. And same for functions.

First of all, the definitions of these constants won't tell you very much. They just represent the registers and bits used in the datasheet of the microcontroller.
If you do want to find their definitions, try looking in ~/.arduino15/.


text:
Turning LED On/Off by using SIM808 with Arduino Mega
I am trying to turn an LED on/off by using GSM 808 module. Here #a0 = LED off and #a1 = LED on. I have used lcdShow function to display characters in LCD display. But nothing appears on display. What is wrong in this code?
#include <SoftwareSerial.h>
#include <Wire.h>
#include <LCD.h>
#include <LiquidCrystal_I2C.h>
//I2C pins declaration
LiquidCrystal_I2C lcd (0x3F, 2, 1, 0, 4, 5, 6, 7, 3, POSITIVE);
SoftwareSerial SIM808 (10, 11);
char inchar;
const int LED = 2;

void setup ()
{

    Serial.begin (9600);
    SIM808.begin (9600);
    delay (10000);
    SIM808.print ("AT+CMGF=1\r");
    delay (100);
    SIM808.print ("AT+CNMI = 2,2,0,0,0\r");
    delay (100);

    lcd.begin (16, 2);
    lcd.backlight ();

    delay (1000);

    pinMode (LED, OUTPUT);
    digitalWrite (LED, HIGH);
}

void loop ()
{
    if (SIM808.available () > 0)
    {
        inchar = SIM808.read ();
        if (inchar == '#')
        {
            lcdShow (inchar);
            delay (10);
            inchar = SIM808.read ();
            if (inchar == 'a')
            {
                lcdShow (inchar);
                delay (10);
                inchar = SIM808.read ();
                if (inchar == '0')
                {
                    lcdShow (inchar);
                    digitalWrite (LED, LOW);
                }
                else if (inchar == '1')
                {
                    lcdShow (inchar);
                    digitalWrite (LED, HIGH);
                }
            }
        }
        SIM808.println ("AT+CMGD = 1,4");
    }

}

void lcdShow (char i)
{
    lcd.setCursor (0, 0);
    lcd.print (i);
    delay (5000);

}

Firstly your code was really poorly formatted, making it difficult to see what it did.
After reformatting my best guess as to why you LCD is blank is that the SIM808 is does not have any data available.  print something in the else statement.
Next it could be that the LCD is not working, print something out in setup().
You might also want to add a delay to loop() to prevent the Arduino spamming your SIM808.

source: Stack Exchange

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

sort: votes


text:
POST request on Arduino MKR1400 GSM not working
Im trying to send a POST request from the Arduino MKR1400 GSM board to a server with a database.
I've tested the server using Postman (https://www.getpostman.com/) and it handles the POST request correctly, the json data gets uploaded to database fine.
The problem is that the same POST request from the Arduino MKR GSM 1400 does nothing. I've tried using client.print and I get the same result.
I'm not sure what I'm doing wrong or how to debug this issue, any ideas?
Arduino code:
#include <MKRGSM.h>
#include "Credentials.h"

// Definiciones para el GPRS
const char PINNUMBER[]     = SECRET_PINNUMBER;
const char GPRS_APN[]      = SECRET_GPRS_APN;
const char GPRS_LOGIN[]    = SECRET_GPRS_LOGIN;
const char GPRS_PASSWORD[] = SECRET_GPRS_PASSWORD;

GSMClient client;
GPRS gprs;
GSM gsmAccess;
GSMScanner scanner;

char ip[4] = {xxx,xxx,xxx,xxx};
char ipstring[14];
char path[] = "/atcapp.php";
int port = 80; // port 80 is the default for HTTP

char respName[30] = "Arduino MKR GSM 1400";
char toolName[30] = "Herramienta martillo";
char location[30] = "Mave Aeronautica S.L.";
char tlState[4] = "OUT";
unsigned long int user_id = 4294967295;
unsigned long int tool_id = 1234567899;
unsigned long int tmeStmp = 1532684104;
char notes[100] = "";

char postData[200];
char packetData[500];

void setup() {

  Serial.begin(9600);
  while(!Serial);
  sprintf(ipstring,"%d.%d.%d.%d",ip[0],ip[1],ip[2],ip[3]);
  post(respName,user_id,location,toolName,tool_id,tlState,tmeStmp,notes);

}

char post(char* resp,unsigned long int userid,char* location, char* toolName,unsigned long int toolid,char* toolState,unsigned long int timeStamp,char* notes)
{
  Serial.println("Connecting to GPRS Network...");
  boolean connected = false;

  while (!connected) {
    if ((gsmAccess.begin(PINNUMBER) == GSM_READY) &&
        (gprs.attachGPRS(GPRS_APN, GPRS_LOGIN, GPRS_PASSWORD) == GPRS_READY)) {
      connected = true;
    } else {
      Serial.println("GPRS connection failed");
      delay(1000);
      return -1;
    }
  }

  if (client.connect(ip, port)) {
    sprintf(packetData,"POST %s HTTP/1.1\nHost: %s\nUser-Agent: Arduino/1.0\nConnection: close\nContent-Length: %d\nContent-Type: application/json\nCache-Control: no-cache\n\n{\n\"responsable\":\"%s\",\n\"user_id\":%lu,\n\"loc\":\"%s\",\n\"tool\":\"%s\",\n\"tool_id\":%lu,\n\"tool_state\":\"%s\",\n\"timestamp\":%lu,\n\"note\":\"%s\"\n}\n",path,ipstring,sizeof(postData),resp,userid,location,toolName,toolid,toolState,timeStamp,notes);
    client.beginWrite();
    for(int i=0;i<sizeof(packetData);i++){
        Serial.write(packetData[i]);
        client.write(packetData[i]);
    }
    client.endWrite();

    while(client.connected()){
      Serial.println("Client still connected.");
      while(client.available()){
        Serial.println("Client still available.");
        char c = client.read();
        Serial.print(c);
      }
    }

    Serial.println("disconnecting.");
    client.stop();

    Serial.println();
    Serial.println("Done.");
    return 1;
  }else{
    Serial.println("Cannot connect to server.");
    return 0;
  }

}

void loop() {}

Serial port output:

It's my first time ever asking a question here, any contructive criticism is more than valuable to me. Thank you in advance,

The problem most likely stems from your Content-Length header.  You are using sizeof(postData) as the length of your content - however postData is a 200 byte array which is not used for anything. sizeof() will always return 200 for that regardless of what the rest of your program is doing.
Content-Length must be equal to the number of bytes after the second of the two \n separating the header from the body.  The best way to calculate that is up add up the length of all the strings that get inserted into the body formatting (using strlen() not sizeof()), and then add to that a constant value which is equal to the number of static characters (including \n) in the body (I make that 108 possibly?).
int dataLen = 108;
dataLen += strlen(resp);
dataLen += strlen(userid);
dataLen += strlen(location);
dataLen += strlen(toolName);
dataLen += strlen(toolid);
dataLen += strlen(toolState);
dataLen += strlen(timeStamp);
dataLen += strlen(notes);

Alternatively you pre-format the body into a separate string and use strlen() on that to get the length before starting to send data.  Of course, you don't need to store all the header in the string, since you can just send that line-by-line...
sprintf(packetData,"{\n\"responsable\":\"%s\",\n\"user_id\":%lu,\n\"loc\":\"%s\",\n\"tool\":\"%s\",\n\"tool_id\":%lu,\n\"tool_state\":\"%s\",\n\"timestamp\":%lu,\n\"note\":\"%s\"\n}\n",resp,userid,location,toolName,toolid,toolState,timeStamp,notes);
client.beginWrite();
client.print(F("POST "));
client.print(path);
client.println(F(" HTTP/1.1"));

client.print(F("Host: "));
client.println(ipstring);

client.println(F("User-Agent: Arduino/1.0"));
client.println(F("Connection: close"));
client.print(F("Content-Length: "));
client.println(strlen(packetData));
client.println(F("Content-Type: application/json"));
client.println(F("Cache-Control: no-cache"));
client.println();

client.print(packetData);

client.endWrite();

Note the use of F() around your static text to save copious amounts of RAM on AVR-based boards. Not really necessary on an ARM-based board, but a good thing to get into the habit of to keep things portable.
If you want to debug what is being sent I would suggest making a "debug" wrapper class that comprises both client and Serial:
class TwinPrint : public Print {
    private:
        Print *_ch1;
        Print *_ch2;

    public:
        TwinPrint(Print &ch1, Print &ch2) : _ch1(&ch1), _ch2(&ch2) {}
        size_t write(uint8_t c) {
            _ch1->write(c);
            _ch2->write(c);
            return 1;
        }
};

You can then construct a new object:
TwinPrint debug(client, Serial);

and do your writing to that and it will come out on both client and Serial at once:
debug.print(F("POST "));
debug.print(path);
debug.println(F(" HTTP/1.1"));

debug.print(F("Host: "));
debug.println(ipstring);

debug.println(F("User-Agent: Arduino/1.0"));
debug.println(F("Connection: close"));
debug.print(F("Content-Length: "));
debug.println(strlen(packetData));
debug.println(F("Content-Type: application/json"));
debug.println(F("Cache-Control: no-cache"));
debug.println();

debug.print(packetData);

I used strlen() and it worked! The debug class is a great idea! So the F() function "grabs" the strings from flash instead of the SRAM? Thank you soo much for answering so soon!

F() is a macro that forces the strings to stay in flash instead of being copied to SRAM (on Harvard architecture systems, anyway). It then causes a different variant of the print function to be called which reads the data directly from flash.

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


text:
Problem in reading data from encoder with arduino
Hello guys I am trying to count the number of the steps of a stepper motor with an encoder (Avago heds).
I found an Arduino sketch to count that steps and display them on the console and I found online the scheme to connect that encoder to Arduino.
The problem is that the encoder returns as output only 0, even if I rotate manually the motor. I also tried to measure the voltage of the encoder with a voltmeter but the voltage does not change even if I rotate the motor.
That is the Arduino Sketch
Here some picture's of Arduino-encoder connections

P.S. The motor works because I tried it before
Thank you for help

What is the point of a stepper motor with an encoder? When you make 100 steps with the stepper motor, it has done 100 steps.

@Jot it can skip or something can exceed the holding torque, it also allows calibration on startup without a detectable home position or limit switches .

@ratchet freak you are right

I think the encoder @zzan has pick only outputs relative position information. So the argument of using this encoder to find home position may not work out.  2. Most design steppers to have more than adequate torque for an application so detecting slipping is not necessary. 3. There are much simpler ways to find home position such as end-stop switches found on 3d printers and CNC machines.

Additional thought, are you sure the shaft is rotating the encoder wheel?

Yes the encoder wheel is rotating. I am building a robot arm and I need the encoder to determine the steps to go in a position with the motors turned off

Is the encoder this one? https://www.robotdigg.com/product/893/1000-line-rotary-incremental-encoder-kit

yes, do you have any idea? @sa_leinad

try to use the oscilloscope to visualize the outputs of channel A &B

In my experience (industrial encoders and PLCs) when the output don't change when the motor shaft is rotated its usually one of the following:

The set screw connecting the motor shaft to the encoder that isn't tight,
broken wire (bad connection to the encoder) or
a bad encoder.

Your picture shows what looks like a cover over the encoder coupling to the motor.  Look and make sure that the encoder is actually rotating with the motor.
Then double check your connections.  If a DMM still shows no voltage changes (use AC range if turning the motor to show that the encoder output is pulsing).
If there is still no joy, its likely that the encoder is bad.


text:
How to print 'µ' in the serial monitor?
I have been trying to print the letter µ on the Serial Monitor of Arduino IDE but I failed to do so. Is there any way to print µ or any other Non ASCII characters such as Ó,ß,Ô,Ò,õ,Õ,þ, etc using Serial.print()?

Most of what follows has already been covered in previous answers. I am
posting this nevertheless because I feel no answer so far makes the
whole story clear enough. Let me break down the question into two
sub-questions.
1. How can I get non-ASCII characters correctly print on the serial monitor?
The answer is simply send them as UTF-8.
That's really all there is to it. The serial monitor expects you to send
UTF-8, and it will print the characters correctly only if you use this
encoding. But that brings the second question:
2. How can I get the characters as UTF-8 in my Arduino program?
Here you have several options:
Option 1: encode them yourself
For example, the Greek letter “μ” (U+03BC) in UTF-8 is (0xce 0xbc). You
can send those bytes explicitly, like
Serial.write(0xce);
Serial.write(0xbc);

or, more comfortably, like
Serial.print("\xce\xbc");

The second syntax is more convenient because it allows the character to
be embedded within a longer string.
Option 2: let the Arduino IDE encode them
If you can get the characters in the IDE's editor window, either with an
appropriate keyboard layout or by copying and pasting from another
application, then you can use them as is in the string:
Serial.print("μ");

The editor will save the source code as UTF-8, and those UTF-8 bytes
will go undisturbed from the source file to the compiled program, to the
Arduino memory, to the serial port, and finally to the serial monitor.
This option is the best for readability. However, it is somewhat
fragile: if the source code ever gets re-encoded (e-mail clients and
servers sometimes do that), then the resulting program will not work as
expected.
Options 3: let the compiler encode them
You can ask the compiler to do the UTF-8 encoding for you with the
syntax
Serial.print(u8"\u03bc");

Here, the escape sequence \u03bc is a way to represent the Unicode
character U+03BC (i.e. “μ”), and the u8 prefix means that you want the
string as a byte array encoded in UTF-8.
Note that, in practice, the u8 prefix is not needed, as the gcc
compiler assumes UTF-8 by default. I would keep the prefix anyway
because it doesn't hurt to make the encoding explicit, and it may avoid
angering some language lawyer...
Note also that the syntax above only works for characters U+0000 through
U+FFFF, i.e. the basic multilingual plane. For other Unicode characters,
you have to use the syntax \U + 8 hex digits. For example, the
character “” (U+1F60E: smiling face with sunglasses) can be printed
with:
Serial.print(u8"\U0001f60e");

Clarification about UTF-16: A common misconception has it that with
\u you write the characters as UTF-16 code units, and with \U you
write UTF-32 code units. But it is incorrect:
both syntaxes are used to describe a
single character (technically, a code point), irrespective of the
encoding. Since the UTF-16 encoding for “” is (0xd83d 0xde0e), one
could be tempted to write
// Write as UTF-16 code units in the source code.
Serial.print("\ud83d\ude0e");  // WRONG

but then the compiler rightfully complains
error: \ud83d is not a valid universal character
error: \ude0e is not a valid universal character

So forget about UTF-16. There is no UTF-16 involved anywhere, except in
the internal representation used by a Java widget used to implement the
serial monitor, which is a completely irrelevant implementation detail.

The Serial Monitor uses Unicode, so sending characters in that format is possible.  The UTF-16 code for µ is 03BC, and you can send it by prepending \u:
Serial.print("\u03BC");

The actual stream of transformations is you provide Unicode (essentially UTF-16) in your string. C++ then converts that into a stream of 8-bit characters in UTF-8 format, which is then sent down the serial connection. Java then receives those and interprets them as UTF-8, recombining them back into the original UTF-16 characters for display in the JTextArea that comprises the Serial Monitor in the Arduino IDE.
This complex transformation is done because:

UTF-8 is easier to stream over an 8-bit data link, but is very hard to work with in a program (because of variable-length byte sequences), and
UTF-16 is hard to stream (and breaks ASCII compatibility) but is far easier to work with programmatically (since it is just fixed size 16-bit characters).

So your 0x03BC gets transformed into 0xCE,0xBC which is the UTF-8 representation of the Unicode character 0x03BC.

Comments are not for extended discussion; this conversation has been moved to chat.

It depends on your operating system, the arduino version and perhaps even on the selected board.
You have selected a weird character, because there are two versions: the micro µ and the mu μ.
See: https://en.wikipedia.org/wiki/Mu_(letter) and https://en.wikipedia.org/wiki/Micro-. They are not the same.
In linux with the Arduino 1.8.5 and Arduino Uno board, everything supports UTF-8 (the Arduino ide, the serial monitor and the ino file).
To test it, I have written the micro character with AltGr+m in the sketch. It is stored in the ino file as C2 B5, which is UTF-8. It shows in the serial monitor as µ.
With gtkterm, it shows as a µ, and in hexadecimal and it shows C2 B5. That confirms that everything is UTF-8 in linux with Arduino version 1.8.5.
The Unicode "\u03BC" shows a µ in the serial monitor. It is stored in the ino file as 5C 75 30 33 42 43. That is not UTF-8 and not UTF-16, but ASCII for the characters "\u03BC". That is okay, since that is what is typed in the sketch. With gtkterm it shows a µ and CE BC in hexadecimal mode. The CE BC is UTF-8 for mu.
That means the Unicode is translated to UTF-8. Perhaps the compiler translates it to UTF-8?
These are the only tests that I did. It is just a very small part of all possibilities.
Conclusion:
Try to type µ (mu or micro) in the Arduino ide editor.
Using AltGr+m will only work if you have selected a certain keyboard settings. Perhaps you can copy the character from the Wikipedia page.
Using Unicode "\u03BC" seems to be possible.
[ADDED]
The internal format of text in Java was UTF-16, but only a fixed two byte format, not the four bytes. It was therefor only a subset of the Unicode characters. The newest Java version supports the real UTF-16 format for user strings, and thus supports all the Unicode characters.
The data that is stored to a ino file and the data that is transmitted to the serial monitor can be ASCII for normal characters with the addition of UTF-8. Most special characters that I use require two bytes in the UTF-8 format.
For Majenko: look at the binary data of a ino file and the binairy serial data. It is not a fixed two byte per character, but just one byte for normal characters.
I still don't know who translates the Unicode description of a character to UTF-8. It would be indeed weird if the compiler did that, so somewhere Java might automatically translate that.

It depends on none of those things. It depends purely on what is receiving the raw bytes as to what you place in your sketch. Since that is Java, and Java use 16 bit UTF-16 (regardless of operating system) you embed 16 bit UTF-16 codes in your strings to display things in your serial monitor. If you are sending to something else then you embed the correct codes for whatever you are sending to. But since this is the serial monitor then it is UTF-16 and will always be UTF-16.

@Majenko , I think you need a night sleep and have a look at it again. In the past the ino file stored UTF-8 characters but the serial monitor did not accept them. The arduino version does matter. In the past there were a number of differences with UTF-8 in Windows and linux.

No one cares about UTF-8. Only UTF-16.

And saving UTF-8 in the ino file has nothing to do with sending UTF-16 to the serial monitor.


text:
Do I need one N3904 for each LED?
I want to control 4 (or more) LEDs using the PWM output pins of my Arduino.
Here is how I have it on a breadboard, and it's working for me.
Question:
Is this schematic inefficient? Are there any issues with this design?

How powerful are your LEDs?

It'll be more efficient if you'd just connect anode to the PWM output and cathode to the ground through resistor. Now there will be more current through the base to the ground than through LED

I will be using pink, blue, green, and yellow LED's.
I need to control each LED independently, and change voltage dynamically (fade on / off  or blink etc.. )
Hopefully that helps some.

@ThomasWeller sorry, do you mean using the PWM output pins to supply power to each LED?  If I turn on multiple LED's at the same time, would they receive enough power?  I guess I'm not sure if there is a voltage difference when using analogWrite(n, 255) across multiple pins at the same time.

@KIIV oh wow, I think you're referring to something like the schematic in the answer for this question: https://arduino.stackexchange.com/questions/34989/controlling-common-anode-rgb-led-with-pwm-can-individual-colors-be-done-w-o-tr?rq=1
That is really neat and may be a much simpler circuit design. Thanks

@user3228313 Just keep that resistor for each LED. Without it, you might be operating on the maximum IO port currents and it may fail eventually

in general, MOSFETs are a better way to go than BJTs for switching on/off (incl PWM) and they are more efficient energy-wise, not dropping a junction of voltage to be multiplied by the load...

In the schematic you don’t have any resistors between the PWM pin an the base of the transistor. You really need to add those. Also the resistors for the leds are typically placed on the other side of the transistor (connected directly to the leds).


text:
Can multiple Arduinos be connected to a single relay?
I have a 16 channel relay that will basically manage 16 different contacts. However, each channel in the relay needs to be controlled by an individual Arduino. So in total I would have 16 different Arduino boards that will each control a single channel in the relay. Is this possible? If so, how do I make the conenctions?
 I tried it earlier using several arduinos and connecting their ground wires together but did not seem to work, the relays remained energized. I am using the SAINSMART 16-Channel 12V Relay Module

That board is intended to allow one micro-controller to control 16 relays. Why not get 16 single relay boards for your 16 arduino's? Also, having a common ground, plus connecting each arduous to a different relay should have worked.

@esoterik too expensive and the parts will take longer to arrive. What do I connect to the 5V input though? A separate power supply or can just one arduino power it?

you colud have one supply powering all the arudinos, and the board yes.

@esoterik so I have one arduino powering the relay module and hooked up to channel 1. Another arduino hooked up to channel 2. Only channel 1 seems to work. (both arduinos are grounded together)

Why do you need 16  Arduinos???

@juraj each arduino is meant to have its own IP address and will handle different things

one Arduino can handle different things

@Juraj orginally we were going to use something like the mega or something similar. However, each arduino is meant to simulate a specific site and has its specific properties. Using multiplexers or a single larger arduino was not going to simulate very well as the code would also need to be switching between different states. Our only possible setup is using 16 arduinos

Looking at the schematic, here are some points to be kept in mind when using this relay board:

The relay board should be powered through the 12V connector
The relay board has its own 5V regulator
The optocouplers are attached in "reverse"

So, the external connections should be

Connect all the arduino grounds together, and connect them to the board ground
Do not connect any +5V wire together
Connect arduino 1 to IN1, arduino 2 to IN2 and so on
Writing a HIGH value on the INx pin will result in the relay to be de-energized (so contact goes in NC position), writing a LOW value on INx pin energizes the relay (so contact goes in NO position)

If making this connection the board does not work as expected, try to detach all the arduino boards and manually shorting IN1 and +5V, IN1 and GND, IN2 and +5V, ...

You could think of using 16 Arduino's sending messages (or a control signal) to a Master Arduino which controls the 16 relays.
You can use a protocol (like ModBus, I2C). Or you can connect each Arduino to a dedicated input pin of a 16:1 Multiplexer and let the Master check all 16 lines one by one to check which relay need to be enabled.
This way you can even add more intelligent logic in the Master if needed.

You wrote that joining Arduino ground together didn't work.
This leads me to believe that you didn't do the most important connection. You need to have each Arduino ground connected to the Relay Module ground. Usually this requirement is fulfilled, because people power all devices from the same power supply.
Without that Relay Module inputs are "floating", and their states are random.

the relay's ground is also connected to all of the arduino's ground

and is there one 5 V power source?

each arduino has its own power source, and the module has a dedicated 12V power supply


text:
How arduino boards eliminate the need to press buttons to flash?
I've come across many Arduino shields for various boards like the Uno, ESP8266, and ESP32 which sometimes have a button for flashing and other times they do not because the flashing is automatic.
When I upload a binary sketch to ESP32 directly through a separate Serial to USB converter, I have to make the button connections and press the buttons manually for the uploading process to work.
The manual button pressing flashing process for the ESP32 goes like this:

Hold the Reset button (IO0 to ground)
Hold the Flash button (EN to ground)
Release the Reset button (IO0 to float)
Release the Flash button (EN to 3.3v)
The board is now in flashing mode
Press "Upload" in Arduino IDE
Wait until the IDE log shows "Connecting..."
Wait until the sketch is fully uploaded
Press the Reset button (IO0 to ground then float)

Arduino boards like the WeMos Lolin32 board eliminate the button pressing process completely during the flashing process.
QUESTION: Which part of the hardware on the Lolin32 board makes the flashing process autonomous?
Here's the manual uploading schematic:
And here's the WeMos Lolin32 board, that eliminates the button pressing process completely when I upload a sketch:
I believe the answer will also apply to any other auto-flashing board out there.

I'm not familiar with this board, but according to this schematic:
https://wiki.wemos.cc/_media/products:lolin32:sch_lolin32_v1.0.0.pdf
U4 (one of the small 6-leg components) connects to IO0 (pin 25) on the ESP-32. The transistor inside U4 combines the RTS and DTR signals (from U6 USB-Serial converter IC, which will be the large IC marked SIL2104) to put IO0 in the correct state for flashing. The RTS and DTR signals can be set by the host (the computer doing the flashing).
Apologies for the lack of depth, but the short answer is components U4 and U6 on the board work together on the command from the host computer to put IO0 in the correct state for flashing.

Now I know a little bit more about the components on Arduino shields! Thank you for looking into this for me.

From this, I went on to learn more about the U6 component (SIL 2104 F01BP 1711+)  and find out why it has 4 GPIO pins: https://www.silabs.com/documents/public/data-sheets/cp2104.pdf

@DemSec, i think that it has 4 GPIO pins because the manufacturer has decided that it would make the device more useful


text:
Arduino network with minimum wiring
For a parking management system I am going to create an Arduino network.
An Arduino with an ultrasonic sensor will be placed above each parking space. If car is parked at specific location Arduino will inform master (PC) and also turn RED light ON.
I am not sure how I can make network with minimum wiring. I think RS485 will be suitable for this purpose.
There will be almost 200 Arduinos in a network. I have following questions in mind:

Should I go for RS485 protocol or something else?
Can RS485 support 200 devices as there will be only short communication (i.e device ID and parking status)?
I am planning to lay CAT6 cable. Two pairs will be used for power transmission and two pairs will be available for communication.

Where is the question in the third point?

Cabling detail is provided so that if someone have better communication method over 4 wires, I can go with it easily

This sounds, to me, like a job for CAN.  It's the current de-facto standard for industrial inter-MCU cabled connections. It's used, not only in automobiles, but also to control elevators and almost all other modern industrial distributed applications.
Note that CAN is designed to only support up to 30 nodes, so you would need to split your network into sections and have groups of nodes amalgamated together into a single sub-network.  For 200 nodes you may want 10 subnetworks - that is, 20 nodes connected together to one super-node, which is then connected to the "backbone" CAN bus.
However, CAN can be run at lower baud rates than normal, and that increases the number of nodes you can have on any one network segment. It potentially (bus capacitance permitting) support thousands of nodes.
Another option is to use CAN to connect multiple "master" nodes together into a backbone, and then those "master" nodes connect to a number of sub-nodes using LIN (which is cheaper to implement than CAN).

LIN can support a maximum of 15 nodes (plus one master node) per network, so you can get a theoretical maximum of 29*15 (assuming 1 CAN node is the connection to the PC), or 435 nodes.
You could also use RS-485, but that is also limited to around 30 "unit loads", and the number of nodes you could put on one segment is dependent on the "load" each node imposes. In practical terms it's rare to go over 30-40 nodes on a single segment, and grouping nodes together into sub-networks (as above with CAN/LIN) would be needed. So you may as well use the current standard for this kind of communication, and use CAN/LIN.

Note that whereas the limit on LIN nodes is a hard one, CAN will work fine with a ridiculously high number of nodes, if you pick an equally ridiculously low baudrate.

@DmitryGrigoryev I'm not familiar with the "standard" CAN protocol. Does that support more nodes, or would you have to use a non-standard protocol as well?

CAN has an 11-bit address field (and extended CAN bumps it to 29), which is plenty for 200 devices. Standard CAN baudrates start with 125kbps (supporting ~30 nodes along ~500m of distance) but most transceivers can be configured to much lower baudrates like 16kbps.

@DmitryGrigoryev Sounds even more ideal.

Hmmm it's sound great. I'm not much familiar with CAN network. I'll check on Google and come back soon. But looking briefly it looks like expense choice. As RS485 and CAN both can support almost same number of nodes depending upon load. Rs485 is much cheaper solution.  But by the way now I'm very clear I have to divide my network in small parts. Thanks a lot man

@Majenko Personally I would have said that in this application (one master and several receivers) the RS485 would have been better. CAN is more useful when you have an asynchronous network (is it called this way?), where nodes can communicate at will and there are some precedences to be respected. What are the advantages of CAN in this case, in your opinion? RS485 is much cheaper (you can use the UART peripheral, while CAN peripherals are not integrated in cheaper uC)

@frarugi87 CAN is the current standard for industrial applications. If you stick to a standard, then when someone else comes along after you to maintain it or upgrade it, etc, they can more easily know what it is all about.

Regarding your third point, a CAT6 cable may not work as well as you expect for power delivery depending on the topology you choose. The most common variety of CAT6 uses AWG24 wires with a resistance about 0,085 Ohm/m, so a 100 m chunk of such cable will have a resistance of about 17 Ohms. Assuming a current of 100mA, you will lose 1.7V in the cable, so if you supply it with 5V, the load will only see 3.3V.
This is one more reason to split your network into segments. If I were to implement this project, I would power the "backbone" cable with higher voltage (12 - 24V) and install DC-DC converters producing 5V locally in each upper-level node.
It seems from the comments that you're looking into solutions which would allow you to use standard UARTs for communication. You can of course use RS485 (you will still need several segments). Otherwise, I advice you to look at how LIN is implemented: essentially, a 19200 bps UART signal is made open-drain (to combine all TX/RX pairs into a single wire) and amplified to 12V for noise immunity. Software-wise, a master sends a frame including slave's address and waits for a reply, then talks to the next slave and so on. Slaves only respond when they receive a frame with their address in it.
If you don't want to spend extra effort and implement something standard, at least looking into an existing spec while implementing your own solution will save you a lot of trouble.

Yes you are absolutely right. And i was also planning to supply 12V supply with voltage regulator.  At different points.

@umair please note that Dmitry suggested using "DC-DC converters"; don't go for a generic "voltage regulator" (which usually are linear), use a switching converter

@frarugi87 Unless the OP wants to defrost the parking lot in winter :)

@DmitryGrigoryev "it's not a bug, it's a feature" ;)


text:
The voltage level fluctuates whenever ESP8266 receives signal
Good afternoon dear community,
I am trying to built a WiFi communication with Arduino using ESP8266 module. There is one servo, one step motor connected to Arduino and whenever the ESP8266 Wi-Fi module receives a signal, the voltage level on the motor and servo fluctuate dramatically, which causes inaccurate results on how motor and servo behaves. I have connected the ESP8266 module using SoftwareSerial, and even when the signal is not transferred into motor or sevo, the voltage levels change whenever a data is received by the WiFi module.
Below is my code,
#include <Servo.h>
#include "SoftwareSerial.h"
SoftwareSerial softSerial(10, 11); // RX, TX

// Components:
Servo servo1;
Servo firstESC;

// Motor:
const int MAX_SPEED = 1850;
const int MIN_SPEED = 1200;
int armValue = 1500;
int speedIncrease = 20;
int speedDecrease = speedIncrease * 3;

// Direction:
int currentPos;
const int MAX_ANGLE = 120;
const int MIN_ANGLE = 60;
const int MID_ANGLE = 90;

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

   softSerial.begin(9600);
   // softSerial.setTimeout(10);

   // Setup servo:
   servo1.attach(9);
   servo1.write(90);

   // Setup direction:
   Serial.println("The motor is arming in 2 seconds, please wait.");
   firstESC.attach(8);

   // Arm the motor after 2 seconds:
   delay(2000);
   firstESC.writeMicroseconds(armValue);

   Serial.println("Serial is setting up, wait time: 3000 ms.");
   delay(3000);

   // Check board communication:
   softSerial.println("AT");
   delay(1000);
   while (softSerial.available()) {
     String message = softSerial.readString();
     Serial.println(message);
     delay(1000);
   }

   // Connect to WIFI:
   Serial.println("Connecting to wifi, wait time 4000 ms.");
   softSerial.println(--- COMMAND TO CONNECT WIFI ---);
   delay(4000);
   while (softSerial.available()) {
     String message = softSerial.readString();
     Serial.println(message);
     delay(1000);
   }

   // Wait for connection to be stable:
   delay(2000);

   // Get IP address:
   Serial.println("Requesting IP Address.");
   softSerial.println("AT+CIFSR");
   delay(2000);
   softSerial.println("AT+CIPMUX=1"); // Set multiple connection available.
   while (softSerial.available()) {
     String message = softSerial.readString();
     Serial.println(message);
     delay(1000);
   }

   delay(2000);

   // Set up server:
   Serial.println("Connecting to server..");
   softSerial.println("AT+CIPSTART=3,\"TCP\",\"192.168.1.67\",1235");
   delay(2000);
   while (softSerial.available()) {
     String message = softSerial.readString();
     Serial.println(message);
     delay(1000);
   }

   Serial.println("Set up is complete, loop started.");

}

String inString = "";
bool reading = false;

void loop() {

   while (softSerial.available() > 0)
   {
    char inChar = softSerial.read();

    if(inChar == 'O') {
      reading = false;
    }

    if(reading) {
      if (inChar == ','){
        Serial.println(inString);
        int val = inString.toInt();

        //Motor input
        if (val >= MIN_SPEED && val <= MAX_SPEED){
          setSpeed(val);
        }

        //Direction input
        else if (val >= MIN_ANGLE && val <= MAX_ANGLE ){
          setRotation(val);
        }
        inString = "";
      }
      else{
        if(inChar !='\0' && inChar != '\n' ){
          inString += inChar;
        }
      }
    }

    if(inChar == ':') {
      reading = true;
    }

   }

   if (Serial.available())
   {
      String message = Serial.readString();
      // Serial.print(message);
      setSpeed(message.toInt());
   }
}

void setSpeed(int customSpeed){
  firstESC.writeMicroseconds(customSpeed);
}

void setRotation(int angles){
  servo1.write(angles);
}

This might be an issue with having a weak (or not stabilized) power supply. When system momentarily draws to much current it drops the voltage. What do you use to power your circuit?

When it is connected to USB or a 7.5 V power supply, creates the same issue.

The ESP8266 is notoriously noisy, chiefly because the cheap boards the ESP8266 is commonly sold on don't implement any form of power filtering.
So you really have to add your own.  As I had to recently when adding an ESP8266 board to an audio system.
For that I came up with this schematic:

VCCA is your main incoming power.  VCCD feeds the power into the ESP8266. The motors are connected to the same point as VCCA.

Are you planning on marketing this as a kit?

I wasn't, no. I guess I could though...


text:
How to stop extra LEDs from lighting in LED cube
So I build LED cubes and the way I have it programmed is I use an analog pin for the ground layers and set them to high when i want an led on that layer lit up. So lets say I wanted the following LEDs lit

But in reality the LEDs light up in all the layers that are set to high obviously so this is what actually ends up lighting

What should I incorporate in order to avoid this happening. I am using an Arduino Nano, do I need to edit my code or is it hardware?

You turn on one, turn it off, then turn the next one on and turn it off. Do that very fast and it looks like they are both lit.

Doesnt work because im spinning the cube around fast so 1 millisecond is noticeable

Then you will need to change the circuit so each LED is directly wired, and not in a matrix. If you can't use matrix multiplexing then you can't use a matrix. Simple.

There has to be a better way that i can control parts of the leds and still have a sturdy design thats a cube

You don't have a cube, you have a square. And if you are spinning it then multiplexing won't, as you have noted, work well. You have the choice of multplexing (flicker, few wires) or non multiplexing (no flicker, lots and lots of wires).

You may need to go back to the drawing board. Maybe the way you are designing whatever it is you are designing is wrong.

I know a better way of designing what im making but it requires a lot more work. I was just wondering if there was a special way to control each LED but thank you for the help so i didnt waste more time finding a method that doesnt work haha

The only way you could use multiplexing would be to have the frequency really really high. I'm talking MHz range. You may be able to find a driver chip that does that.

Do you want to turn those comments into an answer and ill give you the dub

I have come up with another option - I'll detail it in my answer.

Your circuit design has to be used with multiplexing. Multiplexing introduces flicker. Since you seem to be wanting to move the grid of LEDs rapidly that flicker will translate into a very undesirable effect.
So you have a number of choices:

Re-design your system so that you don't use multiplexing. With each LED directly driven you get zero flicker, but you end up with as many wires and GPIO pins needed as you have LEDs (although shift registers could be used to move the bulk of the wiring closer to the LEDs). That's impractical.
Use multiplexing but have the frequency so high that flickering is no longer noticeable. We're talking thousands or millions of loops per second to keep it looking smooth (depending on how fast you are spinning the grid). You would need a high speed multiplex driver chip for this.
Time your multiplexing to the spinning of the grid.

The third option relies on quite a high rate of spin, since your multiplexing increments one column or row for each revolution. With 5 columns to work through it would take 5 revolutions to work through the entire grid.
You need some way of identifying the start of each revolution (e.g., a hall-effect sensor), and each time you start a new revolution you illuminate just one column of LEDs. The faster you spin the smoother the effect will be.
If you want to have LEDs on or off for just part of the revolution it's then down to you to work out when to turn them on or off for that one specific column. That's when the fun really begins.

Upvoted. Just a remark about 1: you can use e.g. 74HC595's (in daisy chain mode) to upto 32 LEDs with a few pins. Although you need to wire from those 74HC595's to each LED (lots of wires).

@MichelKeijzers Indeed. Plus of course you'd probably then be spinning those around really fast as well, which adds to the instability of the whole thing. Not ideal.

Not ideal indeed :-)


text:
Send AT commands to ESP8266 from Arduino Nano serial monitor
I have an Arduino nano and an ESP8266-01.
The first thing to do seems to be to send AT commands via the serial monitor and see the replies.
ESP connect as follows:
  GND   GND
  GPIO2 not connected
  GPIO0 not connected
  RX    to Arduino RX via level shifter
  TX    to Arduino TX via level shifter
  CHPD  3.3V
  RST   3.3V
  VCC   3.3V

Image of breadboard (imgur rejects)
https://www.dropbox.com/s/aif8afi29amy02h/20180807_135218.jpg?dl=0
When connecting the red light comes on and the blue light flashes quickly (and the Arduino RX light flashes with it) then goes out.
Here is the sketch I'm using. (The ESP8266 must be disconnected from RX+TX for uploading of the sketch to work.)
     void setup() {
  Serial.begin(115200);

  pinMode(LED_BUILTIN, OUTPUT);
  digitalWrite(LED_BUILTIN, HIGH);
  delay(1000);
  digitalWrite(LED_BUILTIN, LOW);
}

void loop() {
  digitalWrite(LED_BUILTIN, HIGH);
  delay(250);
  digitalWrite(LED_BUILTIN, LOW);
  delay(3000);
 }

(I like to blink the LED to demonstrate that uploading worked.)
With the serial monitor set to 115200 (NL&CR) I sent AT and nothing happens.
What have I got wrong? I really don't understand! Thanks in advance for any suggestions.
(This is actually my third ESP8266. The first worked fine on 5V but stopped working after I set the baud rate to 9600. I presume 5V killed it but it's strange that it worked for so long. The second, connected as above, when powered up made that power supply red hot and melted the jumpers.)

First problem is that io 0 of the esp8266 must be pulled HIGH for normal boot. With io 0 not HIGH, the esp8266 starts in flashing mode.
Your other problem is the reset pin connection. It must be connected with pull-up resistor or not connected.
See ESP8266 Hardware Design Guidelines

Pin32 serves as an RST pin which can be left floating when it is not
  used. The reset pin is held low when the chip is enabled. In order to
  avoid resets caused by external interference, the lead is generally
  required to be short, and no external pull-up resistor is necessary

I suspect that "The reset pin is held low when the chip is enabled." is a bad translation. They say in pin description "32 EXT_RSTB I External reset signal (Low voltage level: Active)". What they mean is that the chip resets when reset pin is set LOW.

Disconnecting it hasn't made any difference.

remove the level shifter from esp8266 TX pin

With TX connected directly to Arduino TX: no change except that the ESP8266 blue light does not now flash when powering it on.

important! set io0 of esp8266 HIGH with a pullup resistor

Put GPIO0 via 3k3 to 3.3V and still nothing.

remove Serial.begin from Nano sketch or better put Nano in permanent reset connecting reset pin of Nano to ground

Progress!
With Arduino RST connected to GND powering on the ESP produced junk on the terminal.
I then tried all the different baud rates until I found that at 74880.
GPIO0 connected or disconnected makes no difference.
TX via level shifter makes no difference. ESP RST to 3.3V makes no difference.
Still no response from AT.

If I connect EXP TX and TX directly to Arduino TX and TX (resp.) then I get a response from AT but it is junk.
Changed the baud rate to 115200 and AT works with direct connection.
So is my level shifter bust?

the bootllog is printed at 74880 and it contains junk (chinese characters perhaps)

AT works with TX,TX directly connected without Serial.begin.

So:

Connect the ESP8266 RX/TX directly to the Arduino, not via the level shifter.
No need to connect GPIO0.
RST can be either left floating or connected to 3.3V; it makes no difference.
No need to Serial.begin; an empty sketch will work.

This is what you want to see in the terminal:
AT

OK
AT+CWMODE?

+CWMODE:2

OK
AT+CWMODE=1

OK
AT+CWLAP

+CWLAP:(3,"SKY61611",-83,"90:21:06:79:fb:0a",1,110,0)
+CWLAP:(3,"SKY3CA89",-90,"60:38:e0:d4:7d:7d",6,96,0)
+CWLAP:(3,"PLUSNET-TS2H",-75,"a4:08:f5:ae:ab:c2",6,103,0)
+CWLAP:(3,"SKY3CA89",-79,"90:21:06:c6:1f:6d",6,120,0)
+CWLAP:(3,"MY WIFI 6739",-38,"18:e3:bc:2c:67:39",6,127,0)
+CWLAP:(3,"BTHub6-CF7H",-88,"88:a6:c6:27:53:a4",6,108,0)
+CWLAP:(3,"SKY7A62E",-79,"7c:4c:a5:1c:7f:59",11,130,0)
+CWLAP:(4,"EE-mce6kx",-86,"e4:3e:d7:71:35:f3",11,128,0)

OK

The next thing to do is to set the ESP8266's baud rate to 9600 so that it can be used with SoftwareSerial. The command to do this is
AT+UART_DEF=9600,8,1,0,0

Then we can move the ESP8266 off the Arduino's RX/TX pins onto some other pins and forward commands from the terminal to the ESP8266 and print the responses.
#include <SoftwareSerial.h>

#define RX 10
#define TX 11
SoftwareSerial esp8266(RX, TX);

void setup() {
  Serial.begin(9600);
  esp8266.begin(9600);
  Serial.println("setup() done");
}

    // Check for messages form the ESP8266 and process them.
void processEsp() {
  while (esp8266.available() > 0) {
    String line = esp8266.readStringUntil('\n');
    processLine(line);
  }
}

void loop() {
  if (Serial.available() > 0)
  {
    String command = Serial.readStringUntil('\n'); // AT+CWLAP
    Serial.println("Command Sent: " + command);
    esp8266.println(command);
  }

  processEsp();
  //Serial.println("...");
  //delay(1000);
  // We wait once.
  // During that wait the buffer fills, and we only see what's in the buffer.
}

void processLine(String line) {
  Serial.println(line);
}

The serial reader must run in a tight loop; a delay causes it's buffer to fill and characters beyond the buffer length are lost. Enabling the delay causes the AT+CWLAP response to be truncated.
There is no way to detect the end of a response to an AT command. The ESP8266 can send anything at any time. What it sends should be processed line by line; the line/record delimiter is \r\n.

the WiFiEsp library has standard Arduino networking API over esp8266 AT commnands. the library can detect the end of the response. (you could al least upvote my answer)


text:
Arduino sensing its 'Motion'
I am working on a project where I need the Arduino to 'sense' at what direction its moving. For example, I want the Arduino to 'sense' that it
is moving towards 'forward' direction, 'backwards' direction etc.
Is that possible using an Arduino? Can I use a motion sensor to do this (probably not)?
Can any one please help me to find the right 'direction'?

For this you need a acceleration/gyro sensor, like the MPU6050.
By tracking x/y/z movements, you can define what is forward/backards etc. Also you can track angles/tilts (in 3 directions).
See an example how to use it here: MPU-6050

Thank you, I don't wanna go deep here, but is there a library present which I could use to make my work easier?

You can change the example as library, or maybe this link helps: https://maker.pro/arduino/tutorial/how-to-interface-arduino-and-the-mpu-6050-sensor
I never tried the MPU6050 myself.

Well I tried by borrowing one from a friend, it worked  thanks


text:
TM1638 making high pitch sound?
I have a TM1638 board with 8 seven-segment displays, 8 LEDS, and 8 buttons. Each time multiples leds are on, the board makes an annoying high pitch sound.
I'm controlling it with an Arduino Uno.
Should I worry about the sound and is it normal?
This is my board :

What board do you have?

check your ground connections

Where does the sound come from exactly? When your LEDs are on, they draw power from the power supply. Cheap switching power supplies will exhibit a ringing sound under load (Spulenfiepen / coil whining, https://en.wikipedia.org/wiki/Electromagnetically_excited_acoustic_noise_and_vibration#Reduction_of_%22coil_noise%22)

I would guess it is a harmonic from the multiplex signal. Touch each part with a pencil eraser and see if it goes away.  Can you change the voltage by maybe 0.02 volts and see if it changes. Without a schematic I can only guess. I have seen these symptoms before but not with this hardware.

This thread is getting old but this LED&KEY device seems to still be fairly popular so this may still help someone else. I'm using one to control a radio receiver and the constant buzz can get pretty loud.
I found this article (A second look at the TM1638 LED & key controller) which mentions the same issue which was solved by inserting a 100Ω resistor between VCC and the VCC pin. I also added a 1000μF electrolytic capacitor across the VCC and GND pins (well, fairly close to them anyway). This quieted down the buzz a lot though it's still there. The resistor is key though the capacitor helps a bit.
I also tried moving the breadboard connections to a separate, smaller breadboard, away from the MCU and radio receiver chip and was able to use lower values (10Ω and 47μF). I was no longer able to hear the buzz at all.


text:
Using EEPROM Anything in loop()
I'm trying to make a programm for Arduino Bluno Beetle, that saves a string in the loop. Here is my code:
#include <EEPROM.h>
#include <EEPROMAnything.h>
struct config_t{
   String lastThing;
    } savedValues;
void setup(){
   EEPROM_readAnything(ADDR, savedValues);
   Serial.println(lastThing);
}
String readString="asd";
void loop() {
 //...
 lastThing=readString;
 EEPROM_writeAnything(ADDR, savedValues);
}

(The EEPROMAnything.h can be found here: https://playground.arduino.cc/Code/EEPROMWriteAnything?action=sourceblock&num=1)
The code works until the 11th line. It gives there the following error:
'lastThing' was not declared in this scope

Does anybody know how to fix this problem?

lastThing is neiher a global nor a local variable. It is the name of a member in the config_t structure. What do you want to do in the loop?

My program receives data from a mobile phone with bluetooth, and writes it to an OLED screen. I need the EEPROM to save the last sent thing, and at a reboot to write it on the screen.

EEPROMs have limited writes, if you write to it in a loop you will exhaust all your writes very quickly!

Lol. Putting that write in the loop is a quick way to exhaust your eeprom.

The 'current' version of the EEPROM library (which should be included with the IDE) has EEPROM.put, which is designed to write any variable type. As a bonus, it only writes if the data is different, so can use it repeatedly without wearing out your EEPROM (as much).

See https://www.arduino.cc/en/Tutorial/EEPROMPut

it will not write the content of the String object to EEPROM. the String object handles a pointer to a character array on the heap. but it contains only a pointer.

The proper syntax for referring to a struct member is [structName].[memberName]. Changing lastThing in lines 8 & 13 to savedValues.lastThing fixes the "undeclared" error.

it is better not to use String type at all and it can't be saved to EEPROM. You can save a copy of the internal c-string of the String with strcpy(savedValues.lastThing, readString.c_str());
#include <EEPROM.h>

#define ADDR 512

struct config_t {
  char lastThing[32];
  int lastNum;
} savedValues;

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

  EEPROM.get(ADDR, savedValues);
  Serial.println(savedValues.lastThing);
  Serial.println(savedValues.lastNum);
}

void loop() {
  if (Serial.available()) {
    String readString = Serial.readStringUntil('|');
    int n = Serial.parseInt();

    strncpy(savedValues.lastThing, readString.c_str(), sizeof(savedValues.lastThing));
    savedValues.lastNum = n;
    EEPROM.put(ADDR, savedValues);

    //clean rest of the input (crlf)
    byte b;
    while (Serial.readBytes(&b, 1) > 0);
  }
}

There are cases where dynamic allocation must be used. Personally I try to avoid it as hell, since these are microcontrollers and do not have plenty of memory, but in some cases you can't. Then you added a lot of assumptions to the code without highlighting. Do you know this project so well that you can assume that strings are separated by a pipe mark? Do you know that strings will never exceed 32 chars and you are so confident that you even don't check it? You are aware that if the user writes "This is a really wonderful day :)" you will have all sort of bad behaviors, right?

I replaced strcpy with strncpy. It is a test sketch for EEPROM, not a user friendly Serial input handling demo.

Very huge disclaimer: the code in this answer is untested, and moreover I never played with String objects (I don't like dynamic allocation on arduino). Consequently bugs are expected in this code. If you find any (for instance, the relocation does not work how I suppose, or the parameters should be passed in another way in the read function) please write in the comment so I can fix this
EDIT: Since there were complaints about this, I tested it and.. It works. The read and write functions work so, in the end, it appears that all the researches I did for this answer were complete and allowed me to correctly implement it

As pointed out, lastThing is not a variable, it is a field in the savedValues variable. So the correct syntax would be
lastThing=readString;

This said, your code won't work and has performance issues. First of all it uses the EEPROM.write method, which overwrites the value in eeprom thus lowering its life, and then you will save a pointer to a memory area (4 bytes), which is not the thing you want to save.
In my opinion, it is better to save it "manually":
// Write i in EEPROM, starting from address addr.
// Return the number of bytes written (2 if everything is ok)
uint16_t writeUInt16ToEeprom(uint16_t addr, uint16_t i)
{
    uint16_t currAddr = addr;

    // Only if there is enough space
    if ((currAddr + 2) <= E2END)
    {
        // Write the 2 bytes in eeprom
        EEPROM.update(currAddr++, i >> 8);
        EEPROM.update(currAddr++, i & 0xFF);
    }
    return (currAddr - addr);
}

// Write s in EEPROM, starting from address addr.
// Return the number of bytes written
uint16_t writeStringToEeprom(uint16_t addr, String s)
{
    uint16_t currAddr = addr;

    uint16_t len = s.length();

    // Only if there is enough space
    if ((currAddr + len + 2) <= E2END)
    {
        // Write the string length
        currAddr += writeUInt16ToEeprom(currAddr, len);

        // Write the string bytes
        for (uint16_t i = 0; i < len; i++)
            EEPROM.update(currAddr++, s.charAt(i));
    }

    return (currAddr - addr);
}

// Read i from EEPROM, starting from address addr.
// Return the number of bytes read (2 if everything is ok)
uint16_t readUInt16FromEeprom(uint16_t addr, uint16_t & i)
{
    uint16_t currAddr = addr;

    // Only if there is enough space
    if ((currAddr + 2) <= E2END)
    {
        i = EEPROM.read(currAddr++);
        i = i << 8 | EEPROM.read(currAddr++);
    }
    return (currAddr - addr);
}

// Read s from EEPROM, starting from address addr.
// Return the number of bytes read
// S should be already allocated when entering the function
uint16_t readStringFromEeprom(uint16_t addr, String & s)
{
    uint16_t currAddr = addr;

    uint16_t len = 0;
    s.remove(0);

    // Check if there is enough space for the length
    if ((currAddr + 2) <= E2END)
        currAddr += readUInt16FromEeprom(currAddr, len);

    // Check if there is enough space left for all the chars
    if ((currAddr + len) <= E2END)
    {
        s.reserve(len); // Should allocate only once, thus speeding up

        for (uint16_t i = 0; i < len; i++)
            s.concat((char)(EEPROM.read(currAddr++)));
    }
    else
        currAddr = addr;

    return (currAddr - addr);
}

String lastThing;

void setup(){
    readStringFromEeprom(ADDR, lastThing);
    Serial.println(lastThing);
}

String readString="asd";
void loop() {
    //...
    lastThing=readString;
    writeStringToEeprom(ADDR, lastThing);
}

Note: you should also check the values returned from the functions to check whether the writing or reading was successful.
In this case I did not use the struct, since in your example the struct is not used. If you really need it, because for instance you want to save also an int, you can do something like this:
struct config_t{
    String lastThing;
    uint16_t myIdx;
} savedValues;

uint16_t writeUInt16ToEeprom(uint16_t addr, uint16_t i)
...

uint16_t writeStringToEeprom(uint16_t addr, String s)
...

uint16_t readUInt16FromEeprom(uint16_t addr, uint16_t & i)
...

uint16_t readStringFromEeprom(uint16_t addr, String & s)
...

// Write s in EEPROM, starting from address addr.
// Return the number of bytes written
uint16_t writeStructToEeprom(uint16_t addr, struct config_t s)
{
    uint16_t currAddr = addr;
    currAddr += writeStringToEeprom(currAddr, s.lastThing);
    currAddr += writeUInt16ToEeprom(currAddr, s.myIdx);
    return (currAddr - addr);
}

// Read s from EEPROM, starting from address addr.
// Return the number of bytes read
// S should be already allocated when entering the function
uint16_t readStructFromEeprom(uint16_t addr, struct config_t s)
{
    uint16_t currAddr = addr;

    uint16_t readVal = readStringFromEeprom(currAddr, s.lastThing);
    if (readVal == 0)
        return 0;
    currAddr += readVal;

    uint16_t readVal = readUInt16FromEeprom(currAddr, s.myIdx);
    if (readVal == 0)
        return 0;
    currAddr += readVal;

    return (currAddr - addr);
}

void setup(){
    readStructFromEeprom(ADDR, savedValues);
    Serial.println(lastThing);
}

String readString="asd";
void loop() {
    //...
    savedValues.lastThing = readString;
    savedValues.myIdx = 22;
    writeStructToEeprom(ADDR, savedValues);
}

I think that the idea is pretty easy to understand. Basically you manually write a function for each type you want to write (e.g. writeUInt16ToEeprom), then use these "building blocks" to create complex functions (e.g. writeStructToEeprom). For items which do not have a fixed width (Strings) you first save the length, then the bytes. What I mean with "fixed width" is that you know at compile time the number of childs it has For instance, the struct has two "childs" (the string and the integer), while the string has an unknown number of childs (n characters).
You can write a template function for all the integers like this:
// Write i in EEPROM, starting from address addr.
// Return the number of bytes written
template <class T> uint16_t writeIntegerToEeprom(uint16_t addr, T i)
{
    uint16_t currAddr = addr;

    // Only if there is enough space
    if ((currAddr + sizeof(T)) <= E2END)
    {
        // Write the bytes in eeprom
        for (uint8_t idx = 0; idx < sizeof(T); idx++)
        {
            EEPROM.update(currAddr++, (8*(i >> (sizeof(T) - 1 - idx))) & 0xFF);
        }
    }
    return (currAddr - addr);
}

// Read i from EEPROM, starting from address addr.
// Return the number of bytes read
template <class T> uint16_t readUInt16FromEeprom(uint16_t addr, T & i)
{
    uint16_t currAddr = addr;

    // Only if there is enough space
    if ((currAddr + sizeof(T)) <= E2END)
    {
        i = 0;
        for (uint8_t idx = 0; idx < sizeof(T); idx++)
        {
            i = i << 8 | EEPROM.read(currAddr++);
        }
    }
    return (currAddr - addr);
}

You can use it for all the integer types, using it like the UInt16 variant above. Avoid using it for classes or structs, since in some cases (e.g. the struct with string example above) it may not save what you want

but that is in the EEPROIM library as put() and get() for any reference. https://github.com/arduino/ArduinoCore-avr/blob/master/libraries/EEPROM/src/EEPROM.h

@Juraj are you saying that EEPROM put and get will allow to put and get the struct with the String? I doubt that. You can use "put" instead of the very last template implementation, but I don't think the rest of the answer must change

@downvoter: can you please explain why the -1? I think that the answer is on topic with the question (not declaration of the item), and moreover addresses the main problem with the OP implementation, which is the fact that he wants to save a string but he isn't actually doing so with his code

I am the downvoter.  No, you can't write String with put(), but your solution is not elegant and not tested. And we should discourage use of String.

I posted my answer

@Juraj Can you suggest how I can make it more "elegant"? About the not tested, did you check my code? Does it work? And finally, about the strings, they are not the "evil", they are instruments. I agree that whenever possible their use should be discouraged (as I wrote, I never used them, so I guess how they work and made researches but I don't have first hand experience), but sometimes they must be used

"elegant" would be effective use of library functions. you propose to add redundant functions to the sketch

Let us continue this discussion in chat.


text:
Wake up a PC from an Uno
I want to wake up a PC via a USB-connected Arduino. When using a Pro Micro (Leonardo) I can do it, as its HID interface can wake up a PC. That is, in the Device Manager, under "Keyboards", the relevant HID device under "Power Management" has an "Allow this device to wake-up the PC" checkbox.

However, I need to use an Uno for this project. There's a hack (see link below) which flashes the ATMega16U2 on an Uno to act as a HID keyboard. It works fine, but this HID keyboard on a flashed Uno does NOT have the "Allow this device to wake up the PC" checkbox, i.e. I can't wake up my PC. I tried, the PC doesn't wake up. I know I can use an Ethernet shield on an Arduino to send a Wake up on LAN packet, but I don't want to add any shields, if I don't have to. Any advice how to do this?
EDIT: I was pointed to 2 libraries, NicoHood and LUFA (links below) to code a HID keyboard for the ATMega16U2 on an Arduino Uno. The problem is that acquainting myself with the subject and (either) library, would take several days, which is why I'd prefer to find an already-compiled simple HID device that does what I want. If I can't find one, I have a "dumb" solution: since the Leonardo can wake up a PC, I can hook it up to the PC, power the Uno (with my code) off the Leonardo, link one digital pin between the Uno and the Leonardo, so that the Uno can trigger a USB keystroke on the Leonardo. This is kludgy, since it uses the Leonardo just to send one USB keystroke to wake up the PC, but it would work.
LUFA
NicoHook Keyboard API
HoodLoader
Relevant links:
Arduino Uno as a USB HID Interface
Wake a touchscreen using a Pro Micro

I don't think it's that simple. I think the device driver has to have the wake-up ability coded in, i.e. be able to send out the relevant message

The HID library by NicoHood uses a special bootloader in the 16U2, https://github.com/NicoHood/HID It can send media keys and the power key.

Thanks. I'll try to get in touch with the author, as I'm not sure what the minimal required setup would be.

Try a different USB port.

Can you explain the reason why you need to use UNO?

I need to use a shield which only fits the Uno

Got it working: my Uno can now wake up a PC. I followed the HoodLoader wiki and I used the HID-Bridge sketches (below). It took about 2-3 hrs.
HoodLoader
HID-Bridge


text:
Can adjustable constant current/voltage source be made with Arduino?
I would like to create a 18650 battery automatic management system that can handle and restore used up cells using solar panels for power. To do that I need to create adjustable constant current source that will limit the current/voltage going into the cell/cells to a small enough value.
Since there are more features I would like to implement (like checking cell capacity) I would love to use Arduino with least amount of components as possible to keep the cost down.
My first question is: Will Arduino be fast enough to control a MOSFET that will pump magic pixies into a capacitor to achieve steady value of voltage on said capacitor?
The pseudocode for logic I'm proposing is simpe:

Use ADC to check voltage on the capacitor (or a very small value power resistor when working as current source)
Calculate required voltage adjustment
Use AnalogWrite to set new PWM value into internal PWM controller.

Second question: PWM causes a lot of "switching" in the MOSFET. When MOSFET is not saturated state it's resistance is high and a lot of power is wasted as heat. Would it be possible NOT to use PWM to control it, but instead to turn it OFF or ON each cycle to minimize power loss? Since the batteries have some internal resistance voltage variation of +-20% should be acceptable.

When you have to ask, don't do it. The risk of damaging the battery is too high. There are dedicated chips to charge batteries. I suggest to buy a charger from a well known brand.

The dedicated chips work great with new and shiny 18650. The used up ones have special needs. At this moment I'm restoring them by hand one by one. For example first hour of charging cannot exceed 50mA if voltage of 18650 was initially less than 1,5V. I was able to get 1500mAh (out of nominal 2500mAh) from cell discharged to 0,5V taken out of old laptop. I would prefer to delegate this task to Arduino because it takes a lot of time, and checking the cell temperature every 10 minutes is tedious.

There are dedicated charge ICs that will trickle charge if the voltage is too low. Check the datasheet. I’d use a dedicated chip for charging. And use an Arduino to measure capacity. Or buy a charger-doctor from China that measures the mAh for you.

I already have all the stuff you can buy from china, but I had to modify most of it because it tends to overcurrent (it starte with 100mA and not 50mA) and overvoltage (charges up to 4.26V) batteries. I'm trying to design a universal (and cheap) solar powered "used battery management system" that might end up being a KIT at some point. I would like to prototype it with Arduino before I rewrite everything for native execution in ATtiny/ATmega or something similar. I tested that Arduino Bootloader makes ATmegas run much slower in some cases.

you can slow down either side's voltage variations with a capacitor. you can pick one large enough to guarantee you plenty of time to read the ADC.  2. you can safely assume MOSFETs switch instantly for your practical application, which at 5v is pretty close to true for logic-level FETs and sub-1amp loads. secondly, the internal resistance is so small anyway (milliohms) that it takes several amps to even slightly warm them.

You are basically describing (if you add an inductor and a diode into the mix) a simple switching regulator.  That is, at its simplist, a PWM signal, some smoothing (inductor, diode, capacitor), and feedback.
Use the Arduino's PWM to switch a P-channel MOSFET in the voltage supply. That switched supply is then fed through an inductor, and then smoothed with a capacitor:

simulate this circuit – Schematic created using CircuitLab
M1 does the switching of the power to charge the rest of the circuit.  L1 + C1 smooths the PWM out giving a constant smooth (ish) voltage. D1 completes the circuit between L1 and C1 in one direction only keeping the charge in the right part of the circuit.
R1 keeps the MOSFET turned off when not being driven.
R2 is a very small "shunt" resistor (maybe 0.1Ω for example).
The size of C1 and L1 are determined by the switching frequency of your PWM and the current demands of the circuit.  The higher your switching frequency the smaller your inductor can be, The higher your current demands the larger C1 needs to be.
Reading A1 gives the output voltage of the circuit, so you can adjust the PWM (using PID would be good) to get a specific voltage.
Reading A0 and A1 and subtracting one from another gives you the voltage drop across R2. From that, you can calculate the current through R2 using Ohm's Law. You can then use that to adjust the PWM to give you a specific current.
Of course, you can't do both at once. You either have a constant current (during the first charging phase to bring the cell voltage up to 4.2V), and then switch to constant voltage until the current drops to around 0.3C.  For dead cells, an initial constant current phase of (IIRC) 0.1C can recover the cell.
Some important notes about lithium cells:

They explode (just ask Samsung), so take care. It can be good to do your experimenting with the cell contained within a fireproof container.
Lithium Ion and Lithium Polymer cells don't like being over-discharged, but as long as they haven't been reverse charged they can generally be recovered.
Cells that are used in a series pack and haven't been charged with a proper balancing charger may well have been reverse charged if the pack has "died".

The reverse charge thing is what actually kills a Lithium cell.  Basically, no two cells will have exactly the same capacity. If you have, say, three cells in series and you discharge the whole pack to below the recommended minimum, once cell will have less charge than the others. If that cell hits zero the current from the other cells will start flowing backwards through it, and that backward current causes copper crystals to deposit on the electrolyte layer between the electrodes. Those pierce the electrolyte layer and short the two electrodes together, and at that point the cell is dead. No amount of recovery charging will get it back, it's physically damaged.
So in summary:

A single cell that has been over-discharged by itself will generally be recoverable.
A series pack of cells that has been over-discharged may well have physically damaged one of the cells in the pack through reverse charge flow.

Will Arduino be fast enough to control a MOSFET that will pump magic pixies into a capacitor to achieve steady value of voltage on said capacitor?

Sure. You should pre-condition your power so it is always within a tolerable limit (i.e., feed your solar panel power through a suitable 5V buck regulator to give a clean 5V supply). There will always be some latency in the circuit due to how long the inductor "resists" changes in the voltage. A typical Arduino takes ~100µs to sample an ADC. In this kind of environment, that time is negligible since it's generally much faster than a single period of PWM. You can't respond faster than one period of PWM anyway.

When MOSFET is not saturated state it's resistance is high and a lot of power is wasted as heat. Would it be possible NOT to use PWM to control it, but instead to turn it OFF or ON each cycle to minimize power loss?

That's what PWM does. It's ON or OFF. On at the start of a cycle, then off part way through.  Yes, there is a brief period twice per cycle while it does the switching, but that will be minimal compared to the on and off periods. The losses from that switching will be negligible compared to, say, running a MOSFET as an adjustable resistance controlled from an op-amp with feedback from a current shunt (i.e., a linear regulator).

Thanks for the general answer, but you didn't address my questions. The solar panel provides a "random" voltage anywhere from 6V to 48V and my question is if the Arduino at least has the chance respond fast enough to dynamic changes. ADC measurement takes time, logic takes time, changes to PWM take time and in that time voltage on regulator output can escalate making a lovely red lithium colored fire. Physically broken cells can be easily detected. They don't decrease current in last phase of charging (and heat up) or they have high self discharge rate. I use old laptop batteries for cells.

@FilipFranik Since you don't specify any specific Arduino, yes, there are "Arduinos" that are plenty fast enough. Probably even a simple Uno would be fast enough. Especially if you first pass your solar cell power though a normal switching regulator to give a steady 5V - that way there won't be any surprises. Also the indictor works two ways: Not only does it try to keep the voltage up when the fet switches off, it also tries to keep it down when the fet switches on. You don't get instant rises on the output because of spikes on the input.


text:
Serial receiver (Arduino Micro ATmega32U4) in bad state
I have configured two Arduino Micros as a pair of multiplexer/demultiplexers communicating via Tx and Rx.
Everything works great except for one little thing. If I reset the sender (multiplexer) the receiver (demultiplexer) goes into a bad state resulting in random low and high outputs.
Resetting the receiver brings it back to a normal state but I am hoping someone might have a better solution. Using the serial monitor I noticed that during the reset process on the sender there are some seemingly random bits being transmitted toward the end. Not sure if this has anything to do with it.
The code for the sender is:
byte PINBold;
byte PINDold;
byte PINFold;

byte PBmask = B11111110;
byte PDmask = B11010011;
byte PFmask = B11110011;

void setup() {
  Serial1.begin(3704400); // Speed
  DDRB = DDRB & B00000001; // Sets pins to digital input: 11,10,9,8,MI,MO,SCK
  DDRD = DDRD & B00101100; // Sets pins to digital input: 2,3,4,6,12
  DDRF = DDRF & B00001100; // Sets pins to digital input: A0,A1,A2,A3,A4,A5
}

void loop() {
  if (((PINB & PBmask) != PINBold) |((PIND & PDmask) != PINDold) | ((PINF & PFmask) != PINFold)) {
    Serial1.write(PINB);
    Serial1.write(PIND);
    Serial1.write(PINF);

    PINBold = PINB & PBmask;
    PINDold = PIND & PDmask;
    PINFold = PINF & PFmask;
  }
}

The code fore the receiver is:
void setup() {
Serial1.begin(3704400); // Speed
DDRB = DDRB | B11111110; // Sets pins to digital output: 8,9,10,11,MI,MO,SCK
DDRD = DDRD | B11010011; // Sets pins to digital output: 2,3,4,6,12
DDRF = DDRF | B11110011; // Sets pins to digital output: A0,A1,A2,A3,A4,A5

PORTB = PORTB | B11111110;
PORTD = PORTD | B11010011;
PORTF = PORTF | B11110011;
}

void loop() {
if (Serial1.available() > 2) {
PORTB = Serial1.read();
PORTD = Serial1.read();
PORTF = Serial1.read();
}
}

There is a bug in your code; in line ████ you should have written ████████ rather than ████████. Try changing it and it will work

Make a protocol for the serial communcation, with a start byte, a checksum and a trailer byte. During reset the tx pin is set as input, thus it is high impedance and will pick up noise. Did you forget a pullup resistor?

@frarugi87 edited to include code.

@Jot I used pull down resistors, should still be okay correct?

@Michael there are some issues in your code; let me write a more complete answer to fix them

@Michael just one question: do you need a full 3*8 byte transfer or you need only 7+5+6 bytes? I mean, you have excluded some pins from the three ports..

The tx signal is idle high. The first low pulse is the startbit. With a pulldown resistor you create a startbit as soon as you reset the arduino. Use a pullup resistor.

@frarugi87 I am only using the pins listed as inputs and I need it to send whenever any pin has changed state.

Without a start byte, a checksum and a trailer byte, at least use the start byte as a sync byte. When you would send the masked value instead of the actual port value, is it possible to send 0xff or 0x01 as sync byte? I think it is possible.

@Jot Switching to a pull up resistor seems to make it work correctly!! I was unsuccessful with a sync byte earlier today, I'll have to play with that some more.

@frarugi87 I've edited my post to include my receiver code. Admittedly this is the extent of my abilities. I tried your codes modifying the receiver to include PORTX = receivedPortX however the receiver is not doing anything. All pins are high. My code works but you have made some great points and some type of protocol would be great.

@Michael I included your code in the receiver code, and added one condition I did not think of previously (when you turn on the receiver, the signal is not sent; now it is). Please tell me whether this works or not; if it doesn't, just tell me and I'll try to test it

@frarugi87 There was no change with the new code.

@Michael sorry, there was a bug. in the receiver, inside the switch, the test with serial available should be >= 3 rather than >3; fixed now; I tested it on two UNOs, using only four bits of PORTB (but now it should work even in your case). Test the two codes

@frarugi87 hmm, Still no change.

@Michael Still one more bug fixed: the Serial1 was Serial in some lines (when sending the 'H' char and when receiving the bytes). Please check with the code now and see if it works (fingers crossed)

@frarugi87 That did it! It appears to function correctly! I will test it thoroughly and report back sometime later. I don't mind telling you this is a piece of equipment in a really cool physics experiment!

@Michael Glad that worked :) As I wrote, I was not able to test it, and so the bugs arose. But in the end we managed to have it working ;)

Ok, there are some issues in your code. First of all, are you sure that a baudrate  of 3.7Mbps is what you need? Can't you go a bit slower?
If you are dealing with mechanical parts (e.g. buttons), then a refresh rate of 100Hz cannot be noticed; to send 3 bytes you need 30 bits, and at 9600 bit/s this means 320 Hz of frequency. Reducing the speed increases the rejection to noise too, so I'd go with a lower speed (even a 38.4kbps is fine).
Then you are reading the PINx registers too many times, which can lead to inconsistency. What happens if the value changes after the if but before the updating of the value? It's better to store it in a variable.
These, however, are not the root cause of your problem. The main issue, as anticipated by Jot, is that you are not using a protocol to synchronize the two elements. This means that at the bootup the receiver does not know if it is at the beginning of the "frame" or in the middle. Moreover start conditions when the sender is not online are not ignored.
So a "protocol" must be agreed between the two. The simplest one I can think of revolves around the fact that you can reserve a bit for the flow control.
Looking at your port masks, I can see that if we split the PINB values in the two nibbles and then move the lowest one one bit to the left, we get that bit 3 is never used for transmitting a pin data:
PINB 76543210 -> 7654x321 (pin 0 was not used)

consequently we use this as a control bit. It has value 1 for the first bit in the frame, and 0 otherwise. On the receiver side, you look for a byte with this bit set, then record also the other two, then check if the other two have a 0 in this position and, if confirmed, you have your frame.
This solution has the highest throughput, but may be a bit fragile when some noise is present (false start of frames, possibly).
For this reason I suggest you to add another byte to the packet, thus having to transmit four bytes. Again, the first one has the bit set in position 3, and the other have zero. But in this case the first byte has a predefined value, and consequently the receiver has just to look for this specific value (and the robustness is increased.
Ok people, I can hear your question. Where is the code? Well, here it is. For the sender, you have to perform a bit of manipulation on the bytes to be sent. I chose the hex value 0x5A because it has a lot of transitions (difficult to replicate from a noise) and it has a 1 bit in position 3. I also changed the things said at the beginning (baud rate and reading PINx only once); feel free to revert the changes if you have different needs. Moreover I initialized the old variables, and I set the direction of the pins based on the mask rather than having it done manually (easier to maintain).
EDIT: I added the possibility to get the current status by sending a char on the serial interface (useful when the receiver boots up)
byte PINBold;
byte PINDold;
byte PINFold;

const byte PBmask = B11111110;
const byte PDmask = B11010011;
const byte PFmask = B11110011;

const byte StartOfFrame = 0x5A; // bit 3 is always '1'

void setup()
{
    Serial1.begin(38400); // Speed
    DDRB = DDRB & (~PBmask); // Sets pins to digital input: 11,10,9,8,MI,MO,SCK
    DDRD = DDRD & (~PDmask); // Sets pins to digital input: 2,3,4,6,12
    DDRF = DDRF & (~PFmask); // Sets pins to digital input: A0,A1,A2,A3,A4,A5

    PINBold = ~PBmask; // Force a 1 in a forbidden position -> force a sending at first round
    PINDold = ~PDmask;
    PINFold = ~PFmask;
}

void loop() {
    byte currPINB = PINB & PBmask;
    byte currPIND = PIND & PDmask;
    byte currPINF = PINF & PFmask;

    bool shouldSendData = false;

    if ((currPINB != PINBold) || (currPIND != PINDold) || (currPINF != PINFold))
    {
        PINBold = currPINB;
        PINDold = currPIND;
        PINFold = currPINF;
        shouldSendData = true;
    }

    while (Serial1.available())
    {
        Serial1.read();
        shouldSendData = true;
    }

    if (shouldSendData)
    {
        Serial1.write(StartOfFrame);
        Serial1.write((currPINB & 0xF0) | ((currPINB >> 1) & 0x07)); // send currPINB 7654_321, where _ is a '0'
        Serial1.write(currPIND); // bit 3 is always '0'
        Serial1.write(currPINF); // bit 3 is always '0'
    }
}

On the receiver side, what you need is to wait for the start of frame, then you have your data. I prefer to implement it as a very small state machine. I also added a bonus timeout feature to exit from the payload state after 10ms of inactivity.
EDIT: Added the sending of a char at the beginning, to trigger a resending of the status from the master (if available). Included also the functional code from the question, since the OP added the receiver
const byte StartOfFrame = 0x5A; // bit 3 is always '1'

const byte PBmask = B11111110;
const byte PDmask = B11010011;
const byte PFmask = B11110011;

// State machine states
const byte SM_WaitingForSOF = 1;
const byte SM_WaitingForPayload = 2;

byte SM_CurrentState;

bool receivedData;
byte receivedPortB;
byte receivedPortD;
byte receivedPortF;

uint8_t startOfTransmissionMillis;
const byte transmissionTimeout_ms = 10;

void setup()
{
    Serial1.begin(38400); // Speed

    DDRB = DDRB | PBmask; // Sets pins to digital output: 8,9,10,11,MI,MO,SCK
    DDRD = DDRD | PDmask; // Sets pins to digital output: 2,3,4,6,12
    DDRF = DDRF | PFmask; // Sets pins to digital output: A0,A1,A2,A3,A4,A5

    SM_CurrentState = SM_WaitingForSOF;
    receivedData = false;
    receivedPortB = 0;
    receivedPortD = 0;
    receivedPortF = 0;

    Serial1.write('H'); // Any byte is ok; it is used to trigger a sending of the status
}

void loop() {
    receivedData = false;

    switch (SM_CurrentState)
    {
        case SM_WaitingForSOF:
            while (Serial1.available() > 0) // can also be a "if"
            {
                if (Serial1.read() == StartOfFrame)
                {
                    SM_CurrentState = SM_WaitingForPayload;
                    startOfTransmissionMillis = (uint8_t)millis();
                    break;
                }
            }
            break;
        case SM_WaitingForPayload:
            if (Serial1.available() >= 3)
            {
                receivedPortB = Serial1.read();
                receivedPortD = Serial1.read();
                receivedPortF = Serial1.read();

                if (((receivedPortB & 0x08) | (receivedPortD & 0x08) | (receivedPortF & 0x08)) == 0)
                { // All the payload bits have '0' as bit 3, so communication was ok
                    receivedData = true;
                }

                SM_CurrentState = SM_WaitingForSOF;
            }
            else if ((((uint8_t)millis()) - startOfTransmissionMillis) > transmissionTimeout_ms)
            {
                SM_CurrentState = SM_WaitingForSOF;
            }
            break;
        default:
            SM_CurrentState = SM_WaitingForSOF;
            break;
    }

    if (receivedData)
    {
        PORTB = (PORTB & (~PBmask)) | (receivedPortB & 0xF0) | ((receivedPortB & 0x07) << 1);
        PORTD = (PORTD & (~PDmask)) | receivedPortD;
        PORTF = (PORTF & (~PFmask)) | receivedPortF;
    }
  }
}

Beware: untested code. I'm confident that no major bugs are present, but some tweaking may be necessary


text:
ESP8266 GET request code -1
I've read several other posts but I still couldn't solve the issue. I'm trying to connect to a website which is HTTP (not HTTPS) but I always get code -1 as response. If I open the link in the browser it works well. Not sure what I am missing? Here's my full code:
#include <ESP8266HTTPClient.h>
#include <esp8266wifi.h>

const char* ssid = "";
const char* password = "";

void setup() {
  Serial.begin(115200);
  WiFi.begin(ssid, password);

  while (WiFi.status() != WL_CONNECTED) {

    delay(1000);
    Serial.print("Connecting..");

  }
}

void loop() {

  if (WiFi.status() == WL_CONNECTED) {
    HTTPClient http;
    http.begin("www.francescosoave.com/blind/getTime.php");
    http.addHeader("Content-Type", "text/html");
    int httpCode = http.GET();

    Serial.print("HTTP CODE: ");
    Serial.println(httpCode);

    if(httpCode > 0){
      String payload = http.getString();
      Serial.print("PAYLOAD: ");
      Serial.println(payload);
    }

    http.end();
  }

  delay(2000);
}

You omitted the protocol part of the url. The HttpClient implementation requires it.
Use http.begin("http://www.francescosoave.com/blind/getTime.php");
Do not use Content-type header. You do not send any content.
Turn-on debug in Tools menu. Set Debug Port to Serial and Debug Level to HTTP_CLIENT to see the error messages.

to add an additional point to @juraj answer these are the HTTP code for various errors written in ESP8266HTTPClient.h
#define HTTPCLIENT_DEFAULT_TCP_TIMEOUT (5000)

/// HTTP client errors
#define HTTPC_ERROR_CONNECTION_FAILED   (-1)
#define HTTPC_ERROR_SEND_HEADER_FAILED  (-2)
#define HTTPC_ERROR_SEND_PAYLOAD_FAILED (-3)
#define HTTPC_ERROR_NOT_CONNECTED       (-4)
#define HTTPC_ERROR_CONNECTION_LOST     (-5)
#define HTTPC_ERROR_NO_STREAM           (-6)
#define HTTPC_ERROR_NO_HTTP_SERVER      (-7)
#define HTTPC_ERROR_TOO_LESS_RAM        (-8)
#define HTTPC_ERROR_ENCODING            (-9)
#define HTTPC_ERROR_STREAM_WRITE        (-10)
#define HTTPC_ERROR_READ_TIMEOUT        (-11)

-1 usually indicate bad URL or bad wifi connection

-1 means that connect failed. in this case because of the wrong port used because of the missing protocol part


text:
Controlling servo via serial port without any delay
I have such code:
void setup() {
Serial.begin(9600);
}
void loop() {

}
void serialEvent() {
  while (Serial.available()) {
   Serial.println(Serial.readString());
  }
  }

When I send there something - it's sent with a delay (1-2 seconds). How can I make it so that Serial.readString() is carried out without delay?
Please, help me)

Don't use readString - it has a 1 second timeout. https://majenko.co.uk/blog/reading-serial-arduino

@Majenko, hmm... In serial port i got such string: engine:100b. How i can got key (engine) and value (100)?

https://majenko.co.uk/blog/splitting-text-c

readString() uses a 1 second timeout to determine when the end of a string occurs. It's not suitable for anything - I have no clue why they included it in the API.
Instead you need to read the data a character at a time (as and when characters become available) and use a suitable string termination indicator to trigger processing of the string.
A common termination indicator is \n (line feed) or \r\n (carriage-return followed by line feed).
Read each character when it arrives on the serial port and add it to a string (not a String, a string - a NULL-terminated array of char). Only when you see \n arrive should you then start examining the string to see what you have received, and act on it accordingly.
I have a blog post here that details reading from serial, and another one here that shows you some techniques for splitting up strings (strtok() is a useful function). There's also plenty of other questions here about splitting strings with answers detailing similar methods.


text:
How do I pull chip select pin up and down, when I have CAN shield and Newhaven Display 4.3CTP-SHIELD-N share the same chip select pin(10)?
I am currently working on an Arduino project, which must be able to listen to the data going through CAN bus and display it on the Touchscreen LCD Newhaven Display 4.3CTP-SHIELD-N.
Problem is that Sparkfun CAN shield and the LCD shield share the same chip select (CS/SS) pin 10. I've tried changing the chip select of the CAN shield by changing values in library headers, but it did not work and now I think that I should pull pin 10 low, when executing CAN code, then pull it up for the CAN shield. Afterwards, do the same for the LCD shield, but I do not know how to write the code for that. Is this the right way to think about the problem or am I missing something?
At this point, I am very confused because some people say that, if two shields have same chip select pin, it's impossible to stack them. Others claim that they succeeded in stacking two shields like that.
What other methods are there for stacking two shields with the same chip select pin?
I am using this CAN library: https://github.com/sandeepmistry/arduino-CAN/blob/master/API.md
This LCD library: https://github.com/NewhavenDisplay/FTDI_FT801

You will have to use a different chip select pin for one of the shields.  You should do it to the display shield since that goes on top.

Change the code to use a different chip select pin for the display shield
Break or cut off pin 10 from the display shield, and solder a wire from where pin 10 was to your newly chosen chip select pin.

Would it still work, if I didn't cut/break the pin 10 of the display, but connected it to another pin via a male-to-female jumper cable?

Sure, but it could be awkward. Just keep it away from the other shield's pin 10.


text:
Arduino MKR WIFI 1010: WiFi101 shield: NOT PRESENT
A few days ago I received my MKR WIFI 1010 including MKR2UNO Board. Vin Connected via power plug, and USB to PC connected as well. The Blink example works fine. Or any example excluding WIFI.
I tried to use examples in "Examples>WIFI101" like Firmware Version or Scan Networks. It always comes back with "WiFi101 shield: NOT PRESENT"
I even attempted to tun "Tools>FirmwareUpdater" By testing the connection, it comes back with "Programmer not responding". I read somewhere that a double-tap on the reset button might help. After doing this and a click on "refresh-list", I see two ports displayed. A click on the new port and "Test connection" Same result "Programmer not responding".
On the MKR 1010 I see three LED's on: They are labeled "ON", "L" and "CHRG" which is slow flashing as well.
I seem not to be able find tutorials or any help really pertaining to MKR wifi 1010. Since this board is different from MKR WIFI 1000, the examples there are not helping.
I also cant find any layout and explanation pf the on-board LED's. Very frustrating!
I hope, any of you can give me some help.
Thanks a lot!

The right WiFi library for the MKR1010 is WiFiNINA. You can install it in Library Manager.
the schema of the board is here
from variant.h
// LEDs
// ----
#define PIN_LED     (6u)
#define LED_BUILTIN PIN_LED

you can get support from developers on Arduino forum

Thanks for the fast reply. However, running an example from "Examples>WifiNINA>ScanNetworks" produces only "Communication with WiFi module failed!" error. What now??? –

official support https://forum.arduino.cc/index.php?board=121.0

The WiFi101 is a shield for the Uno using the ATWINC1500 module.
The MKR1010 is a complete board with an ESP32-based module.
The two are completely different. You can't use the library for one on the other.
You need the WiFiNINA.h library which is available in the library manager, or from Github here.

the board is not in beta boards, but in 1.6.19. the WiFiNina library is in Library Manager

@Juraj You changed your mind then, and deleted your comment?

:-) yes. do not trust anyone. I was on a phone. I am looking into it deeper now on a computer

the NINA module (ESP32) is connected over SPI. the WiFiNina library uses SPI. the libraries are not so different. the WiFi1010 later renamed to WiFiNina is not so big rewrite of WiFi101.

Thanks for the fast reply. However, running an example from "Examples>WifiNINA>ScanNetworks" produces only "Communication with WiFi module failed!" error. What now???

I would appreciate a working example, so far everything fails

@Majenko, it turned out on arduino forum, that he got a MKR1000, not MKR1010

@Juraj D'oh! ...