text:
What to do with Arduino floating pins?
I have some unused pins, should I connect them together and to the ground or leave them floating?

Just leave them floating. The only problem with that is that under certain circumstances this can cause the MCU to use a bit more current. This is only a problem if you run of batteries. The datasheet suggest enabling the internal pull-ups, like Majenko suggested, but I never had much luck with that, as it ended up drawing more current somehow. In the end I set them to OUTPUT and LOW.

@Gerben With the pullups enabled you can only get leakage current through the MOSFETs and internal resistor (which will be in the order of nano amps, if that). With an input floating current gets drawn every time the input switches state as it flaps around. Actively driving a disconnected output will theoretically cause more current consumption through the input circuitry since it is only the leakage current of the FETs that limits it, not the leakage current plus the resistance of the pullup.

@Gerben Leakage current is stated as 1µA @ 5.5V through the input circuitry in the datasheet. That means a resistance of 5.5MΩ. Add to that the ~30kΩ of the pullup and the leakage would be 0.995µA with the pullup enabled, compared to 1µA with the output being driven.

@Gerben You might find this interesting: http://www.ti.com/lit/an/scea046/scea046.pdf

@Majenko I think that's what the datasheet mentioned. Having the input voltage float and fluctuate in between Vih and Vil making the input(compare) circuitry consume more power. I think that's probably pretty rare. Also, only applies if the MCU is awake, which isn't a lot in all of my battery powered projects.

@Gerben In sleep mode the input is disconnected and the input to the schmitt trigger is clamped to ground.

The simplest thing to do is set them to INPUT_PULLUP.  If you want a purely hardware solution then you could connect them to GND through some resistors (10kΩ or whatever you have in that kind of order of magnitude will do).
You don't want to just tie them directly to ground, and you don't want to link them directly together - that could lead to short circuits and dead IO ports if any of the pins happened to get set as output and HIGH in software.

How would using the internal pull-up resistors lead to higher current consumption (Gerben's comment)? Perhaps address that in your answer (whether it is true or not)?

It wouldn't. It would do the opposite. A pulled up pin can only use current that flows as "leakage current" through the input circuitry (minuscule amounts). A floating pin uses current every time it causes the input circuitry to switch states.

It was just my observation in one or two of my projects. So take that with a grain of salt.

I saw instability with a kiosk audio player I built years ago, when I left the unused pins floating.  Once I grounded them through a 10k resistor, all was OK.  This was in a very dry environment so I suspect static was the problem.

Leaving them floating in most cases won't do any harm. Even touching the pins won't destroy anything. Tying extra external hardware is just unnecessary (though a 10k resistor would be harmless as well). Of course, you could also think about potential extra usages for those pins if you want to make your design a bit "future-proof". For example, adding 4k7 pull-up resistors to A4 and A5 and a connector could allow you to use the I2C interface for additional functions.


text:
Why the unsigned long is overflowing?
I want to convert hour to seconds but unsigned long is overflowing, here's the code:
#include <Wire.h>
#include <DS3231.h>

RTClib myRTC;
unsigned long seconds;
char timestr[9];

void setup() {
  Serial.begin(250000);
  Wire.begin();
}

void loop() {
  DateTime now = myRTC.now();

  snprintf(timestr, 9, "%02d:%02d:%02d", now.hour(), now.minute(), now.second());
  seconds = (now.hour() * 3600);
  Serial.println(timestr);
  Serial.println(seconds);
  delay(100);
}

And the console output is:
16:33:36
4294959360

Why is this happening?

It's not the unsigned long that's overflowing but the calculation that you're assigning to it.
3600 is a signed integer (by default), and now.hour() is an unsigned byte. The unsigned byte gets promoted to match the "largest" type in the calculation - a signed integer - and then the calculation is performed, resulting in a signed integer.
That signed integer is then assigned to an unsigned long and, if the result is negative (as it may well be - 10*3600 > 32767) you end up with a massive number.
The simple "cure" is to ensure that one value in the calculation is an unsigned long. And the best way of doing that is to make your constant an unsigned long: by appending "UL" to it:
seconds = (now.hour() * 3600UL);

source: Stack Exchange

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

sort: votes


text:
Can I use an AC signal to make an LED light up with arduino?
I want to use a 220VAC load as a signal and act as a switch to my arduino so Labview could interpret it as an LED ON state. I used a 4n33 octocoupler but it seems that the LED Simulation on labview keeps fluctuating. I think it's because of the negative half of the signal being blocked. Is there a way to fix this?
Here is my schematic

What code do you use to check the pin and send the value to Labview?

There's certainly an issue with your optocoupler circuit aside from the fluctuation you observe.
During a negative half-wave of 220V, you expect D1 to block the current through the LED. However, 1N4007 as any power rectifier has significant leakage current, about 5μA at normal temperature and up to 50μA when the diode is hot. This current will go though the LED which may have a much lower admissible reverse current (typical 0.1μA), damaging it. One possible schematic would be:

simulate this circuit – Schematic created using CircuitLab
Note that D1 is here not to block reverse current, but rather conduct it safely, protecting the LED of the optocoupler. Also, consider reducing the value of R2 while realising the bulk of current limitation with a non-polar capacitor: this setup will limit the current just the same but will dissipate 0.5W of heat instead of 2W as your resistor would.
Now, in either case the LED is only active when it's forwad-biased, which is less than half of the time, so it's quite normal that you see this fluctuation. In most cases, it can be reasonably dealt with by software: read your pin 3 times with a 5ms delay after each reading, and make a logical AND of your three readings.
If, for some reason you cannot do that in software, you could implement an envelope detector in hardware. I strongly suggest to do it on the low-voltage side instead of 220V side (as e.g. here)

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


text:
strtoul behavior between C and Arduino
I have this code C code that compiles OK on my laptop
#include <stdlib.h>
#include <stdio.h>
#include <string.h>

unsigned int crc32(const void *m, size_t len) {
  const unsigned char *message = m;
  size_t i;
  int j;
  unsigned int byte, crc, mask;

  i = 0;
  crc = 0xFFFFFFFF;
  while (i < len) {
    byte = message[i];
    crc = crc ^ byte;
    for (j = 7; j >= 0; j--) {
      mask = -(crc & 1);
      crc = (crc >> 1) ^ (0xEDB88320 & mask);
    }
    i = i + 1;
  }
  return ~crc;
}

int main() {
  char str[] =
      "620004";
  size_t len = strlen(str);
  unsigned int crc = crc32(str, len);

  size_t len2 = (len + 1) / 2;
  unsigned char arr2[len2];
  for (size_t i = 0; i < len; i += 2) {
    arr2[i / 2] = strtoul((char[3]) {str[i], str[i + 1], '\0'}, 0, 16);
  }
  crc = crc32(arr2, len2);
  printf("CRC: 0x%X\n", crc);

  return 0;
}

And I'm trying to port it to Arduino
#include <CRC32.h>

void setup() {
  Serial.begin(115200);
  uint8_t byteBuffer[] = "620004";
  size_t numBytes = sizeof(byteBuffer) - 1;
  size_t len2 = (numBytes + 1) / 2;
  unsigned char arr2[len2];
  CRC32 crc;
  for (size_t i = 0; i < numBytes; i += 2) {
    arr2[i / 2] = strtoul((char[3]) {byteBuffer[i], byteBuffer[i + 1], '\0'}, 0, 16);
  }
  for (size_t i = 0; i < numBytes; i++){
    crc.update(byteBuffer[i]);
  }

  uint32_t checksum = crc.finalize();
  Serial.print("CRC: ");
  Serial

But I'm getting a
Arduino: 1.8.9 (Linux), Board: "Arduino/Genuino Uno"

/home/nico/Arduino/crc32/crc32.ino: In function 'void setup()':
/home/nico/Arduino/crc32/crc32.ino:11:50: warning: narrowing conversion of 'byteBuffer[i]' from 'uint8_t {aka unsigned char}' to 'char' inside { } [-Wnarrowing]
     arr2[i / 2] = strtoul((char[3]) {byteBuffer[i], byteBuffer[i + 1], '\0'}, 0, 16);
                                                  ^
/home/nico/Arduino/crc32/crc32.ino:11:69: warning: narrowing conversion of 'byteBuffer[(i + 1u)]' from 'uint8_t {aka unsigned char}' to 'char' inside { } [-Wnarrowing]
     arr2[i / 2] = strtoul((char[3]) {byteBuffer[i], byteBuffer[i + 1], '\0'}, 0, 16);
                                                                     ^
crc32:11:84: error: taking address of temporary array
     arr2[i / 2] = strtoul((char[3]) {byteBuffer[i], byteBuffer[i + 1], '\0'}, 0, 16);
                                                                                ^
exit status 1
taking address of temporary array

This report would have more information with
"Show verbose output during compilation"
option enabled in File -> Preferences.

And I'm not really understanding what's the issue here with the strtoul function and its different behavior on Arduino

All those errors are related to (char[3]) {byteBuffer[i], byteBuffer[i + 1], '\0'}, it has nothing to do with strtoul. Who knows how old is the compiler where it works.

Btw first two are caused by difference between:  char str[] = "620004"; and uint8_t byteBuffer[] = "620004";

Please make an answer, don't post an answer as a comment. Comments are for clarifying the question.

In some architectures a "char" is an "unsigned byte". In others it's a "signed byte".  The AVR specification mandates a signed byte for char. Whatever you are compiling on probably mandates an unsigned char.
You cannot assume one or another. If you are working with an array of characters (a "string") you should be assigning it to a char data type. That way the signage of the data type and the "string" content will match.
By using uint8_t you are specifically telling it to use an unsigned byte.
strtoul() expects a char. Since on AVR char is signed, when you try and squeeze an 8-bit value into a 7-bit + sign space it warns you. Which is good. You potentially lose the 8th bit of your data.
The main error, though, is:
error: taking address of temporary array

This is caused by you creating a new temporary array within the parameter list of strtoul.
{byteBuffer[i], byteBuffer[i + 1], '\0'}

Then you take the address of that array and pass it to the function.  That is not good. Imagine the situation where the function returns something that is dependent on that address. For instance a function that returns a pointer to all but the first character of the string.  Once the function returns that returned pointer points to an area of memory that is no longer valid - the temporary array has already been disposed of.
I know that's not the case in your code, but it's a possibility you can conceive.
Yes, temporary arrays like that are perfectly valid in some versions of C++. But those are fairly recent versions, and the Arduino compiler isn't that recent (I don't know which version introduced them as valid off hand, but we're up to GCC version 8 now. Arduino is still down at version 5.something IIRC).
Suffice it to say, don't use temporary arrays like that (which is a shame, because it's damn useful).  Instead you have to assign it to a new array and pass the pointer to that array instead:
char tempArr[3] = {byteBuffer[i], byteBuffer[i + 1], '\0'};
 arr2[i / 2] = strtoul(tempArr, 0, 16);

That way the address you're passing to the function is one that is allocated on the stack and is guaranteed to exist past the lifetime of the function call (right up until the end of the current scope).

Not questioning the language issues that were pointed out, but simple answer to what you asked,

"... what's the issue here with ... its different behavior on Arduino"

is that these are two different compilers, possibly written to two different standards of the language (the standards evolve over time) and likely run with different error- and warning suppression switches.
And not to be pedantic but to clarify, it hasn't actually run on the Arduino yet, not having compiled successfully in that environment. The differences you see are entirely due to the differences between the two compilers and the error-options they were run with.


text:
Arduino vs 12bit ADC
12bit ADC will give us about 1.2mV per step:
5 / 4096 = 0.00122

But if we give Arduino a 1.2V voltage reference we get 1.1mV per step:
1.2 / 1024 = 0.00117

Does that means Arduino can be more accurate than a 12 bit ADC?

precision, not accuracy. you can give your 12 bit ADC a lower ref than 5v, so that would quickly be more precise than the uno. An external is likely to be less noisy as well.

In a word, no.
The Arduino uses a rather crude 10-bit ADC. If you feed it a small voltage reference, you can divide that small voltage into 1024 steps. (as you say, about 1.1mV/step)
If you feed the same small 1.2V reference voltage into a 12-bit ADC, you'll get 4 times as many steps for the same range. (about 293μV/step)
And, as mentioned before, the ADC's in Arduinos are not very good. They're slow, and not very accurate.
(To be technical, precision is how exactly you DESCRIBE your answer. A decimal reading using more decimal places is more precise than a reading with less decimal places. Accuracy is how close the measured value is to the actual value. If you're sloppy with your measurements but use lots of decimal places to write it down, and the answer is very far off, you have a precise but inaccurate answer. (e.g you measure something as 1.0000001 millimeters, but it's really 2.5 mm.
A 12-bit ADC is more precise than a 10-bit ADC, but it may or may not be more accurate. Given the crude nature of the ADCs in Arduinos, a dedicated 12-bit ADC is likely to be more accurate than built-in one.)


text:
Quick noob question about connecting 16x2 LCD
In this tutorial the writer used digital pin 2-5 and pin 11 and 12, can I use other I/O pins if I define it in the library?
const int rs = 12, en = 11, d4 = 5, d5 = 4, d6 = 3, d7 = 2;
LiquidCrystal lcd(rs, en, d4, d5, d6, d7);

Yes, you can. There is nothing special about the pins an LCD like this uses, it's just simple IO.  You can even use the "Analog" pins for digital IO.  The only pins to stay away from, which is a good rule in general, are the TX and RX pins (pins 0 and 1 on the UNO) as they are used for communication with the PC through USB.  All the other pins are fare game for something as simple as an LCD.


text:
request for a member "X" in something not a structure or a union
i was programming a Self Balancing    Robot, I am writing the code in vscode using platformio extension.
when i put the code i need to get the angle out of the gyro in another file (named angle.c) and including it in the main program, the ide throws with error, in every line I use the Wire library in the angle.c, however same code copy and paste it in the main program and it works.
P.S. the angle.c is just a file of functions and doesnot have any class.

Check the command when compiling angle.c. Is that that right compiler? Try the extension .cpp instead.

the compiler is checked, i'll try the .cpp extension

you can't include Wire.h in .c . Wire.h defines a class

that is it you are right, no please post it as an answer, so that i can accept it

the solution is to change the extension into .cpp because Wire.h defines classes

A .c file is compiled with C compiler. If you include Wire.h which contains a class definition, the C compiler doesn't understand it and generates errors.
If your angle.c file doesn't have C code not compatible with C++, then change the extension of the file to .cpp and it will be compiled with C++ compiler.


text:
using two mpu6050 to get more accurate and precise angles
i have been using this gyro for a while, now i am aware of all measures taken, to improve the outcome of this board.
my question is: would using two at the same time improve the results?
if yes how to use them both?
thanks in apporch

Using two IMU on same board might not give you that same result as IMU units data depends upon placement and orientation soldered. They are advised to be soldered at the center of your board, as two IMU  can't soldered at the center of same PCB in same orientation.

@vaibhav, yes got it. it is actually not a problem since the acceleration measured is the same on all the board  (law of physics). the only reason to put the imu in the center is to avoid noise out of vibrations.

Maybe you can account for the displacement from the center by calculation. But using 2 units will only reduce some of the electrical noise in the sensors. Often a big part of noise on the gyros data comes from vibrations in the device. Let's say you are building a robot. The motors will induce vibrations, when running. These can get caught up by the gyros, depending on the positions of gyro and motor and the form of the frame. What kind of device are you building?

would you mind chrisl of you put your comment as an answer so i can accept it.

Using a Kalman filter might help here.


text:
How does the dual 5V and 3.3V output on the Uno R3 work exactly?
I'm constructing a circuit that needs both voltage supplies (for 3.3V RFID and 5V relay, GPS and screen) but the Uno is physically too big so I need to use a nano or mini pro, both of which I can only get in 5V. I understand how to use a regulator to drop 5V to 3.3V for the RFID-IC power but I keep seeing instructions to use a level shifter between the IC outputs and arduino input pins. I was just wondering if the Uno has a built-in level shifter for all pins or some other method as the I/O pins do not have specified voltages or uses.
Thanks for your time.

Pins of the UNO/Nano/Mini/Mega board are connected to GPIO pins of the MCU without any additional circuit. The ATmega MCU running at 5 V will sense 3.3 V as HIGH because of the threshold level to convert voltage to logic state.
ATmega will read the pin HIGH from 0.6 * Vcc, so at 5 V Vcc the threshold is 3 V.
Sources:

Schematics of Arduino Uno
Datasheet of ATmega328p (28.2 DC Characteristics)

There are no built-in level shifters on the Uno; it doesn't need them. Uno's 3.3v pin is merely a convenience for supplying a low-current 3.3v device but there is no provision made for level shifting if/when that is necessary.
Genuine Uno's can deliver a max of 150mA to the 3.3v pin, so plan your current-budget conservatively. In my dual-voltage designs (2 voltage rails on a board with 3.3v & 5v parts), I reduce the "raw" 5v with a 3.3v regulator (typically an LM1117-3.3 part) rather than drawing it off of the regulated 5v power. (I put "raw" in quotes because I usually supply the board with a pre-regulated 5 volts (USB or wall-wart).
For I/O levels, a 3.3v part's HIGH level is within the range of what Uno will read as HIGH. In the other direction, Uno's HIGH level is too high for a 3.3v part and needs to be shifted down to 3.3v. If there are only one or two such signals (Uno -> 3.3v device), a voltage divider circuit would be less expensive and use less board space than a level-shifter. The level-shifter board would be an extra purchase but it is a quick and dirty solution if you have the space for it.

You can get pro-mini in 3.3V, but this has little to do with your problem.
The nano runs on 5V, but has an on-board regulator which supplies 3.3V power, although the logic I/O is 5V.
Level shifters can be used to perform logic level translation, but are not always needed.
The output of a 3.3V logic circuit will drive the INPUT of a 5V logic circuit (technically this is marginal, but works in practice).
5V logic outputs can be connected to 3.3V inputs with a simple voltage divider (you can use level shifter or other methods). Without some means of limiting voltage there is a risk of damaging the 3.3V logic.
Without more detail of exactly what you are planning it is not possible to be more precise.

Thanks, my question was mainly to clarify my own understanding of why a 5V nano or pro-mini would need a level shifter but the Uno does not.

I am building an e-bike security system. Part 1 is a rfid reader embedded in the handle bar which the arduino uses as a test for the presence and ownership (via nfc ring) of the rider, driving a relay to connect the accelerator while authorised user is present. Part 2 is a GPS tracker which disables all of the bike functions when activated. Part 3 is a possible future addition which will be a display unit replacing the current factory unit.

@DanBailey, "why a 5V nano or pro-mini would need a level shifter but the Uno does not". not one of them needs logic level conversion from 3.3 V on input pin and any 3.3 V input controlled by them and not 5 V tolerant should have a logic level conversion


text:
Change css form color from esp32 if statement
I am fairly new to arduino and ESP though am very familiar with css and javascript.
I have an esp webserver that includes a button
client.print("<button style='background-color: #F30C0C; color:#000;'></button>");

but need it to change the css backbround-color when pin is reading HIGH
 if (c == '\n') {
          currentLineIsBlank = true;
          buffer = "";
        }
        else if (c == '\r') {
          if (buffer.indexOf("GET /?relay1") >= 0)
            relayPIN1read = digitalRead(relayPIN1);

          if (relayPIN1read == HIGH) {
            digitalWrite(relayPIN1, LOW);
          }
          if (relayPIN1read == LOW) {
            digitalWrite(relayPIN1, HIGH);
          }
        }
      }

Does any one know of any way to do this?

First print everything up to the colour. Then print the colour, which you change depending on the state of the pin. Then print the rest.
client.print("<button style='background-color: ");

if (digitalRead(PIN) == HIGH) {
    client.print("#0CF30C");
} else {
    client.print("#F30C0C");
}

client.print("; color:#000;'></button>");

I  did try that, but seamed to go HIGH and LOW as if it was in a 2 count loop.. but will give it another go... Thank you

@Ben You are sending a "toggle" command rather than a "set" or "reset" command. You should separate it out and use a similar system as the colour to change the command the button sends.

dont know what i was going last time.. but that worked like a charm.. thanks very much for your time :)


text:
Arduino Nano drivers
I got a Arduino Uno awhile ago and it took me awhile to set up but it worked when I downloaded the IDE. This time when I bought an Arduino Nano it doesn't pop up with the driver. Doesn't show up anywhere in device manager. I've tried to reinstall the IDE to see if that would work but it didn't. What should I do/try next?

Is it a real Nano or did you get some cheap POS from eBay / Amazon?

@Majenko That was quick, yes it is a real one. Arduino Nano A000005.

I'm not sure if the IDE comes with the FT232RL drivers any more - if it doesn't you may need to manually install them from the ftdichip website.

I downloaded a FTDI VCP driver and I ran it until nothing popped up anymore but after all of that nothing happened nothing in device manager still. Doesn't make any sound when I plug it in.

Check your usb cable.

It is on if thats what you're saying, green light on the top

That means nothing. Some cheap usb cables lack data wires. Power works but nothing else.

Well I did burn out the cables that I used last night so I'm gonna have to go find another one

How the hell do you burn out a usb cable?!?!

12v through usb hub but I found another cable and it works lol ty for suggestions. :)


text:
Arduino controlled LCD 16x2 is very very dim
I was testing out whether my 16x2 LCD works. I hooked it up to the arduino.
Some white box appeared which probably meant it works fine, but the box and the blue background looked very dim even when the potentiometer was turned to the maximum, and did not have the bright blue background which I saw on google.
FYI I soldered copper wire on the LCD and shoved them onto the breadboard since I did not have any pin headers. Would this be a cause of the problem?

Looks like you have no back light. Is the back light wired correctly?

I can't see much solder on the LCD on that photo. Are all of those wires soldered on?

I suggest you invest a dollar or so and get some proper wires. Those bare wires, which don't look soldered on, from the top view, just don't cut it. It also looks like the individual wires would short with each other (or are actually shorting).
It will light up when the backlight is correctly connected, which is impossible to tell from your photo.

It even looks like the “K” pin does not have a wire on it at all. Just a blob of solder filling the pad.


text:
Can I use the PWM pins as regular digital input/output pins?
In regards to the arduino which has pwm pins, can I use these pins as normal input/output digital pins or not? Thanks in advance.

have you tried?

Not directly related to the question but perhaps noteworthy, you can also use the Analog-In pins as regular digital IO.

Yes that is true and an often overlooked fact. Indeed most pins have multiple functions. Arduino pinout diagrams are extremely useful to see what an individual pin is capable of. Most have more than one function. Some have more than two functions.

Yes you can use them as ordinary digital io pins. PWM is essentially a normal digital output pin that is repeatedly turned on and off at a high rate.
The magic is that the turning off and on is done in the hardware according to the duty cycle  (I.e. there is no need for software to perform the on/off operations) . This is why only some pins can do h/w PWM, because the PWM hardware is not added on to all pins.
If you are not using the pin for PWM, it is available for you to use as required.


text:
Velleman KA02 not working on Mega 2560 r3
I have a Velleman KA02 audio shield. When I use this shield on an Arduino UNO R3 with this sample code, it works. And by "work" I mean when I interact with the Serial Monitor (by pressing Y, for example), I hear the playback.
However, if I place this audio shield on a Mega 2560 R3, the shield no longer works (pressing Y does nothing). I read about the SPI library, and the document seems to suggest that MISO, MOSI, SCK and SS are different for the Uno vs the Mega. For the Uno,

MOSI: 11
MISO: 12
SCK: 13
SS: 10

and the article is consistent with the constants defined in the ISD1700.h file. For the Mega,

MOSI: 51
MISO: 50
SCK: 52
SS: 53

I can modify ISD1700.h for use with the Mega easy enough. However, I do not think I can just sit the audio shield right on top of the Mega with the modified code and have it work. I used some (male to female) jumper wires to connect from the Mega pins 50, 51, 52, 53 to the audio shield pins 12, 11, 13, 53 (correspondingly). Additionally, I have jumper wires connecting the power and ground from the Mega to the audio shield. What works is that the audio shield has power and I am able to press the physical buttons on the audio shield to record and playback. What does not work is that when I enter Y in the serial monitor to force a playback, although the character is read and the switch case is reached, the playback never happens.
Any ideas on what I am doing wrong? On the Velleman site, they seem to suggest that this audio shield only works with the Uno, but the Illustrated Assembly Manual says that the audio shield should work with the Mega.

put the shield on and it should work. don't change ISD1700 chip(10); to ISD1700 chip(53);

Nevermind, I solved it. There's 6 pins located on the Uno and Mega labelled ICSP, and those were the key. I simply connected the MOSI, MISO and SCK pins on the Mega to the audio shield (along with GND and 5V) and also the 10 pin (audio shield) to the 53 pin (Mega) via a male to male jumper. The header code was modified to work with the new values, and now I am able to send character signals via the serial monitor.

and why did you change ISD1700 chip(10); to ISD1700 chip(53);? 10 is a good for CS


text:
Serial Communication between arduino and nodeMCU
I am trying to connect a nodeMCU to arduino mega using serial communication so that i can read data from firebase.

I have put the following code on the NODEMCU.
#include<SoftwareSerial.h> //Included SoftwareSerial Library
//Started SoftwareSerial at RX and TX pin of ESP8266/NodeMCU
SoftwareSerial s(3,1);

void setup() {
  //Serial S Begin at 9600 Baud
  s.begin(9600);
}

void loop() {
  //Write '123' to Serial
  s.write('h');
  delay(1000);
}

And the following on the MEGA
int data; //Initialized variable to store recieved data

void setup() {
  //Serial Begin at 9600 Baud
  Serial.begin(9600);
  Serial1.begin(9600);
}

void loop() {
  if(Serial1.available()){
  data = Serial1.read(); //Read the serial data and store it
  delay(1000);
  Serial.print(data);}
}

I have connected TX1(arduino) to RX(nodeMCU) and RX1(arduino) to TX(nodeMCU) yet when ever i upload the code it doesnt work until i press the reset button then  some random numbers are passed over then eventually 123 comes accross. I am trying to do 2 way comunication but will worry about that when i finish this.

Any help would be much appreciated as I have spent the last 15 hours trying to solve this problem but to no avail.
Cheers, Hamish

you did not say how you connected the two controllers together ... please list all wires and all pins

Why not use the standard Serial instead of SoftwareSerial?

you use old esp8266 SoftwareSerial on hardware Serial pins of the esp8266. and you set the pins swapped in the SoftwareSerial constructor


text:
Choosing between ESP32 and Arduino Pro Mini
This is probably a fundamental question but I am hoping to get some pointers on how to chose between Arduino Pro Mini and ESP 32.
I am hoping to make a wrist based wearable like fitbit. Three primary needs are

Accelerometer or MPU module is important to collect movement data.
Wi-fi is not important because I think bluetooth would be enough to sync the data to a cell phone.
Battery management is of course more critical as I want it to last longer.
Smaller the dimensions, better for design and aesthetics.

My first choice was using Arduino  pro mini because it is smaller and less  power consuming.  However, we do need to manually connect BLE module like HC-05 to it. Now I think ESP32 could also be a good option because it has both wifi and bluetooth although I do not care about wifi.
Now I found these useful comparisons on web

Arduino and NodeMcu (ESP8266) like this
Between ESP32 vs ESP8266 like this
Between Nano or pro mini like this

However, none of them help me directly in my case. I understand ESP32 and ProMini are meant for different things and hence should not be compared for a single project. May be I am missing something more fundamental. Any guidelines in this would really help.

why not compare with nRF5? 32bit ARM Cortex M0 with Bluetooth

Absolutely. I was about to suggest the same thing. Something like the nRF51822 would be a far better fit for your project.


text:
Arduino Communication with Sim 900
Im using an arduino uno and a sim 900, the simcard is setup and working as I can make a phone call to it and it rings.
The sim 900 is powered via the power jack and the uno is currently powered using USB.
I am trying to print out incoming text messages however with serial monitor open I only see "Initialising...".
    #include <SoftwareSerial.h>

//Create software serial object to communicate with SIM900
SoftwareSerial mySerial(7, 8); //SIM900 Tx & Rx is connected to Arduino #7 & #8

void setup()
{
  //Begin serial communication with Arduino and Arduino IDE (Serial Monitor)
  Serial.begin(9600);

  //Begin serial communication with Arduino and SIM900
  mySerial.begin(9600);

  Serial.println("Initializing...");
  delay(1000);

  mySerial.println("AT"); //Handshaking with SIM900
  updateSerial();

  mySerial.println("AT+CMGF=1"); // Configuring TEXT mode
  updateSerial();
  mySerial.println("AT+CNMI=1,2,0,0,0"); // Decides how newly arrived SMS messages should be handled
  updateSerial();
}

void loop()
{
  updateSerial();
}

void updateSerial()
{
  delay(500);
  while (Serial.available())
  {
    mySerial.write(Serial.read());//Forward what Serial received to Software Serial Port
  }
  while(mySerial.available())
  {
    Serial.write(mySerial.read());//Forward what Software Serial received to Serial Port
  }
}

I cant for the life of me figure out why its not printing anything else out? Can anyone give me any guidance or what to check?

Check out https://arduino.stackexchange.com/q/13683/19409

I think I see on the shield jumpers to use it over SoftwareSerial even if it is on the Uno

The 'Initializing' printout happens because that is sent directly to the UNO's hardware serial port.  The rest doesn't happen because it is directed to the SIM card via SoftwareSerial pins 7 & 8, and the SIM card apparently isn't responding.
Cut the problem in half:  Connect pins 7 & 8 together, and run your program again.  If you get "AT" and the rest, then you know the 'MySerial' port is active and working correctly, and the problem is in the SIM 'half'.  Maybe you have an incorrect wire connection there, or maybe the SIM card's default serial rate isn't 9600, or something like that.  YMMV ;-).
As a test, I ran your program on a UNO, with a jumper wire between pins 7 & 8.  Unfortunately this did not work, but now I knew that the problem had nothing to do with the SIM shield. The result wasn't what I expected, but now I had 'cut the problem in half'.
Now that I had determined that the SIM card wasn't a factor (so far, anyway), I could concentrate on the 'UNO half'.  After some web research I found that 'Software Serial' doesn't support 'loopback' (looping the transmit line back into the receive line) because it cannot simultaneously transmit and receive.  Fortunately, the 'AltSoftSerial' library by Paul Stoffregen does support simultaneous transmit & receive, and so will support loopback.
So, I installed the library on my Arduino setup, and compiled and uploaded the example shown below.
#include <AltSoftSerial.h>

// AltSoftSerial always uses these pins:
//
// Board          Transmit  Receive   PWM Unusable
// -----          --------  -------   ------------
// Teensy 3.0 & 3.1  21        20         22
// Teensy 2.0         9        10       (none)
// Teensy++ 2.0      25         4       26, 27
// Arduino Uno        9         8         10
// Arduino Leonardo   5        13       (none)
// Arduino Mega      46        48       44, 45
// Wiring-S           5         6          4
// Sanguino          13        14         12

AltSoftSerial altSerial;

void setup() {
    Serial.begin(9600);
    //while (!Serial); // wait for Arduino Serial Monitor to open
    Serial.println("AltSoftSerial Test Begin");
    altSerial.begin(9600);
    altSerial.println("Hello World");
}

void loop() {
    char c;

    if (Serial.available()) {
        c = Serial.read();
        altSerial.print(c);
    }
    if (altSerial.available()) {
        c = altSerial.read();
        Serial.print(c);
    }
}

After uploading the code, I 'looped' pin 9 back to pin 8, and found that when I sent characters to the UNO via the hardware USB port, they showed up again 'echoed' to the serial output after having traversed the AltSoftSerial port 8/9.
So at this point I have solved the UNO 'half' of the problem; the rest is up to you! ;-)

or maybe they wired the SoftwareSerial to pins 6 and 7 on the shield and not to RX and TX

Or a thousand other possibilities.  I'm not familiar with the SIM shield, so hard for me to say....

then why did you write an answer?

Thanks for you answer, I did come across the software serial not being fully supported however I'm quite a newbie to arduinos. I've moved towards using a different shield for my project but I will try again using your very helpful answer.

Glad to help, and I hope you continue to enjoy your adventures in Arduino-land.  If you have the time, please mark my answer as 'Accepted', as (I think) that will improve my 'reputation' score and let me help others as well.


text:
How fast should I be able to write to AT45DB321D flash memory?
I checked the AT45DB321D datasheet and it says it operates at either 66 MHz oder 33 MHz. Both of these speeds are higher than what an Arduino Nano supports (my google fu fails me here, but according to the Arduino SPI doc it's probably on the order of 4 MHz).
According to the datasheet

Data can be clocked in from the input pin (SI) into either buffer 1 or buffer 2. To load data into the standard DataFlash buffer (528 bytes), a 1-byte opcode, 84H for buffer 1 or 87H for buffer 2, must be clocked into the device, followed by three address bytes comprised of 14 don’t care bits and 10 buffer address bits (BFA9-BFA0). The 10 buffer address bits specify the first byte in the buffer to be written. [...] Data will continue to be loaded into the buffer until a low-to-high transition is detected on the CS pin.

Which means to write a single byte I would need

1 opcode byte
3 address bytes
1 data byte

totaling 5 bytes or 40 bits which at 4 MHz yields 10 µs.
My code, as below, yields roughly 48 µs per byte (outputs a duration of ~12380 µs for transfering 256 bytes). I'm using the DataFlash library.
#include <SPI.h>
#include "DataFlash.h"

static const int csPin    = 10;
static const int resetPin = 8;
static const int wpPin    = 7;

DataFlash dataflash;

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

  SPI.begin();

  dataflash.setup(csPin, resetPin, wpPin);
  dataflash.begin();

  long start = micros();
  dataflash.bufferWrite(0, 0);
  for(int i = 0; i <= 255; i++) {
    SPI.transfer(i);
  }
  long afterBuffer = micros();

  Serial.print("Writing 256 values to buffer: ");
  Serial.println(afterBuffer - start);
}

void loop()
{
  // nothing
}

It's very likely I'm missing something, but especially if I want to transfer larger chunks of data at once I'd like to speed up that process a bit. Creating a 256 byte buffer and writing it all at once
// outside time measurement
uint8_t buffer256[256];
for(int i = 0; i <= 255; i++) {
  buffer256[i] = i;
}
// inside time measurement
SPI.transfer(buffer256, 256);

takes roughly the same time.
tl;dr: Is everything working correctly/what am I doing wrong? How can I speed up writing to a flash chip using an Arduino Nano?

The fastest that SPI can work at is F_CPU/2, so for a 16MHz Arduino that's 8MHz.

I would attach an oscilloscope and measure; that's the best way to see whether my assumptions about clock frequencies and times are right.

"Data will continue to be loaded into the buffer until a low-to-high
  transition is detected on the CS pin."

The dataflash.bufferWrite command writes the opcode and address bytes and then in the for loop you write 256 data bytes. The data bytes are written at once, without preceding each single one with the opcode and the address. (So it does already what you want to do.)
It doesn't matter whether you write the byte at once or each with a single SPI write. SPI can only send them sequentially. And the initial opcode and address is only send once with the dataflash.bufferWrite command.
BTW: There are two buffers to write to 1 and 2. So I'm curious why the command dataflash.bufferWrite(0, 0); works. IMHO that should be dataflash.bufferWrite(1, 0); or dataflash.bufferWrite(2, 0);.
You also not start the internal writing to the pages. There is no command e.g. dataflash.bufferToPage(1, 7);. The data are only transfered into the flash's buffer.
Because data is not written into a memory page, you'll lose it, if you switch off the power.
UPDATE
I fear I understood your question not completely. As I now see, you wondered why you need 48 µs in average for 256 Bytes when the SPI Bus is driven with 4MHz.
I looked a little in the codes and docs. And that's what I found:
The DataFlash lib selects a different Clock divider:
/* Setup SPI */
SPI.setDataMode(SPI_MODE3);
SPI.setBitOrder(MSBFIRST);
SPI.setClockDivider(SPI_CLOCK_DIV2);

SPI_CLOCK_DIV2 results after some computation to a frequency of Fosc/2. The computation are very difficult to follow, because they use an 8 bit number which is divided into 2 nibbles each of them defines a part of a register content. But I'm quite sure the result is Fosc/2. But that would result in a clock frequency of 8 MHz. That can not explain your observed timings.
BTW: There is also in interesting deprecation note about setting the clock speed this way. ;-)
  // This function is deprecated.  New applications should use
  // beginTransaction() to configure SPI settings.
  inline static void setClockDivider(uint8_t clockDiv) {
    SPCR = (SPCR & ~SPI_CLOCK_MASK) | (clockDiv & SPI_CLOCK_MASK);
    SPSR = (SPSR & ~SPI_2XCLOCK_MASK) | ((clockDiv >> 2) & SPI_2XCLOCK_MASK);
  }

But then I saw another thing that could be a problem. There are to single value transfer functions. One for bytes (uint8_t) and one for integers (uint16_t). Your count variable is an integer so the two byte transfer method is used, resulting in two byte per transfer and therefor 512 bytes. But that also no explanation for the observations. And writing buffers works only with uint8_t[] so ??.
What else could have happened?
The MCU could be clocked by a lower frequency then 16MHZ. I think there are fuses that can be configured to reduce the master clock speed for using the MCU with lower voltage (like 3.6 Volt).
The missing beginTransaction / endTransaction (DataFlash doesn't use this) of the SPI bus could have impact on the interrupts which could distort the timing. (But that's a very wild guess ;-))
The observation that, transferring twice the amount of data with the single int transfer method does take roughly the same time than the buffered method gives us a hint, that possibly the SPI speed is not the problem.
In the function dataflash.bufferWrite(0, 0); there is e.g. a wait function
waitUntilReady(); that could cause a long delay of ~12 milli seconds. You can easily try that, by taking the dataflash.bufferWrite(0, 0); out of the timing.
void DataFlash::waitUntilReady()
{
    while(!isReady()) {};
}

uint8_t DataFlash::isReady()
{
    return status() & AT45_READY;
}

uint8_t DataFlash::status()
{
    uint8_t status;
    reEnable();     // Reset command decoder.
    SPI.transfer(DATAFLASH_STATUS_REGISTER_READ);
    status = SPI.transfer(0);
    disable();
    return status;
}

You're right, bufferWrite(0, 0) works because internally it's (among other things) SPI.transfer(bufferNum ? DATAFLASH_BUFFER_2_WRITE : DATAFLASH_BUFFER_1_WRITE);. Also, I am aware of the transfer of the buffer to the memory page, but that's outside the scope of this question (and takes approx. 50 µs as well ;-).

Thank you. I assumed something like that, but was not sure. I read the question a second time and now I hope, I see the problem. I'll update the answer.

@Raketenolli I've updated the answer.

Sorry for not getting back to this sooner, and now I'm wondering whether I changed anything back then that I now forgot about. I am now observing between 660 and 670 µs consistently for the entire writing operation, which means roughly 2.6 µs per byte. The SPISettings speedMaximum parameter only has an effect when set to less than 8000000, where the duration will increase to 940 µs (and then in steps to 1520, 2500 and 4560).


text:
Using an L298N driver together with servo motors on the same arduino
I'm using an L298N driver (powered by a 12V, 1.5A adapter) on a MEGA Sensor Shield (powered by a USB cable). Everything works fine and I can control the direction and the speed of the DC motor, however when I activate anything else on the shield - the motor will not spin unless I set the PWM to its highest frequency.
Please note that I am using Max/MSP to controls the motors, so when I say activate - I mean setting up the PinMode of pin 17 to "Servo". If I set up the Servo first and then the DC motor pins - it will again start spinning only at maximum PWM, there's no signal reaching the driver otherwise.
Am I missing something in my setup? I would use Arduino Mega on its own, however I need to use over 25 Servo motors together with the L298N driver, which makes the sensor shield inevitable.

It seems that the issue is with the fact that PWM is only supported on pins 2-13, so I shouldn't have connected it to pin 46.


text:
How does WiFiServer.status() work?
What are the possible outcomes of calling status() on a WiFiServer from ESP8266WiFi.h? The only documentation I could find only says it returns uint8_t. Here's the link.

wl_status_t at this page https://github.com/esp8266/Arduino/blob/master/libraries/ESP8266WiFi/src/include/wl_definitions.h

The basic set of functions of the esp8266 WiFi object follows the API of the Arduino's first WiFi library for Arduino WiFi Shield. It is documented here.
The esp8266 implementation of status() focuses on state of the STA and maps SDK status to some of Arduino documented codes.
wl_status_t ESP8266WiFiSTAClass::status() {
    station_status_t status = wifi_station_get_connect_status();

    switch(status) {
        case STATION_GOT_IP:
            return WL_CONNECTED;
        case STATION_NO_AP_FOUND:
            return WL_NO_SSID_AVAIL;
        case STATION_CONNECT_FAIL:
        case STATION_WRONG_PASSWORD:
            return WL_CONNECT_FAILED;
        case STATION_IDLE:
            return WL_IDLE_STATUS;
        default:
            return WL_DISCONNECTED;
    }
}


text:
Create one server in AP mode and another in station mode
I'm trying to connect one ESP8266 to WiFi as a WebServer in station mode and to another ESP8266 as a server (that has no web pages) in AP mode.
The problem is both servers are being created in AP mode, between the ESP's, while one of them (the webserver) should be created in station mode and accessible from WiFi. The only way I can reach the webserver is connecting to the AP and accessing its IP (as access point) from my computer.
What I wanted was to access the webserver connected to my WiFi using the IP that my router gave to the hosting ESP, while the two of them would communicate using the server without web pages.
I've already tried using the same IP for both servers, inverting the order of creation of the servers and using both ESP8266WiFi.h and ESP8266WebServer.h. I've read something about the later not working with too much code inside the loop and, since the web page I want is pretty simple, I'm using ESP8266WiFi.h. Here's my code:

#include <ESP8266WiFi.h>
//#include <ESP8266WebServer.h>

WiFiServer internalServer(81);
WiFiServer externalServer(80);
//ESP8266WebServer externalServer(80);
IPAddress IP(192, 168, 4, 15); // Default IP for the AP mode, the one I'm using.
IPAddress mask = (255, 255, 255, 0);
WiFiClient internalClient;
WiFiClient externalClient;

void setup() {

  Serial.begin(115200);

  pinMode(LED_BUILTIN, OUTPUT);

  WiFi.mode(WIFI_AP_STA);

  // Config. AP mode:
  WiFi.softAP("my-access-point", "my-password");
  WiFi.softAPConfig (IP, IP, mask);

    // This connection is ok:
  internalServer.begin();
  Serial.println("Internal server created.");
  while (!internalClient) { // waiting for the internal client to connect before continuing. This works fine.
    internalClient = internalServer.available();
  }
  Serial.println("Internal client found.");

  // Config. STA mode:
  Serial.print("Connecting to Wi-Fi");
  WiFi.begin("my-wifi", "my-wifi-password");
  while (WiFi.status() != WL_CONNECTED) {
    Serial.print(".");
    delay(500);
  }
  Serial.println(" Ready.");

  // Config. external server.
    // This connection isn't working
  externalServer.begin();
  Serial.print("External server created with IP: ");
  Serial.println(WiFi.localIP()); // This is the IP I expected to use to connect to the external server.
                                  // But it is accessible at 192.168.4.15.

void loop() {
  // handling external client:
  externalClient = externalServer.available();
  if(!externalClient) { return; } // proceed only when there is a request.
  String request = externalClient.readStringUntil('\r');
  Serial.println("Request: " + request);

  // The answer is just a hello world:
  String answer = "..."
  externalClient.println(answer)
  Serial.println("Answer: " + answer);

  handleInternalClient();
}

The internal client is supposed to turn on the builtin led when it receives "on" from the server and turn it off when it receives "off", and that is working fine so I think the code for it isn't necessary. If you need it, please ask.
What I want is the other ESP talking to this one through 192.168.4.15 in the AP network and my computer talking to it through whatever IP my router gives to it, in my WiFi.

It is not documented, but you can construct WiFiServer or ESP8266WebServer with IP address. If you use the IP address of the AP, the server will be available only on the SoftAP. If you use the IP address of the station, the server will be available only on STA interface.
If the IP of the interface is known before setup(), you can simply define WiFiServer internalServer(apIP, 81); instead of WiFiServer internalServer(81);. But if the IP must be first evaluated in setup() (from DHCP, or config file), then the following example shows how to set WiFiServer IP and port in setup().
#include <ESP8266WiFi.h>

WiFiServer internalServer(81);
WiFiServer externalServer(80);

void setup() {
  ...
  internalServer = WiFiServer(WiFi.softAPIP(), 81);
  externalServer = WiFiServer(WiFi.localIP(), 80);
  internalServer.begin();
  externalServer.begin();

It worked! Thanks a lot. But I also had to remove the SoftAPConfig() command. Any idea why?

was it before or after internalServer = WiFiServer(WiFi.softAPIP(), 81);? SoftAPConfig should be before it, to have the right SoftAP IP

can you have a sever available on both interfaces at once?

@dandavis, at default it listens on all activated interfaces


text:
How do I implement reverse enumeration?
Basically I'm trying to output a string based upon a value in an array, the following code is what I have come up with to achieve my desired result, but I have a feeling that there is a better way to do it.
String day(int day) {
  if (day == 1) return "Sunday";
  if (day == 2) return "Monday";
  if (day == 3) return "Tuesday";
  if (day == 4) return "Wednesday";
  if (day == 5) return "Thursday";
  if (day == 6) return "Friday";
  if (day == 7) return "Saturday";
  else return "Undefined";
}

void setup() {
  Serial.begin(57600);
  while (!Serial);
  Serial.println(day(1));
}

void loop() {
;
}

This prints "Sunday" in the Serial monitor
I would appreciate any input on how to optimize this code, thank you!

Just one little thing to add to all the answers. Since this is "enumeration" I suggest substituting the magical int number with a refactor friendlyenum.

My method makes use of the __FlashStringHelper class:
// For convenience:
typedef const __FlashStringHelper *FlashString;

FlashString reverseEnum(int val) {
    switch (val) {
        case 0: return F("Option zero");
        case 1: return F("Option one");
        case 2: return F("Option two");
        default: return F("Invalid Enum");
    }
}

Printing now is as simple as:
Serial.println(reverseEnum(2));

Because it's a "flash string" the print function is overloaded properly and it performs the proper PROGMEM reading.
You can, of course, assign to a FlashString:
FlashString myString = reverseEnum(2);
Serial.println(myString);

Or if you don't want to use a typedef you can use the raw type:
const __FlashStringHelper *myString = reverseEnum(2);
Serial.println(myString);

It's just much cleaner to use a typedef.

Thanks for the info, I was really hoping for a way to use the enum, forwards and backwards without having to code out the reverse.

You could possibly craft something really horrible and complex with many layers of preprocessor macros, but it would be nasty and hard to understand. So don't. ;)

I'm no expert, but I imagine something along these lines would work:
char* day(int day) {

  static char* dayName[7] = {"Sunday", "Monday", .... };

  if (day > 0 && day < 8) {
    return dayName[day-1];
  }
  else
    return "Undefined";
  }
}

In any case, I'll be interested to hear why it's wrong (-:

Yeah, an array of char* C strings seems better than a long switch statement. (Voted)

Pointers to string literals should be const char* rather than char *.

@EdgarBonet - Curious - what's the advantage of const here? Is it style, speed, storage...?

Correctness. In C++, you are not allowed to modify the contents of a string literal.


text:
what happens on Arduino power-on, and how long does it all take?
Here's what I think happens and how long it takes (FIXME means I don't know).  I'd like to end up with solid max times for everything if possible.

Power-on, input caps to the 328P begin charging and Vcc to the 328P rising

From the time it first comes to life, internal 328P hardware holds an
internal reset line low.

Vcc to 328P climbs past the power-on reset voltage threshold V_pot, which has
a maximum value of 1.6V (see the ATmega328P_datasheet_revision_DS40002061A.pdf
Table 29-11).  For a 9V battery with a typical internal resistance of 2 ohms,
the time constant with the ~100 uF of input capacitance on the Arduino
is RC = (2 * 0.0001) = 0.0002 s.  So this normally happens pretty fast,
but note that if additional loads are connected to the Arduino Vcc or Vin
things might take longer.

A reset timer on 328P begins running.  When it expires the internal reset
line will be released.  How long this timer will run depends on fuse settings.
For the default Arduino fuse settings the timer will run for about 65 ms.
For a 3.3V Arduino variant the typical time will be slightly longer (~69 ms).
See ATmega328P_datasheet_revision_DS40002061A.pdf Table 29-11 Chapter 9
for details.

The PD7 line of the ATMEGA16U2 chip on on the Arduino holds the external
reset line low past the point in time at which the internal reset is released,
which causes the EXTRF bit of the MCUSR register on 328P the 328P to end up
set (indicating an external reset).  FIXME: does it actually work like this
(hold it low longer)?  FIXME: How long exactly?

The external reset is released by the ATMEGA16U2

The bootloader on the 328P begins executing

The bootloader examines the MCUSR and finds that EXTRF is set, but WDRF
of MCUSR is not set.  It therefore quickly flashes the on-board LED several
times and the attempts to download a new program over the serial line.
This process takes about 1.6 s total.

The download attempt terminates with a watchdog timer timeout and consequent
watchdog timer reset.  The EXTRF bit of MCUSR remains set (it is sticky and
is only cleared by a power-on reset or explicit 0 write).  Time: pretty quick

The bootloader starts executing (again).  Time: pretty quick

The bootloader examines the MCUSR and finds that the EXTRF and WDRF bits
of the MCUSR are both set.  It interprets this to mean that the bootloader
just executed and terminated due to a watchdog timeout, i.e. it decides that
an upload attempt has already been made.  It therefore clears the WDRF flag
(since it thinks it probably set it itself) and jumps to the start of the
application flash instead of making an upload attempt.  Time: pretty quick

All the setup code required to provide the C environment your main()
program requires runs.  This includes for example copying global variable
intial values from flash to RAM, etc.  Time: FIXME?

main() begins executing.

Why not measure this yourself, for your specific setup?

I've made a shield that can turn a controlled arduino on only once in a while (so can operate years on battery).  It also supports wake due to a user signal line activity (it exposes it's own Vcc from low-Iq regulator for this circuitry), and it propagates this signal to controlled arduino once it's safely turned on.  I'm interested in the worst-case time from when one of these signals fires to when arduino is on and running user code that can see the propagated signal, including in cases when user cuts RESET EN on controlled Arduino and reprograms fuses for fast rising power.

Are there any reasons you have to use an Arduino for this?

The 16u2 doesn't hold the "reset" pin low. While the chips is still in pre-startup, all the output pins are High-Z. when running it set the "reset" pin to HIGH (pull-up), and then to OUTPUT. So the pin is never OUTPUT LOW. It's High-Z, then pull-up HIGH, then HIGH. Also the "reset" pin is not directly connected to the reset of the 328p, but via a 100nF capacitor.

If the line from the 16u2 isn't doing it how is the MCUSR EXTIF getting set on power on?  The bootloader always runs and attempts a download, so it's getting set somehow.  But I thought that a normal power-on of a 328P caused PORF to be set but not EXTIF.  I looked around for the actual code that's on the 16u2 but didn't find it.

This is something that is far far easier to measure than to try and calculate.
Here's an Arduino Uno R2 with a simple sketch that just turns on D2.  Green is the power (7V to the barrel jack) and yellow is D2.

As you can see it takes 1.544 seconds (according to the resolution of my oscilloscope which, over those time scales, isn't that great) before D2 is driven high.
The sketch is simply:
void setup() {
  pinMode(2, OUTPUT);
  digitalWrite(2, HIGH);
}

void loop() {
}

This is consistent with what I've measured with timer1 on my controller (~1.520 actually without Arduino environment setup whatever that consists of).  So this is a right number for stock arduino with stock optiboot (as of this writing anyway).  It would still be nice to know some of the particular numbers though for cases when the obvious arduino hacks are done.  I guess C (and Arduino wiring) environment setup is the big remaining unknown.


text:
Stepper motor based clock movement with DS3231
I am working on a clock movement that is powered using a stepper motor and the GSM2 driver board. The delay between steps needed to achieve 1 rpm on the second hand works out to 25 ms. In my current setup, I am sending pulses to the driver board using the delay() function. This works reasonably well, although it is not accurate enough for me. To remedy this problem, I ordered a DS3231 RTC module, thinking I could use that to replace delay()/millis(). However, I can't figure out how to achieve millisecond resolution using the RTC. It seems like it should be strait forward given the oscillator on board the RTC is 32kHz. I am new to arduino programming and am out of my comfort zone with this one.
Does anyone know of a way to achieve the 25 ms pulses we need while still retaining the accuracy of the RTC? Is it possible to use the RTC to correct the output produced by the built in delay()/millis() function? How would you then translate that output to pulses sent to the stepper motor driver board?
Internet research produces some mixed results on whether or not this is possible. I have yet to see an example of a clock with millisecond resolution. The theory behind it makes sense, but I don't know where to start.

It is unclear, why you need the high accuracy, and you didn't include your code. So my explanations will be as broad as your question.
"millisecond resolution" is a broad term. Generally you have to consider 2 different errors.

The jitter for every millis() value
clock drifting over time

You can eliminate the second point quite easily using the RTC with the Time library. It uses the RTC as a reference, so that you don't have the clock drifting this much. Though, you would have to use the libraries functions for all time related things, since it does not change the value of millis() or it's siblings.
Also, for low differences in the range of a few milliseconds, you should better use micros() instead of millis() (if you are not using the RTCs functions).

How would you then translate that output to pulses sent to the stepper motor driver board?

It is unclear, why exactly you need "millisecond resolution", and you didn't show us your code. But there are multiple Stepper libraries on the web, for example the standard Stepper library or the AccelStepper library (Accelstepper is more capable, don't know, if you need it). With the AccelStepper libraries you can set a certain speed and target position and then you simply call then run() method (haven't looked up the name, but there is definitely a function like that) until the desired position is reached. The method itself will only pulse the stepper, if it is time to do so. So you are freed from doing all the stuff with millis(), since the library is doing that for you.
Though the libraries are using the Arduinos internal time: millis() and siblings. To change that, you would have to change the library.

Consider a Phase Locked Loop (PLL) to synchronize your 40x 25ms pulses with your 1pps RTC.
If you need 25ms/pulse to get 1rpm, that's 2400ppm or 1pulse/0.025ms=40pps.  If you get a 1pps pulse out of the RTC, you can use it to discipline your timing.  https://www.romanblack.com/one_sec.htm is a good reference.
The basic trick is to keep track of the mismatch and run faster when it is slow, and run slower when it is too fast.
Try something like the below, but replace the LED pulse stuff with your stepper code.
// pps_pll.ino for https://arduino.stackexchange.com/questions/67699/stepper-motor-based-clock-movement-with-ds3231
//
// Adapting code from https://www.arduino.cc/reference/en/language/functions/external-interrupts/attachinterrupt/
// to do a PPS PLL per https://www.romanblack.com/one_sec.htm

const int pps = 40;
const int pulse_us = 1;
const int pulse_interval = (1000L / pps);
int count = 0; //
int count_at_sync = 0; //
unsigned long next_pulse = 0; //
unsigned long pulse_off = 0;

const byte led_pin = LED_BUILTIN;
const byte interrupt_pin = 2; // Choose pin per https://www.arduino.cc/reference/en/language/functions/external-interrupts/attachinterrupt/
volatile byte state = LOW;

void setup() {
  pinMode(led_pin, OUTPUT);
  pinMode(interrupt_pin, INPUT_PULLUP);
  attachInterrupt(digitalPinToInterrupt(interrupt_pin), sync_ISR, RISING);
}

void loop() {
  unsigned long loop_micros = micros();  // capture start of loop time
  if (loop_micros >= next_pulse) {
    // Schedule pulse
    digitalWrite(led_pin, HIGH);
    next_pulse += pulse_interval ;
    pulse_off = loop_micros + pulse_us; // schedule off time
    // PLL accounting
    count++;
    if (count_at_sync > 0) next_pulse++; // too fast: slow down
    else if (count_at_sync < 0) next_pulse--; // too slow: speed up
  }
  if (state == HIGH && loop_micros >= pulse_off) {
    state = LOW;
  }
  digitalWrite(led_pin, state);
}

void sync_ISR() { // called by 1pps interrupt
  count_at_sync = (count -= pps); // PLL accounting and record synchronization state
}


text:
Why calling digitaWrite(pinNum,HIGH) before setup() not working?
I am writing a library to operate a linear actuator, let's call the library ActuatorV2. It is composed of two files, a .h and and .cpp files. To create an object, I instantiate the object as follows
Actuator act(pulsePin,directionPin,enablePin);

Within the constructor of the object, four tasks are performed:
1) pin assignment,
2) setting pin modes,
3) setting pulse frequency
4) enabling the actuator.
When performing the fourth task (enabling), I simply set the enablePin to HIGH as follows digitalWrite(enablePin,HIGH); There is absolutely nothing special here, but for some odd reason, when setup() is called in the sketch, the enablePin is set back to LOW. I know this because I have an LED light connected to the enablePin, and I visually monitor it during the operation.
Any idea why this happens?
I am aware that in the documentation of setup() here, it is clearly stated that pinMode() should be placed in setup(). But I have used the approach shown in the MWE before a few months ago, and it was working just fine.

Hardware used
MacBook Pro
Arduino Due
MWE
Sketch
#include <ActuatorV2.h>

// defining actuator pins and properties
const int pulstPin      = 4;
const int directionPin  = 5;
const int enablePin     = 6;
const int pulseFrequency= 500;

// initializing the actuator
Actuator act(pulstPin, directionPin, enablePin, pulseFrequency);

void setup() {
    // do nothing
}

void loop() {
    // do nothing
}

Library (Actuator.h, Actuator.cpp)
Actuator.h
#ifndef Actuator_h
#define Actuator_h

#include<Arduino.h>

class Actuator{
    private:
    // private variables
    // pins
    int _pulsePin;
    int _directionPin;
    int _enablePin;
    // pulse frequency parameters
    int _pulseFrequency;
    int _pulseDelay = 5;   // 2.5 microseconds manufacturer recommendation
    int _interpulseDelay;

    // private methods
    void assignPins(int pulsePin, int directionPin, int enablePin);
    void setPinModes();

    public:
    // constructors
    Actuator(int pulsePin, int directionPin, int enablePin, int pulseFrequency);
    // public methods
    void setPulseFrequencyParameters(int freq);
    void enable();
};

#endif

Actuator.cpp
# include<ActuatorV2.h>
# include<Arduino.h>

Actuator::Actuator(int pulsePin, int directionPin, int enablePin, int pulseFrequency){
    // 1) pin assignment
    assignPins(pulsePin,directionPin,enablePin);

    // 2) setting pin modes
    setPinModes();

    // 3) setting pulse frequency
    setPulseFrequencyParameters(pulseFrequency);

    // 4) enable actuator
    enable();
}

void Actuator::assignPins(int pulsePin, int directionPin, int enablePin){
    _pulsePin = pulsePin;
    _directionPin = directionPin;
    _enablePin = enablePin;
}

void Actuator::setPinModes(){
    pinMode(_pulsePin,OUTPUT);
    pinMode(_directionPin,OUTPUT);
    pinMode(_enablePin,OUTPUT);
}

void Actuator::setPulseFrequencyParameters(int pulseFrequency){
  int _pulseFrequency = pulseFrequency;
  int minPeriod = 10; // 10 micro-seconds which is 4 X 2.5 (manufacurer recommended pulse width for reliable operation)
  /*
  ---------------------------------------------------------------------
  Pulse shape

  3.3 V
        |  |``````````|                     |``````````|
        |  |          |                     |          |
        |__|          |_____________________|          |__________ time
  0   V
           \__________/\____________________/
                pd              ipd
           \________________________________/
                     one pulse

  pd: pulse delay. Minimum 3 micro seconds
  ipd: inter-pulse delay. Minimum 3 micro seconds
  ---------------------------------------------------------------------
  */

  float period = 1.0/((float) pulseFrequency);

  if (period < minPeriod){
    _pulseDelay = 5;
    _interpulseDelay = 5;
  } else  {
    _pulseDelay = 5;
    _interpulseDelay = period - _pulseDelay;
  }
}

void Actuator::enable(){
  digitalWrite(_enablePin,HIGH);
  delay(500); // delay to observe the result if effective.
}

This is why many library classes have a begin() method: in order to defer to setup() the initializations that should not be done in the constructor.

@EdgarBonet, does that mean setup() dose reset things? I didn't know how to read the source code, but I still would like to know why this worked before, and it isn't working now.

Your constructor runs before main. Main initializes the hardware, including setting the pin modes to a default sane setting.

@Majenko, your reply is very helpful. I actually went to your other answer, and I found all what I needed there. Thanks again.

@Majenko it's probably true for the DUE - initialization is way more complex on ARM devices. For AVR based Arduinos all I can see is starting timers and ADC - it's not messing with pins at all. However there is also weak call for initVariant, so it might be different for each variant too.

The point is you can't trust it. So don't do it...

We can't trust it for sure. Thinking back, I might have been using an Arduino Uno when a code similar to my MWE worked. Thanks again.


text:
How can I use a variable to choose which Serial port to interact with?
In my use case I have multiple devices connected to the serial ports of an arduino. Currently I write to them using Serial1.write(), Serial2.write(), etc.
How can I choose the port programmatically, for example:
for(int i = 0; i < numDevices; i++){
  Serial[i].write();
}

what have you tried? ... what errors did you get?

I'm not getting any errors because, as stated, I know how to write it 'hard-coded' but not the way I want. I didn't try Serial[i] because that's obviously wrong, but I can't find any docs on how to write to a variable pin.

You may use an array of pointers to the actual serial ports. For
example, on an Arduino Mega:
const size_t PORTS_COUNT = 4;
const HardwareSerial *ports[PORTS_COUNT] = {
    &Serial, &Serial1, &Serial2, &Serial3
};

void setup() {
    for (size_t i = 0; i < PORTS_COUNT; i++)
        ports[i]->begin(9600);
}


text:
how to use keypad button multiple integer value input
I have been working on water flow sensor which measures volume then i need to restrict the amount of water which disperse from depend on the user input form the keypad so how can i store the input form the keypad into a variable.

Various tutorials about keypads can be found on the web. Have you tried one of these? What didn't you understand?

When you use the keypad library, there is a command to read a key:
 myKeypad.getKey();

Store these keys in a (string) buffer, and after a certain key is pressed (e.g. #), parse the string buffer to retrieve the integer (with the c function atoi, see here for a description).


text:
How detect I2C errors with requestFrom()
I am going to use MCP23017 chips, and some of them will be cabled with a 1 meter max unshielded cable. I am expecting that certain transmissions may toss errors. So I want to tackle this problems by using the built in error detection of I2C, polling the inputs frequently (every 20ms or so) and by debouncing the received data in code by comparing the previous state to the current state of every input pin.
If you write bytes to an I2C slave with the Wire library. You can use the return value of Wire.endTransmission(); to test if the slave has acknowledged the message.
How does this work when you are requesting bytes using Wire.requestFrom( address, 3 ); for example. This function does return the amount of received bytes. Can we check this value with the value of the amount of bytes we requested?
I have read the TI document over how I2C works

The master will continue sending out the clockpulses, but will release the SDA line, so that the slave can transmit data. At the end of every byte of data, the master will send an ACK to the slave, letting the slave know that it is ready for more data. Once the master has received the number of bytes it is expecting, it will send a NACK, signaling to the slave to halt communications and release the bus. The master will follow this up with a STOP condition

So the master either ACKs or NACKs a read-in byte. Does the Wire library automatically make several attempts with reading? Oris there something in the Wire library which we can use to detect a failed read operation?
Is it perhaps so that the requestFrom() function may return a different amount of bytes than you requested with which would indicate that atleast 1 read operation failed?
So could I attempt something like
doItAllAgain:

for(int i = 0 ; i < 5 ; i ++ )
{
    Wire.beginTransmission( address ) ;
    Wire.write( register ) ;
    if( !Wire.endTransmission() ) break ; // if no error, break out of for loop
    Serial.println(F("write operation failed");
}

Serial.println(F("write operation succes");

byte requestedBytes = 3 ;
byte returnedBytes = Wire.requestFrom( address, requestedBytes ) ;

if( requestedBytes != returnedBytes )
{
    Serial.println(F("read operation failed");
    goto doItAllAgain ;
}
else
{
    Serial.println(F("read operation also succes");
    byte byte1 = Wire.read() ;
    byte byte2 = Wire.read() ;
    byte byte3 = Wire.read() ;
}

You can only get little information about unsuccessful transmission as long as e.g. a slave which is actually there does not acknowledge. I2C has no way of figuring out if transmitted data is corrupted or not. This is the mayor problem because instead of not reacting, slaves can behave erratically. To deals with that you have to implement error checks yourself, for example by validating a checksum.

From what I understand. If the dataline has a flank change while the clockline is high, there will be a NACK and this should work in 2 directions. Regardless how could I possibly add a checksum while reading out an Mcp23017 device? To have a checksum system, the slave device should be able to accept and transmitt checksum bytes correct?
I have a bare arduino at my desk with no I2C devices, I will check what the requestFrom() function returns when there is no device

Ok, so Wire.requestFrom() returns 0 when no device is connected. This means that this function does incorporate a check on NACK bits.

The Wire library does not give you any possibility to get error states, when requesting bytes from a slave. Basically you are stuck with the number of bytes being read.
Though you can read some information from that. If the number of bytes is zero, the slave didn't answer (either because its not there, or because it cannot send any byte currently). This equals a NACK by the slave after the address byte.
Other than that the I2C protocol doesn't give any more information. On requesting the slave is sending data and the master is acknowledging it. That means, that the slave cannot generate a NACK in this process. In fact that also means, that the returned number of bytes can only be zero (on NACK on address) or equal to the number of requested bytes, since after the address ACK from the slave the master will continue to generate clock pulses, until it has read all bytes, that it wanted. If the slave doesn't have any more data to send before that, it cannot stop the transmission. It would just stop driving the data line, resulting in all high data bytes (0xFF).
Also I doubt, that it would be really useful in your case. I2C is made for small distances, mostly on the same PCB. It can be used for longer distances, but your mileage may vary. If your setup really can corrupt the communication on the I2C lines, your biggest problem will be a stuck bus. The I2C protocol is generally not prepared for noisy environments and it incorporates states, where the devices on the bus can wait infinitely. This is also reflected in the Wire library. That means, that big noise on the lines will often lead to the bus being stuck in the middle of a transaction, needing you to reset the devices (not only the slaves, but also the master) to get the bus free again. I would go so far to say, that is it more likely to get the bus stuck, than to get corrupted data. So any information about errors is not really helping you here, since you won't get out of requestFrom() in the first place. Your code can very well get stuck there.
I suggest, that you test your setup thoroughly with the wanted run times. If the bus gets stuck too often for you, then you should make your setup more robust (shielded cables, or using an extra MCU with the I2C slave and using a more robust communication interface between main MCU and extra MCU).


text:
Have I damaged my arduino?
I was trying to build a finger print lock system.. While my arduino was connected with my pc, I mistakenly plugged the adapter and turned it on. I immediately switched it off. It was working fine (port 3?) Now suddenly port 3 disappeared and the only available option I have is port 1, which is not working! My window is also alerting me that it didn't recognize the device. I searched for it in device manger but no others devices option is available

or you damaged the USB port. what adapter and how did you plug it?

12v 2A power adapter. I plugged it into the port in the board that is given for adapter.

on genuine Arduino Uno it shouldn't cause a problem

I probably didn't burn it as the solinoid lock and the sensor is perfectly working and when I connect the USB, my arduino uno gets power. Im not just able to upload any code as there is no port 3 option to select.

Which model of Arduino?
The design of most models has circuitry that handles getting power from both the barrel connector and the USB port, and switches between them intelligently.
Thus the answer should be "no, no problem." However, what else does your 12 adapter power? You might want to post a full circuit diagram of your project.
Also, as Juraj says, Arduino brand microcontrollers are designed to handle this situation. Knockoff models may cut corners.

https://drive.google.com/drive/mobile/folders/1JWxkBoONwUHxvn-4A6pfhs0_0sCHIo5Q?usp=drive_open     I'm following the circuit and the codes given in this drive. Its arduino uno r3. The Solenoid lock and the sensor is perfectly working as i already uploaded my codes. But I was trying to reload it again so that I can start everything from the beginning. Collecting ids and all that ... but r3 port has completely disappeared from the option and this is why I'm not able to upload any new code.


text:
Are these GND connected resistors on the Arduino Due redundant?
Does anyone know why these 4 resistors are there (attachment)? It seems like they are useless since connected in a loop to GND.
Full schematics here: https://store.arduino.cc/arduino-due

Just guessing RN is for resistor network.  So they may have more than they needed to use.  I'd say probably "unused".  If that what you meant by "redundant?"  Hard to say with any certainty.  It may be better to ask the electronics stack exchange.

RN2B would be resistor network 2, resistor element B. There appear to be 4 resistors, A through D, inside one resistor-network package. You can see RN5 has the two unused resistors unconnected. The reason RN1 and RN2 have them connected to ground might have to do with noise. EDIT: looking at the eagle file, it seems like they connected them to ground to make the ground-plane flow better. My only question is why they didn't use a single resistor network here, instead of using only halve of two resistor networks.

Yes, they are redundant. They are elements of resistor arrays (multiple resistors in one package) that aren't used. They have just connected all unused pins of those packages to ground.
If you want to know why they would have unused elements, it's all to do with optimizing the manufacturing process. If you have, say some 100k arrays elsewhere in your design and you want to have maybe one or two other 100k resistors elsewhere, rather than adding another component of a discrete 100k resistor it's cheaper to use a 100k array and not use some of the elements. One of the factors in the cost of pick-and-place operations is the number of different components. By keeping the number of component types to a minimum they keep the manufacture costs to a minimum.

great thanks, so if I understand correctly I could just use 1 resistor network (consisting of 4 resistors) to apply pullups to JTAG_RESET, JTAG_TDI, JTAG_TCK and JTAG_TMS and then get rid of the other 4 resistors? I'm designing a board based on this, hence the question.

Sure. A resistor array is just four individual resistors in a convenient package.


text:
Why is there a cutoff on these accelerometer measurement values? - ADXL375
I'm using a Teensy 3.2 to read data from an ADXL375 using SPI. In general the communication is going just fine and I can activate settings etc.
However, when I try to read X, Y or Z data it seems like some part of the measurement values are missing.
I'm performing measurements with the ADXL375 and writing the LSB values straight to an SD card, so no conversion to g or anything like that. The accelerometer range goes to +/- 200g, so that should give a max LSB value of about 200*20(scale factor) = +/- 4000 LSB.
During some tests I was swinging the accelerometer with my hand, and tapping it directly with a pen, which gives a momentary high impact. The swinging values are represented well and look credible to me, however the pen tapping values seem to be cut off at precisely 511 LSB, see graphs. That seems incorrect. So why is that?
N.B. The range of the ADXL is fixed to 200 g, so no choice to be made there.
My thinking is that something is going wrong with the conversion of the two ADXL registers (two's complement) to form a single number.
This is the conversion I'm doing (i.e. I'm reading out the FIFO in one go):
void ADXL375::saveFIFO(){
    int fifo_index;
    int16_t x, y, z;
    fifo_index=0;
//    readFrom(DEVICE,ADXL375_INT_SOURCE_REG,1,buff);

    for(int i=0;i<32;i++){
        multiByteReadSPI(ADXL375_DATAX0_REG, 6, bufferSPI); //read the acceleration data from the ADXL375
        x = (((uint16_t)bufferSPI[1]) << 8) | (uint16_t)bufferSPI[0];
        y = (((uint16_t)bufferSPI[3]) << 8) | (uint16_t)bufferSPI[2];
        z = (((uint16_t)bufferSPI[5]) << 8) | (uint16_t)bufferSPI[4];

        // Serial.print(bufferSPI[5], BIN); Serial.println(bufferSPI[4], BIN); // z
        // Serial.print(bufferSPI[1], BIN); Serial.print(","); Serial.println(bufferSPI[0], BIN);  // x

        if (x & 0x8000){ // Check if the binary number is negative, by checking whether left most bit is 1 or not.
            // If negative, then perform not operation and add one to get magnitude
            x = ~x + 1;
            x = - x;
        }
        if (y & 0x8000){ // Check if the binary number is negative, by checking whether left most bit is 1 or not.
            // If negative, then perform not operation and add one to get magnitude
            y = ~y + 1;
            y = - y;
        }
        if (z & 0x8000){ // Check if the binary number is negative, by checking whether left most bit is 1 or not.
            // If negative, then perform not operation and add one to get magnitude
            z = ~z + 1;
            z = - z;
        }

        lastFiFo[fifo_index]    =   newistFiFo[fifo_index];
        newistFiFo[fifo_index]  =   x;
        fifo_index++;
        lastFiFo[fifo_index]    =   newistFiFo[fifo_index];
        newistFiFo[fifo_index]  =   y;
        fifo_index++;
        lastFiFo[fifo_index]    =   newistFiFo[fifo_index];
        newistFiFo[fifo_index]  =   z;
        fifo_index++;
        // debugPrint(x); // debugPrintln(", Saving fifo");

                // x = (((int16_t)bufferSPI[1]) << 8) | bufferSPI[0];
        // y = (((int16_t)bufferSPI[3])<< 8) | bufferSPI[2];
        // z = (((int16_t)bufferSPI[5]) << 8) | bufferSPI[4];
        // scaleXYZ(&x,&y,&z);

    }

 }

This is the SPI Multibyte Read function I'm using:
void ADXL375::multiByteReadSPI(uint8_t regAddr, uint8_t numberOfBytes, uint8_t *dataBuffer){

    SPI.beginTransaction(SPISettings(5000000, MSBFIRST, SPI_MODE3));

    digitalWrite(_chipSelectPin,LOW);

    uint8_t readMBaddr;

    if (numberOfBytes > 1){ // for an actual multibyte read
        readMBaddr = 0b11000000 | regAddr; //  From left to right: read (1),  yes multibyte (1), and then a bunch of zeros
    }
    else{ // for single byte read
        readMBaddr = 0b10000000 | regAddr; //  From left to right: read (1),  not multibyte (0), and then a bunch of zeros
    }

    SPI.transfer(readMBaddr);

    for (uint8_t k = 0; k < numberOfBytes; k++ ){
      dataBuffer[k] = SPI.transfer(SPI_DUMMY_VALUE);
    }

    digitalWrite(_chipSelectPin,HIGH);

    SPI.endTransaction();

}

I also had a look whether the SPI transfers are okay. The image shows one multibyte read, consisting of a command byte on the far left, and then 6 read bytes after that. Nothing out of the ordinary there.

link to EE SE version of the question: https://electronics.stackexchange.com/questions/611607/why-is-there-a-cutoff-on-these-accelerometer-measurement-values-adxl375

I found the answer. Turns out the datasheet of the ADXL375 is wrong, and the user can actually change the range themselves (even though the datasheet says you can't). In my case, the range was unintentionally set to 25 g (instead of 200 g). See below the full explanation by bvn123 - which was posted in 2017, yet Analog Devices has still not updated the datasheet.

I use ADXL345 and ADXL375 under a uC software, which was written for
ADXL345.
The Datasheet for ADXL345 says about ±2g/±4g/±8g/±16g ranges and
corresponding to these ranges 10/11/12/13bits resolutions.
The Datasheet for ADXL375 shows only one range ±200g and 13bits
resolution. .
Inspite of the ADXL375 Datasheet's info, that Register 0x31 only state
for bits D3:D2:D1:D0 is 1n11 (D3 is the Full resolution bit, D1:D0 are
the Range bits), the ADXL375 reacts for D1:D0  and D3 change in the
Register 0x31 the same way, as the ADXL345,
So, in reality ADXL375 also provides 4 ranges (±25g/±50g/±100g/±200g).


text:
Running out of GPIO & looking for suggestions
I'm working on a project using a NodeMCU and am quickly running out of GPIO pins. I'm trying to decide which way to go to complete it.
Right now, I have the MCU connected to a MAX31856 PT100 thermocouple (SPI), a PWM output, a transistor (acting as a switch), a single button and a single LED. I'm needing to add at least 2 more of the MAX31856, a display (either I2C or SPI) and a rotary encoder/button.
I've looked into GPIO expanders, but I'm doubtful that the available libraries for the additional hardware will work through the expanders. I have a Mega that will work without a doubt, but then I will have issues with WiFi & MQTT. I looked at the Mega's with onboard WiFi, but I got so confused in reading how to program it, setting the DIP switches, etc that it doesn't seem like a valid choice.
Can anyone offer guidance?

MAX31856 is SPI so use an SPI display

i would move less-used interface hardware to the app to keep cost down and free up pins. i would also use i2c everything. You can use GPIO10 as an input. you can use A0 for the button. You can use GPIO3 for input and GPIO1 for output if you don't use Serial. You can use GPIO0 for the rotary encoder button, if it's never pressed on boot.

Two main solutions comes to my mind:

GPIO expander (as you mentioned). It is really easy to use them as digital inputs or outputs. So you can connect button, LED, transistor and maybe even display (you did not specified type of the display, so I assume standard LCD 1602 or 2004 display). You can also connect SPI-CS signals to the expander, but this depends on used libraries...
Auxiliary Arduino e.g. Nano. Arduino can be used for measurement of the temperature and other stuff and NodeMCU for communication. In this case you have to implement some kind of communication between these two boards (SPI, I2C or UART).


text:
Determing approximate bicycle speed for distancemeter
I'd like to build a self-contained bicycle distancemeter similar to those now used by local police, i.e. that measure and display the distance between the bicycle handlebar's end and passing cars and beep when distance is less than 1m on 50-km/h roads. In order to avoid detecting cars when stopped at traffic lights, I need to determine whether the bicycle is moving above a minimum speed, say 10 km/h. How can I do that without having to install additional hardware on the bicyle, like a magnet on the wheel and a sensor on the fork? Accelerometers?

GPS is probably simplest.

Accelerometers are not a good choice for this, since they output nothing on constant speed. Like Majenko wrote, GPS is the simplest

Many GPS modules will directly report your ground speed to you.

I have built many years ago a device nearly identical to what you describe. I did not have the additional requirement of a minimum speed of 10 kph, however. As noted in the comments, that is likely best resolved with GPS as you are detecting motion, not absolute speed figures.
I used "arduino gps library" as the search terms and found many options. One of them, TinyGPS++ appears to have what you require and much more:

TinyGPS++ is a new Arduino library for parsing NMEA data streams
  provided by GPS modules.
Like its predecessor, TinyGPS, this library provides compact and
  easy-to-use methods for extracting position, date, time, altitude,
  speed, and course from consumer GPS devices.
However, TinyGPS++’s programmer interface is considerably simpler to
  use than TinyGPS, and the new library can extract arbitrary data from
  any of the myriad NMEA sentences out there, even proprietary ones.

I would definitely appreciate the "considerably simpler" aspect, as well as the "extract arbitrary data" portion, which seems specific to your project.
There may be other libraries that provide your objective, this was the first on the search returns.
The device I constructed used the common ultrasonic detector with a transmitter and receiver pair, coupled to a set of seven-segment LED display blocks. When the slightly-less-than-one-meter distance was presented, my device would trigger a pair of cameras. For your beep purpose, it would be straight-forward to redirect the camera trigger to a piezo speaker module or any other suitable audio device. I did not require GPS or other speed information.

I realize I already own a self-contained matchbox-sized USB-rechargeable Bluetooth GPS from Globalsat. So it's just a matter of getting a Bluetooth shield or a Bluetooth-equipped Arduino board.

I like your idea of the camera. I gather I then need an SD shield to store photos. No Arduino board has all that?

The cameras I used were off-the-shelf point-and-shoot digital cameras made by Canon. They support CHDK modifications which allow for remote shutter release. I'm unfamiliar with SD/Arduino/cameras.

GPS would be simple in terms of being self-contained, but a GPS module is somewhat expensive, and is also a big power drain.
I'd recommend a wheel sensor. Some modern wireless bike-computers use accelerometer based wheel RPM sensors. You attach them to the spokes and they detect the motion with/against the force of gravity as they travel up and down. They use wireless communication like BLE (Bluetooth Low Energy.) If you added a BLE module to your Arduino you might be able to pair it with a wireless RPM sensor and measure speed that way, with no wires or magnets needed.
EDIT:
I don't know for sure what wireless protocol these accessories use. If it's not BLE then interfacing them with an Arduino might be harder.

Are you sure bike computers use BLE and not some custom wireless link, or ANT, which is not BLE.

No, I don't know which wireless protocol they use. That's why I said "wireless communication LIKE BLE."  I guess I should have been clearer on my lack of specific knowledge."


text:
Powering Moisture sensor via arduino pin
Can someone help me. I have this sensor
I just connected it to the 3V pin of my arduino only I read online that its better to connect it to a Arduinopin for power so you can put it off when not measuring. How do I do this? Can I just connect it to, let's say D4 and put this to HIGH and LOW or do I need something more. I googled a bit but found all kinds of different solutions. Some even talked about the need to PULLUP and PULLDOWN. whats the best way to do this.

If the sensor draws less than about 20mA when running then yes, you can just power it from any GPIO pin and set it HIGH for on or LOW for off. If you need more than about 20mA then you will need to switch the power with a transistor.

Thnx :). How do I find out how much mA it draws? its not on the board itself.

RTFM. If it's not in the FM then RTFM for the major component(s). (F = Fine :p )

The entire circuit board, including the LM393, power light and it's resistor, uses 2.2 mA at 3.3 VDC (4.12 mA at 5 VDC). Once the comparator is "triggered", the "D0-LED" and it's associated resistor come in to play which bumps the current up to 3.6 mA at 3.3 VDC (7.82 mA at 5 VDC).
I think it would be OK to use digitalWrite(pin_number, HIGH) to power the circuit board, then use digitalWrite(pin_number, LOW) to turn the power off.

Where did you find the specs? And do you read Dutch?

I used a DVOM with a variable output power supply to test one of the boards. This "voltage comparator board" is a common "addition" to several different moisture / rain sensors available on Aliexpress, Ebay, Amazon, etc. I don't read, write, or understand Dutch.

It worked. It gave lower numbers but I'm making % out of them anyway. thnx :)


text:
Waking an ESP8266 from Light-Sleep using a signal from MQTT?
I was wondering if it would be possible to wake an ESP8266 from a request over MQTT while it is in Light-Sleep mode? I am planning to implement a smart switch that would receive messages from a Raspberry Pi to turn off and on, however, I don't want to have to manually hit a button to trigger an external reset (I've seen this done in many examples already). I also don't think it would be efficient for me to just set a timer and have the ESP wake up in intervals. For instance, if I want to have the smart switch turn on an appliance and the PI sends a request over MQTT when the ESP is sleeping... this will do me no good. Curious if anyone has run into this issue before and what recommendations you have.

I was wondering if it would be possible to wake an ESP8266 from a request over MQTT while it is in Light-Sleep mode?

No. The ESP8266 has to be awake to communicate with the MQTT server.
The best you can hope for is a periodic wakeup to connect to the server and check for any new data.  But of course that relies on the data being set to QOS 2 so it keeps trying to be delivered until the ESP8266 is awake to receive it.


text:
Taking data from main 120V 50/60Hz power
How can I take data from my house main power and reconstruct it signal? I used an transformer and an inverter amplifier to low voltage to 5 volts and read it with A0 analog pin, but I got a very strange datan and just a few numbers
data = analogRead(A0);
 Serial.println(data);

What kind of data are you trying to retrieve?

The Sin wave at 60Hz

Please show us the sketch you used that gave you the "...very strange data and just a few numbers".

Please show us a complete sketch and a sample of the corresponding data

The Serial output on an Arduino is quite slow. By printing your output, you will slow down the readings so much that it will appear to be nonsense.
You should collect a series of readings into a C array of floats in RAM, stop recording, and then log that array of values.
Note that you don't have a lot of RAM to work with on most Arduinos, so you will only be able to record a small number of values. A Mega 2560 has a lot more memory than others (8KB). It's still not a lot, but better than other boards. One of the ARM based Arduinos will have both a much faster processor and a lot more RAM.

I have working code which could be added to this answer after a little cleanup https://github.com/jandrassy/Regulator/blob/4c1f15e00f51d618293ae441706c3f6027a56405/util/RegulatorDev/RegulatorDev.ino#L243

Is the speed of data transmission really such a big problem here, that you need to buffer the data? I mean, it's only 60Hz. I would think, that is is sufficient to choose a higher baudrate.

"Is the speed of data transmission really such a big problem here...?" Yes. Imagine a Serial.write() takes 1/10th of a second. You need what, 10 readings per full cycle of a sine wave to get a crude picture of its shape? That would mean you would need 600 readings/second. If instead you get 10 readings per second, out of phase with the wave, you're going to see seemingly random readings.