text:
Arduino 10bit ADC is not accurate?
I'm reading the voltage with voltage divider:

simulate this circuit – Schematic created using CircuitLab
 | Arduino is connected to both USB and a 9V adapter.
float r1 = 100000;
float r2 = 9980;
float adc, voltage, analog;
void setup() {
  Serial.begin(9600);
  analogReference(EXTERNAL);
  pinMode(A0, INPUT);
}

void loop() {
  for (int i = 0; i < 256; ++i) {
    analog += analogRead(A0);
  }
  analog = analog / 256;
  adc = analog * 1.228 / 1023;
  voltage = adc / (r2 / (r1 + r2));
  Serial.print(analogRead(A0));
  Serial.print(", ");
  Serial.print(analog);
  Serial.print(", ");
  Serial.print(adc);
  Serial.print(", ");
  Serial.print(voltage);
  Serial.println(" ");
  delay(100);
}

Here's the accuracy test result:
Input | Arduino | Difference
 1V      0.89V     -110mV
 2V      1.90V     -100mV
 3V      2.92V     -80mV
 4V      3.93V     -70mV
 5V      4.95V     -50mV
 6V      5.97V     -30mV
 7V      6.98V     -20mV
 8V      8.00      0
 9V      9.01      +10mV
 10V     10.02     +20mV
 11V     11.04     +40mV
 12V     12.06     +60mV

The input voltages measured by DMM and was spot on voltage, like 1.000V.
I didn't test voltages above 12V but it seems the difference is gonna increase by 20mV with each 1V increase, that means at 50V voltage reading is gonna be off by ~1V!
Even with 10bit resolution of Arduino I should have had steady accuracy with some percentage of difference(right?), but as you can see the result shows that the reading is not steady at all!
Why the voltage difference decrease/increase when voltage changes at the input?

As stated by Majenko, the ADC can in principle have all sorts of
errors. However, if you look at your data, you should notice that the
error is essentially linear with the voltage. This means that the
non-linearity error is quite small, and you are mainly seeing the offset
and gain errors. This is fortunate, because these errors are easy to
remove, given good calibration data.
The table you wrote in in your question happens to be a perfectly good
calibration table. By fitting a straight line to it you can get a
calibration function, and then correct the readings simply by adding
this to your code:
voltage = 0.9848815 * voltage + 0.125354;

Or you could instead figure out the correction at the ADC level and
replace
adc = analog * 1.228 / 1023;

by
adc = (analog + offset) / scale;

where offset and scale are computed from the calibration.

Edit: Here is how I extracted the calibration coefficients from the
data.
First, I saved the data in a text file calibration.tsv and cleaned it up
to remove the units and add a comment marker (#) in front of the column
labels:
#Input | Arduino | Difference
 1      0.89     -110e-3
 2      1.90     -100e-3
...

Then I looked at the data with gnuplot. Since I want to know how to
correct the readings, I plot the amount I have to add (minus column 3)
v.s. the Arduino reading (column 2):
plot 'calibration.tsv' using 2:(-$3)

At this point it appears it's linear with what looks like mostly
quantization noise. I model this as a line of equation a*x+b, and
compare the line with the data:
a = -1e-2
b = 0.12
plot 'calibration.tsv' using 2:(-$3), a*x+b

The line is quite off the data, but it's a reasonable first
approximation. Now I ask gnuplot to perform a least squares fit, then
take another look:
fit a*x+b 'calibration.tsv' using 2:(-$3) via a, b
replot

Now the fit looks quite good. When it completed the fit, gnuplot
displayed:
Final set of parameters            Asymptotic Standard Error
=======================            ==========================
a               = -0.0151185       +/- 0.0002953    (1.953%)
b               = 0.125354         +/- 0.002173     (1.734%)

so now I know I can correct the data with:
voltage += -0.0151185 * volatage + 0.125354;

which is equivalent to what I wrote above.

How do you calculate the offset and scale?

@newbie, put the data in Excel/Calc, draw a chart with expected values and function  and then change the offset and scale values for the function until the lines in the chart match

@Juraj Like This?

The voltage = 0.9848815 * voltage + 0.125354; code almost calibrated the reading with ~ -60mV steady difference (it can't measure below 130mV though), where did you get those values? can you please explain more with math included?

@newbie: I am an old timer who likes text-mode programs rather than Excel, Calc and such, so I used gnuplot. See expanded answer.

@newbie, column B should have a function in cells. and the function should use two other cells with the coefficients you want to fine-tune

@Juraj I've never used excel before and have no idea how to do what you want me do to...

@newbie, example https://github.com/jandrassy/Regulator/tree/master/util/Calc

Yes, you are right that the Arduino ADC is not accurate.  If you read the datasheet (ATMega328P section 28.9, ADC Characteristics) you can see a lot of "error" and "non-linearity" characteristics.
These all add up to inaccuracies in your readings.  For example the "Offset error" at your VREF could be as much as ±4.4mV, and the "Gain error" the same. Non-linearity can be as bad as 2mV, etc.
The Arduino ADC is not meant to be accurate. It's meant to be simple and cheap to implement. (It is a "Successive Approximation ADC" - approximation here is the keyword...) If you want a higher accuracy then there are more suitable ADC chips available that give that accuracy.

I was expecting 100mV error to be steady like 1.100V, 2.100V ... Wasted so much time calibrating this ...! beside using external ADC do you think it's good idea to switch to a PIC micro-controller with 12bit ADC. i'm asking this because PIC is cheaper.

I would always say use a PIC over an ATMega, but then I am a PIC junkie- however increased resolution does not equate to increased accuracy. It's still an SAR with the inherent inaccuracies which that gives you. Since the inaccuracy looks to be pretty linear you can use calibration and calculations to remove it. You have a straight line, the formula for which (if you remember school maths classes) is y = mx + c

Re “successive approximation ADC”: any measurement whatsoever is always an approximation. The keyword here is “successive”: it means the ADC works by iteratively refining the approximation.

@EdgarBonet And because the sampled voltage is stored in a tiny capacitor, and it's impossible to read a voltage without drawing some current, each successive comparison will affect the voltage across that capacitor making it less accurate with each bit that is approximated. So it's successively worse approximation. It's a successive approximation that can only ever be approximate.


text:
Unused lines of code causing program to crash
I have a project which essentially involves WiFi, a web server, and an LED. I'm using the Inbuilt LED on my ESP8266 for testing at the moment. I am using the Arduino IDE for programming.
I had a problem where my code would crash after connecting to WiFi. By commenting out functions in my loop, I narrowed down the crash problem to my function that handles the LED. Here I ran into a problem, commenting out each block of code individually, and even a few at once, I wasn't able to prevent the crash. There must be more than one line causing the crash. Commenting out the entire function was the only thing that worked.
After hours of troubleshooting, I was left at the stage where I had the contents of all the if statements and loops and such commented out.
Here is what left me utterly confused. Here is the if statement:
if(webSocketActive){
    Serial.println("websocket is active, setting brightness");
    analogWrite(LED_BUILTIN, 1024 - lightBrightnessAdjust);
} else {
    //other stuff with more if-statements that are empty
}

At this point, if I comment out the analogWrite line, the program works fine. But if I leave it like this, it crashes after connecting to WiFi. (I didn't post my entire program because it is over 1000 lines long).
The baffling part about all this is, webSocketActive is never set to true prior to this point in the code... The Serial.println() never does anything, meaning the ESP definitely doesn't execute the instructions inside the if statement. But, for some inexplicable reason, simply having the analogWrite() uncommented crashes the program, even if it never executes that line.
I've also had other issues where putting some sort of Serial.print() function in the loop to repeatedly run somehow doesn't make the code crash. Could someone let me know what is going on?

Sounds like you could have some form of buffer overflow or variable alignment issue, and adding / removing code randomly changes allocations of variables or constants. You should turn on debugging and see what the crash actually is.

@Majenko So, I turned on debugging for WIFI+CORE and some other stuff. When my first test worked, I uncommented everything else in the function. It works. Why? What change does turning on debugging make?

It basically adds a load of serial prints... so it does something similar to your program changes. With debugging off and it crashing do you get an exception code on serial?

Yes I do, it's a hardware watchdog reset, so no stack dump. rst cause:4, boot mode:(3,6), wdt reset. The thing is, as I pointed out in my post, when I added a Serial print into my loop (or just into my function, which is in the loop) the program wouldn't crash. Why would this happen?

It's impossible to say.

@Majenko is there any effect Serial.print() would have on the program at all?

Well, yes. It would change the internal layout of the code. Instructions will move locations. Constant data structures will be in different places. Lots of things could change.

You put identical comments at the answers telling that you solved the issue. Please make this an answer and mark it so that we all know that your problem is solved, and how. It will help others with a similar problem.

Turns out that the MDNS.begin() in setup and the MDNS.update() in the loop was, presumable, causing some sort of undefined behaviour, since the code didn't always crash. I commented out these two lines, and the code works fine now, minus the MDNS.

I think I might know the problem (maybe you've fixed it after two weeks) but your analogWrite(Pin, Val)might end up being out of range, remember that analogWrite only takes an int of 0 to 255 therefore if your lightBrightnessAdjust variable is lower than 769 then we will get an int above the accepted input range of analogWrite().
I know the code never actually runs but it still compiles and maybe Arduino doesn't like even a possible error.
Maybe I didn't explain it very well but here's the Arduino documentation for it.
Another possible solution could be perhaps you could try defining int amount = 1024-lightBrightnessAdjust; variable beforehand and then entering the variable into analogRead because it could be fussy about doing math inside the function params (just a thought)

Turns out that my code wasn't the issue. The MDNS.update() in the loop was what was causing the code to crash. Commenting that out fixed the issue.

Overwriting an array could clobber that functions return address.
Allocating from the heap, enough memory for the up-growing heap and the down-growing stack to collide, could cause or create the conditions for clobbering function-local data, function return-return address, or heap data, including the heap meta-data required to de-allocate that heap-block.
Writing through an uninitialized or overwritten pointer can cause about any memory corruption you can imagine; and the result can be data dependent and/or data-memory map dependent, and quite possibly non-repeatable.
Clobbering the interrupt vector of an enabled interrupt can cause improperly jumping into any part of your code, and is quite likely to be unrepeatable.

There's too much we don't know about the unseen rest of your code to do much more than speculate on possible points-of-failure.

Turns out that my code wasn't the issue. The MDNS.update() I had in the loop was what was causing the code to crash. Commenting that out fixed the issue.

source: Stack Exchange

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

sort: votes


text:
Serial monitor when port is being used by another application
I am controlling some LEDs via the USB serial port using a Tkinter/Python3x script to debug what I suspect is a hardware problem.
from tkinter import *
import serial

usbport = 'COM3'
ser = serial.Serial(usbport, 9600, timeout=1)

def init():
    print("Started")

class App:

    def __init__(self, master):

        frame = Frame(master)
        frame.pack()
        self.scale1 = Scale(master, from_=0, to=255, command=lambda ev: self.getBright(1), bd=5, bigincrement=2, length=360, width=30, label='RED')
        self.scale1.set(128)
        self.scale1.pack(side=LEFT)
        self.scale2 = Scale(master, from_=0, to=255, command=lambda ev: self.getBright(2), bd=5, bigincrement=2, length=360, width=30, label='GREEN')
        self.scale2.set(128)
        self.scale2.pack(side=LEFT)
        self.scale3 = Scale(master, from_=0, to=255, command=lambda ev: self.getBright(3), bd=5, bigincrement=2, length=360, width=30, label='BLUE')
        self.scale3.set(128)
        self.scale3.pack(side=LEFT)
        self.centre = Button(frame, text="Centre All", command=self.centre)
        self.centre.pack(side=TOP)

    def getBright(self, slider):

        if slider==1:
            brt = self.scale1.get()

        if slider==2:
            brt = self.scale2.get()

        if slider==3:
            brt = self.scale3.get()

        ser.write(255)
        ser.write(slider)
        ser.write(brt)

    def centre(self):

        for LED in range(0, 4):

            ser.write(255)
            ser.write(LED)
            ser.write(128)

        self.scale1.set(128)
        self.scale2.set(128)
        self.scale3.set(128)

init()
root = Tk()
app = App(root)
root.mainloop()

On the Arduino Mega 2560 side I read in from serial a start byte, LED label & a brightness value...
int user_input[3];
int start_byte;
int LED;           // which LED to pulse? r=1 g=2 b=3
int brightness;
int i;

// LED pins
#define REDPIN 7
#define GREENPIN 8
#define BLUEPIN 9

void setup()
{

  // LED outputs
  pinMode(REDPIN, OUTPUT);
  pinMode(GREENPIN, OUTPUT);
  pinMode(BLUEPIN, OUTPUT);

  Serial.begin(9600);
}

void loop()
{
  if (Serial.available() > 2) {

    start_byte = Serial.read();
    if (start_byte == 255) {

      for (i = 0; i < 2 ; i++) {
        user_input[i] = Serial.read();
      }

      LED = userInput[0];
      brightness = user_input[1];

      switch (LED) {

        case 1:
          analogWrite(REDPIN, brightness);
          break;

        case 2:
          analogWrite(GREENPIN, brightness);
          break;

        case 3:
          analogWrite(BLUEPIN, brightness);
          break;

      }
    }
  }
}

Now I would like to see what is actually being sent via the serial port to the Arduino using the serial monitor (yes I know I can just print the values in the Python terminal that's not what I'm asking).
The problem is that the Arduino Serial Monitor is locked out. I'm guessing this is a Windows thing (Win10 x64)? Has anybody here come across this?

I think this is totally normal. Only one application can use the port at once

Wire USB to Serial adapter to any other hw Serial of the Mega and print there

Serial data can only go to one place at a time. Either your Python program can receive the data, or the Serial Monitor can receive the data. Similarly the serial port can only receive data from one place at a time.
So Windows prevents you doing something invalid by locking you out of the serial port when something else is using it.
This is normal, and entirely desired functionality.
Your simplest option is to just print what you receive in your Python program.

So this is an in built Windows thing then? I have no problem reading a serial port from multiple applications when using Raspbian.

That's because Linux us far more sophisticated than Windows. However, if you open the port multiple times on Linux only one program will receive data. Which one? Impossible to say.

@Majenko "Which one? Impossible to say." Very sophisticated, indeed. ;)

@DataFiddler It depends on many factors. Maybe it will be the last one connected. Maybe the first. Maybe it will be a 50/50 split. I don't know the answer. Some Linux kernel hacker might, but I don't. Personally I use socat on Linux to "tee" the data off and pass it out to another pty device if I need to debug at that sort of level.

@Majenko: Thanks for bringing socat to my attention.

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


text:
Increase or decrease the brightness of Nextion display
I have a nextion display. I want to implement this issue of it. Start the program. If for example I don't touch the display for 15seconds, it should to turn off its brightness. If I touch the screen on any point, it should to increase its brightness.
For this I m build this code:
In PreinitializeEvent of page 0, I have insert this code:
tm0.tim=0
tm0.en=1
dim=30

In Touch Release Event of page 0, I have insert this code:
dims=100

But if I try to start the program, the brightness is always the same. Not increase.
/EDIT
I use Nextion Edito 0.58

PreinitializeEvent is a View of NExtion IDE

@bircastri, in this stackexchange.com space we primarily concern our selves with answering questions about developing using the Arduino IDE.  While the Nextion IDE looks interesting, some may consider it off topic.  Also, consider the Nextion IDE its self may not have the feature you are looking for.

dim sets the brightness for that session
dims sets the default brightness and remains even after reset.
I've found the most effective way is to add the code to the page's preinitialize tab.
Obviously if you use dims on page 0 all the pages will have that brightness

The original question has been improved (which is appreciated) to include the IDE which the poster is using.  In this stackexchange.com space we primarily concern our selves with answering questions about developing using the Arduino IDE. While the Nextion Editor looks interesting, some may consider it off topic.
For those who come here interested in controlling the brightness of their Nextion Display and are using the Arduino IDE, there is this answer:
There appears to be several Nextion Arduino Library efforts to choose from.  If you are using this Nextion Display Library, here is the example code which set the screen brightness.  The part of the code which sets the screen brightness is rather simple and resides in the Arduino loop() function.  In the loop() function the brightness is set repeatedly as the program continues to run:
void loop() {
  int brightness = analogRead(A0);
  int bright = map(brightness, 0, 1024, 0, 100);
  String dim = "dim=" + String(bright);
  myNextion.sendCommand(dim.c_str());

}

For those of you using the Nextion editor and the Nextion Arduino Libraries, there is this github.com Issue which talks about adding multiple missing Nextion features including a screen brightness function. This issues appears to still be OPEN (Bad support? / Bad house-keeping?). But is over a year old so may have be incorporated.  If so, here is the example code from that link:
/**
* Set the brightness of the display.
*
* @param buffer - number (0 - 100).
*/
bool setBrightness(byte buffer);

Since you didn't specify which Nextion Library you are using and since you didn't show us the simplest version of your code which still does not work, we have to guess at the most probable answer.

I have added this information of the first post. I use anyway Nextion Edito 0.58v


text:
Reset I2C connection with arduino as slave
I am currently using I2C serial communications with arduino as slave and raspberry pi as the master. I am sending sensor data from arduino to raspberry pi. I need to reset the I2C connection once the sensor readings cross a threshold. I tried setting the TWCR =0 but it throws a Error 121 Remote I/O error on the raspberry pi when I do that. I also read that one way is to set TWCR =0, but for this I need to execute the Wire.begin(), Wire.onRequest(), and Wire.onReceive() again. Can you please tell me how to run these again since they are put in setup function. Does it mean I need to restart the Arduino program again? Or can I put these in void loop()? Thanks for the help.

Why do you need to reset the I2C connection? And you can use all the functions of the library wherever you want

Hi Chrisl, I want to reset the connection because I don't want Arduino to send any more values to the master once the sensor readings cross a threshold value. Is there a better way to implement it?

You have a misconception about how I2C works. Unlike Serial (UART) I2C is a strictly master-slave interface. The slave cannot do anything without the master, since only the master controls the clock. Thus you don't need to reset the I2C interface to stop the transmission from the slave to the master.
When the master requests data from the slave the following happens: First the master sends the address of the targeted slave, including the direction bit set for "reading from slave". The slave with this address reacts with an acknowledgement (ACK) and start to transmit one byte. This byte get's acknowledged by the master. When the master decides, that it has received enough data, it does not acknowledge (NACK), which let's the slave stop it's transmission. Then the master sends a STOP condition to stop the I2C transmission.
I don't know, how you implemented the I2C communication on the Pi. Normally, when you initiate a read transaction from the master, you provide a number of bytes, that you want to request from the slave. The I2C module/library will then request data from the slave, until is has received all the requested bytes.
Thus you don't need to reset the I2C connection on the Arduino. The master totally controls the communication. When you end the transmission on the master, the slave cannot send further data.
Setting TWCR to zero in the middle of transaction will disrupt the I2C communication protocol. Thus you get an error on the Pi, that states an error in the I2C communication protocol. Just use the correct implementation of the I2C protocol to end the transmission correctly.


text:
Getting an Arduino Uno and MKR zero to communicate
I'm very new to Arduino and especially the forum so please let me know if I am on the wrong topic or anything.
Anyways let me get straight to the point. I am working on a school project where I need to create a robot head that can move and talk using the Arduino Uno. I have the speech files as a .wav and from what I gathered you need an sd card reader connected to the Uno to read .wav files. So I purchased the Arduino MKR Zero, but after I got the board I realized that it is a standalone board, not a file reader for the Uno. This project is due next week so I need to figure out how to make the MKR Zero read the files and play them off the speakers but have it timed and programmed off the Uno. Is this possible with the hardware I have?
Here is a picture of my setup:

you don't need the Uno

I do because the MKR Zero doesn't have enough ports for all the motors that I need to use for my project.

Let the MKR Zero play the wav files. It has DAC on A0 and AudioZero library to play wav files from SD card.
You can use Serial communication to command the Zero from Uno. In Uno use hardware Serial or create SoftwareSerial to send commands to Serial1 of MKR Zero. You can then test the MKR first with commands sent from Serial Monitor.


text:
Why did it blow up?
I recently designed a PCB to hold an Arduino Nano, IMU and other components. I'm using this platform as the fly computer of a homemade drone. This is one of my first PCB designs and I'm not an expert, so perhaps I'm missing something obvious here.
Now let us get to the problem. I started by testing each component, the Arduino (CPU), CPU + IMU, CPU + HC-05, CPU + HC-05 + RTX(RC receiver). At this last point, the Arduino stopped responding, the RX TX and POW LEDs stay ON all the time. I can't upload new software to it.
I noticed that the ATmega328 was extremely hot! I tried powering the Arduino from the +5V and same result (LEDs stuck ON).
During testing, I had a 3SLiPo battery connected to the PW(top right) of the PCB, and the Arduino was also connected to my PC through the USB port.
Do you see any issues with the PCB design itself?
List of the components tested:

Arduino NANO
HC-05
FlySky receiver
R1 1k
R2 2K
C1 10uF

Thanks.

how much current does the RTX need for operating?

@chrisl Something like 40mA

Do you see any issues with the PCB design itself? -- Aside from the too-thin power traces and terrible grounding? No, nothing jumps out at me...

You say: "3SLiPo battery connected to the PW(top right) of the PCB, and the Arduino was also connected to my PC through the USB port."  I would be suspicious you are driving the power from 2 different sources.  There is a diode in the Nano between the USB's power and 5V Regulator.  But I still would only use one power source at a time.

@Majenko I didn't even think of making the power traces wider, thats a good idea for future PCBs. Regarding the grounds, how would you improve that?

Generally speaking, people usually "flood" the ground.

Yep, @st2000 has it right. A single near-solid ground fill that covers everything is the normal way - then ground connections are just "thermal" connections to that plane.

@st2000 Yeah not sure why I did that. Also having mixed grounds from the battery and the USB doesn´t sound great.

Again, generally, all grounds need to be tied together.  I should add that, generally, all grounds should connect at a single point (flooding will probably get you there).  Not looped around the board (which is usually thought of as bad because of ground loops, trace resistance & noise).

Thanks for your comments, I'm tempted to try this again (without the two power sources) before redesigning the PCB.

May I ask, why the HC's Tx/Rx are not connected to the arduinos serial? And what's the purpose of R1 and R2?

The HC-05 is surely connected to SoftwareSerial. And the resistors are a voltage divider, because the HC-05 needs 3.3V logic level at it's RX.

@SimSon Sure, I do a lot of debugging using the USB port and also I update the code often, so I didn't want to be unplugging the HC05 all the time. As chrisl said, those resistors are used to reduce the voltage into the HC RX (it expects 3.3V not 5).

For higher currents, a DC-DC converter (or if you really want to save every gram one provided by either of the 4 ESCs) might be a good idea.
I don't see any additional problem with the PCB either, but the code could explain what happened. Maybe you initialized the wrong pin as an output?
One more thing to check: my Nano clones have AMS1117-5.0 as an LDO, but its pinout is different than a non-AMS one. If the manufacturer loaded the other one into the machine for that batch, that could cause trouble (but only if someone used it from VIN). Just look at the trace from VIN to the LDO to be sure.


text:
Sparkfun CCS811 Air Quality Sensor is just not working
I have an Arduino Uno board and a SparkFun ccs811 sensor. I tried to reproduce the howto from the SparkFun homepage (https://learn.sparkfun.com/tutorials/ccs811-air-quality-breakout-hookup-guide?_ga=2.45231532.967238096.1560976781-258902726.1560976781), including the error states part.
I uploaded one picture of the wiring (updated). I also tried to use an alternative hardware connection with SDA to A4 and SCL to A5, as mentioned in the code comments (see homepage).
However, it is just not working, and I always get this error code in the serial monitor beginCore exited with: I2C_ERROR
Here is my code (without the top comment block):
#include <Wire.h>

#include "SparkFunCCS811.h" //Click here to get the library: http://librarymanager/All#SparkFun_CCS811

#define CCS811_ADDR 0x5B //Default I2C Address
//#define CCS811_ADDR 0x5A //Alternate I2C Address

CCS811 mySensor(CCS811_ADDR);

void setup()
{
Serial.begin(9600);
Serial.println("CCS811 Basic Example");

Wire.begin(); //Inialize I2C Harware

//It is recommended to check return status on .begin(), but it is not
//required.
CCS811Core::status returnCode = mySensor.begin();
Serial.print("beginCore exited with: ");
switch ( returnCode )
{
case CCS811Core::SENSOR_SUCCESS:
 Serial.println("SUCCESS");
 break;
case CCS811Core::SENSOR_ID_ERROR:
 Serial.println("ID_ERROR");
 break;
case CCS811Core::SENSOR_I2C_ERROR:
 Serial.println("I2C_ERROR");
 break;
case CCS811Core::SENSOR_INTERNAL_ERROR:
 Serial.println("INTERNAL_ERROR");
 break;
case CCS811Core::SENSOR_GENERIC_ERROR:
 Serial.println("GENERIC_ERROR");
 break;
default:[enter image description here][2]
 Serial.println("Unspecified error.");
}

if (returnCode != CCS811Core::SENSOR_SUCCESS)
{
Serial.println(".begin() returned with an error.");
while (1); //Hang if there was a problem.
}
}

void loop()
{
//Check to see if data is ready with .dataAvailable()
if (mySensor.dataAvailable())
{
//If so, have the sensor read and calculate the results.
//Get them later
mySensor.readAlgorithmResults();

Serial.print("CO2[");
//Returns calculated CO2 reading
Serial.print(mySensor.getCO2());
Serial.print("] tVOC[");
//Returns calculated TVOC reading
Serial.print(mySensor.getTVOC());
Serial.print("] millis[");
//Simply the time since program start
Serial.print(millis());
Serial.print("]");
Serial.println();
}

delay(10); //Don't spam the I2C bus
}

Can it be, that your ground connection to the sensor is at the wrong place? On the image it looks like the violet wire is connected one pin to the right of the ground pin

You were right; i just fixed it and uploaded a new image. But its still not working.

You need to solder those headers to the breakout. Just inserting them into the plated-through-holes doesn't give a reliable connection.

So simple, though hard to recognize :D


text:
Audio Zero not responding on MKR Zero
I have a Arduino MKR Zero set up with a sd card in it and a speaker hooked up to the ground and DAC0. I have a .wav file on it called "test.wav" and it is 8 bit mono 88200hz recording. I am using the AudioZero example to try to play this audio file off the speaker but it is not working. When I upload and run the code and open the Serial Monitor to check to see if it has any errors or sucesses reading the files it is just blank. It uploads the code all fine, but the Serial Monitor says nothing at all and the speaker doesnt play anything. Did I set it up wrong somehow?
Here is the code that it is running:
  Simple Audio Player for Arduino Zero

 Demonstrates the use of the Audio library for the Arduino Zero

 Hardware required :
 * Arduino shield with a SD card on CS4
 * A sound file named "test.wav" in the root directory of the SD card
 * An audio amplifier to connect to the DAC0 and ground
 * A speaker to connect to the audio amplifier

 Arturo Guadalupi <a.guadalupi@arduino.cc>
 Angelo Scialabba <a.scialabba@arduino.cc>
 Claudio Indellicati <c.indellicati@arduino.cc>

 This example code is in the public domain

 http://arduino.cc/en/Tutorial/SimpleAudioPlayerZero

*/

#include <SD.h>
#include <SPI.h>
#include <AudioZero.h>

void setup()
{
  // debug output at 115200 baud
  Serial.begin(115200);

  // setup SD-card
  Serial.print("Initializing SD card...");
  if (!SD.begin(SDCARD_SS_PIN)) {
    Serial.println(" failed!");
    return;
  }
  Serial.println(" done.");
  // hi-speed SPI transfers
  SPI.setClockDivider(4);

  // 88200 sample rate
  AudioZero.begin(2*44100);
}

void loop()
{
  int count = 0;

  // open wave file from sdcard
  File myFile = SD.open("test.wav");
  if (!myFile) {
    // if the file didn't open, print an error and stop
    Serial.println("error opening test.wav");
    while (true);
  }

  Serial.print("Playing");

  // until the file is not finished
  AudioZero.play(myFile);
  AudioZero.end();

  Serial.println("End of file. Thank you for listening!");
  while (true) ;
}

add while (!Serial); after Serial.begin to wait for Serial Monitor connection

When I do that it looks like it is initializing correctly because the serial monitor now says Initializing SD card... done.   But then it just freezes on that and doesn't get any further.

try the CardInfo example of the SD library

The card info example runs just fine and gives me all the info with no errors.

did you test the speaker or buzzer with tone()?

Yes I did. The tone works just fine as well.

To use the Serial monitor with Arduino MKRZERO, use SerialUSB instead of Serial, i.e. SerialUSB.println("something");


text:
Trying to create a delay function whilst performing other functions, using Timer.h libraries. Arduino uno
I am having a compilation error saying invalid useof template-name 'Timer without an argument list.

First: What is your font dude? XD Second: Please don't show images of code here. Instead you should copy and paste the code as text into your question. Then select the code and click on the {} button to format it correctly. And third: You should include the complete error message (as text like the code) into your question. Also provide links to the Timer library, that you are using.

Second: Which timer library are you talking about? Have you looked at its doc/examples ?

i love the font ... what is its name?

Read, play with, and understand the Arduino BlinkWithoutDelay basic example.
Understand means learn that it does not only apply to blinking, but to any time related action without blocking the main loop().
It's better learning the basics than using libraries in a wrong way.

thank you for your avid response, it was my first time posting here. i will Read, play with, and understand the Arduino BlinkWithoutDelay.


text:
Monitor serial0 while code is being uploaded
I'm trying to upload the sketch on a Mega 2560 via the serial port 0 using another microcontroller.
To better undestand the process, I decided to first observe what avrdude is doing while it is uploading a hex file. To do this, I'm using another arduino (ESP32) with the following sketch:
void setup()
{
    Serial.begin(115200);
    Serial2.begin(115200);
}

void loop()
{
    while (Serial2.available()) {
        Serial.print(Serial2.read(), HEX);
        Serial.print(":");
    }
}

ESP32's Serial(serial0) is connected to PC via USB, and Serial2 is connected to Mega's Serial(serial0), the one connected to PC via USB, used by avrdude.

According to this answer the first things avrdude is sending over the serial interface are:
STK_GET_SYNC / CRC_EOP  (0x30/0x20)

But this is not what I receive through ESP32:
1B:1:0:1:E:1:14:1B:2:0:C:E:10:C8:64:19:20:0:53:3:AC:53:0:0:31:1B:3:0:8:E:1D:4:4:0:30:0:0:0:33:1B:4:0:8:E:1D:4:4:0:30:0:1:0:35:1B:5:0:8:E:1D:4:4:0:30:0:2:0:37:1B:6:0:8:E:1D:4:4:0:50:0:0:0:56:1B:7:0:8:E:1D:4:4:0:50:0:0:0:57:1B:8:0:8:E:1D:4:4:0:50:0:0:0:58:1B:9:0:8:E:1D:4:4:0:58:8:0:0:59:1B:A:0:8:E:1D:4:4:0:58:8:0:0:5A:1B:B:0:8:E:1D:4:4:0:58:8:0:0:5B:1B:C:0:8:E:1D:4:4:0:50:8:0:0:54:1B:D:0:8:E:1D:4:4:0:50:8:0:0:55:1B:E:0:8:E:1D:4:4:0:50:8:0:0:56:1B:F:0:5:E:6:80:0:0:0:99:1B:10:1:A:E:13:1:0:C1:A:40:4C:20:0:0:71:C0:0:0:81:C0:0:0:7F:C0:0:0:7D:C0:0:0:7B:C0:0:0:79:C0:0:0:77:C0:0:0:75:C0:0:0:73:C0:0:0:71:C0:0:0:6F:C0:0:0:6D:C0:0:0:6B:C0:0:0:69:C0:0:0:67:C0:0:0:65:C0:0:0:63:C0:0:0:61:C0:0:0:5F:C0:0:0:5D:C0:0:0:5B:C0:0:0:59:C0:0:0:57:C0:0:0:56:C0:0:0:53:C0:0:0:51:C0:0:0:4F:C0:0:0:4D:C0:0:0:4B:C0:0:0:49:C0:0:0:47:C0:0:0:45:C0:0:0:43:C0:0:0:41:C0:0:0:3F:C0:0:0:3D:C0:0:0:3B:C0:0:0:39:C0:0:0:37:C0:0:0:35:C0:0:0:33:C0:0:0:31:C0:0:0:2F:C0:0:0:2D:C0:0:0:2B:C0:0:0:29:C0:0:0:27:C0:0:0:25:C0:0:0:23:C0:0:0:21:C0:0:0:1F:C0:0:0:1D:C0:0:0:1B:C0:0:0:19:C0:0:0:17:C0:0:0:15:C0:0:0:13:C0:0:0:11:24:1F:BE:CF:EF:D1:E2:DE:BF:CD:BF:0:E0:C:BF:22:E0:A0:E0:B2:E0:1:C0:1D:92:A9:30:19:1B:11:0:5:E:6:80:0:0:80:7:1B:12:1:A:E:13:1:0:C1:A:40:4C:20:0:0:B2:7:E1:F7:4C:D0:C2:C0:7B:CF:1F:92:F:92:F:B6:F:92:11:24:2F:93:3F:93:8F:93:9F:93:AF:93:BF:93:80:91:5:2:90:91:6:2:A0:91:7:2:B0:91:8:2:30:91:4:2:23:E0:23:F:2D:37:20:F4:1:96:A1:1D:B1:1D:5:C0:26:E8:23:F:2:96:A1:1D:B1:1D:20:93:4:2:80:93:5:2:90:93:6:2:A0:93:7:2:B0:93:8:2:80:91:0:2:90:91:1:2:A0:91:2:2:B0:91:3:2:1:96:A1:1D:B1:1D:80:93:0:2:90:93:1:2:A0:93:2:2:B0:93:3:2:BF:91:AF:91:9F:91:8F:91:3F:91:2F:91:F:90:F:BE:F:90:1F:90:18:95:78:94:84:B5:82:60:84:BD:84:B5:81:60:84:BD:85:B5:82:60:85:BD:85:B5:81:60:85:BD:80:91:6E:0:81:60:80:93:6E:0:10:92:81:0:80:91:81:0:82:60:80:93:81:0:80:91:81:0:81:60:80:93:81:0:80:91:80:0:81:60:80:93:80:0:80:91:B1:0:84:60:80:93:B1:0:80:91:B0:0:81:60:1B:13:0:5:E:6:80:0:1:0:84:1B:14:1:A:E:13:1:0:C1:A:40:4C:20:0:0:91:0:80:91:91:0:81:60:80:93:91:0:80:91:90:0:81:60:80:93:90:0:80:91:A1:0:82:60:80:93:A1:0:80:91:A1:0:81:60:80:93:A1:0:80:91:A0:0:81:60:80:93:A0:0:80:91:21:1:82:60:80:93:21:1:80:91:21:1:81:60:80:93:21:1:80:91:20:1:81:7A:0:80:91:7A:0:81:60:80:93:7A:0:80:91:7A:0:80:68:80:93:FF:FF:FF:FF:FF:FF:FF:FF:FF:FF:FF:FF:FF:FF:FF:FF:FF:FF:FF:FF:FF:FF:FF:FF:FF:FF:FF:FF:FF:FF:FF:FF:FF:FF:FF:FF:FF:FF:FF:FF:FF:1B:15:0:8:E:1D:4:4:0:50:0:0:0:45:1B:16:0:8:E:1D:4:4:0:50:0:0:0:46:1B:17:0:8:E:1D:4:4:0:50:0:0:0:47:1B:18:0:8:E:1D:4:4:0:58:8:0:0:48:1B:19:0:8:E:1D:4:4:0:58:8:0:0:49:1B:1A:0:8:E:1D:4:4:0:58:8:0:0:4A:1B:1B:0:8:E:1D:4:4:0:50:8:0:0:43:1B:1C:0:8:E:1D:4:4:0:50:8:0:0:44:1B:1D:0:8:E:1D:4:4:0:50:8:0:0:45:1B:1E:0:3:E:11:1:1:19:

I can't find 30:20 anywhere. What am I missing?
The baud rate is 115200 everywhere which I believe is the right one. The link is good because if I send char 'A' from PC over the serial connected to Mega, I get 41: via ESP32 on the other side, which is correct.

Are both ESP32's serial ports implemented in hardware?  Do the research because if 1 is implemented in software the ESP32 may not be able to echo back everything it sees on the hardware serial port.

the bootloader responses on TX. and do you reset the board? the avrdude uses stk500 protocol, which is documented, no need to reverse engineer it

@st2000 According to online docs they are both hardware. It's also labeled on the board and when I send a random char from PC to Mega, I receive the correct value via ESP32, but when I look at what I receive during sketch upload, makes no sense. @Juraj I'm interested in what avrdude is sending first, which should be 0x30,0x20,  not 0x1B,0x01. I don't reset the board, the usb-to-serial chip already does it. The sketch upload from PC works. I just want to confirm the the first thing it sends is 0x30,0x20 to help me going.

Agreed, online it says the ESP32 has 3 hardware UARTs.  But when the Arduino development environment was ported to the ESP processor, did it actually use the hardware UARTs? And if it did, how well implemented is the firmware? For that matter, how well is the ESP's hardware implemented?  The type of problem I am concerned about occurs when many bytes are transferred rapidly. Of course the 1st byte, for such problems, should always make it through. Also, I agree with @Juraj. Use the existing documentation to develop you own programmer. Nothing says that what avrdude does is correct.

@Juraj In C:\Program Files (x86)\Arduino\hardware\arduino\avr\boards.txt I have mega.menu.cpu.atmega2560.upload.speed=115200. I have also tried 57600 and 9600. What baud rate you think is being used?

The answer you link to is about the Uno. The Mega uses a different bootloader and, IIRC, a different protocol.

@EdgarBonet Yeah, I just noticed that if select AVR ISP programmer and click Burn Bootloader I can see 30:20 multiple times on the other side at the ESP32. So the serial it's fine. But there are no replies from the bootloader. I'll have to find an alternative for Mega. Thanks!

and what is what you try to do? AVR ISP is a programmer (hardware) to flash without bootloader

@Juraj The same protocol that AVR ISP is using, Uno and many others that have optiboot, are using. Mega however is using wiring bootloader, that is why I see 1B:1:0:1:E:1:14 as the first message, which is wiring_open(). In the end I want to be able to program mega via WiFi through internet. I think I'll try adapt ESP8266AVRISP for ESP32.

you can use my ArduinoOTA library to remote upload to Mega, if the Mega can access the network with some Arduino library (WiFiNINA?) https://github.com/jandrassy/ArduinoOTA


text:
I2C communication between arduino and raspberry pi breaks under stress for unclear reasons. Why?
I am having a behavior I cannot explain while using arduino mega as a I2C slave for a raspberry pi master.
I am showing here an idealised program that shows the issue. I experience pretty much the same behavior in the real application (a keyboard firmware). What I am doing is the following:

the arduino issues an interrupt on pin 23 at evert loop to inform the raspi that there's some data to be read.
the raspi sends a request as master to the arduino.
arduino receives the request in the Wire handler, and issues a reply of 32 bytes. I fill these 32 bytes with a uint8 counter just as a check.
the cycle starts again.

This is the code for the raspi
import time
import RPi.GPIO as GPIO
import smbus

GPIO.setmode(GPIO.BCM)
GPIO.setup(4, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)

bus = smbus.SMBus(1)
address = 0x42

def callback(channel):
    data = bus.read_i2c_block_data(address, 0x00, 32)
    print(data)

GPIO.add_event_detect(4, GPIO.RISING, callback=callback)

while True:
    time.sleep(1)

GPIO.cleanup()

and this is the code of the arduino
#include <Wire.h>

byte IRQ_PIN = 23;

volatile unsigned int counter;

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

    pinMode(IRQ_PIN, OUTPUT);
    digitalWrite(IRQ_PIN, LOW);
    Wire.begin(0x42);
    Wire.onRequest(requestEvent);
    Wire.onReceive(receiveData);

}

void signalMaster() {
  noInterrupts();
  irq();
  interrupts();
}

void irq() {
  digitalWrite(IRQ_PIN, HIGH);
  digitalWrite(IRQ_PIN, LOW);
}

void requestEvent() {
  byte buf[32];
  counter++;
  memset(buf, counter, 32*sizeof(byte));
  Wire.write(buf, 32);
}

void receiveData(int byteCount){
  while(Wire.available()) {
    Wire.read();
  }
}

void loop() {
  signalMaster();
  delay(1);
}

As you can see, the point is that I am banging the I2C really, really fast, and the loop is very tight and fast. This is the point of the exercise and the problem to solve arises from this.
Now, once in a while I get an occasional IO error with the raspi python code. This code occasionally fails once, and then everything resumes to normal, but once in a while, it completely breaks down and never recover.
I attached a logic analyser to it, and this is what I found. D3 is the interrupt pin. The others the I2C bus. In a normal transaction, I can see everything working properly (disregard the different content of the response, it was an earlier run)

and a zoom in to the master request and the reply:

When I have a permanent failure, however, the picture is very different

Zoom in:

This makes little sense to me. Why would it perform a data write, and who is writing 0x85FF... in my buffer?
Thanks

The format is perfectly fine for an actual multi-byte write transaction. It's like the Python library is calling write_i2c_block_data instead of read_i2c_block_data. It must be some bug at the Raspberry end of things, possibly in the py-smbus library.

i'll do some debugging tonight.

@Majenko Ok, from a brief check of the current code, the smbus module is a direct call to i2c_smbus_access, which then just performs an ioctl... so if there's a bug, this goes quite deep. As a curiosity, could the fact that I am using 3.3v vs 5v be a factor? I read conflicting opinions on pairing arduino and raspi without a level shifter in the middle.

The voltage difference wouldn't cause the Pi to perform a completely different transaction.

It might be complete nonsense, but dissabling interupts on the arduino, than triggering the raspi, and than enabling the interupts sets the arduino in a state where it can not react on (now possible) I2C/SMBus interrupts.The raspi is really fast compared to the arduino and there might be a race condition. I admit; I do not believe in this solution myself, but if there no other solution it's worth a try ;-). How do you power/pull up the I2C bus. The resistors might be to high. Your Logic analyzers are no oscis. It shows you the logic levels not the real Voltages.  Th. might also be a problem.

@PeterPaulKiefer I am using an arduino mega 2560 which has internal resistors for the i2c bus. I have an osci as well, so I can give it a check. I must suspend the interrupts as I want to be sure that the interrupt pin is not kept high for a very long time if the ardu is disrupted.

If you power the I2C bus with the arduino than you use 5V (or is it a 3.3V Arduino?). That might destroy your raspi, please be careful with that.
That's also an issue with the interupt PIN 5V is to high for the raspi it might tolerate that for a time, but it is a risk. You can use a voltage divider by two resistors.

The interrupt routines of the arduino should not run for a long time. And, as you react on the rising edge of the interrupt pin on the raspi , it is not a problem if the interrupt pin is high as long as you set it to LOW before the next interrupt. On the other hand, interrupts are necessary for IC2 to work. You could loose information if interrupts don't work, when the raspi started sending before enabling interrupts..

@PeterPaulKiefer Excellent points. I'm going to rework a few things tomorrow evening and see what happens. When it comes to power, currently the arduino is powered via USB, and the raspi via a power supply. So yes, technically they are on different voltages. However, the idea is that both will be powered through the same 5V power supply. Of course the logic levels will not change regardless of the supply. Is a voltage divider resistor enough, or should I use a logic level converter? what is their physical difference?

The 5V from power supply are regulated to the operatng voltage of the Raspi. That's not the same. It's 3.3V.  See Bruno Bronosky's answer.
https://raspberrypi.stackexchange.com/questions/3209/what-are-the-min-max-voltage-current-values-the-gpio-pins-can-handle.

If your signal flows from the higher Voltage to the lower, a Resistor devider might be sufficient. If the signal goes to both directions highV <--> lowV you need a level shifter. If the signal flows from the lower to the higher Voltage and the device with the higher voltage interprets the high Level of the device with the lower Voltage as a high also, you can connect the device directly together if you be sure, that the higher Voltage device never put power on the wire.

What Raspberry are you using? It could be a clock stretchinh problem. I have it too with an Arduino project. If the slave is not able to answer, it try to stretch the clock signal. The Raspberry has some problems with it and once the sync clock is lost both devices will not work anymore... Until you reset the i2c line.

@adriano I am using a pi zero

Not sure, but I think that it is also affected by the clock stretching bug. Once the Arduino stretches the clock, the raspy will loose the synchronisation with your arduino.

Use a logic level conversion IC.

picture source http://msx-elektronika.pl/en/logic-level-converter

I bought two, I'll give it a try this weekend

@StefanoBorini, results?

I added the logic level converter but I still get the same kind of errors. I am unsure at this point what is the reason. I decided that for the time being I just use a traditional keyboard microcontroller, but it's definitely something I have to revisit. I am adding a picture of my setup later tonight

@StefanoBorini, ok. I collected the half of the bounty and two upvotes, so if you now or in the future want to put a bounty on a question, write a comment here and I will put a 50 points bounty on that question (but only if I can't write a useful answer to it :-) )


text:
Interfacing optical mouse with arduino
I have a USB mouse which I am using to measure distance travelled by my bot for a project. I followed this blog to get the optical sensor from the mouse from the arduino and interface it with the arduino. In that blog, the USB wire has been removed and the 4 pins (VCC,GND and 2 data) are connected to the arduino
However,I found the code to not be very robust as the mouse doesn't always establish Serial communication with the arduino.
I have a USB host shield for the arduino. Is there any library which will let me get the x and y coordinates of the mouse using the USB protocol?
And if not, then is there a more stable library which will be more robust than the one used in thr blog linked above?

Serial communication with an USB mouse? Really? A mouse is normally a HID device. I know no mouse, that implements a serial interface. Please show us your code

Are you sure that mouse you are using in your project is PS2/2 compatible?

@chrisl yes..I followed https://www.instructables.com/id/Optical-Mouse-Odometer-for-Arduino-Robot/ this

Yes it is PS2/2 compatible

https://github.com/felis/USB_Host_Shield_2.0 is the library for the USB host shield.


text:
KY-040 rotary encoder skipping steps
Yesterday I asked a question about de-bouncing this rotary encoder and Jsotola suggested that I should use a method like This to detect the previous state and then do the counting. using that method each turn is counting twice in one turn so I came up with my version of de-bouncing the rotary encoder:
int s1, s2;
int count = 0;
boolean right = 0;
boolean left = 0;
int rotary = 0;
unsigned long timer = 0;
unsigned int bounce = 50;

void setup() {
  Serial.begin(9600);
  pinMode(6, INPUT);
  pinMode(7, INPUT);

}

void loop() {

  s1 = digitalRead(6);
  s2 = digitalRead(7);
  if (s1 == 1 && s2 == 1) {
    right = 0;
    left = 0;
    rotary = 0;
  }
  if (s1 == 0 && s2 == 1) {
    left = 1;
  }
  if (left == 1 && (s1 == 0 && s2 == 0)) {
    rotary = 2;
  }
  if (s1 == 1 && s2 == 0) {
    right = 1;
  }
  if (right == 1 && (s1 == 0 && s2 == 0)) {
    rotary = 1;
  }

  if (rotary == 1) {
    if ((millis() - timer) > bounce) {
      count++;
    }
    right = 0;
    left = 0;
    timer = millis();
  }
  if (rotary == 2) {
    if ((millis() - timer) > bounce) {
      count--;
    }
    right = 0;
    left = 0;
    timer = millis();
  }
  Serial.print(s1);
  Serial.print(s2);
  Serial.print(", ");
  Serial.print(count);
  Serial.println(" ");
  delay(15);
}

The code is working just fine. When turning the rotary this are the steps that I get:
10-00-01 < (11) > 10-00-01
problem is if I turn the knob quickly rotary encoder will skip one or two steps like: 01-01-01 < (11) or 10-00-00 < (11).
This problem exist in all methods/libraries (I tested them all), is there anyway to fix this with software/hardware or this rotary encoder is just junk and I should get a better one?

Another method of de-bouncing as Jsotola requested:
 int pinA = 3;  // Connected to CLK on KY-040
 int pinB = 4;  // Connected to DT on KY-040
 int encoderPosCount = 0;
 int pinALast;
 int aVal;
 boolean bCW;

 void setup() {
   pinMode (pinA,INPUT);
   pinMode (pinB,INPUT);
   /* Read Pin A
   Whatever state it's in will reflect the last position
   */
   pinALast = digitalRead(pinA);
   Serial.begin (9600);
 }

 void loop() {
   aVal = digitalRead(pinA);
   if (aVal != pinALast){ // Means the knob is rotating
     // if the knob is rotating, we need to determine direction
     // We do that by reading pin B.
     if (digitalRead(pinB) != aVal) {  // Means pin A Changed first - We're Rotating Clockwise
       encoderPosCount ++;
       bCW = true;
     } else {// Otherwise B changed first and we're moving CCW
       bCW = false;
       encoderPosCount--;
     }
     Serial.print ("Rotated: ");
     if (bCW){
       Serial.println ("clockwise");
     }else{
       Serial.println("counterclockwise");
     }
     Serial.print("Encoder Position: ");
     Serial.println(encoderPosCount);

   }
   pinALast = aVal;
 }

Did you delete your 1st question?  I can not find it.  1) It would be best if you kept a 4 state machine such that you could tell left from right based on the current code and the previous quad-code.  I don't think I see that in your code above. 2) When dealing with firmware sampling one can assume some samples will be missed.   So the software needs to compensate or you need better hardware.  Usually cheap hardware and good software wins out because of cost.  So, I would have the software make up left & right base on history for illegal code sequences.

@st2000 deleted first question because i couldn't explain what the problem actually was and the question was a mess. | How can i detect one step from another when like the example in the question it just skipping all 3 or 2 steps? i need at least the first step...

My guess is the that all those serial.prints are really slowing down your code, making it too slow to detect fast rotary movements. You could for example only print the count, then rotate right fast, and then rotate back slowly, till it reaches the starting position. Then check if count is back to 0.

@Gerben removed delay() and serial prints too, no difference what so ever...

you almost have it  ... the program detects the transition, but you are jumping to trying to determine the direction of rotation .... forget about the direction and focus on consistently detecting either the rising or the falling edge of the signal ... when you see a transition, wait 50 ms and check again ... if a transition is confirmed, then check the signal level .... if it is high, then a rising edge occured ... if it is low, then a falling edge occured .... at this point, do not worry about the direction ... simply increment the counter only on rising edge ... observe the results

@jsotola please if possible post an answer with example.

I applaud you for your tenacity with the "debouncing" idea, but there is an excellent library for this rotary encoder, and the author has also written an article about it: Ben Buxton - rotary encoders done properly. Here is a link to his library: GitHub - buxtronix.
I’ve used an older version of the library before with interrupts, and it worked perfectly for my application. I see the author has updated the library and has 2 example sketches; one uses interrupts, and the other uses polling. I tried both of them today on an Uno and I was very impressed with the polling sketch’s performance. It seemed to equal that of the interrupt method.
If you take the important bits out of the library files, then add them to a sketch, you can see how little code it takes for this "method" of processing the encoder’s output. Here is a test sketch with the library bits in it.

#define R_START 0x0
#define R_CW_FINAL 0x1
#define R_CW_BEGIN 0x2
#define R_CW_NEXT 0x3
#define R_CCW_BEGIN 0x4
#define R_CCW_FINAL 0x5
#define R_CCW_NEXT 0x6
#define DIR_NONE 0x0
#define DIR_CW 0x10
#define DIR_CCW 0x20

const byte pin1 = 5;  // DT
const byte pin2 = 6;  // CLK
int state = R_START;
int counter = 0;

const unsigned char ttable[7][4] = {
  // R_START
  {R_START,    R_CW_BEGIN,  R_CCW_BEGIN, R_START},
  // R_CW_FINAL
  {R_CW_NEXT,  R_START,     R_CW_FINAL,  R_START | DIR_CW},
  // R_CW_BEGIN
  {R_CW_NEXT,  R_CW_BEGIN,  R_START,     R_START},
  // R_CW_NEXT
  {R_CW_NEXT,  R_CW_BEGIN,  R_CW_FINAL,  R_START},
  // R_CCW_BEGIN
  {R_CCW_NEXT, R_START,     R_CCW_BEGIN, R_START},
  // R_CCW_FINAL
  {R_CCW_NEXT, R_CCW_FINAL, R_START,     R_START | DIR_CCW},
  // R_CCW_NEXT
  {R_CCW_NEXT, R_CCW_FINAL, R_CCW_BEGIN, R_START},
};

unsigned char process(){

  // Grab state of input pins.
  unsigned char pinstate = (digitalRead(pin2) << 1) | digitalRead(pin1);

  // Determine new state from the pins and state table.
  state = ttable[state & 0xf][pinstate];

  // Return emit bits, ie the generated event.
  return state & 0x30;
}

void setup(){
  pinMode(pin1, INPUT_PULLUP);
  pinMode(pin2, INPUT_PULLUP);
  Serial.begin(9600);
}

void loop(){
  unsigned char result = process();
  if(result == DIR_CW){
    counter++;
    Serial.println(counter);
  }
  else if(result == DIR_CCW){
    counter--;
    Serial.println(counter);
  }
}

Heres a simplified sketch (It works the same but I didn't like the hex numbers and I don't use define):
const byte pin1 = 5;  // Connected to DT on KY-040
const byte pin2 = 6;  // Connected to CLK on KY-040
int state = 0;
int counter = 0;

const unsigned char ttable[7][4] = {
  {0, 2, 4, 0},
  {3, 0, 1, 0 | 16},
  {3, 2, 0, 0},
  {3, 2, 1, 0},
  {6, 0, 4, 0},
  {6, 5, 0, 0 | 32},
  {6, 5, 4, 0},
};

void setup(){
  pinMode(pin1, INPUT_PULLUP);
  pinMode(pin2, INPUT_PULLUP);
  Serial.begin(9600);
}

void loop(){

  unsigned char result = process();

  // Clockwise rotation.
  if(result == 16){
    counter++;
    Serial.println(counter);
  }

  // Counter clockwise rotation.
  else if(result == 32){
    counter--;
    Serial.println(counter);
  }

}

unsigned char process(){

  // Grab state of input pins.
  unsigned char pinstate = (digitalRead(pin2) << 1) | digitalRead(pin1);

  // Determine new state from the pins and state table.
  state = ttable[state & 0xf][pinstate];

  // Return emit bits, ie the generated event.
  return state & 48;
}

DUDE! it's magic! why i couldn't find this library! Thank you.


text:
Connecting MPU6050 to Arduino Lilypad
To preface, I am very new to Arduino and I watched this video on YouTube.
It shows how you can build a motion controlled car with Arduino and I decided to make this for my school project.
One thing I am having difficulty with is connecting the MPU6050 to the Lilypad. In the video he doesn't really show much of it and just sticks it onto the board.
However, do I need to solder the MPU6050? Where do I solder the pins the underside or the top. Do I need to align the pins with that of the Lilypad?
Sorry if it's a stupid question I genuinely don't know.
The current condition of our lilypad:

What it's supposed to look like:

If you see the images, in addition to the yellow light of the MPU 6050 and the red light of the HC 05, the red light of the Lilypad is also supposed to light up like the second picture, however in ours, only the MPU 6050 and the HC 05 lights up and not the Lilypad.

In This tutorial explains how to connect MPU6050 to an Arduino.

Since you seem to need some orientation, I will explain a few things, to get you started.
The MPU6050 is a device, that communicates through the I2C interface. It uses 2 communication lines (SCL for the clock and SDA for the data). To use is with the Lilypad, you have to connect those two lines, Vcc (5V) and Ground. If you look at a pinout diagram, you can identify, which of the pads are SDA and SCL on the Lilypad.
It is up to you, if you connect the mentioned lines via soldering or by other means. Normally you would solder connecting wires between the MPU6050 and the Lilypad. If you want the MPU to be removable, you can solder a cable with a pin header (for example female) to the Lilypad and the according pins to the MPU (for example a male pin header). That way, you could also stick the MPU to the board and remove it again if necessary. How you are doing it is not important, as long as the electrical contact is good.

There are also a lot of tutorials and ready to use libraries for the MPU6050 on the net. newbie already posted a link to a tutorial. Also Adafruit has a library on github with examples, that explain how to use it. That way you should be able to get started with your project.
Good luck!

Thanks for the help but there is still a problem, can you please check the images that I uploaded above? The LED of the Lilypad is not lighting up even though the other two are and I'm very confused. I already connected the Lilypad and the MPU 6050 like you said with female jumpers and pin headers.

Edit: I briefly used a 9V battery, is that a problem? Also, I haven't uploaded the code into theLilypad

A 9V block battery is not a good choice, because it can only provide low current (it is only meant for low current applications). Better a series of AA batteries or a LiPo pack (though I don't have much experience with this)


text:
How to read voltage using ADS1115
I'm very new to this. I found this tutorial.
But it don't explain how to read voltages higher than Arduino 5V. I have connected a 100K ohm resistor to positive and 10K ohm to negative of my 24V power supply.
I need some guidance for writing the code for this specific ADC, please.

So you want to measure the voltage of your power supply?

Yes i want to measure voltages higher than 5V.

You cannot measure much more than 5V with that device neither. (VDD +0.3V)
You and that "tutorial") use an adafruit library and should get information from them.
If those 2 resistors (100k + 10k) build a voltage divider and negative is connected to GND, 24V is reduced to 24V/11 ~ 2.18V between the two resistors.

i know that Datafiddler but i don't know how can i convert and read that 2,18V to 24V!

It's called "math". For example: Arduino has 10 bit precision and usually 5V reference voltage. That means one step is  5V / 1024 = 0.004883V. And if you divide input voltage by 11, that means you have to multiply previous result by 11 too.

i did what you said: voltage = voltage * 11 but it's showing lower voltage than actual voltage.

If you try something and it doesn't work as expected, please write this information into the question (not the comments). You wrote, that you tried the calculation and got lower voltages. So write in your question: the code that you used for calculation with all relevant values, what voltages are outputted by it and what voltages you measured how externally.

As KIIV mentioned you need to do the math:
Use this online voltage divider calculator to calculate your maximum input.

Keep in mind you shouldn't exceed Arduino 5V.
Use a multimeter to measure the resistors actual resistance.
Do the math for your example assuming R1 is exactly 100K and R2 10K you have to multiple the voltage by 11.
remember any error is going to multiple by 11 too, so make sure the first reading is accurate/stable.

ADS1115 is actually 15bit which will give you resolution of 32768, with default PGA setting you get:
6.144 / 32768 = 0.0001875V per bit.
Voltage = (your ADC reading) * 0.0001875V;
Voltage = Voltage * 11;

Take a look at This question/answer to see how I did reduced Arduino ADC noise, some steps can be done for ADS1115 as well.


text:
Privacy of a program
I have created a algorithm and using arduino harware, and I don't want that users of my hardware could read or copy the Program so is there any security code or something that I could use. But I must access it whenever I needed to. It should be like admin and users.

A quick search gave me this question. Maybe that is fitting for you

Chances are that I could pretty easily copy your algorithm without ever seeing your code.  I'd just need to play with the product for a little while.  Keeping the code a secret isn't the way to make money in this business anymore.

The code that's sent to Arduino is "compiled" which means it's changed from human readable form to a binary data that can be understood by the processor. The "code" you wrote remains on your computer only.
This itself is a way of encryption since it's impossible to retrieve the original source code from that binary data. That data can only be "decompiled". This is a process that takes the binary data and converts it automatically into a human readable code, but it's not the same code that you originally made. It doesn't have comments, and logical variable names. This makes it also hard to understand.
Decompilation is usually to difficult and time consuming to even bother doing that unless your hardware is a lock on a vault with million dollars inside. If that's the case don't use Arduino, but instead use a custom designed chip with cryptographic key built inside the hardware.


text:
Using arduino as a remote control
I have old Sony amplifier (F117R) and CD player (CDP-590), both equipped with IR remote controls. The problem is that I bought them as vintage without remotes.
I have a rough idea how to build dedicated RC for both units but I'm missing the essential part - how is the signal encoded for the units?
I can find tutorials where the can be taught the codes from working remote control and how to build universal RC from that.
Is there any chance where to find IR codes for Hi-Fi units remote controls?

Just a little suggestion on an alternative approach:
https://www.ebay.ie/itm/Original-Sony-RM-S310-Remote-Control-for-TA-F410R-F411R-Audio-System-Tested/264447792621
https://www.ebay.ie/itm/Remote-Control-For-Sony-CDP-590-CDP-391-CDP-M201-CDP-M301-Compact-CD-Player/274003755223

https://irq5.io/2012/07/27/infrared-remote-control-protocols-part-1/

http://hifi-remote.com/wiki/index.php?title=Main_Page

http://picprojects.org.uk/projects/sirc/sonysirc.pdf

http://www.righto.com/2010/03/understanding-sony-ir-remote-codes-lirc.html

IR remote controls are not simple enough to be properly addressed in much less than a book. You will find this article VERY useful. There are hundreds of codes that use this format and it is likely you will find what you need. http://www.remotecentral.com/features/irdisp1.htm


text:
Reading data from multiple sensors from Arduino with ESP8266
I am trying to do a project where I need to get data from multiple sensors simultaneously. I am planning to use a Arduino to get the readings from the sensors. I am thinking to control the Arduino using ESP8266 as I would finally like to have internet capabilities for my project. I have worked with Arduino before but this is my first time with ESP8266 and I don't know much about. What I would like to know is if its feasible? I read that I need to use SoftwareSerial library to achieve this. Am I correct? I have tried to google for similar examples but most of the results direct to using a single pin on the Arduino controlled by ESP8266 and the Blynk app. Apart from that I could not find much information. I would be very much grateful if you could point out some similar projects or examples. Thanks a lot for your time in advance.

You want to use the esp8266 as the main MCU or only as network adapter? I recommend the second option with Mega. Mega has 4 Serials so don't use SoftwareSerial. I you put AT firmware 1.7 in the esp8266, you can use my WiFiEspAT library

Hi Juraj. I intend to use Mega as the main MCU and esp8266 as the network adapter. I will look into the WiFiEspAT library as you suggested. Thanks for the advice.

What are those sensors? Why don't you just use the esp without the arduino?

i always do it backwards, if for no other reason than OTA is faster for dev cycles and the ESP is WAY faster/stronger than the mega, making it the better "brain"

Sim, I need to use multiple load cells and a solenoid lock. So I am planning to use mega as it gives me more I/O pins.


text:
Obtain retained MQTT message
I’m using ESP8266 with Arduino code. Each device posts a ‘state’ and an ‘avail’ messages for a specific topic.
I wish to be able to read those retained messages and not only right after connecting and subscribe to MQTT broker.
EDIT 1  - Clarifications

I'm using Raspberry Pi Zero W as a MQTT Broker ( Local ).
When device boots, it changes its state from offline to online, but a different process checks periodically if state is offline or online for current device and others on the network.
it is not same as when subscribing to a retained topic, that you get the state at that specific time.
Storing chage of state in a variable, is one way to do it, but is there a different way ?

Sorry, question edited.

@jsotola - I'm subscribed for specific topic, but how I actively ( on demand -  inside an if statement ), verify that my retained state is online or offline ?

@Guy.D, when you say: "it is not same as when subscribing to a retained topic, that you get the state at that specific time." what do you mean?  If the publisher and the broker were on line all the time and the subscriber just came on line, the retained Node-RED message (topic and payload) would be  the last message sent from the publisher.

Once a message has passed through an MQTT broker there is not a way to retrieve it from the broker.
Consider instead deciding upon the action at the time the message is received by the subscriber.  If this decision needs to be made at a later time consider storing the state in the of the payload of the message on the subscriber.
Also consider running Node-RED.  If the platform running the MQTT broker can support Node-RED (such as a Raspberry Pi), it turns out to be convenient to run both on the same computer.  Node-RED contains nodes (graphical programming blocks) which can subscribe to and publish to MQTT topics.  By connecting other nodes to these, the topic and payload can be manipulated.  Of interest is an option within the Output MQTT node.  Here you can select Retain True.  This page explains how this option works:

Once you have sent a retained message to a topic, all subscribers will
  receive that message when they subscribe.
To clear a previously retained topic from the broker, send a blank
  message to that topic with the retain flag set.

This is the only way I had in mind ( storing state change in a specific variable ), but I was hoping there is a better way.

Please edit your question: 1) Add your comment in which you make it clear why you want to retrieve old MQTT topics.  2) Tell us what you are running your MQTT broker on.  3) What you will do with the on-line / off-line information.  As there are additional tools that work well with MQTT that may apply to your situation.

thank you. edited

@Guy.D, I need to go off line for a while.  If you do edit your question to make it better - I am going to assume you are using a normal personal computer for the MQTT broker.  That platform likely will support Node-RED a graphical programming language designed to process MQTT topics which uses a web page interface.  It will take some time to get used to - so we need to make a decision, based on your edited question, if it is worth the effort to install and learn.

thank you, did you see Q was edited with information asked?

Yes, it will be an effort, but I think installing and learning Node-RED will solve your problems.  And perhaps you can process your MQTT message payloads partly on Node-RED simplifying the code on your MQTT Arduino clients.

By the way- updating status to offline ( generated by lastwill) won’t update the specified variable


text:
Running many devices on 5V pin. How to provide external power
I'm using my Arduino DUE 5V pin to power a lot of sensors and I'm worried about the drop in current.
I'm powering the board using the USB port. Is this the correct way or is there a different way of powering the board to make sure the current drop is limited as much as possible?
Thanks in advance.

There is a maximum current you can use from the 5V pin(s), so it is good to split the current going into the Arduino.
You can use a breakout board for a USB, connect the USB to the breakout board, connect it both to the Arduino, and in parallel to the sensors; meaning the current used for the sensors is not going through the Arduino. You might need 2 break out boards, one for the input USB, one for the output USB.
Note there is a maximum current for USB too.


text:
Using a scrolling text in OLED Adafruit_SSD1305
I have been in internet for the past week looking for a way of programming a scrolling text (either left or right) using Adafruit_SSD1305 but I only find scrolling commands for Adafruit_SSD1306. Has anyone tried this before? I really need help on this

Please share links of what you found for the SSD1306. Maybe it can be reused for the SSD1305

The SSD1305 hardware apparently does include scrolling support (SDD1305 datasheet - see section 10) but apparently the Adafruit driver didn't implement it. But The SSD1306 looks so similar to the SSD1305, that if the SSD1306 software driver won't work with it "out of the box" (worth a try!), you could probably compare the two software drivers and back-implement that feature into the the 1305 driver yourself.


text:
Serial Commmunication between two arduino
I want to send the voltage magnitude received on an analog pin of atmega328Pu to another arduino uno using Serial communication pins TX and RX and display the value on the receiver arduino's Serial monitor.
Transmitter Arduino Code:
void setup()
{

  Serial.begin(9600);

  pinMode(A0, INPUT);

}

void loop()

{

  int voltage=analogRead(A0);

  Serial.println(voltage);

}

Receiver Arduino Code:
void setup()

{

  Serial.begin(9600);

}
int incomingByte = 0;

void loop()
{
if (Serial.available() > 0) {
    incomingByte = Serial.read();
    Serial.print("I received: ");
    Serial.println(incomingByte, DEC);
}

}

Problem: Now the Problem I am facing is that Serial Monitor of Receiver arduino does not shows anything, it remains blank. Please analyse this system help me in finding out the best way to get around this problem?

You need to connect GND (0V) between the to. Electricity flows in circles.

Connect the grounds of the two Arduinos together. Their serial transmitters and receivers need the same voltage reference.
pinMode(A0, INPUT); is not needed. pinMode() only affects the digital part of the pin driver. (But it probably isn't doing any harm, either).
The transmitter Arduino will be sending 1, 2, 3, or 4 ASCII bytes - the digits 0-9, representing the D/A result, 0 - 1023. In decimal, those digits will look like 48, 49, ..., 57 (for a '0', '1', ... '9', respectively). So the receiving Arduino will be handling characters, not numbers. It needs to collect all of the characters, then repeat them onto it's terminal output.

Thanks for the Help. It works Now

The problem is that a serial connection usually connects two devices, in your case it's three (sensor arduino, receiving arduino and your pc).
To get around this you have to use an additional software serial on different pins on the receiving arduino (unfortunately the atmega328 has only one hardware serial interface).
As long as you don't have to send anything from pc to the receiving arduino and from the receiving arduino to the sensing one you could try to simply disconnect the wire receiving-TX to sensing-RX and see if it works. In this latter case you could actually get rid of the receiving arduino at all.
Edit: another important point was mentioned in JRobert's answer: grounds of devices communicating with each other must always be connected!

Thank you very much for the help.

If your problem is solved please accept an answer so the question is closed


text:
Arduino Nano 33 IOT - Bluetooth Classic (Serial)
I've an arduino nano 33 iot and I'm working with the first time with bluetooth.
So far BLE is working fine, I can use an app on my smartphone to check the services and characteristics.
Is it possible to send data over serial via Bluetooth on this board ?

This board has multiple processors on it.  The main processor (SAMD) rus your arduino code.  There is also an ESP32 based processor which runs the WIFI and the Bluetooth.  There is a pretty featured library for controlling the WIFI called WIFININA.  This library does NOT have any bluetooth functions though.  Therefore, until someone writes a library which lets you control the bluetooth functions of that ESP32 chip, I don't think you'll be able to send arbitrary serial data via bluetooth.  It is "possible" to do this but not without a lot of technical wizardry.
Here are some links to examples of what the code might look like if you were writing code directly to the ESP32 chip here https://github.com/espressif/arduino-esp32/blob/master/libraries/BluetoothSerial/examples/SerialToSerialBT/SerialToSerialBT.ino

Thanks for the reply!
So for the moment I'll continue with BLE as I've not the skills or time to write such a library!
Or use another bluetooth board/extension board.

Just FYI, BLE stands for Bluetooth Low Energy so it is itself also Bluetooth.

Yes I know. But you there is a difference in communication between Bluetooth "classic" and low energy is it correct ?
Like Serial over low energy is not possible ?


text:
Test for wrong Wifi password?
Maybe this is a dumb question, but is there a way to test for wrong Wifi password?
I know you can do WL_CONNECT to check if the password works, but is there a command for checking if the password is wrong? Not just by waiting.

my esp is trying to connect to the WiFi

i guess that makes my esp client

https://github.com/esp8266/Arduino/blob/40f456aca3a568a09a5bec275b36a79869ce8bef/libraries/ESP8266WiFi/src/ESP8266WiFiSTA.cpp#L633

there's no way to tell if a password is right or wrong other than by trying to use it.

@dandavis but the WiFi class does not return the info even though it's available. It simply returns an error.

@Juraj I think this comment is worth to be posted as an answer as it might be really useful for others in the future.

The information is available on SDK level. If you include #include "user_interface.h", you can use function wifi_station_get_connect_status(). It returns one of:
STATION_GOT_IP
STATION_NO_AP_FOUND
STATION_CONNECT_FAIL
STATION_WRONG_PASSWORD
STATION_IDLE

The WiFi.status() function uses function wifi_station_get_connect_status(),  but returns WL_CONNECT_FAILED for STATION_WRONG_PASSWORD.

one can check for wrong password using the following code snippet
  if (WiFi.status() == WL_CONNECTED)
  {
    Serial.println("Connected successfully");
  }
  else if (WiFi.status() == WL_NO_SSID_AVAIL)
  {
    Serial.println("Wifi network is not avaliable");
  }
  else
  {
    Serial.println("Password is not correct");
  }

more information can be found on GitHub here:
https://github.com/aeonSolutions/aeonlabs-ESP32-C-Base-Firmware-Libraries


text:
Arduino Due 16U2 Programming Port Documentation
Are there any documentation or whatsoever on what the 16U2 does when trying to program the Sam3X in Arduino Due?
I reallynwant to know what's wrong with my made up board but can't get pass the No Device Found problem.
Been searching it but I can't find any. I can't understand the hex file burned on the MCU.

did you upload the firmware to the ATmega 16u2? the firmware is in arduino/hardware/sam/1.6.11/firmwares/atmega16u2

https://www.arduino.cc/en/Hacking/Upgrading16U2Due

Yes, I'd already uploaded that firmware to the 16U2.

The 16u2 is merely acting as a usb to UART adapter. You can just as well use an ft232 or other serial adapter.
Of course the 16u2 needs firmware installing on it in order to function. That firmware is available (possibly bundled with the ide, or for download, not sure at the moment).

But I believe it is also responsible in asserting the reseta and erase pins that is needed for the SAMBA bootloader in the Sam3x and something about the CDC.

And you should have copied that from the due schematic, yes? And the firmware you install in the 16u2 does all that it needs to.

Yes. I've got everything (connections, voltage levels) of the pins in my board and due the same during power up but I'm still getting the No device found error. So I'm think that something I'd miss and I want to see it by looking at the code and what to expect on the pins using a scope.

If you're going to that sort of level then you really need a physical Due to compare it with.


text:
Is the johnny-five library and javascipt good for Arduino projects?
I am new to Arduino. I just have my Arduino UNO kit and started to do some small projects with node.js and the Johnny-five library.
My question is why there not many content about javascript+Arduino in web, and the last news on Johnny-five website dated last year.

Is js development still relevant for Arduino?

johnny-five makes the arduino nothing more than a peripheral for a computer ... the arduino contains a very basic code that allows the computer to send commands to the arduino .... most people want to use the arduino as a standalone system

Because Johnny-five covers about 1% of the possible use cases for an Arduino and hardly anyone uses it because of that?

js is great to use for web interfaces with the ESP chips, but it's not very good to actually program the low-power, low-ram device itself. As MCUs get more powerful, and further blur the lines between them and SBCs you will see JS as a more viable option. I would say the big obstacle now is attitude; embedded programmers don't take JS seriously. Heck, they don't even take arduino very seriously. Looking at the site, it seems that j5 only runs on expensive corporate boards that nobody wants, and ardnuio ones that are too weak and don't have wifi, and nobody wants a usb tether.


text:
Pin Mappings from Arduino Metro M4 Express Board to SAMD51
After looking through the internet, I coudln't find any document (not in the datasheet, no nice graphics on google image searches) that showed the mapping between the Arduino breakout board and the SAMD51. Does such a mapping exist?
I'm answering my own question below, but perhaps someone knows of a better table.

Edit: Since writing my answer, I found this Google Sheet that does a much better job.
Arduino has some schematics on their website. Here's an image I used to build the following list below.
There are in this format: Arduino Pin | SAMD51 Pin | SAMD51 Description
Analog
A0  3   PA02/EINT2/AIN0/VOUT0
A1  14  PA05/I5/AIN5/VOUT1/SERCOM0.1
A2  15  PA06/I6/VREFC/AIN6/SERCOM0.2
A3  13  PA04/I4/VREFB/AIN4/SERCOM0.0
A4  11  PB08/I8/AIN2/SERCOM4.0
A5  12  PB09/I9/AIN3/SERCOM4.1

Digital
D0  44  PA23/I2C/I7/SERCOM3.1 +5/SOF/I2SFS1
D1  43  PA22/I2C/116/SERCOM3.0+5.1/I2SDI
D2  40  PB17/SERCOM5.1/I2SMCK0
D3  39  PB16/I0/SERCOM5.0/I2SCK0
D4  26  PB13/I13/SERCOM4.1/I2SMCK1
D5  27  PB14/I14/SERCOM4.2/PCC8
D6  28  PB15/I15/SERCOM4.3/PCC9
D7  25  PB12/I12/SERCOM4.0/I2SCK1
D8  42  PA21/I5/SERCOM3+5.3/I2SDO
D9  41  PA20/I4/SERCOM3+5.2/I2SFS0
D10 37  PA18/I2/SERCOM1+3.2
D11 38  PA19/I3/SERCOM1+3.3
D12 36  PA17/I2C/I1/SERCOM1.1+3.0
D13 35  PA16/I2C/I0/SERCOM1.0+3.1
GND
AREF    4   PA03/I3/VREFA/AIN1
SDA 63  PB02/I2/AIN14/SERCOM5.0
SCL 64  PB03/I3/AIN15/SERCOM5.1

SPI
MOSI    29  PA12/I12/I2C/SERCOM2.0+4.1
SCK 30  PA13/I13/I2C/SERCOM2.1+4.0
MISO    31  PA14/I14/SERCOM2+4.2


text:
Can someone help me solve a loop question and a couple others for my program?
I am currently working on the elegoo uno r3 smart car kit that uses arduino. I have written some code and it works for the most part but I could use some help. I am trying to figure out what i need to do to get my square program to loop and continue to until the stop button is pressed. Can anyone help me out please? Also, I have 2 programs in it. One is for obstacle avoidance which is controlled by button 2 and the square program which is controlled by button 3. The stop button will be used to stop either program. I will put the code below.
#include <Servo.h>

//#include <ArduinoJson.h>

//     Left motor truth table
//Here are some handy tables to show the various modes of operation.
//  ENB         IN1               IN2         Description
//  LOW   Not Applicable    Not Applicable    Motor is off
//  HIGH        LOW               LOW         Motor is stopped (brakes)
//  HIGH        HIGH              LOW         Motor is on and turning forwards
//  HIGH        LOW               HIGH        Motor is on and turning backwards
//  HIGH        HIGH              HIGH        Motor is stopped (brakes)
#include <IRremote.h>

//#include <Servo.h>
Servo myservo;      // create servo object to control servo
//Servo servo;             //  Create a DC motor drive object
//#include <stdio.h>

//#include "HardwareSerial.h"

int Echo = A4;
int Trig = A5;

//ir remote button values/ data sheet===========================
#define f 16736925    // FORWARD
#define b 16754775    // BACK
#define l 16720605    // LEFT
#define r 16761405    // RIGHT
#define s 16712445    // STOP
#define KEY2 16750695 //obstacle avoidance mode
#define KEY3 16756815 //square mode

#define KEY_STAR 16728765
#define KEY_HASH 16732845

// define IO pin
#define ENB 5
#define IN1 7
#define IN2 8
#define IN3 9
#define IN4 11
#define ENA 6
#define RECV_PIN 12
#define ECHO_PIN A4
#define TRIG_PIN A5
#define LED_Pin 13
#define carSpeed 250
int rightDistance = 0, leftDistance = 0, middleDistance = 0;

IRrecv irrecv(RECV_PIN);

decode_results results;

void forward(){

  analogWrite(ENA, carSpeed);
  analogWrite(ENB, carSpeed);
  digitalWrite(IN1, HIGH);
  digitalWrite(IN2, LOW);
  digitalWrite(IN3, LOW);
  digitalWrite(IN4, HIGH);
  Serial.println("Forward");
}

void stop_r() {
  digitalWrite(ENA, LOW);
  digitalWrite(ENB, LOW);
   /* digitalWrite(IN1, LOW);
  digitalWrite(IN2, LOW);
  digitalWrite(IN3, LOW);
  digitalWrite(IN4, LOW);*/
  Serial.println("Stop!");
}

void back() {
  analogWrite(ENA, carSpeed);
  analogWrite(ENB, carSpeed);
  digitalWrite(IN1, LOW);
  digitalWrite(IN2, HIGH);
  digitalWrite(IN3, HIGH);
  digitalWrite(IN4, LOW);
  Serial.println("Back");
}

void left() {
  analogWrite(ENA, carSpeed);
  analogWrite(ENB, carSpeed);
  digitalWrite(IN1, LOW);
  digitalWrite(IN2, HIGH);
  digitalWrite(IN3, LOW);
  digitalWrite(IN4, HIGH);
  Serial.println("Left");
}

void right() {
  analogWrite(ENA, carSpeed);
  analogWrite(ENB, carSpeed);
  digitalWrite(IN1, HIGH);
  digitalWrite(IN2, LOW);
  Serial.println("Right");
}

void stop_() {
  digitalWrite(ENA, LOW);
  digitalWrite(ENB, LOW);
   /* digitalWrite(IN1, LOW);
  digitalWrite(IN2, LOW);
  digitalWrite(IN3, LOW);
  digitalWrite(IN4, LOW);*/
  Serial.println("Stop!");
}

//Ultrasonic distance measurement Sub function
int getDistance() {
    digitalWrite(Trig, LOW);
    delayMicroseconds(2);
    digitalWrite(Trig, HIGH);
    delayMicroseconds(10);
    digitalWrite(Trig, LOW);
    return (int)pulseIn(Echo, HIGH) / 58;
}

//--------------------ZIG ZAG----------------------------------------------------

//init the car
void setup() {

  //pinMode(IN1, OUTPUT);     //set IO pin mode OUTPUT
  //pinMode(IN2, OUTPUT);
 // pinMode(ENB, OUTPUT);
 // digitalWrite(ENB, HIGH);  //Enable left motor

  myservo.attach(3);  // attach servo on pin 3 to servo object
  Serial.begin(9600);
  pinMode(Echo, INPUT);
  pinMode(Trig, OUTPUT);

  pinMode(IN1, OUTPUT);     //set IO pin mode OUTPUT
  pinMode(IN2, OUTPUT);
  pinMode(ENB, OUTPUT);
  digitalWrite(ENB, HIGH);  //Enable left motor

  pinMode(ENB, OUTPUT);
  pinMode(IN1, OUTPUT);
  pinMode(IN2, OUTPUT);
  pinMode(IN3, OUTPUT);
  pinMode(IN4, OUTPUT);
  pinMode(ENA, OUTPUT);
  digitalWrite(ENA, HIGH);//forward
  digitalWrite(ENB, HIGH);

  pinMode(IN3, OUTPUT);     //set IO pin mode OUTPUT
  pinMode(IN4, OUTPUT);
  pinMode(ENA, OUTPUT);
  digitalWrite(ENA, HIGH);  //Enable right motor

  //attachInterrupt(0,CHECK_IR,CHANGE);

  irrecv.enableIRIn(); // Start the receiver

  stop_r();

  //pinMode(IN3, OUTPUT);     //set IO pin mode OUTPUT
  //pinMode(IN4, OUTPUT);
  //pinMode(ENA, OUTPUT);
  //digitalWrite(ENA, HIGH);  //Enable right motor
}

//main loop============================================================================================================================
void loop() {

  if(irrecv.decode(&results)){
    Serial.println(results.value);
    irrecv.resume();
  }
  delay(100);

  //square();

 if (results.value == KEY2){
     digitalWrite(ENA, HIGH);
     digitalWrite(ENB, HIGH);
    obstacleavoidance();
    //irrecv.resume();
  } else if (results.value == s){
    stop_r();
    results.value = 12;
    //irrecv.resume();
  }

  if(results.value == KEY3){
    digitalWrite(ENA, HIGH);
     digitalWrite(ENB, HIGH);
    square();
    //irrecv.resume();
  }else if (results.value == s){
    stop_r();
    results.value = 12;
    //irrecv.resume();
  }

 /* if(results.value == KEY3){
    square();
  } else if (results.value == s){
    stop_r();
  }*/

 /*if (key_pressed == KEY2){
    obstacleavoidance();
  }
  while (key_pressed == s){
    stop_r();
  }*/

}

void get_keys(){

}

void CHECK_IR(){
  if(irrecv.decode(&results)){
    Serial.println(results.value);
    //key_pressed = results.value;
    irrecv.resume();
  }
  delay(100);
}

void square (){
  Serial.println("square");
  digitalWrite(IN1, HIGH);
  digitalWrite(IN2, LOW);
  digitalWrite(IN3, LOW);
  digitalWrite(IN4, HIGH);   //go forward
  delay(1000);

  digitalWrite(IN1, LOW);
  digitalWrite(IN2, LOW);
  digitalWrite(IN3, LOW);
  digitalWrite(IN4, LOW);   //stop
  delay(1000);

  digitalWrite(IN1, HIGH);
  digitalWrite(IN2, LOW);
  delay(660);              //right wheel turning forward

  digitalWrite(IN1, LOW);
  digitalWrite(IN2, LOW);
  digitalWrite(IN3, LOW);
  digitalWrite(IN4, LOW);   //stop
  delay(1000);
}

void obstacleavoidance(){

  myservo.write(90);  //setservo position according to scaled value
    delay(500);
    middleDistance = getDistance();
    //delay(100);
    if(middleDistance <= 20) {
      stop_r();
      delay(500);
      myservo.write(10);
      delay(1000);
      rightDistance = getDistance();

      delay(500);
      myservo.write(90);
      delay(1000);
      myservo.write(180);
      delay(1000);
      leftDistance = getDistance();

      delay(500);
      myservo.write(90);
      delay(1000);
      if(rightDistance > leftDistance) {
        right();
        delay(360);
      }
      else if(rightDistance < leftDistance) {
        left();
        delay(360);
      }
      else if((rightDistance <= 20) || (leftDistance <= 20)) {
        back();
        delay(180);
      }
      else {
        forward();
      }
    }
    else {
        forward();
    }
}

you need to clean up your code before you do anything else ... there is no reason for repeated commands in setup() .... you define functions for left(), right(), forward(), etc. but you do not use the functions in square()

Your problem is, that you use blocking code for square() and obstacleavoidance(). Nothing else can happen during a delay() call, not even checking for a button (unless you use interrupts). You should rewrite your code without any delay() calls, so that the Arduino can do this, like changing outputs, when the time has come, and check the buttons inbetween. To do that look at the BlinkWithoutDelay example, that comes with the Arduino IDE. It explains how to use millis() as a time source.

Also you should look into Finite State Machines (FSM). That's a rather simple programming technique, that will help you odering the your code and giving it a good structure to work with. For both mentioned coding styles there are tutorials on the web.

@sempaiscuba Could you possibly help me rewrite the code in the way you are explaining? I am completely new to Arduino programming.

Start with learning how to use millis(). There are tons od tutorials for that on the web. After you understood that, you can search for FSM implementation. There should be enough material, that can be googled. I remember, that I already wrote answers about FSMs on this site.

Hannah, people that write software are inherently lazy, so because your code does the same thing over and over its quite alien to most people on here :)  As a rule of thumb if you copy and paste it more than once it should be a function.
You have functions at the top of the code to move the car, but you don't seem to use them.  Using them will make the code shorter, but also much more readable.
In your setup() function you are repeatedly setting the pinMode of pins.  Group all your pinMode() call and then use the pins.  Again this will make the code easier to read and less likely to break when you change it.
So back to your question, how to you make the bot run around in squares until you press a button?  Well it will be something like this:
void square ()
{
  while (condition)
  {
    for (int side = 0; side < 4 && condition; ++side)
    {
      forward ();
      delay (1000);
      stop ();
      right ();
      delay (660);
      stop();
    }
  }
}

You need to work out a way to tie make condition be updated by your stop button, I don't want to do everything for you.
Hope that helps, if not shout out.

As chrisl points out in their answer, if you use delay then you won't be able to detect button presses (or anything else) while the delay is running. The OPs code really need to be refactored using millis().


text:
Using Library LoRa.h with Wemos D1 R2 for Lora Shield
I have been using Lora Shield for communication between server and multiple sensor with arduino . But recently i must save data received to Cloud . So i choose Wemos D1 R2 that have similar board with arduino . But when i upload example code , LoraReceiver can'nt get data . Can Anyone Solve my problem ?

we have no idea what equipment you are using, how it is connected, what program you are running and what errors you get ... do you think that we can answer your question?

When you change boards you must also update your pin connections in software.  When you initialize the Lora Shield, you probably specify a few data pins.  Those pin numbers cannot be assumed to remain the same on the new ESP8266 based board.  Furthermore, the ESP8266 board is 3.3v logic while Arduinos are 5v logic so you must ensure that the shield and sensors will also work with 3.3v.


text:
Circuit with a tip120 works with a Led but, don't with a vibrator motor
I have 2 Arduino Nano's. One with RF transmitter and the other with an RF receiver of 433 MHz and both have two 3v vibration motors. I want one Arduino to send a string to the other Arduino to let him know which vibrator he needs to vibrate. The connection works, when the Arduino with the transmitter sends a message, the other Arduino gets the message and sets pin 2 (the pin for the vibrator via a tip120) HIGH. But the vibrator does not vibrate. When I change the vibrator with a led it works, the led goes on and off. So why does the led work but the vibrator motor not?
I use the VirtualWire library for the RF modules.
Here is the code and I also provided a summary:
Summary: This is the receiver Arduino code. message_received is the string variable where the message is stored and in the loop, that message is to check what it contains. And then the led goes off and on.
#include <VirtualWire.h>

byte message[VW_MAX_MESSAGE_LEN]; // a buffer to store the incoming messages
byte messageLength = 255; // the size of the message

String message_received;

String message_go_on = "GO_ON";
String message_go_off = "GO_OF";

void setup() {
  Serial.begin(9600);
  vw_setup(2000); // Bits per sec
  vw_rx_start(); // Start the receiver
  Serial.println("RECEIVER MONITOR");
}

void loop() {
  // put your main code here, to run repeatedly:
  if (vw_get_message(message, &messageLength)){ // Non-blocking
    Serial.print("Incoming message: ");
    for (int i = 0; i < messageLength; i++){
      Serial.write(message[i]);
      message_received += (char)message[i];
    }
    Serial.println();
  }
  if(message_received == message_go_on){
    digitalWrite(2, HIGH);
  }
  if(message_received == message_go_off){
    digitalWrite(2, LOW);
  }
  message_received = "";
}

Summary: This is the code of the transmitter. I have 2 messages that I want to send every 200 milliseconds. The send method is for the transmitter and it needs a char array so I change the string to a char[] with a toCharArray() method.
#include <VirtualWire.h>

String message_go_on = "GO_ON";
String message_go_off = "GO_OF";

char buf1[VW_MAX_MESSAGE_LEN];
char buf2[VW_MAX_MESSAGE_LEN];

void setup() {
  Serial.begin(9600);
  vw_setup(2000); // Bits per sec

  message_go_on.toCharArray(buf1,VW_MAX_MESSAGE_LEN);
  message_go_off.toCharArray(buf2,VW_MAX_MESSAGE_LEN);
  Serial.println("TRNASMITTER MONITOR");
}

void loop() {
  send(buf1);
  delay(200);
  send(buf2);
  delay(200);
}

void send (char *message)
{
  vw_send((uint8_t *)message, strlen(message));
  vw_wait_tx(); // Wait until the whole message is gone
}

The circuit of the receiver Arduino:

I think the vibrator might be undersupplied but why would the led work?
Thanks for the help!

where is the vibrator? off screen at the bottom of the picture?

why did you post all that code? ... you said that it works with an LED, so a simple LED blink code should be used to troubleshoot the motor problem

The TIP120 is possibly the worst transistor you could choose for this job. It is a Darlington Pair transistor, and those have a (relatively) massive forward drop of between 2 and 4 volts. It works with the LED because an LED needs a tiny amount of current to operate compared to the motor and has a fixed forward voltage of its own. The motor doesn't, and is being starved of power by that huge voltage drop (it's getting maybe half the voltage it should be getting).
Throw away that TIP120 and replace it with a decent N-channel MOSFET - one with a "threshold voltage" (VGS) of 2.5V or less ideally.

Also note that to drive an inductive load like a motor you'll need a flyback diode to protect the transistor from back EMF.

@DuncanC Like the one you can see on the breaboard image?

I'm not going to try to trace out a picture of a breadboard. Now that you mention it I do see a diode in the breadboard, but it's worth calling out anyway because others who are not aware of the requirement read this tread