Can I share the VCC (5V) on my Arduino Pro mini with multiple modules?

Yes, you can do that as long as the total current draw of the modules you attach to VCC doesn't exceed the on-board regulator maximum current output.

The Arduino Pro Mini has a MIC5205 regulator capable of delivering up to 150 mA, which is quite low if you plan to attach many modules to its output. So you should look through your modules datasheets and find out the total current draw, including the Pro Mini board itself, and check that against the 150 mA limit.

According to the HC-SR04 datasheet, each module draws 15 mA. The Arduino Pro Mini itself draws about about 20 mA. The BLE module peak current consumption is 12.5 mA at active RX and 11 mA at active TX, so lets say 25 mA peak current draw for the BLE module.

Everything adds up to a worst case 105 mA peak current draw, within the maximum 150 mA limit. So it should be fine, but I would avoid connecting much more modules to that VCC rail.

ADDED according to your additional question:

If you run out of digital I/O pins, you can use the analog pins as digital pins if needed.

Additional note (thanks go to @jwpat7 for pointing this out in the comments):

However, this is true only of A0–A5 on most Uno and Nano Micro Arduinos, and not true of A6, A7 (except on -PB MCU models like ATmega168PB and ATmega328PB, where A6, A7 can be used as digital pins).


The AVR implementation of sscanf() does not support parsing floating point numbers, thus you only get zeros out of it. You can't use the %f specifier with it. You need to convert these numbers by yourself with functions like atof() or similar.
Splitting a string into parts can be done many ways. You could use sscanf() to split up the string parts and then use something like atof() to actually convert to float. Or you use strtok() for splitting (see my answer to this question). Or you use one of the many other options, that you get, when googling for something like "Arduino split string" or "Arduino split c string".
Note: Using the String class in Arduino is easy for beginners, but not a good practice (dynamic allocation, heap fragmentation). Look at Majenkos blog for more information about that. Since you already used a function for C-strings, I would suggest moving completely to C-strings (which are basically only an array of char).


How can I power an Arduino in a 3-phase environment?

The very short answer is that the Arduino board itself is designed to be powered by low-voltage DC (but you almost certainly already know this). So what you're really asking, I think, is "can you use the mains power supply that converts mains AC to DC on a three-phase supply?"

The answer to that is a guarded yes. You will need to confirm that you are connecting to a single phase (basically what you were doing in testing) and that the voltage is appropriate for your power adapter.

The abridged version of the gory details follows…

Three-phase supplies are almost always used for motor or other power applications – for a low power device like an Arduino (or even lighting or small appliances) you don't typically need three-phase. What is usually done is to take the power supply for those devices either from phase-to-neutral or phase-to-phase – depending on the configuration of the three-phase supply.

Wikipedia has an article on three-phase power that explains the common connection schemes (Y or star where the three phases are wired to a common point, and delta where they are wired in a triangle). What is significant is that you will typically get a high and a low voltage depending on how you connect to a three-phase system. For example in the US a common Y three-phase service will give you 120 V phase-to-neutral and 208 V phase-to-phase.

A true 3-phase (as in needs to connect to all three phases) low-voltage power supply will probably be quite expensive. But you also don't need one. Unless you are building an "industrial" device all you need is a "normal" low-voltage power supply that is designed for the voltage that you'll be connecting it to.

All you need to do is to confirm the voltage that you'll be using and check that your power supply is rated for it. Many low voltage supplies are designed to be "universal" and you'll see a rating like 100-240 V, 50-60 Hz. That's likely to work on most three-phase supplies as long as the connection isn't phase-to-phase in a part of the world where the high voltage is in the 400 V range.


Arduino read PWM duty cycle value with input (analog / digital)

The code shown in my answer to question 18183, “Read RC receiver channels using Interrupt instead of PulseIn”. That answer has code to read four channels of RC PWM.  It can easily be adapted to work with eight channels.  It has an ISR that runs when selected pins change.  It sorts out which channel(s) changed, and stores the value of micros() at each change.

Also see my answer to question 19106, “Can external interrupts be OR'd together on the '328 (Uno)?”  That answer includes a sketch for generating appropriate ISR code.  My answer to question 32572, “How to detect the direction of a rotary encoder?”, shows another instance.

Digital input, as used in the code mentioned above, takes under  a microsecond ten microseconds in the ISR.  As noted in dannyf's comment, unrolling the for loop and (where possible) using constants instead of variables can reduce the in-ISR time to 3.4 μs.  Note, ISR entry and exit still add several microseconds.

10-bit analog input, on the other hand, will take around 104 microseconds per reading, a time comparable to some of the pulse widths you'll be measuring.  So it isn't fast enough.  If degraded ADC accuracy is acceptable, decreasing the ADC-clock scale factor as explained in a webpage at microsmart.co.za can get AD conversion time down to 20 μs.  This is around three times as long as digital input takes, so rather slow.


What do I do with the potentiometer on Adafruit RGB LCD

The potentiometer is for setting the contrast level of the LCD. The Shield Kit shown also comes with a pot (the one with the orange face). Assembled it should look like this:

Notice the pot in the lower right corner to the right of the microcontroller ic and above the reset button.


what is the right way to parse JSON to Arduino?

Assuming that String response will contain the json {"light": "off"} and your program is ready to use the ArduinoJson library (#include <ArduinoJson.h> on top), a simple solution could be:

Step1 - declare and initialize StaticJsonBuffer object.

StaticJsonBuffer<80> jsonBuffer;

Step2 - deserialize the json from response.

JsonObject& root = jsonBuffer.parseObject(response);

Step3 - if the deserialization doesn't succeed, warn and break,

if (!root.success())
{
  Serial.print("parseObject(");
  Serial.print(response);
  Serial.println(") failed");
  break;
}

Step4 - otherwise, use json object to get the LED_Control.

  Is the json will really contain {"light": "onn"} or is a typo ?

String LED_Control = root["light"];

if (LED_Control == "onn") {  // 'on' or 'onn' ??
    digitalWrite(pin, HIGH);
    Serial.println("LED ON");
}
else if (LED_Control == "off"){
    digitalWrite(pin, LOW);
    Serial.println("led OFF");
}


In the future, please detail your attempts at solving the problem so far so we can help you better.

Approach the issue as methodically as possible. I don't know how familiar you are with electronics, so please excuse me if you think some of these questions are basic:

Ensure that the servo motor works first without any other motors or
sensors connected to the Arduino Sensor Shield (have you used this servo motor before?)
Ensure that your GVS wiring is in the correct order. Servos come with a 3 way socket that plug straight onto the Sensor Shield: G goes to the Brown or Black wire, V goes to the (middle) Red wire, S goes to the Orange wire. The good news is as the +5V is in the middle, things will not blow up if you put the 3-pin plug on the wrong way. The servo just will not work until you plug it in correctly.
Is the Arduino Sensor shield working correctly. Does the LED pin work? Do other signals sent from the board work?
Remember that servo motors work differently to normal DC motors. You need to use Pulse Width Modulation to set the position. If you have never done this before, you will find the Arduino Servo Motors page useful. Also, you will get some excellent understanding and code from this Adafruit page. It is for a different Arduino shield, but the principles are the same.


Controlling a 240v AC high current relay

Use 1 relay, more precisely a DPST (Double pole, single throw) type. You'll only need 1 signal to drive both, and be sure that both lines are switched off. Electrical installation regulations require double throw relays/switches for certain applications, e.g. in wet rooms like bathrooms.

Note that relays are more delicate devices than they appear to be. A 16A relay may not always be suitable for switching 16A. They have to be derated according to their type of load. And that is almost everything. Not only for capacitive or inductive loads you'll have to limit the current to a fraction of the rated 16A, but even for incandescent lighting (due to the high current peak when switching on). See the manufacturer's datasheet or application documents for the amount of derating.


You're not telling it how big your stack should be, and it defaults to 0 entries, which means nothing gets stored.

class Stack
{
private:
    int *p;
    int top,length;

public:
    Stack(int = 0);  <<== CONSTRUCTOR - DEFAULT SIZE IS 0
    ~Stack();

    void push(int);
    int pop();
    void display();
};

When you make your Stack object you must give it a size for the number of entries in the stack:

Stack stack(4);


How to know which Arduino to choose: Nano, Micro or Pro Micro?

I'm currently using inexpensive Arduino Nano boards running GRBL for a couple of little CNC machines.  The version I have uses an ATmega328 running at 5V and they work very well.

They may be available with 3.3V regulator instead of 5V - I don't know and I preferred to have 5V anyway.

The nano boards that I have look to be a complete Arduino: one side of the board has the ATmega and voltage regulator, the other side of the board has the USB interface chip and some LEDs.

You can purchase Chinese-made nano boards very inexpensively.  Look on eBay for sellers offering free International shipping.


Can an Arduino (Leonardo) be recognized via Bluetooth as a mouse/keyboard?

If I buy something like the HC-05 how would the chip report itself?

As an SPP. I.e., a serial port.

  How is the bluetooth stack handled with regards to identification and authentication?

By the firmware on the HC-05

  Does it somehow copy the usb mouse/keyboard setup?

No.

You need a USB device that can emulate a keyboard. That's not the HC-05. The host microcontroller has absolutely nothing to do with what capabilities the bluetooth interface has.


How to pass a static const (progmem) array to a function

The problem is, when you call sizeof(*phrase), what is returned is 1, the size of the uint8_t array element, the result of your pointer de-reference. On the other hand, if you call sizeof(phrase) inside the function, you get the size of the pointer itself and not the size of the array, as you might expect. When you pass the array to the function via a pointer, the function has no idea if you passed the start of an array to it or merely a pointer to some uint8_t variable, so it can't know what the size is; context has been lost.

Instead, you should call sizeof(phrase) in the same scope where the array was declared and initialized and pass the result to the function, which can then use this value in the for loop.

static const uint8_t PROGMEM heybuddy[] = {
  pPA5, pHH1, pEY, pPA5,
  pBB2, pAX, pDD2, pIY, pPA5,pPA5,pPA5,
};

size_t SIZE = sizeof(heybuddy);  // this is ok since each element = 1 byte

sayPhrase(phrase, SIZE);

The function definition should be:

void sayPhrase(const uint8_t *phrase, size_t size){
  int open = 0;
  for (size_t i=0; i < size; i++){

      if(pgm_read_byte(phrase) != 4 && open == 0){
          Serial.println("mouth open");
          open = 1;
      } else if(pgm_read_byte(phrase) == 4 && open == 1){
         Serial.println("mouth closed");
         open = 0;
      }
      say(pgm_read_byte(phrase+i));
    }
}


Interrupt is activated as soon as I insert a jumper wire into the port

Connect both Pin2 and Pin3 with two 1K resistors to ground.

When a pin that's set as INPUT is "floating" (it's not connected to anything) the value on it is "undetermined" and interrupt can trigger when a neighboring pin status changes, or even just magically by itself. The 1K resistors (called pulldown resistors) will make sure that pin is set to LOW when it's not connected using the jumper.

This circuit should put a stable 0V on Pin3 when switch is unpressed and 5V when it's pressed. You should be able to verify that using any voltage meter.

If the issue persists then swapping the microcontroller on the Arduino is just one of the steps you need to perform. You would also need to burn a bootloader on the chip. It's not a hard procedure but it requires a second Arduino.


I can send AT Commands, but cannot upload sketch to ESP8266 via Generic ESP Module

In order to put the ESP into programming mode, you need to connect GPIO0 to ground as you power it up.

(I have a push button attached to my proto board for this purpose.)


Finding address of OLED using I2C communication and Arduino

You misinterpret how the Wire library is used. Though the first byte in the transmission is called the address byte, the actual address consists only of the 7 higher bits in that byte. The direction bit is not in the address.

So the Wire.beginTransmission() method wants the address as parameter, without the direction bit. That bit is set corresponding to the used function (0 for Wire.beginTransmission() and 1 for Wire.requestFrom()).

0b0111100 is the real address (when connnecting the address pin to ground)(note, that there are only 7 bits, since the address only has 7 bits). The write operation address byte will then be 0b01111000, though the library is hiding that way from you. You need to provide the 7 bit address to the function.

  the second last bit is a dont care

As mentioned above, that is not correct. This bit (the least significant bit of the address) is set by the address pin SA0. It seems, that you have it tied to ground, which sets the corresponding bit in the address to zero. If you would tie it to Vcc, it would be 1.


How to copy files from Yun to local computer?

You simply reverse the arguments.  Whatever you used to copy a file to the Yun you just do the opposite to copy from the Yun.

For instance, if you copied to the Yun using:

scp /my/local/file root@192.168.2.16:/where/you/want/it

Then you would change it around to copy from the Yun thus:

scp root@192.168.2.16:/path/to/file /where/you/want/it/to/go


How to change the resolution of DS18B20?

Simple:

sensors.setResolution(9);

It normally defaults to 9, but then probes the connected device to find the maximum resolution it supports and sets it to that. This would normally be done in sensors.begin() which you omitted from your snippet above. If you don't have that it will be on 9 bit anyway, and also the bus probably won't work regardless.


On my version of this "Adatper" adapter the io pins were not connected. I patched io 0 to the esp-01 like header, to be able to put the ESP in bootloader mode. On the picture you see a paperclip jumper connecting io 0 to ground for flashing mode.

Back then I could leave the jumper connected, because the esp8266 run the sketch after upload. In new versions of esp8266 arduino boards package the esptool hard resets the esp8266 so it returns into flashing mode. This can be changed in platform.txt.

I recommend you to buy an esp8266 dev board with USB (Wemos, NodeMcu and similar)


From what I can tell, the I2C bus multiplexer itself receives and re-transmits on what amounts to a completely separate bus.  So, each bus would need its own pull-up resistors.  That said, the board you've linked that breaks out the multiplexer chip has pull-up resistors on each bus that it's providing:

The breakout also has pull-ups on the bus going to the multiplexor itself:

Beyond that, the ambient light sensor breakout seems to provide its own 4.7K pull-ups. AVR-based Arduinos (and probably others) also enable their own, admittedly weak, pull-ups in the guts of the wire library.
It seems you should not necessarily need to add any additional pull-up resistors of your own to what is already on the buses.

With regard to the O.P. comment given below concerned about too many pull-up resistors.
At some point probably below (perhaps far below) 500 ohms some devices may have trouble sinking enough current to create a LOW. The AVR wouldn't have a problem with 500 ohms for example.
The ATMega328P datasheet (along with most other AVR datasheets) will tell you that the internal pullup value is between 20K-50K.  If you're concerned about too-many-parallel-resistors/too-many-current-paths/too-little-total-resistence, you can take the 20K figure along with multiplexer breakout's 4.7K figure, to calculate pow(1 / 20e3 + 1 / 4.7e3, -1), for about 3.8K, which should be fine.  If you do the same calculation on the multiplexor's individual bus resistor 4.7k and the ambient light sensor breakout's own 4.7k resistor, you get 2.35 k (half), which is also probably fine.  If anything both of these total figures can be made smaller (by adding yet another parallel resistor) for longer buses and at higher frequencies.  If you're worried about these figures you can lower the I2C clock rate.  You can also examine the edges of your signal with a scope.  Also if you really want to dig into this stuff, you read in the official I2C manual.  But, really I think what you have is probably fine.


Arduino Robot. a function-definition is not allowed here before '{' token

You need to look more closely at your braces. Use the auto-format tool (Ctrl+T) to help you. For example:

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

// --------------------------------------------------------------------------- Motors
int motor_left[] = {2, 7};
int motor_right[] = {10, 15};
int LDR = 0;     //analog pin to which LDR is connected, here we set it to 0 so it means A0
int LDRValue = 0;      //that’s a variable to store LDR values
int light_sensitivity = 500;    //This is the approx value of light surrounding your LDR
int LDR2 = 0;     //analog pin to which LDR is connected, here we set it to 0 so it means A0
int LDR2Value = 0;      //that’s a variable to store LDR values
int light_sensitivity2 = 500;    //This is the approx value of light surrounding your LDR
int i;
for(i = 0; i < 2; i++){
pinMode(motor_left[i], OUTPUT);
pinMode(motor_right[i], OUTPUT);
LDRValue = analogRead(LDR);
    Serial.println(LDRValue);

    if (LDRValue < light_sensitivity);
    Serial.println("wat");

}   // <------------------------------------ HERE

// --------------------------------------------------------------------------- Loop

// --------------------------------------------------------------------------- Drive

void motor_stop(){

Where I marked "HERE" you are closing the for loop but you should also be closing setup.

You also have two opening braces here:

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

Proper indentation is very helpful for sorting out these sorts of issues.


Programming a USB mouse connected to the Intel Edison Arduino expansion board

Here's a simple introduction to using the USB mouse as an input device. That might be a good starting point.

http://tahmidmc.blogspot.com/2015/12/using-input-device-on-embedded-linux.html


As you state, the internal EEPROM has a lifetime of 100,000 write cycles. This isn't a guess - a very significant proportion of ATmega328 will reach this number with no issues. I have tested three processors before, and all reached 150,000 cycles with no issues.

It is important to note the failure mode of EEPROM. Most "EEPROM destroyer" projects repeatedly read/write until the data is not written at all. Before this point, the EEPROM will still be damaged. This would be manifested by data not being retained for a reasonable period. It is unwise to rely on anything more than 100,000 write cycles for this reason.

EEPROM is different to the RAM on an ATmega. Writing to it is not simple or quick, but it is wrapped up in a friendly Arduino library, hiding this complexity from the user.

The first level of indirection is the EEPROM library, which is trivially simple], just calling two other functions for read and write. This calls eeprom_write_byte, found here.

This function uses inline assembly, so might not be easily understood. There is a comment that is easily understood though:

  Set programming mode: erase and write

This hints to one of the complexities of dealing with EEPROM - to write to
it, you first need to erase it. This means that if you call EEPROM.write(), it will perform a write cycle regardless of the value you are writing.

This means that repeatedly writing 0xFF will likely have the same effect as writing 0xFF,0x00,0xFF,0x00 etc.

There are ways to work around this - you can try calling EEPROM.read() before EEPROM.write() to see if the value is already the same, but this takes additional time.

There are other techniques to avoid excessive EEPROM wear, but their use depends on your application.


Junk values in EEPROM. while writing large values

It depends on what type of variable you have.  If you have single byte variables like byte or char then it is one value to one address.  But if you have an int value like:
int x = 2000;

then try to store that in EEPROM that will take 2 bytes because an int is 2 bytes in size.  So if you write that to address 5 it will take 5 and 6 to write it.
If you write a long or a float, they are 4 bytes, so they will take 4 address slots in the EEPROM each.
If you just write EEPROM.put(5, 2000); then the 2000 gets seen as either int or long depending on how the code is written.  I don't remember.  But you certainly can't fit 2000 into a byte so it's going to have to take more than one.


1. Uploading the sketch to your ESP8266

Tools > Board > select the appropriate ESP8266 board
File > Examples > ESP8266AVRISP > Arduino_Wifi_AVRISP
Change lines 7 and 8 to match the SSID and password of your WiFi router
Sketch > Upload
After the upload completes unplug the ESP8266 from your computer.

2. Generating the .hex file and the upload command

Open the sketch you want to upload to your ATmega16
Tools > Board > ATmega16
File > Preferences > Show verbose output during: > upload (check)
Sketch > Upload
The sketch will compile and then the upload will fail. This is the expected behavior. The goal of this process is to generate the .hex file that will be uploaded and the correct upload command.
Scroll the black console window at the bottom of the Arduino IDE window up until you see a line that looks something like:

>

E:\Arduino\hardware\tools\avr/bin/avrdude -CE:\Arduino\hardware\tools\avr/etc/avrdude.conf -v -patmega328p -carduino -PCOM54 -b115200 -D -Uflash:w:C:\Users\per\AppData\Local\Temp\arduino_build_288143/Blink.ino.hex:i

3. Connecting the ESP8266 to the ATmega16

Connect the ESP8266 to your ATmega16 board as follows:

+----------+-----------+
| ESP8266  | ATmega16  |
+----------+-----------+
| GPIO12   | MISO      |
| GPIO13   | MOSI      |
| GPIO14   | SCK       |
| GPIO5    | RESET     |
+----------+-----------+

You also need to power the ATmega16. It is recommended to use 3.3 V since this is what the ESP8266 is running at. Make sure the ground of the ESP8266 is connected to the ground of the ATmega16.

4. Starting the ESP8266AVRISP

Plug the ESP8266's USB cable back in to your computer
Tools > Serial Monitor
Select 115200 from the baud rate menu in the bottom right corner of Serial Monitor
You should see something like

  IP address: 192.168.0.100
  Use your avrdude: avrdude -c arduino -p  -P net:192.168.0.100:3000 -t # or -U ...

5. Uploading via ESP8266AVRISP

The second line you saw in the Serial Monitor in step 4 is the sketch's attempt to give you the AVRDUDE command you need to run to upload to your ATmega16 via the ESP8266AVRISP. Unfortunately they got a bit vague at the end. Apparently they are trying to steer you towards using AVRDUDE in terminal mode via the -t option but also mentioning that -U might be preferred. I recommend the latter since the Arduino IDE has helpfully generated the -U command for you already.
Since you need to run a custom AVRDUDE command to upload to your ATmega16 over the network you will not be able to do the upload via the Arduino IDE. Start the command line on your computer.
Now you need to merge the upload command you generated when you did the intentionally failed upload to the ATmega16 in step 2 with the command that was printed to Serial Monitor in step 4. In my examples, this merged command would be:

>

E:\Arduino\hardware\tools\avr/bin/avrdude -CE:\Arduino\hardware\tools\avr/etc/avrdude.conf -v -c arduino -p atmega16 -P net:192.168.0.100:3000 -Uflash:w:C:\Users\per\AppData\Local\Temp\arduino_build_288143/Blink.ino.hex:i

Your command will be similar to mine but the path to avrdude, avrdude.conf, the IP address, port, and path to the .hex file will be different. Enter your merged AVRDUDE command at the command line.
The upload should now proceed successfully.

Comments

The above is quite a complex process. Although it will be significantly easier with subsequent uploads, it will likely still not be as easy as an upload via the Arduino IDE. I would not recommend regularly using the ESP8266 as an AVR ISP simply because it's what you have on hand. Instead I would strongly recommend you to just buy a cheap (~$3 USD with free shipping from China) 6 pin USBasp from eBay.

The primary benefit of using the ESP8266 for this application is that it can be done over the WiFi network rather than the traditional USB connection but it's questionable how often that will truly be useful.


How does serial communications work on the Arduino?

Asynchronous serial (usually referred to as serial) communications is used to send bytes from one device to another. A device could be one or more of the following:

Arduino
PC
GPS
RFID card reader
LCD display
Modem
Other

Clock rate and sampling of data

Unlike SPI / USB / I2C serial communications does not have a clock signal. The sampling clock is an agreed-upon sample rate (known as the baud rate). Both sender and receiver must be configured to be using the same rate or the receiver will receive meaningless data (due to the bits not being sampled at the same rate that they were sent).

The transmission is asynchronous which basically means that bytes can be sent at any time, with varying gaps between them. This graphic illustrates a single byte being sent:

The graphic above shows the letter 'F' being transmitted. In ASCII this is 0x46 (in hex) or 0b01000110 (in binary). The least significant (low-order) bit is transmitted first, thus in the above graphic you see the bits arriving in the order: 01100010.

The "idle" time between bytes is transmitted as continuous "1" bits (effectively, the transmit line is held high continuously).

To indicate the start of a byte, the Start Bit is always indicated by pulling the line low as shown on the graphic. Once the receiver sees the start bit, it waits for 1.5 times the sample time, and then samples the data bits. It waits 1.5 times so that it:

Skips the start bit
Samples half-way through the next bit

If the baud rate is 9600 baud, for example, then the sample rate will be 1/9600 = 0.00010416 seconds (104.16 µs).

Thus, at 9600 baud, after receiving a start bit the receiver waits for 156.25 µs, and then samples every 104.16 µs.

The purpose of the Stop Bit is to ensure that there definitely is a 1-bit between each byte. Without the stop bit, if a byte ended in a zero, then it would be impossible for the hardware to tell the difference between that and the start bit of the next byte.

To produce the above output on an Uno you could write this code:

void setup()
  {
      Serial.begin(9600);
      Serial.print("F");
  }

void loop ()
  {
  }

Number of data bits

In order to save transmission time (in the olden days, heh) you were allowed to specify different numbers of data bits. The AtMega hardware supports data bits numbering from 5 to 9. Clearly the less data bits the less information you can send, but the faster it will be.

Parity bits

You can optionally have a parity bit. This is calculated, if required, by counting the number of 1's in the character, and then making sure that this number is odd or even by setting the parity bit to 0 or 1 as required.

For example, for the letter "F" (or 0x46 or 0b01000110) you can see that there are 3 ones there (in 01000110). Thus we already have odd parity. So, the parity bit would be as follows:

No parity: omitted
Even parity: a 1 (3 + 1 is even)
Odd parity: a 0 (3 + 0 is odd)

The parity bit, if present, appears after the last data bit but before the stop bit.

If the receiver does not get the correct parity bit, that is called a "parity error". It indicates that there is some problem. Possibly the sender and receiver are configured to use different baud (bit) rates, or there was noise on the line which turned a zero to a one or vice-versa.

Some early systems also used "mark" parity (where the parity bit was always 1 regardless of the data), or "space" parity (where the parity bit was always 0 regardless of the data).

9-bit transmission

Some communication equipment uses 9-bit data, so in these cases the parity bit is turned into the 9th bit. There are special techniques for sending this 9th bit (the registers are 8-bit registers so the 9th bit has to be put somewhere else).

Number of stop bits

Early equipment tended to be somewhat slower electronically, so to give the receiver time to process the incoming byte, it was sometimes specified that the sender would send two stop bits. This basically adds more time where the data line is held high (one more bit time) before the next start bit can appear. This extra bit time gives the receiver time to process the last incoming byte.

If the receiver does not get a logical 1 when the stop bit is supposed to be, that is called a "framing error". It indicates that there is some problem. Quite possibly the sender and receiver are configured to use different baud (bit) rates.

Notation

Commonly, serial communication is indicated by telling you the speed, number of data bits, type of parity, and number of stop bits, like this:

9600/8-N-1

This is telling us:

9600 bits per second
8 data bits
No parity (you might see instead: E=even, O=odd)
1 stop bit

It is important that the sender and receiver agree on the above, otherwise communication is unlikely to be successful.

Pin-outs

The Arduino Uno has digital pins 0 and 1 available for hardware serial:

To connect two Arduinos you swap Tx and Rx like this:

Speed

A wide range of speeds is supported (see graphic below). "Standard" speeds are usually a multiple of 300 baud (eg. 300/600/1200/2400 etc.).

Other "non-standard" speeds can be handled by setting the appropriate registers. The HardwareSerial class does this for you. eg.

Serial.begin (115200);  // set speed to 115200 baud

As a rule-of-thumb, assuming you are using 8-bit data, then you can estimate the number of bytes you can transmit per second by dividing the baud rate by 10 (because of the start bit and stop bit).

Thus, at 9600 baud you can transmit 960 bytes (9600 / 10 = 960) per second.

Baud rate errors

The baud rate on the Atmega is generated by dividing down the system clock, and then counting up to a pre-set number. This table from the datasheet shows the register values, and error percentages, for a 16 MHz clock (such as the one on the Arduino Uno).

The U2Xn bit affects the clock rate divisor (0 = divide by 16, 1 = divide by 8). The UBRRn register contains the number the processor counts up to.

So from the table above, we see that we get 9600 baud from a 16 MHz clock as follows:

16000000 / 16 / 104 = 9615

We divide by 104 and not 103 because the counter is zero-relative. Thus the error here is 15 / 9600 = 0.0016 which is close to what the table above says (0.02%).

You will notice that some baud rates have a higher error amount than others.

According to the datasheet the maximum error percentage for 8 data bits is in the range of 1.5% to 2.0% (see the datasheet for more details).

Arduino Leonardo

The Arduino Leonardo and Micro have a different approach to serial communications, as they connect directly via USB to the host computer, not via the serial port.

Because of this, you must wait for Serial to become "ready" (as the software establishes an USB connection), with an extra couple of lines, like this:

void setup()
  {
      Serial.begin(115200);
      while (!Serial)
      {}  // wait for Serial comms to become ready
      Serial.print("Fab");
  }

void loop ()
  {
  }

However, if you want to actually communicate via pins D0 and D1, (rather than by the USB cable) then you need to use Serial1 rather than Serial. You do so like this:

void setup()
  {
      Serial1.begin(115200);
      Serial1.print("Fab");
  }

void loop ()
  {
  }

Voltage levels

Note that the Arduino uses TTL levels for serial communications. This means that it expects:

A "zero" bit is 0V
A "one" bit is +5V

Older serial equipment designed to plug into a PC's serial port probably uses RS232 voltage levels, namely:

A "zero" bit is +3 to +15 volts
A "one" bit is −3 to −15 volts

Not only is this "inverted" with respect to TTL levels (a "one" is more negative than a "zero"), the Arduino cannot handle negative voltages on its input pins (nor positive ones greater than 5V).

Thus you need an interface circuit for communicating with such devices. For input (to the Arduino) only, a simple transistor, diode, and a couple of resistors will do it:

For two-way communication you need to be able to generate negative voltages, so a more complex circuit is required. For example the MAX232 chip will do that, in conjunction with four 1 µF capacitors to act as charge-pump circuits.

Software Serial

There is a library called SoftwareSerial that lets you do serial communications (up to a point) in software rather than hardware. This has the advantage that you can use different pin configurations for serial communications. The disadvantage is that doing serial in software is more processor-intensive and more prone to error. See Software Serial for more details.

Mega2560

The Arduino "Mega" has 3 additional hardware serial ports. They are marked on the board as Tx1/Rx1, Tx2/Rx2, Tx3/Rx3. They should be used in preference to SoftwareSerial if possible. To open those other ports you use the names Serial1, Serial2, Serial3, like this:

Serial1.begin (115200);  // start hardware serial port Tx1/Rx1
Serial2.begin (115200);  // start hardware serial port Tx2/Rx2
Serial3.begin (115200);  // start hardware serial port Tx3/Rx3

Interrupts

Both sending and receiving, using the HardwareSerial library, use interrupts.

Sending

When you do a Serial.print, the data you are trying to print is placed in an internal "transmit" buffer. If you have 1024 bytes or more of RAM (such as on the Uno) you get a 64-byte buffer, otherwise you get a 16-byte buffer. If the buffer has room, then the Serial.print returns immediately, thus not delaying your code. If there is no room, then it "blocks" waiting for the buffer to be emptied enough for there to be room.

Then, as each byte is transmitted by the hardware an interrupt is called (the "USART, Data Register Empty" interrupt) and the interrupt routine sends the next byte from the buffer out of the serial port.

Receiving

As incoming data is received an interrupt routine is called (the "USART Rx Complete" interrupt) and the incoming byte is placed into a "receive" buffer (the same size as the transmit buffer mentioned above).

When you call Serial.available you find out how many bytes are available in that "receive" buffer. When you call Serial.read a byte is removed from the receive buffer and returned to your code.

On Arduinos with 1000 bytes or more of RAM, there is no rush to remove data from the receive buffer, provided you don't let it fill up. If it fills up then any further incoming data is discarded.

Note that because of the size of this buffer there is no point in waiting for a very large number of bytes to arrive, for example:

while (Serial.available () < 200)
  { }  // wait for 200 bytes to arrive

This will never work because the buffer cannot hold that much.

Tips

Before reading, always make sure data is available. For example, this is wrong:

if (Serial.available ())
  {
      char a = Serial.read ();
      char b = Serial.read ();  // may not be available
  }

The Serial.available test only ensures you have one byte available, however the code tries to read two. It may work, if there are two bytes in the buffer, if not you will get -1 returned which will look like 'ÿ' if printed.
Be aware of how long it takes to send data. As mentioned above, at 9600 baud you an only transmit 960 bytes per second, so trying to send 1000 readings from an analog port, at 9600 baud, won't be very successful.

References

Async (Serial) peripheral interface - for Arduino
How to process incoming serial data without blocking
RS-232 - Wikipedia
Arduino Reference - Serial


Vary voltage using relay. Is this possible?

No, you can't vary the voltage with a relay. The only way you could do it with a relay would be to have a selection of different voltages available, and then use multiple relays to select which voltage is used. Less than ideal.

You need to use PWM to create a square wave with varying duty cycle. The duty cycle (the percentage of time the power is on within a given period) defines the average voltage of the output.  That PWM needs to be fed into a MOSFET which will in turn control the 24V power to the lamp.

It's exactly the same as driving RGB LED strips, except it's in the shape of a lamp not a long strip.


Well, I'm not familiar with the Yun, but the first thing that stands out is the missing

Bridge.begin();

line apparently needed to initialize the Bridge library that you use.

And you do have something like

YunClient client = server.accept();

and "more" in the main loop (or a function where applicable) of your code, right ?

And yes, noListenOnLocalhost() is the correct function for serving external clients.


how to make this work auto on off led with fading

Look at your function definitions:

void startOn() // works
void startOff    // doesn't work

You are missing the () after startOff.


GSM library getIPaddress returns local network address 10.X.X.X

The SIM card does not have an IP address. When the data connection is made to your GSM APN it is assigned an IP in a similar way to DHCP. Often the address is the same after the first connection as the service provider will link that to your SIM for audit purposes. If you setup a private APN then you can arrange to have specific range allocated to your SIM card(s). This is normally only done for security of volume reasons.


Serial receiver (Arduino Micro ATmega32U4) in bad state

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


While the PPD42NS has a 5-pin connector, it is shown at seeedstudio.com and howmuchsnow.com connected up with three wires: +5V, Ground, and an LPO or “Low Occupancy Output” signal, which goes low when a particle occludes an LED beam path.  LPO is used as an input to let sketches measure the fraction of time the beam's  occluded, which correlates with number of dust particles.

Yes, a resistive voltage divider will let you use the 0-to-5V occupancy signal as an input to your 3.3V-tolerant ESP8266.

What values of resistors should be used?  Because input pin capacitance is small (eg under 10 pF), signal "crispness" should be about the same over a broad range of resistances – say from a 100Ω+200Ω divider up past 1KΩ+2KΩ;  even 10KΩ+20KΩ might be ok.

The Grove_-_Dust_sensor.pdf data sheet at seeedstudio.com says:

  Output Method  Negative Logic, Digital output,
  Hi : over 4.0V(Rev.2) Lo : under 0.7V
  (As Input impedance : 200kΩ) OP-Amp output, Pull-up resistor : 10kΩ

This suggests (but doesn't clearly indicate) that some sort of open-drain output might be used.  If so, instead of using a voltage divider one could remove the 10kΩ pull-up on the sensor, and pull the output to 3.3 V instead of 5 V, via either an external resistor or using an INPUT_PULLUP pinmode setting (if available on the ESP8266).

Edit: Regarding the comment, “I'm considering use it in conjunction with an MCP23017 I/O expander IC. The GPIO pins on the chip appear to be rated at a max capacitance of 50 pF. Will that affect the range of resistors available? How does resistor choice affect the crispness of the signal, and how can I determine it for myself?”:

The “max capacitance of 50 pF” spec, which is parameter D101 in table 2.1 of the MCP23017 spec sheet, refers to “Capacitive Loading Specs on Output Pins”, ie, how much capacitance MCP23017 outputs can drive.  It doesn't refer to input pin capacitance, so isn't relevant here.

In general, when a signal edge (a rise or fall) arrives at an input pin, the input pin's voltage doesn't change instantaneously.  The input pin's capacitance needs to charge or discharge.  (It charges for a rising edge, discharges for a falling edge.)  The speed of change depends on the RC time constant of the circuit.  A delay occurs, probably 1–3 time constants long, before the pin starts to switch.  (The switch may take a few tens or hundreds of nanoseconds.)

For example, if input circuit capacitance is 10 pF and its effective resistance is 100kΩ, RC = 10 pF · 100kΩ = 10⁻¹¹·10⁵ = 10⁻⁶ seconds = 1 microsecond.  Whether that's large enough to matter for your measurements depends on how many time constants have to occur before the pin starts switching, and on how narrow the LPO signals are.

In short, compute RC, and if it's more than a few microseconds, use a smaller value of R.  Alternately, if you have access to an oscilloscope, attach it to the input and try various resistance values in the voltage divider, to get a feel for how the signals degrade as the resistors in the divider get bigger.

Note, using a voltage divider causes different RC values for falling edges than for rising edges.  For example, suppose an actively driven 0-5V signal enters a divider with 10KΩ in series with 20KΩ, and the 0-3.3 V signal is taken from the resistors' junction.  Then R is 10KΩ for a rising edge, and 20KΩ for a falling edge.  If the 0-5V signal weren't actively driven high, but instead pulled up via a pullup resistor R' when a transistor turns off, then the rising edge R value would be R'+10KΩ for this example.


Problem regarding getting split data of JSON - Another issue

I don't think your loop handles the situation where the data comes in too slowly. Looking at your while condition:

while(Serial.available() || !begin)

Once you receive the start char, this becomes:

while(Serial.available())

Now, if there is a delay in the serial buffer, the loop exits before you have the entire message.

You should change the loop so it only ends when you have all 39 chars.

void loop() {
    while (39 != response.length()) {  // Keep going until full msg {
        // Check for data in serial buffer
        if (Serial.available()) {
            in = Serial.read();
            .....
        }
        // No data?
        else {
            delay(10);
        }
    }

    TPS_Json = data_TPS_Json.toFloat();
    MAP_Json = data_MAP_Json.toFloat();
    .....
}


How to remove Arduino Due and Mega shields without bending pins?

You could modify a couple of wooden clothes pegs to act as reverse pliers.


A byte is 8 bits, it can hold a maximum value of 255.  You can not store the number 1024 in a byte.  You might want to rethink the type on ndx.
If (ndx >= numChars) then why not set newData to true and print it out.  Something has gone wrong if it gets this far and you want to recover if you can.

Apart from those minor issues your code should work as you expect it to.  Do you have a printout of what the slave's serial output was?  (What you were expecting).  Could it be something to do with the differences between SoftwareSerial and Serial?

Edit:

I have just run a stubbed version of you code on a PC and it ran fine, so I'm going to point my finger at the SoftwareSerial link.  It could well be a misinterpretation of the interface it provides.


Writing C Program outside of Arduino IDE?

You're absolutely right about needing to link against other libraries. However, you don't necessarily need to worry about all of the details yourself, unless you want/need to do something unusual. Several alternative IDEs already support Arduino, typically via plugins which handle a lot of the details automatically.

I normally recommend Eclipse as it's a very widely used IDE for various purposes. However, there are several other possibilities. See this question for more information:

What are the other IDEs for Arduino?


Can I solder wall cord directly to servo?

First choice: Attach compatible, polarized connectors to both pigtails.

Alternatively, you can solder it up but the result is certainly less convenient to use. I like heat-shrink tubing for insulating wire-to-wire solder joints, one over each solder joint and a third, slightly larger one over both. (My favorite way to screw this up is to forget to push all three shrink tubes over the wires before I solder the joints. :)


Scroll String Only On Second Line Using 2x16 LCD

You need to reset the stringStart, stringStop and scrollCursor at the beginning of the roop function.

void roop(String line1, String line2) {

  countMovement = 0;
  stringStart = 0;
  stringStop = 0;
  scrollCursor = screenWidth;

  ...

I think you also need to move the lcd.clear up. Or else the screen will be blanked when the roop function is done scrolling.

...

  while ( ( countMovement ) < (line2.length() + screenWidth )  ) {

     lcd.clear();
     lcd.setCursor(scrollCursor, 1);
     lcd.print(line2.substring(stringStart,stringStop));
     lcd.setCursor(4, 0); // 1 = word eat array of words very cool
     lcd.print(line1);
     delay(300);

...


You can use fill_solid.

For example

fill_solid( leds, NUM_LEDS, CRGB(50,0,200));

Or

fill_solid( leds, NUM_LEDS, CRGB::Red);


It looks like the problem may be initialisation order. In C/C++, global variables/objects are usually initialised in the order they are declared, and before any global functions run.

In your case, this means ID_Check() gets called before array is populated, and before setup() runs.

It looks like you need to make sure everything else is setup before your attempting to initialise the Modbus object. I'm not familiar with the library, but perhaps there's a way to set the device ID after it's been constructed (i.e. not in the constructor)?

If not, you could declare slave as a global pointer, and then instantiate it using new in setup().

As a side note, I'm guessing your Modbus_Setup() function didn't work because the slave object in there is completely separate from the slave object that's declared globally and used in loop().


Arduino Due not executing code after power on

After some more research I found out that

a) the issue applies to some Due boards only, not all

b) newer boards seem to have fixed the issue

c) there's a software (firmware update) and hardware (10k resistor) solution

I went with the hardware fix shown here:
http://www.dimdim.gr/2016/03/fixing-startup-issues-with-arduino-dues/

I did not have an SMD resistor at hand, so mine looks ancient but does the job.
Hope that helps others, too.

addendum:

The problem occurs only on some DUE boards and is due to some undocumented behaviour of the ATSAM3X8E processor combined with the behaviour of some MOSFETS installed on the DUE boards. So its occurence is largely a matter of luck.

The fix is simple: you just solder a 10K resistor across the top of this mosfet:

resistor about to be soldered on

resistor designated as R99


Why doesn't the master branch BOSSA work on Arduino Due?

No Arduino did not alter the chip, custom chips are massively expensive. If they are using their own modified version of BOSSA, then there must be a reason for it, probably the support of Arduino's hardware platform. To find out what the difference is, you have to find the code base used for Due and the original version when the code was forked. Often in such cases a project like Arduino can provide a patch to the BOSSA project, and that patch may or may not be applied to the master tree. Only way to find out is to check the BOSSA project repository / bug  reports and documentation.


Send AT commands programatically to ESP8266 without Arduino

You don't use AT commands. You install the esp8266 boards package and program the esp8266 as if it were an Arduino. That means learning the esp8266 WiFi API which has plenty of examples included.

https://github.com/esp8266/Arduino/


Error compiling for Arduino Nano 33 BLE with LiquidCrystal library

The Arduino core for Nano 33 BLE is based on Mbed and can be used in Mbed as library. To achieve this, the Arduino API classes in this core are put in a namespace arduino::. This causes problems for libraries which include individual includes of Arduino API historically copied into cores for different MCU architecture platforms. The Arduino.h file includes the API files in the right way so in this case replacing #include"Print.h" with #include <Arduino.h> in LiquidCrystal.h solves the compilation problem.


From provided picture it is visible that your display is not alphanumeric display (with most popular HD44780 driver). It is a graphical display (most popular: KS0107 or KS0108 or ST7920). You can count horizontal pixels and vertical ones in the picture to confirm its resolution.
Without too many problems you can drive it with your Arduino. Try to use some of 128x64 Arduino libraries. Also, check the rear of the display for any part number to confirm the driver (search in google).
 Good luck!


For a RISING interrupt you never need to disconnect the interrupt to prevent repeat triggering.

A RISING interrupt specifically only triggers the once when the input pin transitions from LOW to HIGH rather than all the time it's in a state like a level interrupt.

Attach the interrupt once in setup() and leave it alone after that.  Your interrupt handler routine can be completely empty.  It will only ever be triggered at the exact moment you press the button.  To trigger it again you will just need to press the button again.


Alternative distance-meter, HC-SR04 doesn't work very well

In general the HC-SR04 is controlled using pulseIn().

When there is nothing within range for the sensor to detect it usually has to wait for pulseIn() to time out. That can take up to a second by default.  While that is happening the rest of the sketch cannot do anything.

You can reduce the timeout in the pulseIn() function, but it's still not going to be perfect - you'll still get a delay which will interrupt your LED sequences.

The ideal way will be to create a "free running" distance sensor system - use a timer to periodically start a ping, and use the Input Capture module of the ATMega to measure the time between the start and end edges of the returning pulse. Everything will happen asynchronously to the rest of your sketch then.

I am not aware of any libraries for Arduino boards, but I have one for the PIC32 based chipKIT boards that I use. It can't ever work on AVR based boards, but you can use it to see the general concepts and how things fit together.


Why do you not want to sleep the processor? If it's running at all, it doesn't matter whether it is polling the UARTs or executing something else; it will still be using power.

The first several paragraphs of the article you linked to describe putting the processor into low-power mode and reducing the power consumption further by disabling some internal hardware modules. When the UART receives a byte, the processor will wake up and continue execution from where it slept. Isn't that what you are asking for?


Where should a modified "pins_arduino.h" be stored for Arduino IDE compile?

Now have 2560 “full pin definition” working.  This is what I think I did:

1) Download IDE with "Windows ZIP file for non admin install " from https://www.arduino.cc/en/Main/Software

2) Download pins.arduino.h from https://forum.arduino.cc/index.php?action=dlattach;topic=200887.0;attach=60348

3) Open the IDE distribution zip file and extract all files into the location where you want the IDE files and your sketches to reside.  Could be anywhere.

4) Before starting arduino.exe from the extracted files, replace the pins.arduino.h file that came with the IDE, with the "all pins defined" version.  It is replaced in folder path: .../arduino-1.8.5/hardware/arduino/avr/variants/mega/pins.arduino.h

5) Place sketch within the same path as everything else (e.g. create a folder like “12.My_Sketches” inside “examples”). For example, I put my test sketch Blinky-2560 in folder path: .../arduino-1.8.5/examples/12.My_Sketches/Blinky-2560/Blinky-2560.ino

Why it worked this time?  The only difference I can see is I got the new pins file inserted in the right place before running the IDE.  It is also possible the sketch has to be in the same path as the rest of the IDE (saw that somewhere!?!?).  Otherwise I don’t think there was anything else different from what I was doing with the previously installed IDE.

Since the “all pins defined” file is a superset of the standard mega pins.arduino.h file, there is full compatibility with the Arduino ATmega2560 PCB.  It would be great if Arduino would make this fully defined pins file the standard that comes with the IDE.

Never did get MegaCore to upload the sketch after the compile.


Sensirion library for SHT7x humidity sensor

You simply create a second instance of the object with different pins and store the result in a different set of variables. Any extra logic of when to do what is purely down to you.


You need to supply power to the ESP to make it turn on.  What you have done at the moment is got the ESP to supply 3.3V to the level shifter, which you need to do.

You need to supply 3.3V to the ESP from somewhere other than the Arduino, it doesn't have the current necessary.


Arduino-RS232 converter baud rate problem

It is never good to base code on delays instead of intervals.  This is especially true for faster intervals where the execution of the code its self consume a significant portion of the interval.  Also note, some protocols only occasionally resynchronize.  RS232 resynchronizes after each byte (about 8 bits of data).  So any accumulated delay errors may impact the integrity of the bits furthest from the resynchronization event.

Instead of delays use the Arduino's built in hardware to send and receive RS232 communications.  The hardware is designed to work independently of code execution and will out perform software implementations especially for the faster baud rates.


You can try using the SPISettings interface:

SPISettings settings(100000, MSBFIRST, SPI_MODE0);

SPI.beginTransaction(settings);
... do your stuff ...
SPI.endTransaction();


Converting my delays to millis for smoother operation

Your delays are making the program jerky, so you have to get rid of them. :)
I have a lengthy discussion about this on my own web site, but basically you need to restructure so that you use a "state machine" and instead of delaying, make a note of the current time (using millis() function) and then do the next step when the time is up.
Just as an example, when you bake a cake you don't stop what you are doing for an hour and stare at the oven while it cooks, do you? You make a note of the time, and come back when the time is up.
One of the Arduino tutorials Blink without delay has an example of doing that.
The example code is (initial comments removed):
// constants won't change. Used here to set a pin number:
const int ledPin =  LED_BUILTIN;// the number of the LED pin

// Variables will change:
int ledState = LOW;             // ledState used to set the LED

// Generally, you should use "unsigned long" for variables that hold time
// The value will quickly become too large for an int to store
unsigned long previousMillis = 0;        // will store last time LED was updated

// constants won't change:
const long interval = 1000;           // interval at which to blink (milliseconds)

void setup() {
  // set the digital pin as output:
  pinMode(ledPin, OUTPUT);
}

void loop() {
  // here is where you'd put code that needs to be running all the time.

  // check to see if it's time to blink the LED; that is, if the difference
  // between the current time and last time you blinked the LED is bigger than
  // the interval at which you want to blink the LED.
  unsigned long currentMillis = millis();

  if (currentMillis - previousMillis >= interval) {
    // save the last time you blinked the LED
    previousMillis = currentMillis;

    // if the LED is off turn it on and vice-versa:
    if (ledState == LOW) {
      ledState = HIGH;
    } else {
      ledState = LOW;
    }

    // set the LED with the ledState of the variable:
    digitalWrite(ledPin, ledState);
  }
}

This won't be a one-line change. You have to re-think how you go about handling time delays.


How to convert read characters to strings?

If I correctly understand your question, then please try following code:

uint8_t str[64];
uint8_t chrCtr = 0;
uint16_t twoChr;
boolean isSecondChr = false;

void setup()
{
  Serial.begin(57600);
}

void loop()
{
  uint8_t chr;
  while (Serial.available())
  {
    chr = Serial.read();
    if ('a' <= chr && chr <='f')
    {
      chr &= 0x5F; // make it uppercase
    }
    if ('0' <= chr && chr <= '9' || 'A' <= chr && chr <= 'F')
    {
      if (!isSecondChr)
      {
        twoChr = chr << 8;
        isSecondChr = true;
      }
      else
      {
        twoChr |= chr;
        isSecondChr = false;
        str[chrCtr++] = hexToAscii(twoChr);
        if (chrCtr == 63)
        {
          str[chrCtr] = 0; // A string always terminated by zero
          Serial.println((char *)str);
          chrCtr = 0;
        }
      }
    }
    else if (chr == '#') // input terminated
    {
      str[chrCtr] = 0; // A string always terminated by zero
      Serial.println((char *)str);
      chrCtr = 0;
    }
    else
    {
      isSecondChr = false;
      // other character will be dropped
    }
  }
}

uint8_t hexToAscii(uint16_t hexWord)
{
  return (hexToBin(highByte(hexWord)) << 4) + hexToBin(lowByte(hexWord));
}

uint8_t hexToBin(uint8_t hexByte)
{
  return hexByte <= '9' ? hexByte - 48 : hexByte - 55;
}


Connect an Arduino directly to RGB LED strip

Those LED strips are multiple parallel chains of 3 LEDs in series, with a 150Ω resistor for each chain.  The chains are arranged as common anode, and the chains are grouped into the three colours for the cathodes.

You require a power supply with enough current to supply all the LEDs (such as the 3A one supplied in the package).

Further, you require a method of switching each of the three channels, such as n-channel MOSFETs, which can handle enough current for each channel (one MOSFET per channel) - that is, 1A per channel if the whole strip takes 3A (but you can "derate" it by providing capacity for more current which helps alleviate some heat dissipation problems).

As long as the MOSFETs are logic level (such as the IRLxxx series) you can then switch them directly using the PWM outputs of the Arduino.


You don't. WifiManager does all that for you. You don't need anything like that in your code. Just follow the examples and read the documentation.

But if you do want to then you just need to remember that WifiManager is merely a library that configures the WiFi for you. If you want to query or alter the WiFi settings you can - exactly as you are right now. The two aren't mutually exclusive.


arduino pro mini analog pins read different values

I made a circuit bellow for you. Note that the top resistor is 100 ohm and the bottom one is only 10 ohm. What I did is called a voltage divider. This way you can read voltages up to 50V. Simply connect the positive of your power source that you want to measure to the red wire and the ground of that same source to the black wire.

I also included a code that you could use:

Please notify me if any mistakes were spotted.

#define sensor A0 //defining sensor pin

float resistor1 = 100; //you can change it if you want, just make sure you also do it on the circuit
float resistor2 = 10;

float Vmax = (5*resistor1 + 5* resistor2)/resistor2;

void setup() {
  pinMode(sensor, INPUT); //declaring sensor as an output
  Serial.begin(9600);

  Serial.print("Do not input more then (V) : "); // print max input voltage
  Serial.print(Vmax);

  Serial.println(); //skip line
}

void loop() {
  float V = analogRead(sensor); //measuring analog values

  V = analogRead(sensor) * Vmax / 1024

  Serial.println(V); //printing voltage
}


openFrameworks appears to have this capability. It's written in C++.

From openFrameworks - Communication:

  Arduino and other serial devices communication

  The communication module has classes to communicate with other devices
  by now through the serial protocol. This mainly allows to communicate
  with devices like the Arduino. There's 2 classes in this module,
  ofSerial which allows to communicate with any device through the
  serial protocol. It can be used to send custom commands to for example
  an Arduino sketch that will receive them and do something in response
  like turn an LED on, move a motor... It also works the other way
  around, you can send messages from the Arduino (or any other serial
  device), for example the read from a temperature sensor to
  openFrameworks.

  The second class, ofArduino, is specific to the arduino, it uses a
  protocol called firmata to send messages to and from the arduino that
  way you don't need to care about implementing the communication
  protocol from the Arduino sketch to openFrameworks and viceversa but
  instead you can just send and read values directly to and from any pin
  in the Arduino.


So... turned out what was happening was all in code. Turns out that I was initializing an interrupt on INT0, when it was low, at the very beginning of my code. Problem was that when it started up on 3V backup power, INT0 was always low because INT0 is tied to the 5V line (it's how it knows to go to sleep). Because INT0 was low and the interrupt was triggering on low it was causing a constant interrupt to occur, never giving the rest of the program any time to run. Switched to enabling that interrupt only once I've entered full waking mode and it works fine now.


A problem in the include file on the line previous could cause the following line to be misinterpreted. To test that try moving the ssid after the password and see if the error changes. Obviously make sure all strings are properly quoted.

#include <WiFi101.h>
#include <WiFiSSLClient.h>

const char* password = "SYDTSTQR";  // your network password
const char* ssid = "SKY1C9D0";    //  your network SSID (name)
String httpsRequest = "https://hooks.zapier.com/hooks/catch/2821422/84ehn1/";


The #define will be substituted in at compile time. So as far as memory usage goes

#define MYSTRING "hello world"
DisplayData(MYSTRING);

and

DisplayData("hello world");

are completely identical.

but

static const char theme[] = "hello world";
DisplayData(theme);

Will store the text in memory and then call DisplayData with a pointer to that memory location. This will require one memory pointers worth of memory extra (unless that is the compiler is being smart that day and realizes it can substitute in the string and save a few bytes).

However if you are using the same string twice or more then things are different.

The static const will only include the string once and then point to it each time, each reference to the string adds only a couple of bytes to the code size.
If you #define the string then every time it is referenced the whole string is inserted into the code at a cost of n+1 bytes where n is the string length.


Arduino exercise that i have no idea how to do

To begin, forget the Arduino for a moment and assume the task of determining true or false from $....# message. Think about what you would have to do, step by step, to accomplish this. (e.g.: Read the buttons; Record the time and the button states. Is there a message from the Serial port beginning with '$'? Then read the rest of the message. etc.) Then, for each of those steps, do the same thing again: write down the smaller steps to accomplish what that step requires. Do that until you can't break it down any further.
Those small steps should each look like something you could do in C++ code (sometimes called "Arduino" code, but it's really C++). Start replacing each English (or your language) steps with the C++ equivalent. Do this until all of the human-language steps are written in C++.
There will inevitably be mistakes. Fix one or a few at a time. When you're stuck, ask here, something like "Here is my (well formatted) code. I tried [this]. I expected to see [that]. But what happened instead was [something else]. How can I fix it?"; or: "I am getting this error message [with its complete text including any line numbers, please] from the compiler. What does it mean, and how could I have found that out on my own?"
Small steps....


Without a data sheet or the device on hand not sure what the middle pin is used for.  On the topic of detecting a broken beam the item you purchased is purely an emitter, in order to detect the beam being broken there are two main ways, using a photodetector on the "opposite end" of the beam but this means having wires trailing the same path as the laser beam, alternatively you could mount a mirror where the beam lands and reflect it back to a photodetector mounted close to the laser diode.  You would them use the arduino to detect the state of the photodetector.


Burn Bootloader to Chinese Arduino 2560 with AVR ISP programmer

That error is common and usually means you either have the wrong board selected or the wrong port.  Check the tools menu. Be sure you have the port for the programmer and not the port for the board if the board is also connected.


Sending code for error detection facing problem with error not able to compile code

Probably the main problem is already in the first lines:

#include ESP8266WiFi.h
#include LiquidCrystal.h
#include FirebaseArduino.h>
#include HX711.h>

You should use the correct formatting:

#include "ESP8266WiFi.h"
#include "LiquidCrystal.h"
#include "FirebaseArduino.h"
#include "HX711.h"

Also, HX711 does not have a constructor with arguments, so instead of

HX711 scale(DOUT, CLK);

uese

HX711 scale;

and in Setup:

scale.begin(DOUT, CLK);

You probably have the code meant for a different library.

See HX711_full_example. Or use the code belonging to your used HX711 library.


How to create custom bootloader with accompanying program loader for ATMega2560

The source of the bootloaders is publicly available, so a simple thing would be to make a minor modification, for example XOR each incoming byte with 0xEE. That would mean the bootloader wouldn't work with normal uploading programs (the IDE) but with a modified uploader.

However even simpler would be to upload your code using ICSP and not include a bootloader at all. Or, leave the bootloader there but turn off the BOOTRST fuse so that the processor ignores it.

That way, it takes some effort for people to replace your code.


how to get serial data to wait until a certain length is reached

I would use a programming concept called a state machine. For example an integer variable called State could be used to track the current status which could for example be WAITING_FOR_DATA or RECEIVING_DATA or DATA_COMPLETE and only print when DATA_COMPLETE. I'm sure there are plenty of examples you could find with an appropriate search.


In this line:

readings[index] =  cs_7_6.capacitiveSensor(30);

...you are assigning an "int" the value from a method of type "long".

Likely you will want to change all your types used to track the capacitance value, including the type of your "capReading" method, to "long".


Figuring out your current needs is simply a matter of adding everything up. If you have 5 2 amp motors, you'll need 5 x 2, or 10 amps just to drive the motors.
You should probably have at least 20% extra capacity, so I'd suggest having a 12V power supply that can put out at least 12A.
15A would be better.
The stiffer your power supply the less it will "bobble" as the load varies.


Arduino writes only one time on SD card - Data log

You are opening the file in read mode but should be opening it in write mode. Change File dataFile = SD.open("datalog.txt"); to File dataFile = SD.open("datalog.txt", FILE_WRITE);.

You can remove this line of code: digitalWrite(10, HIGH);.

The arduino.cc website is also an excellent source of information regarding the SD library.


Char buffer for serial input: char str[2] vs char* str = (char*) malloc(2)

First, a few general notes:

The difference between char str[2] and
char* str = (char*) malloc(2) is irrelevant to you problem. It
changes the place where the array is stored, the meaning of
sizeof str, and malloc() will blow up your RAM if you call it
repeatedly and forget to free().
In your code, sizeof(txt) is the constant 2: the actual size in
bytes of the array txt, irrespective of how much relevant data it
holds.
You want txt and indxto remember their contents across calls to
loop(). You should either make them global or qualify them as
static.
Avoid the String class if at all possible. Here, since you use it
only to compare two strings, you can use the traditional
strcmp() function instead.

Now, the bulk of my answer is just about expanding on what has already
been said about properly terminating strings.
A string is a variable-length list of characters. Whenever you are
dealing with a list that has a variable length, you need to somehow keep
track of this length. There are two common ways to do so:

either you store the length in a variable,
or you put a sentinel value (a value that would be invalid within
the list) after the last element to mark the end of the list.

Both methods are valid, and I am going to illustrate both of them below.
However, in the case of strings, the C++ language uses method 2,
with the ASCII “NUL” character (numeric value 0) as a sentinel.
Method 1:
void loop() {
  static char txt[2];
  static size_t indx = 0;

  while (s.available()) {
    // read input
    char c = s.read();
    txt[indx++] = c;

    // report
    Serial.print("Received: '");
    Serial.print(c);
    Serial.print("', string: \"");
    Serial.write(txt, indx);
    Serial.print("\", size: ");
    Serial.println(indx);
    if (indx == 2 && memcmp(txt, "OK", 2) == 0) {
      Serial.println("Correct message");
    }

    // reset index
    if (indx >= sizeof txt) {
      indx = 0;
    }
  } // if(s.available())
}

Some things to note:

The indx variable holds the length of the string. It also happens to
be the index of the next available cell in the txt array, if any.
The string is printed using the
write(const char *buffer, size_t size) method, which accepts a size
as a second argument. Unlike print(const char *), it doesn't depend
on the string being NUL-terminated.
In order to check that we received “OK”, we have to check for both the
correct length (indx == 2) and correct contents. The contents is
checked using the memcmp() function, which can compare arbitrary
byte arrays and, again, does not depend on NUL-termination.
An important loop invariant here is idx < sizeof txt. It is true at
initialization and is restored by the “reset index” section at the end
of the loop. The “read input” section depends on this invariant to not
overflow the buffer.

Method 2:
void loop() {
  static char txt[3];
  static size_t indx = 0;

  while (s.available()) {
    // read input
    char c = s.read();
    txt[indx++] = c;
    txt[indx] = '\0';

    // report
    Serial.print("Received: '");
    Serial.print(c);
    Serial.print("', string: \"");
    Serial.print(txt);
    Serial.print("\", size: ");
    Serial.println(indx);
    if (strcmp(txt, "OK") == 0) {
      Serial.println("Correct message");
    }

    // reset index
    if (indx >= sizeof txt - 1) {
      indx = 0;
      txt[indx] = '\0';
    }
  } // if(s.available())
}

Again, some notes:

This is actually an hybrid of methods 1 and 2, as the indx variable
is still used to keep track of where to insert the next incoming
character. This just happens to be more convenient and efficient than
putting that character into its own length-1 string and using
strcat().
The array is now one cell longer, to make room for the terminating
NUL.
There is another loop invariant now: correct string termination
(txt[indx] == '\0'). This invariant has to be enforced both on
reading and on resetting.
The string being NUL-terminated, it can now be printed with print()
and compared with strcmp(). The string literal "OK" is guaranteed
to be NUL-terminated by the compiler.

This second method is generally safer because there are a lot of
functions and methods in Arduino and C++ that expect strings to be
NUL-terminated. If your strings are not, you have to be extra careful to
not use any of these string-oriented functions.


Understanding memory fragmentation due to char arrays in functions

by putting the declaration for variable char double2StrBuff1[10];
  inside the function, is the memory allocated from the stack and
  therefore recovered upon exiting the function

This is correct.

  is the fact that double2StrBuff1 is a pointer means that the pointer
  is allocated in the stack but the values are located in the heap
  (therefore what I am doing makes sense)?

No, double2StrBuff1 is not a pointer, it's an array. In C and C++,
when you use an array identifier, it decays to a pointer in many
situations. However, for the purpose of memory allocation, an array is
very different from a pointer.

Heap allocation only happens when using malloc() and new.


Are pins 2 and 3 supposed to be connected?

An input that isn't connected to anything "floats". It will give you unpredictable values. It could be influenced by nearby pins. That is probably what you are seeing. (The metal traces for the 2 pins probably run next to each other on the Arduino's PC board.)

You should either tie an input to ground with a resistor, tie it to +5V with a resistor, or use INPUT_PULLUP mode, which ties it to an internal pull-up resistor. Any of those things will prevent the input from "bouncing around" and giving unpredictable results.

(Note that using a pull-up resistor, either internal or external, has the result of inverting the logic state you get from that input (you get HIGH when the input is not connected to ground, and LOW when it is connected to ground.)


Reading Ground/Open signal wire combonations to power specific LED's - Can it be done?

First of all, Arduino is a 5V device, as such to drive the 9-12V LED you will need to use one or more transistors (depending on the LEDs type, number and connection, in series or in parallel).

Also, powering the Arduino from a 9-12V is not the best option: Arduino Uno has an onboard voltage regulator, but goes up to 9V maximum and, unless you go for the original one or a reputable manufacturer (Arduino is an open source project) I wouldn't go above 6V, because non-reputable manufacturers tend to use lower specs devices, like regulators which can get too hot when powered with high voltage: consider that the regulator will have to dissipate any excess energy into heat.

Said that, and knowing nothing more than what you said about the transmission you are describing, I assume the status open stands for open collector, meaning that it is not going to draw any current, so the following circuit is what you should use:

simulate this circuit – Schematic created using CircuitLab

The diagram assumes you are using digital pins 5 to 8 of your Arduino in INPUT mode and the Arduino GND is at the same voltage level as the transmission: this might be a big assumption, depending on how you power your Arduino (not from a battery pack, to be clear).

When node A is in open state, the voltage on Arduino pin 5 will be 5V, or HIGH as Arduino reports it. When node A is in low state then the voltage on Arduino pin 5 will be 0V, or LOW in Arduino lingo.

Resistors from R1 to R4 are there to limit current drawn when the gearbox is in state low.

UPDATE: I'm assuming the gearbox shares the same ground and operates at 5V,a s the Arduino does. If that's not he case and the gearbox operates at an higher voltage or does not share the same ground, the circuit will not work and you risk damaging the Arduino and/or the gearbox.

You can find a simulation of the above circuit where you can play with the different pins here.

The same occurs for the other pins, so your code will have to scan the 4 pins for their state and update your display accordingly, like:

#define PIN_A 5
#define PIN_B 6
#define PIN_C 7
#define PIN_P 8

void setup() {
  pinMode(PIN_A, INPUT);
  pinMode(PIN_B, INPUT);
  pinMode(PIN_C, INPUT);
  pinMode(PIN_P, INPUT);
}

#define PARK 0;
#define DRIVE_1 1;
#define DRIVE_2 2;
#define DRIVE_3 3;
#define OVER_DRIVE 4;
#define REVERSE 5;
#define NEUTRAL 99;
#define UNDEFINED 255;

unsigned int gear = UNDEFINED;
void loop() {
    bool A = digitalRead(PIN_A);
    bool B = digitalRead(PIN_B);
    bool C = digitalRead(PIN_C);
    bool P = digitalRead(PIN_P);

    if (!A && B && C && !P) {
      // Park - A=low, B=open, C=open, P=low
      gear = PARK;
    } else if (!A && !B && C && P) {
      // Reverse - A=low, B=low, C=open, P=open
      gear = REVERSE;
    } else if (A && !B && C && !P) {
      // Neutral - A=open, B=low, C=open, P=low
      gear = NEUTRAL;
    } else if (A && !B && !C && P) {
      // OverDrv - A=open, B=low, C=low, P=open
      gear = OVER_DRIVE;
    } else if (!A && !B && !C && !P) {
      // Drive 3 - A=low, B=low, C=low, P=low
      gear = DRIVE_3;
    } else if (!A && B && !C && P) {
      // Drive 2 - A=low, B=open, C=low, P=open
      gear = DRIVE_2;
    } else if (A && B && !C && !P) {
      // Drive 1 - A=open, B=open, C=low, P=low
      gear = DRIVE_1;
    } else {
      // none of the above
      gear = UNDEFINED;
    }
    // update your display here
}

Please note the above code is NOT the most efficient, but I believe it's easier to read and understand than a version using bitwise operations to identify the possible combinations.


Why are the Do While loops not stopping?

change >= and <= to > and < respectively.
You want it to stop at 0, but your do-while will do another round, since 0>=0 is true. So your code only stops at -1 and 256.
When legThreeBrightness is 256 it should be counting down, but your if (legThreeBrightness == 255){ doesn't detect this, so the code will continue counting up. I'd probably change this line to if (legThreeBrightness >= 255){ to prevent this from ever happening (which it shouldn't, but still).


How to blink the LED forever when detect an object is more than 30 cm away using ultrasonic sensor

You are initiating the NewPing library with NewPing sonar(trigPin, echoPin,30);. The last parameter is the maximum distance in cm, that will be measured. On the Arduino Playground site of the library it says

  sonar.ping_cm(); - Send a ping, returns the distance in centimeters or 0 (zero) if no ping echo within set distance limit

You're not handling the special case of no ping (in the defined limit), which occurs everytime you exceed 30cm in your case, and your value cannot get greater than 30 cm. You can change the if-statement for your warning from

if(sonar.ping_cm()>=30)

to

if(sonar.ping_cm()==0)


Powering the attiny85 with a separate power source

Does it make any sense...

Well, actually it does make sense and you already rationalize it in your question: less space consumed, expected life time of the coin cell is ok for your intended use case (though you could/should confirm the assumption about power consumption with the AVR's data sheet).

There is nothing wrong in powering the microcontroller with a different voltage than the "power" circuitry, assuming the ground lines are connected and the transistors mentioned are operated in a suitable mode, e.g. open collector/open drain type.


Arduino Pro Mini is burned by 12v. Can I save it?

1. Your microcontroller is probably/maybe fine; your tiny little voltage regulator is dead; here's why:
Sergio, yes, you can probably/perhaps save it: your Arduino (the microcontroller--ie: processor at least) is likely just fine, assuming the linear regulator smoked and failed open, meaning it did NOT pass through the raw input voltage to your ATmega328 mcu. It's the linear voltage regulator that is fried! That's this circled component below:

So, desolder that part and throw it away and you can continue using the Arduino just fine. Just power it with a regulated 5V directly to VCC is all and you'll be fine. I've done exactly this on some parts I exploded or smoked the regulator on (see below), and they continued working just fine.
IMPORTANT: if this is a safety-critical part, or a product, throw away the whole Arduino just in case.
Details on the fixes:

Desolder the voltage regular (circled in the image above, and shown desoldered on my Pro Mini in the photo below) and throw the desoldered voltage regulator away.

Power the board now through Vcc with anything between 3.3V and 5V (recommended: a regulated 5V into Vcc, such as the 5V line coming straight out of your USB hub).

Reflash the bootloader with a USBasp programmer (shown in 2nd of the two photos below).

Upload a new blink sketch via the external USB serial UART to blink the built-in LED13. This works fine on my Pro Mini below shown with exploded and desoldered regulator:
// the setup function runs once when you press reset or power the board
void setup() {
  // initialize digital pin LED_BUILTIN as an output.
  pinMode(LED_BUILTIN, OUTPUT);
}

// the loop function runs over and over again forever
void loop() {
  digitalWrite(LED_BUILTIN, HIGH);   // turn the LED on (HIGH is the voltage level)
  delay(500);                       // wait for a half-second
  digitalWrite(LED_BUILTIN, LOW);    // turn the LED off by making the voltage LOW
  delay(500);                       // wait for a half-second
}

Unplug the USBasp programmer when done, and continue development with just the external serial UART plugged in.

Here's some photos of my Arduino Pro Mini with exploded voltage regulator that I desoldered. I found it today. The Arduino still works fine! I desoldered the regulator around the year 2014 or so, but just re-flashed the bootloader, uploaded the code, tested it, and took these photos today:
Image 1: Arduino Pro Mini used as a data-logging altimeter in ~2014; photo from today. The voltage regulator exploded (read below), so I desoldered it. Both the power LED (top center of board), and LED13 (bottom-left of board) are ON. The power LED comes on automatically so long as you are powering the board through Vcc and GND from your USB port through your USB UART adapter, and the LED13 is blinking ON here due to the blink sketch above AND by powering the board with Vcc and GND from the USB serial UART to the Pro Mini. Note that the LED13 would NOT light up properly with just the USBasp plugged in, even when it was properly powered and programmed by the USBasp. I think it's because the USBasp was interfering with that pin. Plugging in the external serial UART to the Pro Mini's Vcc and GND fixed that, allowing LED13 to function properly as well while the Pro Mini ran the blink sketch above.

Image 2: External USB serial UART (in the USB hub top port), USBasp programmer wired to program the bootloader (in the USB hub under the USB UART), Pro Mini (bottom left) with power LED ON and LED13 (bottom-left of board) OFF.

On the surface, you didn't do anything wrong! You plugged 12V into the correct pin (RAW, which is the battery-in or voltage in line), and that is within the voltage limits of this part. BUT, what you neglected to consider is the power dissipation capability of this footprint or size of a part. The power dissipation capability is soooo low that realistically, 12V is too much, and will destroy the part.
6 years ago or so I made a couple little data-logging altimeters with the Arduino Pro Mini, connected 12.6V (a fully-charged 3S LiPo battery) to the RAW pin, and 15 seconds later: pop! They exploded! Literally, that little voltage regulator exploded into bits with 12.6V in. After that, I never put more than 8.4V in (a fully-charged 2S Lipo battery), and all was well. Since I was powering it from my main RC plane's 3S LiPo motor battery, this was accomplished by just tapping off of 2 of the 3 cells in the battery by plugging into the correct points on the battery's balance lead. So, I was able to use the same battery but just use 2 of its 3 cells instead of all 3 of them.
These regulators are just so tiny that they can't take much heat is all, and since they are linear regulators, all excess voltage is burned off as heat. Here's a couple example power dissipation calculations to make the point:
Imagine you are drawing 100mA total (0.1A) from this regulator. With 12V plugged in, you have to burn off 12V - 5V = 7V in that regulator chip.
Power_dissipated = Current*Voltage = I*V = 0.1A * 7V = 700mW

700mW is HUGE! Pop! Explosion! Dead voltage regulator chip.
But, if you feed it just 8V this same chip would have to burn off only 8V - 5V = 3V of excess voltage:
Power_dissipated = Current*Voltage = I*V = 0.1A * 3V = 300mW

That's 300mW/700mW = 43% as much power, or 57% less power. These numbers are just for example purposes, but you get the point.
Solution? 1) switch to Arduino Nanos, and/or 2) use a much lower input voltage (ex: 8~9V instead of 12V!). Nanos have MUCH bigger and beefier voltage regulators, and Nanos cost like $1 more when buying the Chinese clones.
2. How to calculate 1) how much power your regulator can dissipate without burning up, and 2) how much current you can therefore draw for different raw input voltages to the voltage regulator:
(Also: I wrote an article on my website covering more of these power, current, and voltage specs--see link here and at bottom.)
By the way, looking at the Pro Mini schematic here, I see that the original board used a MIC5205 linear regulator. The Chinese clone you have certainly uses a different regulator, but let's look up the MIC5205 datasheet for benchmarking purposes. A google search for "mic5205 datasheet" leads me here: https://ww1.microchip.com/downloads/en/DeviceDoc/20005785A.pdf. The device is rated up to 150mA current and up to +16V input voltage, but you must consider power!
The equation for that is hidden on pg 5 here:

Power_dissiplation_max =  P_D_max = (T_J_max – T_A)/theta_JA

theta_JA = thermal resistance from Junction to Ambient = 220 degC/W

T_A = ambient temperature = let's say, 40 deg C (104 deg F)

T_J_max = max junction (internal chip) temperature = +125 degC

So, we crunch the numbers:
P_D_max = (125C - 40C)/220 C/W = 85C / 220 C/W = 0.386W = 386mW max
power.

Final result: this tiny, linear voltage regulator, assuming absolute max junction temperature of +125 C (257 F) [HOT HOT HOT!--not good] and ambient air temperature of 40C (104 F) can dissipate 386mW max power before you risk making it go "pop"!
So, assuming you power it with 12V, how much current can you draw?
Voltage drop across the regulator = V_D = Vin - Vout = 12V - 5V = 7V

Power dissipation in the regulator = P_D = current * voltage drop = I*V_D

Solve for I:
I = P_D/V_D = 0.386W/7V = 0.055A = 55mA current!

With 12Vin and 5Vout, any more than 55mA current draw goes "pop" or smokes the chip!
With 8Vin, however, you could draw:
V_D = 8V - 5V = 3V
I = P_D/V_D = 0.386W/3V = 0.129A = 129mA current

With 8Vin and 5Vout, any more than 129mA current draw goes "pop" or smokes the chip!
So, use a lower input voltage and you can draw much more current! How low can you go? Don't go lower than 5V + dropout voltage. The datasheet on p3 for this regulator shows a max dropout voltage of ~350mV, so stay > 5.35V input to get a regulated 5V output.

That's all for this MIC5205 chip, though. Note that other voltage regulators may have dropout voltages as high as 2~3V, so you'd have to have an input voltage of at least 7V or so to ensure a regulated 5V output. I can't see the numbers well enough on your chip to google for its actual Chinese or whatever datasheet to do the calculations for your chip, but you can use my example calculations above to redo these calculations for any datasheet or part.
Other reading:

Google search for "sot 23-5 power dissipation"

Microchip Application Note AN792: A Method to Determine How Much Power a SOT23 Can
Dissipate in an Application

I also wrote an article on my personal website on 6 Jan. 2014 called "Arduino Power, Current, and Voltage Limitations", here, for more info. on these limitations.


class Motor {

This says to start defining a class. A class is like a "container" that holds both data and functions (methods). After defining the class, it becomes like a new variable type that you can declare multiple instances of.

  int enablePin;
  int directionPin1;
  int directionPin2;

These define the 3 integer variables (int=integer; whole numbers like 2, 3, 1000, -5, etc.) that belong to the class and have the identifiers given (enablePin, etc.) Since not otherwise specified, these variables are private, meaning that only other functions in the class can access them. Other parts of the program are not allowed to access these variables.

public:

This means that the following definitions are accessible by parts of the program that exist outside the class.

Motor(int ENPin,int dPin1,int dPin2) {
  enablePin = ENPin;
  directionPin1 = dPin1;
  directionPin2 = dPin2;
}

This defines the only "member function" in this class and because it shares the same name as the class (Motor), it is called a "Constructor", and allows you to pass arguments to an object created from the class -- in this case, if you declare an object of class Motor by myMotor = Motor(1, 2, 3);, the constructor is called with parameters 1, 2, and 3. This constructor happens to just set the private variables to be the same as the arguments passed in.

But... All of this is basic C++, so a book or course on C++ programming would be better in-depth resource to understand this.

The code snippet also is incorrect because it has unbalanced curly-braces -- there is one to open the definition of the class and one to open the definition of the constructor, but only one closing brace.


NodeMCU ESP8266 disconnected from WiFi after several hours running

What you need to do is leave the board connected to your computer and watch the serial monitor to capture the output during the crash.  If the board has a true crash it will output a bunch of information which may tell you why you it is crashing.  It could be a strings/heap problem or maybe a memory issue since you are declaring a new http object every 5 seconds.  Maybe try putting the HTTPClient http; line up where you declare the host variable so that it is a global variable and not a local variable.

Since your loop doesn't test to make sure the wifi connection is still good then if you get a disconnection then the program will just fail and never try to re-connect.  So at the start of your main loop put the same wifi testing logic that is also in the setup function. If the connection is down then reset and start from the very beginning to re-establish the wifi connection.

if (WiFi.status() != WL_CONNECTED) {
    ESP.reset()
  }