text:
MPU6050 Calibrating Accelerometer
I recently got an MPU6050 and I noticed the accelerometer data was a bit off, especially on the Z axis.
I'm running it on a Teensy 4.0 with Adafruit's MPU6050 library and basic example code: https://github.com/adafruit/Adafruit_MPU6050/blob/master/examples/basic_readings/basic_readings.ino
While stable on a flat surface (+Z up), it's reading ~8.5 m/s^2 and when flipped over (-Z up), ~11.6 m/s^2:
+Z:
Acceleration X: -0.06, Y: 0.00, Z: 8.44 m/s^2
-Z:
Acceleration X: -0.01, Y: -0.07, Z: -11.57 m/s^2

Aligning the other axes vertically gives me:
+X:
Acceleration X: 10.16, Y: -0.16, Z: -0.03 m/s^2
-X:
Acceleration X: -9.27, Y: -0.10, Z: -0.18 m/s^2
+Y:
Acceleration X: 0.07, Y: 9.55, Z: -0.10 m/s^2
-Y:
Acceleration X: 0.04, Y: -9.93, Z: -0.05 m/s^2

The X and Y readings could be adjusted fairly close to 9.81 m/s^2 with just an offset, but it seems like the Z axis would also require some scaling.
My question, is there a standard method of calibrating it in code?

I had this exact issue, where when I flipped the sensor to different orientations I would measure gravity as being anywhere between 7 m/s^2 to 10.5 m/s^2. I came to the same solution that st2000 is describing. I'm a little late to this conversation but I figured I can still share my solution to help anyone else who's experiencing the same issue.
First, I flipped the sensor on all 6 sides to record the approximate maximum and minimum acceleration I got for each axis due to gravity (each axis should read somewhere around 16,000 to 17,000 assuming the sensitivity is set to 2G).
My readings at this point were:
    Minimum | Maximum
X | -15,700 | 17,000
Y | -16,650 | 16,250
Z | -16,600 | 16,800

Then I derived a linear correction formula that would take the raw readings from the accelerometer and output the acceleration in m/s^2. I first calculated the "center offset" of each axis by just averaging the minimum and maximum readings for each axis.
          axis_min + axis_max
Center = ---------------------
                   2

Then I scaled the output according to its range so that when the axis reading was at the maximum, the output would be 9.8, and when the raw reading was around the minimum it would output -9.8.
 G = 9.80665 (Acceleration due to gravity)
 Range = axis_max - axis_min

               G
          -----------     2 * G            2 * G
 Scale =     Range     = ------- = ---------------------
            -------       Range     axis_max - axis_min
               2

Now putting it all together we get the following linear equation to calculate the acceleration on each axis:
                                       2 * G                 z_min + z_max
 A(x) = Scale * (x - Center) = --------------------- * (x - ---------------)
                                axis_max - axis_min                2

The function in actual code looks like this:
float axis_correction(float raw_reading, float axis_min, float axis_max, float grav_accel) {
    return (float)(2.f * grav_accel * (raw_reading - (axis_min + axis_max) / 2.f)) / (axis_max - axis_min);
}

Now, with this I get a consistent 9.75 to 9.88 m/s^2, I'm guessing with more tuning I can get this variation down further but this is already much better than the readings I was getting using any of the libraries out there. For reference, here's the plot for the accelerometer readings I got.

The plot shows us the processed readings. The red line is the total magnitude of the acceleration the sensor is experiencing. The purple line plots the nominal acceleration due to gravity. The other three lines are the individual accelerations on each axis. As we can see, the magnitude of acceleration is sticking very close the nominal acceleration due to gravity of 9.8 (except for the spikes and fluctuations from me flipping the sensor).
The ability to reliably measure gravity from various orientations was very important in my specific application and this calibration technique should work very well for me and hopefully others having the same issue!

Yes an accelerometer can be calibrated.  An offset for each of the 3 accelerometers can be found such that the absolute value of the maximum and minimum values of any given accelerometer axis are equal.  The maximum and minimum values can be found by rotating the accelerometer such that each axes is pointed directly toward and directly away from the earth.  Once each axes is normalized each axes needs a magnitude adjustment value such that the maximum value of all axes equal one another.  It may be convenient the product of the maximum of any given axes and that axes' magnitude adjustment value is 9.8 (meters per second * second).

Would you have an article or link you can share so we can have a look. I understand what you're saying but have no idea how to actually do it.

It's a little difficult to find an appropriate article.  This NIST article goes way overboard assuming the 3 accelerometers may not even be orthogonal.  And other articles skip over accelerometer calibration (to be honest, accelerometers are usually good out of the box for most Arduino applications).  Try this Adafruit article it sounds like what you are after.

Thank you for your comment

Yes. Jeff Rowberg's library performs the calibration for you when you power on. You'll need to make sure the module is lying level and still and then send a character over serial to trigger the calibration. A version based on Jeff's library, called Electronic Cats, can be downloaded directly using the Arduino IDE.
Note that Jeff's library is a bit overwhelming/intimidating for new users. If you'd like to learn more about hiding its complexity behind a simple and easy to use interface, or about being able to save the calibration results to persistent memory so that you don't have to perform the calibration every time you power on, or just want to learn more about this topic in general, please consult the following tutorial:
https://youtu.be/k5i-vE5rZR0


text:
Arduino NANO clone not detected by computer
I recently purchased 5 Arduino Nano clones and on my Windows PC they were all working fine.
I then gave one to a friend and after installing the CH34OC driver on his Mac he was able to program a simple Morse code blink program that worked fine on the device. However, after uploading it the COM port was no longer showing and his Mac could no longer detect the device.
We verified that the problem was not with the Serial cable and not with the USB port and other the Arduino clones worked perfectly also. So it must be an issue with the device which when connected the RX and TX lights would stay on and the inbuilt LED would display the Morse code as was programmed. The device would then no longer even be registered by my computer as no noise was made when plugging it in and nothing showed up in device manager as if I simply pugged in a USB cable with nothing attached.
I then used my Arduino UNO to run the Arduino ISP program and then burn the bootloader onto my NANO. This was successful and the a new blink program was loaded and the TX light no longer shows when connected to my computer but it is still entirely undetected as if nothing was plugged in.
I have tries many things including but not limited to:
Holding the reset button when plugging it in
Reinstalling the driver as administrator
Switching out the cable
Changing the USB port
Using the old bootloader
Reinstalling the Arduino IDE
Restarting my computer.
Sadly nothing is working and I am out of ideas. Does anyone have any suggestions for a fix or know how I can diagnose the issue further. For example checking to see if the USB chip on the Arduino is operational or maybe the diode was faulty? Methods for testing these things would be greatly appreciated.

It sounds rather like a fault with the Nano's CH340 chip, the one used to communicate over USB between the Nano and a PC. The Atmega 328p seems to be working, as you say the previously loaded Morse Code program still runs. I expect you can still program the Atmega entirely through its ISP.
If the CH340 has been physically damaged, you can still program the Atmega processor via the ISP but you will no longer have USB capability on-board. You could use a CH340- or FTDI-cable (USB <-> TTL serial) connected to Arduino-pins 0 and 1 to provide off-board USB communication if you want to continue using the Nano as usual.
Update:

Is there any way that I can verify that the CH340 chip has indeed been
damaged as if it is something smaller like a diode I may attempt to
repair it.

I don't know of a way unless a visual inspection shows a bad component. Not that there might not be one, just that that level of board repair is beyond my expertise. And assuming you didn't ever see or smell smoke, I wouldn't expect the defect to be visible. No harm in going over it with a strong magnifier, though....

So I am assuming my best course of action will simply be to program it through ISP then place it in a permanent project.

Is there any way that I can verify that the CH340 chip has indeed been damaged as if it is something smaller like a diode I may attempt to repair it.

source: Stack Exchange

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

sort: votes


text:
Unable to get readings for "Motor with Encoder"
I've posted to the DFRobot forum, who makes the FIT0186 motors, but no one seems to be replying there.  So, excuse the copy pasting.  It's probably an issue with the motor/encoder, but perhaps it has to do with the arduino.  I'm using a Nano, and a TB6612 based motor driver from DFRobot.
I'm trying to get the built-in encoder working for the FIT0186.
The example wiki code doesn't work, and I've modified it as far as I can using sensible changes.
I'm plugging both Hall Sensor A and B outputs to the interrupts.
Currently, when I plug in the 12V, it triggers an interrupt, but then other than that initial pulse, no interrupts are triggerred.
The motor is moving as expected. Attaching my code. Has anyone got the encoder working?
const byte encoder0pinA = 2;
const byte encoder0pinB = 3;
volatile int posA;
volatile int posB;

int DIR1 = 8;
int PWM1 = 9;

void setup()
{
  Serial.begin(115200);
  pinMode(DIR1, OUTPUT);
  pinMode(PWM1, OUTPUT);
  pinMode(encoder0pinA,INPUT);
  pinMode(encoder0pinB,INPUT);
  attachInterrupt(digitalPinToInterrupt(encoder0pinA), encoderA, RISING);
  attachInterrupt(digitalPinToInterrupt(encoder0pinB), encoderB, RISING);

}

void loop()
{
  Serial.print("Pulse:");
  Serial.println(posA);
  Serial.println(posB);

  noInterrupts();
  posA = 0;
  posB = 0;
  interrupts();

  delay(100);

  int value;
  digitalWrite(DIR1, HIGH);

  for(value = 0 ; value <= 255; value += 5)
  {
    analogWrite(PWM1, value);   //PWM Speed Control
    delay(20);
  }

  Serial.print("Pulse:");
  Serial.println(posA);
  Serial.println(posB);

  delay(100);

  for(value = 255 ; value >= 0; value -= 5)
  {
    analogWrite(PWM1, value);   //PWM Speed Control
    delay(20);
  }

  Serial.print("Pulse:");
  Serial.println(posA);
  Serial.println(posB);
  delay(100);

  digitalWrite(DIR1, LOW);
  for(value = 0 ; value <= 255; value += 5)
  {
    analogWrite(PWM1, value);   //PWM Speed Control
    delay(20);
  }

  Serial.print("Pulse:");
  Serial.println(posA);
  Serial.println(posB);

  delay(100);
  for(value = 255 ; value >= 0; value -= 5)
  {
    analogWrite(PWM1, value);   //PWM Speed Control
    delay(20);
  }

}

void encoderA()
{
    posA++;
}

void encoderB()
{
    posB++;
}

that is probably a quadrature encoder ... it has two channels, A and B ... monitor state of A ... at one of the signal edges, check the state of B ... that will tell you the direction of rotation ... for example, check the state of B every time A goes from high to low

Hmm so that was interesting.  When checking now, B increases.  But then when I touch D4, it goes to 0.  Oh boy, magic hour.

From what you have indicated (being wired correctly) there is a high probability you have a bad connection. It could be one of many things such as a loose wire, broken wire, problem with the module, etc... Swp A & B and see what happens.

Thanks, I had the hall sensor gnd and vcc backwards.

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


text:
Arduino Nano 3.0 dimensions without the pins
I think the title of this question is quite clear. I am looking for the exact dimensions of the Arduino Nano 3.0, with the electronic components and the USB mini port on the IC (the Atmega328 one), without the external pins.

It'll be 1.6mm plus the thickness of the thickest component - which you can find in the datasheet for that component - plus a tiny bit for solder float.

Mini-USB-B is around 4mm tall.
Most PCBs are around 1.6mm.
The FT232RL on the bottom is 2mm (max) according to the datasheet. (voltage regulator is 1.8mm). (I'm sure about this tantalum capacitors)
So that's something around 7.6mm total height

What about the components on the bottom?

@user29519 sorry about that. I always mix up those boards. I thought the nano used the ATMega32u4.

I have a nano so let me get a ruler, ok. The usb port takes up most of the room so 4mms, the board itself is 1mm and a tiny chip adds 2mms as well. So 7mms! Hope this helped!

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


text:
Touch-screen, 3 H-bridges and 3 sensors on Arduino Nano 3.0
I am using an Arduino Nanao andI am wondering if there is a way to connect an 2 inch touchscreen, 3 H-bridges (it takes 3digital pins to power one of them and 1 additional to control the voltage) and have 3 analog pins left for sensors?

I think, that there is at least one I2C touchscreen (eg. https://www.adafruit.com/product/1947 )(I2C need 2 pins - SCL(A5)+DATA(A4) - given by HW) and if you need 3x3=9 digital pins for setting direction, you can use also I2C multiplexer on the same 2 pins (http://playground.arduino.cc/Code/I2CPortExpander8574). So you are left with need for 3 PWM pins from (D3,D5,D6,D9,D10,D11).
So there is a way for sure.

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


text:
Sublime as external editor, error on Arduino compile dropdown: "avr-g++ is not recognized...", from Stino
The error message, generated from Sublime, in its entirety...
Compiling KCT_Swimv4l...
Creating C:\Users\ken\Documents\Arduino_Build\KCT_Swimv4l\KCT_Swimv4l.ino.cpp.o...
'"avr-g++"' is not recognized as an internal or external command,
operable program or batch file.
[Stino - Error 1]

This is initial install of "Arduino-like IDE".
I used the following installation procedure:

Install Sublime Text 3
From Sublime, View --> Show Console
From a web browser, open  https://sublime.wbond.net/installation and choose Sublime Text 3 version.
Copy the code there to the Sublime-Console and press enter.
From Sublime, CTRL + Shift + P --> Type "Install" and choose "Install package"
Enter "Arduino" and choose "Arduino-like IDE"
from Arduino --> Preferences --> Select Arduino Application Folder.

Same problem with any sketch.
System Configuration:
-Windows 10 x64, current level
-Sublime Text 3 x64, build 3126
-Arduino IDE 1.8.0
github info on Stino was not helpful.
Has anyone encountered this problem and found a solution for it?
If not, I can open an issue there.

I have now done the following:
Uninstalled Sublime
Searched System drive and removed any remaining Sublime content
Searched System drive and removed any Stino content
Download WinAVR from http://winavr.sourceforge.net/download.html, selecting PATH option
Reinstalled Sublime Text 3 x64
Close & Reopen Sublime
From Sublime, View --> Show Console
From web browser, open https://sublime.wbond.net/installation and choose Sublime Text 3 version.
Copy the code there to the Sublime-Console and press enter
Close & Reopen Sublime
From Sublime, CTRL + Shift + P --> Type "Install" and choose "Install package"
Enter "Arduino" and choose "Arduino-like IDE"
Close & Reopen Sublime
From Arduino --> Preferences --> Select Arduino Application Folder
On Compile, error msg is now different:
  Compiling KCT_Swimv4l...
  Creating C:\Users\kct\Documents\Arduino_Build\KCT_Swimv4l\KCT_Swimv4l.ino.cpp.o...
  cc1plus.exe: error: unrecognized command line option "-std=gnu++11"
  cc1plus.exe: error: unrecognized command line option "-flto"
  [Stino - Error 1]

unrecognized command line option "-std=gnu++11" - sounds like the compiler you installed is too old. It looks like it is from 2010. Right now it is 2017.

@Nick Gammon This was recommendation from answer posted.
Yes, this winavr copy is from 2010, as specified in answer, and the current year is now 2017.  I wondered about that.
Now that I have a starting point, I now see that there is a newer copy at https://sourceforge.net/projects/winavr/, and I will try that out.

@Nick_Gammon  Nope, same copy.  Perhaps you can suggest a direction to pursue.

The avr-g++ that ships with the Arduino IDE would be more recent. For example with IDE 1.6.9 I find: avr-g++.exe (GCC) 4.8.1. That accepts -std=gnu++11 on the command-line.

I found a whole lot of binaries (.exe files) in arduino-1.6.9\hardware\tools\avr\bin where arduino-1.6.9 is my install folder.

Download WinAVR from http://winavr.sourceforge.net/download.html, install it, add(in my case, its: C:\WinAVR-20100110\bin) to PATH variable of your system(If it was left unchecked while installing), And then try to build. I hope your problem will be solved.
Update
I have installed the latest version and found no board selection option. If you want to use it, you can download an older version. from here: https://drive.google.com/file/d/0B4zy7eqONHnuajk2aXlzOTJtaDQ/view it works on older version of arduino(probably 1.5 series)

I have updated problem description to show last actions taken in response to suggestion.
Now get different error msgs.

authors: 008 นูรฟาติน เเวอูเซ็ง


text:
Cannot get HC-12 to function with Arduino Pro Micro clone
[first time usage]
I'm checking this config out with a simple sketch derived from one @ https://www.allaboutcircuits.com/projects/understanding-and-implementing-the-hc-12-wireless-transceiver-module/.
The sketch acknowledges a command from the Serial Monitor and responds accordingly along with an "OK".  I have used this sketch countless times before with numerous HC-12 and UNO, and this particular HC-12 functions properly when connected to such.
For the Pro Micro, the command is echoed back instead, which, in my experience, indicates that the HC-12 is not receiving/responding.
The Pro Micro test config is very basic: Pro Micro, HC-12, USB connection, 5 direct jumper connections for vcc, gnd, pins 4-6. Vcc output reads 4.2 volts.
I specify:
const byte HC12RxdPin = 4; // "RXD" Pin on HC12
const byte HC12TxdPin = 5; // "TXD" Pin on HC12
const byte HC12SetPin = 6; // "SET" Pin on HC12

SoftwareSerial HC12(HC12TxdPin, HC12RxdPin)

I have also tested with an IN4007 in the power connect for the HC-12, but results are the same.
I've swapped HC-12s, and checked out the requisite pins by using another sketch that toggles an led on each.
The Arduino IDE is 1.8.2, and I am specifying a Leonardo board.  This is the suggestion I found whilst researching.
I have seen a few projects using the HC-12 with the Pro Micro and other small boards, but noticed no special considerations for such.
Have you any suggestions or solutions [even better]?

http://arduino.stackexchange.com/questions/1471/arduino-pro-micro-get-data-out-of-tx-pin?rq=1

mico Thanks to the reference cited, I think I finally comprehend the situation.  Reading was easy, comprehension more difficult.
Based upon the reference, I removed the HC-12 specifications, then specified Serial1 for the reads, writes and available check.
I then changed connections, such that the HC-12 RXD pin connects to the Pro Micro TXD pin, and the HC-12 TXD pin connects to the Pro Micro RXD pin.
This works for my the sketch I was using as well as other test cases of mine.

Have you seen the Q&A on providing adequate power?  The HC-12 needs more than 100 mA to work, into the Vin, for all types of Arduino..  It will not work at all if the power is only coming from a USB port.  Have you tried this?  https://arduino.stackexchange.com/questions/33668/how-can-i-provide-enough-power-on-an-uno-to-use-the-hc-12-wireless-module

Solution to problem is as follows:
 For the Arduino Pro Micro [as for the Leonardo], Serial1 must be used instead of a SoftwareSerial specification, e.g.,
SoftwareSerial HC12(HC12TxdPin, HC12RxdPin).

Code is to be modified by changing HC12.available() to Serial1.available().  The same holds true for the reads and writes.
Pins are to be wired such that the HC-12 RXD pin connects to the Pro Micro TXD pin, and the HC-12 TXD pin connects to the Pro Micro RXD pin.
My thanks to @mico for providing the reference that explains it all.


text:
Pls help with this prompt. I've been struggling last 2 days with this and its due tomorrow
"Use an Arduino, two potentiometers, and an alarm. Make one of the potentiometers act like a volume control, and make the other potentiometer control the tone that the alarm makes."
I added what I have so far. I'm not sure how to control the volume

that is a good start ..  the code should be added as text, not as a picture ... the tone() function has no volume control ... perhaps you are supposed to build a volume control circuit

@Mahmodol this site is a question and answer site ... its purpose is to answer questions ... if you ask a clear question, then someone will try to answer it

Post a schematic as you have it wired, part of your frizzy picture is not even connected. With such short notice I will be surprised if you get it resolved in time. When you are given an assignment it is best to start ASAP, waiting until the end causes problems like this and missed assignments.

Welcome to SE/Arduino! Please take the [tour] to learn how this site works. -- What have you tried to read the values of the potentiometers? -- Please [edit] your question, don't add a comment. This is not a forum. ;-)

Use the other potentiometer as a variable resistor. Instead of connecting to pins 1 and 3 (to control tone), Use the 2nd pin of the potentiometer to make a voltage divider. From the 3rd pin go to a + on a buzzer. I don't see the reason to have the circuit connected the way you have. if you want to control the tone with potentiometer, connect it to stable 5v, and connect the second pin with any analog pins that is configured as input. Then, use map function, and map the voltage, accordingly to the tone you'd like to use.


text:
Xbox 360 controller commands to Uno-compatible board via USB module
I am trying to receive commands on a third-party Arduino-Uno-compatible board from an Xbox 360 controller via an M5Stack USB module but I am not seeing the behavior I expect (see heading Expected Behavior).
To be clear, I am talking about reading commands from an Xbox controller using an Arduino, not emulating an Xbox controller using an Arduino.
Hardware

A Bluno Nano. (An Arduino-Uno-compatible board in a Nano-like form factor with program uploading and serial communication via a matching Bluetooth USB dongle. However, I am using a wired USB connection to my PC instead.) The board is recognized as an Uno by the Arduino IDE. The same board has worked as expected for other projects.

An M5Stack USB module (with a MAX3421E chip), which is  primarily meant to be compatible with an M5Stack microcontroller module. Either way, the USB module communicates using SPI.

A wireless Xbox 360 controller, but I connected it to the USB module using a USB cable that plugs in to the controller with a seemingly proprietary connector. Should be in working order.

I am not using an Xbox 360 wireless receiver to connect to the Xbox controller, nor do I want to connect to it wirelessly.
Wiring

I connected the GND (#1/3/5), +5V (#28, VBUS), SCLK (#11, GPIO18), MISO (#9, GPIO19) and MOSI (#7, GPIO23) pins of the USB module to the corresponding pins of the Bluno Nano: GND, +5V, SCK (D13), MISO (D12), and MOSI (D11).

I tried pulling the USB module's EN pin (#6) up to +5V in attempt to make sure it's enabled.

I tried pulling the SS pin up/down. I have not tried connecting it to pins D10 or D8, both of which I have seen as SS pins on Arduino Nano pinout diagrams.

I have not tried connecting the INT pin (#2, GPIO35) to anything.

I believe these are the only useful pins on the USB module.

USB module schematic
The useful pinout is in the bottom right corner.

Attempts

Unplugging and re-plugging the Bluno Nano's USB cable with my PC.

Pressing the Bluno Nano's reset button.

Unplugging and re-plugging the Xbox controller's USB cable with the USB module, or vice versa (that is, starting with it unplugged).

Pressing or holding the center "X" button or other buttons on the controller, presumably to turn it on or hopefully enter some kind of connection-setup mode, maybe.

Using a wired USB mouse instead of the Xbox controller.

Trying various combinations of the above in different orders.

I have ensured that the USB module is receiving power (even though it seems to have no power indicator LED) by using it's additional 5V and GND pins to successfully drive a digital input pin on the Bluno Nano high or low.
I have ensured that the Xbox controller is receiving power because the center "X" button lights up upon being pressed.
Software

Windows 11

Arduino IDE 2.0

USB_Host_Shield_2.0 version 1.6.2 (latest) installed through the library manager. Note that this library seems to be primarily designed for a particular USB host shield, but I see it being used with other USB host shields, including in my USB module's documentation. There is a library for Xbox 360 therein which works with a USB controller or a wireless controller, with example sketches for each.

Either example sketch uploads successfully without errors (although the programmer sometimes gets stuck not responding, whereupon I disconnect, let it error out, reconnect, and retry uploading).
In the Arduino IDE Serial Monitor, I set the baud rate to 115200 to match that specified in either example sketch.
Expected behavior
To be printed in the Serial Monitor (<...> is how I indicate my comments):
XBOX USB Library Started  <instead of "OSC did not start" followed by unresponsiveness to controller button presses, etc.>
<Xbox controller commands upon controls/buttons being pressed, e.g., "LeftHatX: ...">

Attempts

The USB Host Shield 2.0 documentation says about use with an Xbox 360 controller: "To use it via USB use the XBOXUSB library or to use it wirelessly use the XBOXRECV library. Note that a Wireless controller can NOT be used via USB!". It is unclear to me if my wired USB connection to my wireless controller calls for the XBOXUSB or XBOXRECV library, so I tried both libraries (tried both accompanying example sketches) to no avail.

I tried removing the following code snippets one-by-one and in some combinations, to no avail. The program uploads successfully in every case.
#include <SPI.h>

#if !defined(__MIPSEL__)
  while (!Serial); // Wait for serial port to connect - used on Leonardo, Teensy and other boards with built-in USB CDC serial connection
#endif

XBOXUSB Xbox(&Usb);
<...along with the code in `loop()` that requires it to be defined.>

if (Usb.Init() == -1) {
  Serial.print(F("\r\nOSC did not start"));
  while (1); //halt
}
Serial.print(F("\r\nXBOX USB Library Started"));

The program failed here because Usb.Init() == -1.

I tried changing
if (Usb.Init() == -1) {
  Serial.print(F("\r\nOSC did not start"));
  while (1); //halt
}
Serial.print(F("\r\nXBOX USB Library Started"));

to
while (Usb.Init() == -1);
Serial.print(F("\r\nXBOX USB Library Started"));

in attempt to keep trying to enable the connection (while I pressed the controller's "X" and other buttons) to no avail.

I also tried changing the same snippet to
Usb.Init()

in attempt to ignore the -1 return value (which I presume represents an error) and proceed anyway, to no avail.

Using an older version of the USB Host Shield 2.0 library.

Setting the following in the library's settings.h, with no apparent change in output.
/* Set this to 1 to activate serial debugging */
#define ENABLE_UHS_DEBUGGING 1

Setting the following in XBOXUSB.cpp and XBOXRECV.cpp, with no apparent change in output.
#define EXTRADEBUG // Uncomment to get even more debugging data
#define PRINTREPORT // Uncomment to print the report send by the Xbox 360 Controller

For trying with a wired USB mouse instead of the Xbox controller, I used USB_Host_Shield_2.0/examples/HID/USBHIDBootMouse/USBHIDBootMouse.ino, attempted additionally with some of the above modifications, to no avail in any case, leading me to believe that the problem is not specific to the Xbox controller or library for it.
I have also tried the example sketch from the M5Stack USB module documentation after removing parts that would be specific to an M5Stack microcontroller module and unecessary for testing purposes. This was no different.

I am completely lost on what else to try hardware- and software-wise. I have tried searching many questions. I suspect that I'm missing something simple and obvious, or that my setup can't work for whatever reason.
Thank you

Update
After getting past the Usb.Init() problem by connecting the USB module's SS pin, the connection with the Xbox controller still wasn't being established and commands were not being received.

UPDATE: I've gotten past Usb.Init() successfully by connecting the SS pin to D10 (either with XBOXUSB or XBOXRECV) but the main code in loop() that is now reached is not working either because Xbox.Xbox360Connected == 0. This is the case even if I check Xbox.Xbox360Connected after a delay or after pressing buttons on the Xbox controller.

UPDATE: I've gotten exactly the same thing working but with the wired USB mouse and USB_Host_Shield_2.0/examples/HID/USBHIDBootMouse/USBHIDBootMouse.ino.

I tried pulling the SS pin up/down - I was about to suggest that the SS pin is usually controlled by software, and that asserting it usually signals the start of a "transaction" - however the protocol defines that.

You are certain that the controller also sends its data via the USB and not just wireless?

@NickGammon I think you're right about the SS pin. Regarding whether the USB is for data and not solely for power, I can't be 100% sure, but I suspect that it is for data because the USB cable's proprietary connector with the Xbox 360 controller has a sort of 'cuff' around it that seems to very intentionally block the "Connect" button on the back of the controller from being pressed; the USB cable appears to preclude a wireless connection by design. How do I test it -- try to play using the controller in a Faraday cage? :D

Well, if you had a USB analyser (which aren't cheap) you could see if the data being sent changes as you press buttons.

@NickGammon Thanks! I might consider trying a different controller and/or cable, buying an Xbox 360 wireless receiver, or using a joystick instead of the controller.

I discovered that, upon plugging the USB cable into my PC rather than the USB module, the controller appears as "Xbox 360 Wireless Controller via Play & Charge Kit" under "Xbox 360 Peripherals" in the Device Manager.
Turns out, "Play & Charge Kit" refers to the controller's removable rechargeable battery and the USB cable.
According to this, "The play and charge kit only carries power. It does not carry the data required to connect a controller to a PC."


text:
Why HTTPS requests are working with dynamic IP address, and not with static IP address
I am working on a room automation project. I connected an ESP8266 board with WiFi through my home router.I make an HTTPS request from ESP8266. It returns a good response 200 when connected using DHCP's dynamically assigned IP, but returns -1 response when a static IP is configured in it.
My code:
    Rui Santos
    Complete project details at https://randomnerdtutorials.com
  *********/

  // Load Wi-Fi library
  #include<ESP8266WiFi.h>
  #include<ESP8266HTTPClient.h>
  #include<WiFiClientSecureBearSSL.h>

  using namespace std;

  // Replace with your network credentials
  const char* ssid     = "<router_ssid>";
  const char* password = "<router_password>";

  void setup() {
    Serial.begin(9600);
    Serial.println("started");

    // //Configure static IP
    // IPAddress staticIP(192,168,10,55);
    // IPAddress gateway(192,168,10,1);
    // IPAddress subnet(255,255,255,0);
    // if(!WiFi.config(staticIP,gateway,subnet)){
    //   // Serial.println("IP Configuration failed");
    // }

    WiFi.begin(ssid, password);
    while (WiFi.status() != WL_CONNECTED) {
      delay(500);
      // Serial.print(".");
      digitalWrite(LED_BUILTIN,HIGH);
      delay(500);
      // Serial.print(".");
      digitalWrite(LED_BUILTIN,LOW);
    }

    Serial.println("connected");
    digitalWrite(LED_BUILTIN,LOW);

    // set the http client
    BearSSL::WiFiClientSecure client;

    client.setInsecure();
    HTTPClient https;

    while(https.begin(client,"yandex.com",443)){
      Serial.println("client began");

      int code = https.GET();

      if(code == 200){
        Serial.println("code 200");
      }
      else{
        Serial.println("failed");
        Serial.println(code);
      }
      delay(5000);
    }
  }

  void loop(){
}

When I un-comment the above lines, for static IP, the status comes back to -1.
Please guide me what could be the problem?
Note: I have applied port forwarding on my router for the same static IP, with port 5555. Might it be creating the hurdle in HTTPS communication?

you didn't specify a DNS server IP so it can't evaluate the server's name

You are missing the configuration for the DNS servers. This information is provided by DHCP and tells the ESP how to resolve domain names into IP addresses.
IPAddress staticIP(192,168,10,55);
IPAddress gateway(192,168,10,1);
IPAddress subnet(255,255,255,0);
IPAddress primaryDNS(8, 8, 8, 8);
IPAddress secondaryDNS(8, 8, 4, 4);
if(!WiFi.config(staticIP,gateway,subnet, primaryDNS,secondaryDNS )){
  // Serial.println("IP Configuration failed");
}

This uses the Google DNS servers. Note that it is typical for your router to also provide DNS services, you can pick your router as the IP for the DNS, which increases speed as it has a lower latency for things in the DNS cache

i did the additions, but still it is failing connection and returning -1.


text:
Clarification of power-up behaviour of MAX7219 display driver
What is the exact meaning of the Initial Power-Up Section of the MAX7219 data sheet to be found on Page 7?
It says:

On initial power-up, all control registers are reset, the display is blanked, and the MAX7219/MAX7221 enter shutdown mode. Program the display driver prior to display use. Otherwise, it will initially be set to scan one digit, it will not decode data in the data registers, and the intensity register will be set to its minimum value.

Most of this is clear. But specifically, what does the "the display is blanked" mean? Does it mean that the MAX7219 internal SRAM is cleared as part of the power-up sequence or does it mean that because the display is set to shutdown mode by power-up the display will be blank.
I have sought widely and cannot find a definitive statement. Which of these interpretations is correct, or perhaps is there another interpretation?
Why does it matter? Idle curiosity really. My read of the datasheet was that the RAM was cleared and hence did not expect to have to manually clear it.
So I didn't, and was wondering where the flash of random data at power up in my bank of displays was coming from, prior to the first display data write. And I was a bit too slow in accepting I got reading the datasheet wrong, or the datasheet didn't apply to the clone I was using.
I was wondering if someone had a definitive answer from some deep investigation or perhaps insider information. It seems not, and it may not be consistent anyway.
For the clone MAX7219s in my collection, the SRAM is not cleared on power-up. I don't know if that is the case for genuine MAX7219 or for different clones for that matter. In future, I will just assume not and zero out the SRAM manually.
That point about a pull-up resistor on the chip select(CS) line to mitigate erratic behaviour is an excellent one. Random noise here can easily generate unexpected results.
It should be noted though that if the CS line is not the default Slave Select (SS) of the SPI pin group, it is not enough to use a pull-up resistor alone.
The SPI begin function takes care of the case that the default SS pin will glitch low as it is made an output if the corresponding bit in the output register is not set to 1 prior to setting the pin to output mode.
For the default SS pin, begin() does a digitalWrite HIGH first, setting the internal pullup resistor on (and the output register bit to 1) then a pinMode to OUTPUT, thus if the SS pin is already pulled high by a resistor there are no glitches.
However, if the CS pin is a pin other than the designated SS, then the same process must be undertaken by user code. If forgotten, even a pulled up pin will glitch low as the output register, with the bit set to 0, is transferred through to the pin when it is configured as output.
It is easily fixed using the same method as the SPI library uses, digitalWrite a HIGH to the CS pin, then set that pin to OUTPUT. And pull it up, of course.

I'm a little confused. There doesn't appear to be any way for you read the RAM in the the device. So if there were a distinction between the display being blanked and the RAM being cleared (I suspect there isn't) how would you observe that or why would you care? Your question as written is probably better suited to ESE.

If the mechanism is not described in the datasheet then it will be difficult to determine how the blanking is achieved and may even differ between various clones / fakes. However,  if you are asking because you have experienced erratic/random behaviour  at system start then putting a 10k pullup resistor on the load/cs pin may help.

You've edited your initial post extensively so it is not now clear if there is an issue remaining. However,  the point about the external pullup resistor on the load/cs pin is that it minimises the risk of instability at system start, to which these MAX7219 chips are prone, while the MCU pins are still floating. That is, before the internal pullup has been activated.

The Maxim 2021 datasheet does have at least one error: all the bits for Shutdown register -- Shutdown Mode -- are don't cares.
The display is not blank after cold setup, for five frames at 29fps random and changing LEDs light up on my 32x32 matrix. If I reset my 8051 while it's displaying my pattern, the display goes blank and then the last image before I performed the reset appears momentarily followed by blank and my scrolling pattern.

As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.

It isn't clear what a 8051 has to do with the question that the OP asked. Please [edit] and clarify your answer.

I think it's pretty clear from the datasheet.

all control registers are reset

The digit displays are registers, and therefore they will contain zeroes.
Displaying one digit, being in shutdown mode, and minimum intensity are all what would happen if all registers were set to zero.

I have sought widely and cannot find a definitive statement.

Why is this important to know? When powered on it will be blank, as stated. Presumably you will configure it to the way you want it before leaving shutdown mode.

the datasheet contains the phrase Table 2 lists the 14 addressable digit and control registers. ... it is unclear if all control registers are reset includes the digit registers ... like you said, does it really matter?


text:
Problems with green TWI (I2C) port on Arduino Braccio Shield
Summary: The green TWI/I2C port on my Braccio shield I2C port hasn't worked for me so far. Looking for advice or information please.
Detail:
I'm using the Arduino (Tinkerkit) Braccio robot arm for self education. It comes with a Uno based Braccio Shield. Tinkerkit no longer seems to be in business and documentation is a bit scarce. The shield uses KF2510 style connectors for servos (orange), inputs (white), serial (yellow) and importantly for my question a TWI/I2C port (green).

The green four pin TWI/I2C connector provides GND, +5V, SDA (A4), SCL (A5). However the SDA and SCL connections are reported to not be direct, but that "a very tiny chip (located next to the I4 connector) buffers between the green connector and the Arduino pins SDA and SCL" . A photo of the chip described is below.

Contrary to the reports of a "buffer" studying the schematic shows a level shifter PCA9306TI and two sets of 10K pullup resistors (R7,R8 and R11,R12) on the bus on both sides of the chip. VREF2 on the outboard side of the chip has a R9 220K resistor to +5V.

The other side of my I2C connection was an Arduino Pro-mini 5V. I was never able to get it working using the green port described, but it works fine directly hooked into SCL and SDA bypassing the level shifter.
My questions (sorry for the long lead up) are:

Has the green TWI port been level shifted to expect ~3V? (Only really came to this conclusion writing this all up clearly).
If I want to change the green TWI port to 5V I2C can I replace R9 220K with a zero ohm jumper?
The 10K pullups (R7,R8 and R11,R12) seem larger than anticipated (I had anticipated about 4.7K for 5v or about 2.4 for 3V)? Can they be removed and left open if I have a single set of pullups elsewhere on the bus? Or better suggestions?

Thanks!
Update 2021/01/30
Well my I2C debugging skills are improving researching this! As a test bed I set up a clean working I2C bus with two MCU's running the Arduino Example Master/Writer Slave/Receiver sketches by Nicholas Zambetti. I tested the I2C signal on the oscilloscope to make sure it was clean. All good. To that test bed I connected the Braccio shield (5V, GND, SCL, SDA). Connecting the Braccio shield changes the I2C signal in interesting ways, with partial strength (runt) pulses, and round shoulder slow rises. Connecting via the green TWI port seems to accentuate the runt pulse aspect. Also interesting the oscillscope was still able to decode the signal. Still working on figuring this out.
Pic 1. First test - SCA and SCL connected via pin headers in top left of shield picture above.

Pic 2. Second test - SCA and SCL connected via green TWI port

Pic 3. Clean Signal (no Braccio Shield connection)

is your Uno a R3 with the SDA, SCL header pins?

@Juraj, Yes a genuine Uno R3. The additional SDA and SCL pins are present next to the AREF pin, and it is actually these I'm connecting to directly to achieve the work around.

I fear we have a colloring issue. Your green is my blue ;-).
I have looked into the data sheet of the level shifter IC and TI only describes scenarios with a higher voltage on the right side and a lower voltage on the left side. Also the allowed voltage translations do not contain 5V to 5V. So I would say in equal voltage scenario the Level shifter may not work.
Answers

Q1: The TWI port is always used with 5V (not ~3V). The Arduino that is supposed to use the shield might be a 3.6V version (like a DUE or M0). Perhaps the TWI port is only intended for this use case: A low voltage arduino with a 5V device. I admit: This should be noted in the documentation. So perhaps Braccio shields work outside the specification and may works under normal circumstances. But meanwhile I begin to understand why they are out of busines ;-).

Supplement: the SCL and SCL signals are routed to two pairs of header pins as they are connected to different pins on different Arduinos. On a UNO you can not use A4 and A5 for analog as they are used for I2C for example. Do you use A4 A5 in any way? Or did you connect the second I2C pin pair in the power header when you had used the TWI connector? (rhetoric question ;-) of cause I will change the answer if you give me more information ;-) )

Q2: The 220k resistor is necessary as it limits the current through the chip if VRef1 is lower than VRef2. Removing it with 0 Ohms would be a bad idea. As long as 5V is used on both sides, nothing would happen. But if Vref1 is 3.6Volts, you would waste energy and perhaps the chip would take part at a grill fest.

Q3: Most I2C devices breakout boards already use their own pullup resistors. So lowering the pullups is not the best idea. -> too high current with LOW signals as the devices pull ups and the braccio pull ups are set in parallel.
-- There is a chance, that the resistors are too large for devices that don't use their own pull ups, but at a 100kHz bus speed I don't think, this could cause an issue.

BTW: You do not need to exchange the pull ups, if you insist to try out different values. Just use parallel resistors to lower the resistance (10K || 10K -> 5K) [|| means connected in parallel] (R || Rp -> (R*Rp) / (R+Rp))


text:
Serial port stops receiving data after random amount of time
EDIT: Things I have tried so far:

Increasing the baud rate, but this didn't make any difference as it still continued to stop receiving data after random amount of time.

I tried testing one sensor and reducing the sketch to something that only prints in a sketch. I can get the sketch to work up to 2 sensors where it prints the results continuously. 3 or 4 sensors and I get the issue mentioned.

Link to the VL53L4CD library: https://github.com/stm32duino/VL53L4CD
Datasheets:
https://cdn-learn.adafruit.com/downloads/pdf/adafruit-vl53l4cd-time-of-flight-distance-sensor.pdf
https://www.st.com/resource/en/datasheet/vl53l4cd.pdf

I'm currently working on a project where I need to measure distances at two different points using distance sensors (I'm currently using VL53L4CD laser distance sensors). However, this project requires a high sampling rate of 100Hz. To achieve this, I have 4 distance sensors arranged into 2 sensor sets. Each sensor set consists of 2 distance sensors (So for example, sensor set 1 consists of distance sensor 2&3 and sensor set 2 consists of distance sensor 1&4) and I would alternate between reading each sensor set.
This seemed to work at first, I did get a new distance reading every 8ms. However, the serial port stops receiving the distance readings after a very random amount of time. Sometimes the serial port stops receiving new data after 5 seconds, sometimes 30s, sometimes 60 and even 180s.
I'm not sure what's causing this issue what I can do to fix it. Any help is appreciated
(I'm using the Arduino Nano 33 IOT)
Thanks!
Here is my code below:
// Included libraries
#include <Arduino.h>
#include <Wire.h>

// Libraries required for VL53L4CD sensors
#include <vl53l4cd_class.h>
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include <stdint.h>
#include <assert.h>
#include <stdlib.h>

// Definitions
#define DEV_I2C Wire
#define SerialPort Serial

// variables
int alternate = 0; // Variable used to alternate between sensor sets

// Components.
VL53L4CD sensor_vl53l4cd_1(&DEV_I2C, 2); // xshut pin of distance sensor 1 connected to pin 2
VL53L4CD sensor_vl53l4cd_2(&DEV_I2C, 3); // xshut pin of distance sensor 2 connected to pin 3
VL53L4CD sensor_vl53l4cd_3(&DEV_I2C, 5); // xshut pin of distance sensor 3 connected to pin 5
VL53L4CD sensor_vl53l4cd_4(&DEV_I2C, 6); // xshut pin of distance sensor 4 connected to pin 6

/* Setup ---------------------------------------------------------------------*/

void setup()
{
  // DISTANCE SENSOR SETUP
  // Initialize serial for output.
  SerialPort.begin(9600);
  SerialPort.println("Starting...");

  // Initialize I2C bus.
  DEV_I2C.begin();

  // Configure VL53L4CD number 1
  Serial.println("Configuring distance sensor 1");
  sensor_vl53l4cd_1.begin();
  sensor_vl53l4cd_1.VL53L4CD_Off();
  sensor_vl53l4cd_1.InitSensor();
  sensor_vl53l4cd_1.VL53L4CD_SetI2CAddress(0x40);
  sensor_vl53l4cd_1.VL53L4CD_SetRangeTiming(10, 0);

  // Configure VL53L4CD number 2
  Serial.println("Configuring distance sensor 2");
  sensor_vl53l4cd_2.begin();
  sensor_vl53l4cd_2.VL53L4CD_Off();
  sensor_vl53l4cd_2.InitSensor();
  sensor_vl53l4cd_2.VL53L4CD_SetI2CAddress(0x42);
  sensor_vl53l4cd_2.VL53L4CD_SetRangeTiming(10, 0);

  // Configure VL53L4CD number 3
  Serial.println("Configuring distance sensor 3");
  sensor_vl53l4cd_3.begin();
  sensor_vl53l4cd_3.VL53L4CD_Off();
  sensor_vl53l4cd_3.InitSensor();
  sensor_vl53l4cd_3.VL53L4CD_SetI2CAddress(0x44);
  sensor_vl53l4cd_3.VL53L4CD_SetRangeTiming(10, 0);

  // Configure VL53L4CD number 4
  Serial.println("Configuring distance sensor 4");
  sensor_vl53l4cd_4.begin();
  sensor_vl53l4cd_4.VL53L4CD_Off();
  sensor_vl53l4cd_4.InitSensor();
  sensor_vl53l4cd_4.VL53L4CD_SetI2CAddress(0x46);
  sensor_vl53l4cd_4.VL53L4CD_SetRangeTiming(10, 0);

  // Start Measurements
  sensor_vl53l4cd_1.VL53L4CD_StartRanging();
  sensor_vl53l4cd_2.VL53L4CD_StartRanging();
  sensor_vl53l4cd_3.VL53L4CD_StartRanging();
  sensor_vl53l4cd_4.VL53L4CD_StartRanging();
}

void loop()
{
  // Read results from sensor set 1
  if (alternate == 0){
    VL53L4CD_Result_t results2;
    VL53L4CD_Result_t results3;

    // Read results from sensor set 1 (Sensors 2 and 3)
    sensor_vl53l4cd_2.VL53L4CD_ClearInterrupt();
    sensor_vl53l4cd_2.VL53L4CD_GetResult(&results2);
    sensor_vl53l4cd_3.VL53L4CD_ClearInterrupt();
    sensor_vl53l4cd_3.VL53L4CD_GetResult(&results3);

    Serial.print("Distance 1-1 = ");
    Serial.print(results2.distance_mm);
    Serial.println(" ");
    Serial.print("Distance 1-2 = ");
    Serial.print(results3.distance_mm);
    Serial.println(" ");

    alternate = 1; // Change value so sensor set 2 is read in the following loop
  }

  // Read results from sensor set 2
  else if (alternate == 1){
    VL53L4CD_Result_t results1;
    VL53L4CD_Result_t results4;

    // Read results from sensor set 1 (Sensors 1 and 4)
    sensor_vl53l4cd_1.VL53L4CD_ClearInterrupt();
    sensor_vl53l4cd_1.VL53L4CD_GetResult(&results1);
    sensor_vl53l4cd_4.VL53L4CD_ClearInterrupt();
    sensor_vl53l4cd_4.VL53L4CD_GetResult(&results4);

    Serial.print("Distance 2-1 = ");
    Serial.print(results1.distance_mm);
    Serial.println(" ");
    Serial.print("Distance 2-2 = ");
    Serial.print(results4.distance_mm);
    Serial.println(" ");

    alternate = 0; // Change value so sensor set 2 is read in the following loop
   }
   Serial.println(millis());
}

I'm unfamiliar with the VL53L4CDs, but for us to help you, do you mind linking the library that you've used in the post (and a link to the datasheet wouldn't hurt either)? Also, how does adding sensors help with the sampling rate? My hunch here is to say that you might be overflowing your I2C buffer, but I say test one sensor first, then a set of sensors, and IF that works alright, I'd start looking at two sets again and thinking about a more sophisticated flow control implementation. Do you know how much data each sensor (not set!) provides per reading? Also, try increasing the baud rate.

You might increase the baudrate so the serial buffer is less likely to overflow. Does it work without all the printing (use a LED for debug-blinking)?

Adding to @datenheim's comment: With 9600 baud you can transmit at most a bit less than 1000 bytes per second. With your sample rate of 100 Hz equaling a period of 10 ms, only 9 to 10 characters per sample are possible. -- A virtual serial connection via USB is much faster, though. The set baudrate matters only, if at least on one end a real serial line is involved. Using your PC and the Arduino built-in USB module, this is not the case, AFAIK.

Anyway, since you have no timing control in the provided sketch, I don't see how a serial buffer can overflow. All printing methods should block if their buffer is full. This way, your loop is timed by the speed of the serial transmission.

To make the problem smaller, reduce your sketch to something that only prints in a loop. If this runs long without problems, it is not the printing. Then do the same with only the sensor reading. [Edit] your question and add the findings, please.

Hi all, thanks for the replies and suggestions. @Nick, regarding the sampling rate of each sensor, each sensor has a maximum sampling rate of 100Hz. However at this high of a sampling rate the readings are quite inaccurate. The idea is to set the sensor to operate at a slightly lower frequency to increase the accuracy and by using two sets of sensors, I can read one set of sensor while the other set is measuring, therefore increasing the sampling rate while maintaining the accuracy (at least that's what my FYP supervisor suggested). I have also edited my post to include what I've tried so far.

Right now I suspect it could be because the USB port on my laptop cannot provide the required amount of current. I've read somewhere that the USB port on laptops only provide 100milliAmps? According to the datasheet, the peak current for a sensor can reach a maximum of 40mA. Could it be that this is why I can only use a maximum of two sensors before the problem manifests itself?

@JinYuan I doubt it's the laptop, since usually USB ports can provide up to 500mA, which should be plenty for your Arduino and the sensors. I'm not sure what's exactly going on at the moment, but your control flow should be a bit different; you can either use STM's VL53L4CD_CheckForDataReady() function or actually instantiate interrupts for all 4 sensors and process them as sets on a set interval. I don't think of 100 Hz as a high sampling rate as your loop probably runs at 100 times faster than that...well, or at least, could, as I don't know if those functions are blocking are not.

@JinYuan You can also use Adafruit's library as well and you could also try powering the a set of sensors (two sensors) from a different source than your laptop. If you  have a logic analyzer,  you could put that up just to see how the data transfer is happening when you have all 4 hooked up at the same time.

@NickS. I tried powering all of the sensors using an external source and this seems to fix the problem. I was receiving all of the distance readings consistently and the serial port did not stop receiving data.

@JinYuan sounds good, you should post your own answer then! Also, it does depend on the USB port of the laptop on how much power it can provide - some indeed are limited to only 500-750 mW (or 100-150 mA), while other can provide up to 1.5A (charging ports). Still a bit weird you saw the issue as you saw it, since the Nano 33 should be pulling on average around 50-60, if not about 100 mA just by itself (which depends on whether you are using BLE/BT/WiFi and how), but hey, if it works it works!

I tried powering all of the sensors with an external power source and this seems to solve the issue, I got consistent readings from all the distance sensors and the serial port did not stop receiving data. It might have been the USB port on my laptop that was causing these issues.


text:
Is there a good reference for Arduino Due memory architecture and usage?
It's been harder than I expected to find a reference source or usage guide.
There's a number of sources I've looked at along the road to this question:

The Due is listed here and here as having 512KB flash memory, 96KB SRAM and zero EEPROM.

The arduino foundation tutorial notes that Due memory architecture is different but doesn't expand further.

@Majenko's answer to this previous question notes, "There is no PROGMEM required on ARM. There is no memory bus separation between Flash and RAM"

The SAM3x datasheet block diagrams show a unified bus (i.e. Von Neumann architecture (not Harvard architecture like the AVR boards))

This answer on the Arduino Forum suggests (regarding allocating constants to flash), "[...] all you have to do is use "const" in the variable declaration. [...]  Everything that's "const" gets put into flash without consuming any RAM. PROGMEM, pgm_read_byte() and the other AVR names are defined only so code designed for AVR can compile. But they do absolutely nothing on [SAM3X MCUs] "

The F() macro seems to still work.

So my question is searching for links to a reference or guide for memory usage on the Arduino Due. I hope a guide (or your answers) might explain the differences caused by the change to a Von Neumann architecture bus, what is stored where, highlighting which memory handling techniques developed for Harvard architecture AVR MCUs remain relevant on the Due.
If there is no guide I'm hoping this question and your answers may become a good reference point. Thanks for reading!

Would it be correct to say that for Arduino Due, all constants (including in-code string literals not using F())  are stored in flash?

So (review feedback welcomed) in the Arduino Due SAM3x memory architecture compared to the AVR architecture:
Non-volatile flash memory
contains:

program instruction code (same as AVR)
bootloader (same as AVR)
all runtime C++ constants including incode string literals (different to AVR)

is accessed by:

C++ const data definition code and incode literals (different to AVR)
C++ instruction code (same as AVR)
PROGMEM, PSTR(), F(), pgmspace library *_P functions are not required and compile for platform compatibility only (different to AVR).

Volatile SRAM memory
contains:

variable dynamic storage, organised in a stack and heap structure (same as AVR)
no static/constant storage, which now stays in flash (different to AVR)

is accessed by:

C++ data definition code (same as AVR)

Usage

Heap fragmentation remains an issue to be managed. Preferencing local to global allocation, and avoiding dynamic heap allocation remains relevant to Arduino Due (e.g., Arduino strings)

Techniques to move constants to flash memory are not relevant for Due, but may be relevant for multi-board compatiblity.

Yes, the Arduino Due uses a flat memory model with a single address space for Flash and RAM. Therefore all constant data sits in flash and does not need to be copied to RAM at startup, like the AVR-based arduinos do. The progmem stuff for the AVR-based CPUs is required because they need to use different instructions to read data from flash than from RAM. This is no longer the case on the Due (nor most other 32-bit MCUs, such as the ESP32), and a string address in an instruction works just the same whether its in RAM or in Flash (as long as it's not written to, of course).
The F() macro is available for convenience, so that you can more easily write code that works for all Arduino boards. On the Due, it is basically implemented as no-op.
When you're working on the memory model of the Due, I might point to this question, showing that there's a bug in the memory management implementation of the Due, allowing unlimited memory allocation.


text:
How to remove Arduino Due and Mega shields without bending pins?
What's your suggested technique for reliably removing Arduino Due and Mega shields while minimizing the chance of bending the strip header pins?
For example, there's a similar discussion here where the asker ended up building a jig to keep everything parallel, but the main PCB was screwed down into the jig (a disadvantage). There is a heap of PCB Pullers/Extractors on the web, but they all seem to relate to edge connected cards.
I'm hoping for multiple answers / techniques. Interested to hear how you do it, or for you to upvote an answer you like. Maybe everybody is just doing the best they can with finger wriggling and manual pin straightening?

I use the handle of one of the toothbrushes I use to clean PCBs. Anything long, solid, and above all non-metallic, makes a good lever.

A non-conductive pair of reverse pliers might be useful, but I'm not sure they exist. https://www.expandingpliers.com/

slowly. one corner a little, second corner a little, ... and repeat

Thanks @Juraj, yes I suspect that's the most common approach and certainly what I have been doing, but I always seem to need to straighten pins afterwards.

I think I've found a nearly perfect tool in Knipex 45 10 170 reverse pliers. The only downside I can currently see is that they're conductive. The (unmodified) wooden clothes peg idea I found did not have enough grip or leverage.

To make them non-conductive (and add some protection for the boards as well), you might try a couple of plier-tip sleeves cut from plastic- or surgical rubber- tubing. Thanks for the tip on the pliers!

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

(source: niceshops.com)

Here's the easiest solution. Spend $10 on Amazon and buy one of these "hose pliers".  Put the tips on the double pin end. Gently squeeze. Simple!
https://www.amazon.com/dp/B07G5QSQFQ?ref_=cm_sw_r_apan_dp_Q2FM8GDW6EPGVSNA5XDZ_1

It's an indirect answer to my original question, but having made a number of Due/Mega shields over the year or so since then, I've started making the side pins ~3mm longer than the double row end pins. This helps.

@Majenko's comment suggesting using a toothbrush handle as a lever reminded me of auto trim levers. I remembered I had some, and have done some quick testing. They give a little more strength I would say, but not much (if any) more control than using fingers.


text:
Actual baud rate of UNO R3 Firmata protocol
Probably a silly question. But the Internet is confusing me.
The Firmata website says the default baud rate is 57600. But AFAIK, the baud rate set for UNO R3 is 9600(In Windows device manager, it say so). I'm making the Firmata client program and have to set the baud rate. I'm confused whether it's similar to the serial protocol or not.
[Using the StandardFirmata sketch]

The baud rate is whatever the program opening the port requests it to be. The stuff in the device manager is only the default used if nothing else is specified when the port is opened.
And the Firmata protocol just squirts bytes over serial. It's based upon the MIDI protocol, which is just serial.

So clearly I should declare as 9600?

If the sketch you are running has the baud set to 57600 then the program you use to communicate with your sketch has to be set to 57600. Ignore device manager. It's completely irrelevant.


text:
Insufficient RX signal delta when using MKR RS485 + Nano, but not Mega
I'm having an issue where an arduino Mega has been used to communicate with an RS485 bus, using an MKR shield [1] as a breakout board. When I build it with a Mega, the system works fine. I've torn down and rebuilt multiple times, and it works every time, no troubles.
However when I build it with a nano it does not work - rx is faulty. Devices on the bus can hear the nano, and a response pulse train is sent back correctly, so outgoing communication is fine.  However at the RX pin on the nano, the serial signal is present when viewed on an oscilloscope, but ranges between +5V and 4.5V, and the RX LED never flashes.
The layout is a simple wiring, there are no (relevant) external components (there is an LCD, but this works fine), just pin-pin connections.
Why is it the mega seems to work, but the nano not? I'm currently guessing that the /RE pin on the MKR RS485 device (MAX3157 [2]) is not being powered properly, and I am seeing the un-amplified serial output? I can't understand why this would be, though, as both the mega and the nano have the same rated max current per-pin.
I've checked the /RE line alone when disconnected, and it is correctly at 5V when not driven, and drives to 0V when the pin is pulled low.
Is there an alternative fix I could use to bring the +5V-4.5V to +5V-0V ? Do I need to have the
[1] MKR Shield schematic : https://www.jameco.com/Jameco/Products/ProdDS/2294031Schematic.pdf
[2] Max datasheet : https://datasheets.maximintegrated.com/en/ds/MAX3157.pdf

Are you sure that the RX pin is in input mode?

OK, answering myself here. It looks like the output of the shield is unable to drive hard enough against the internal pullups of the nano, for some reason. (Yes, its definitely in input mode, you check check the port values, and it is correct)
Leaving the RX output from the shield to float, it works fine, but if connected to an external pullup resistor, then it does not - and I get the same behaviour as when the RX is tied to the nano.
I've been unable to disable the nano's internal pullups in software for some reason. It looks like I will need to add a buffer to increase the drive current. This is a little irritating as it means another breakout board!


text:
ESP32 stack error when reading from BLE device
I'm using this code here to read data from a BLE thermometer using an ESP32.
The code sometimes works fine and i can get the data:
+ Connect : a4:c1:38:69:0c:ff
 * Connected a4:c1:38:69:0c:ff
 + Found our service
 + Found our characteristic
 + Notify callback for characteristic ebe0ccc1-7a0a-4b0c-8a1a-6ff2997da3a6
temp = 21.8 C ; humidity = 48.0 % ; voltage = 2.564 V
 * Disconnected a4:c1:38:69:0c:ff

Other times i get a CPU panic, related to a stack error:
+ Connect : a4:c1:38:69:0c:ff
 * Connected a4:c1:38:69:0c:ff
 + Found our service
 + Found our characteristic
 + Notify callback for characteristic ebe0ccc1-7a0a-4b0c-8a1a-6ff2997da3a6
temp = 21.8 C ; humidity = 47.0 % ; voltage = 2.564 V
Guru Meditation Error: Core  0 panic'ed (Unhandled debug exception)
Debug exception reason: Stack canary watchpoint triggered (btuT)
Core 0 register dump:
PC      : 0x4000c472  PS      : 0x00060a36  A0      : 0x8012b791  A1      : 0x3ffcf7e0
A2      : 0x3ffcf7f4  A3      : 0x00000000  A4      : 0x00000268  A5      : 0x3ffcfa14
A6      : 0x3ffde1ad  A7      : 0x00000026  A8      : 0x8012987e  A9      : 0x3ffd0270
A10     : 0x3ffdb99c  A11     : 0x3ffddca8  A12     : 0x3ffd050a  A13     : 0x00000001
A14     : 0x00000004  A15     : 0x00000000  SAR     : 0x00000010  EXCCAUSE: 0x00000001
EXCVADDR: 0x00000000  LBEG    : 0x4000c46c  LEND    : 0x4000c477  LCOUNT  : 0x00000003

ELF file SHA256: 0000000000000000

Backtrace: 0x4000c472:0x3ffcf7e0 0x4012b78e:0x3ffcf7f0 0x40129815:0x3ffcfa80 0x40125e62:0x3ffcfd10 0x401286e8:0x3ffcfd30 0x4012987b:0x3ffcffc0 0x40125e62:0x3ffd0250 0x401286e8:0x3ffd0270 0x4012987b:0x3ffd0500 0x40125e62:0x3ffd0790 0x401286e8:0x3ffd07b0 0x4012940a:0x3ffd0a40 0x40125e62:0x3ffd0a60 0x40129621:0x3ffd0a80 0x40125e62:0x3ffd0aa0 0x4012933d:0x3ffd0ac0 0x40129359:0x3ffd0ae0 0x40125e62:0x3ffd0b00 0x40125fa1:0x3ffd0b20 0x4012fb36:0x3ffd0b40 0x401042a6:0x3ffd0b60 0x4008ff9e:0x3ffd0b90

Rebooting...

I'm using an ESP-WROOM-32 with PlatformIO, what could be the issue?

the issue could be a software bug

Same problem, but I fix it. Use lib https://github.com/h2zero/NimBLE-Arduino

To help others. I resolved this issue by using the ArduinoBLE lib instead of the ESP32_BLE one I was using.

Usually we're looking for a little internal structure to answers rather than one-liners. So, if you have any useful details to add, that would be nice. But, otherwise if that resolved it cool. Welcome to ASE.


text:
Why doesn't this code for an 8x8 LED matrix work properly?
There's an Arduino Uno (Keyestudio KS0078) and a 788BS 8x8 LED matrix.
I built the circuit as on the image and ran this program:
#define MY_PERIOD 200

int displayColumn = 0;
uint32_t tmr1;

unsigned char Text[] = { 0x00, 0x1c, 0x22, 0x22, 0x22, 0x22, 0x22, 0x1c };

void Draw_point(unsigned char x, unsigned char y) {
  clear();
  digitalWrite(x + 2, HIGH);
  digitalWrite(y + 10, LOW);
  delay(1);
}

void show_num(void) {
  unsigned char i, j, data;
  for (i = 0; i < 8; i++) {
    data = Text[i];
    data <<= displayColumn;
    for (j = 0; j < 8; j++) {
      if (data & 0x01) {
        Draw_point(j, i);
      }
      data >>= 1;
    }
  }
}

void setup() {
  Serial.begin(9600);
  int i = 0;
  for (i = 2; i < 18; i++) {
    pinMode(i, OUTPUT);
  }
  clear();
}

void loop() {
  show_num();
  if (millis() - tmr1 >= MY_PERIOD) {
    tmr1 = millis();
    displayColumn++;
    if (displayColumn > 7) {
      displayColumn = 0;
    }
  }
}

void clear() {
  for (int i = 2; i < 10; i++)
    digitalWrite(i, LOW);
  for (int i = 10; i < 18; i++)
    digitalWrite(i, HIGH);
}

I got the code from the Keyestudio examples wiki and added a part with displayColumn and shifting to the left every 0.2 sec. But instead of fading out fully on the 7th step, one LED (x=0, y=6) stays on. Even if I stop executing show_num when displayColumn > 7 it stays on as long as there is power. Why?
UPD: I removed dynamic shifting in loop and set displayColumn in 5, 6 and 7 - the display showed correct result and was empty when displayColumn was equal to 7. Obviously the bug hides between "transitions".
UPD2: If I try the programm with other symbol, the bug on the step 7 always repeats with other LED which was the last lighted one on the step 6.
UPD3: Debug data by request of @thebusybee (repeated blocks removed)
x,y:2,1 x,y:3,1 x,y:4,1
x,y:1,2 x,y:5,2
x,y:1,3 x,y:5,3
x,y:1,4 x,y:5,4
x,y:1,5 x,y:5,5
x,y:1,6 x,y:5,6
x,y:2,7 x,y:3,7 x,y:4,7
displayColumn: 1
x,y:3,1 x,y:4,1 x,y:5,1
x,y:2,2 x,y:6,2
x,y:2,3 x,y:6,3
x,y:2,4 x,y:6,4
x,y:2,5 x,y:6,5
x,y:2,6 x,y:6,6
x,y:3,7 x,y:4,7 x,y:5,7
displayColumn: 2
x,y:4,1 x,y:5,1 x,y:6,1
x,y:3,2 x,y:7,2
x,y:3,3 x,y:7,3
x,y:3,4 x,y:7,4
x,y:3,5 x,y:7,5
x,y:3,6 x,y:7,6
x,y:4,7 x,y:5,7 x,y:6,7
displayColumn: 3
x,y:5,1 x,y:6,1 x,y:7,1
x,y:4,2
x,y:4,3
x,y:4,4
x,y:4,5
x,y:4,6
x,y:5,7 x,y:6,7 x,y:7,7
displayColumn: 4
x,y:6,1 x,y:7,1
x,y:5,2
x,y:5,3
x,y:5,4
x,y:5,5
x,y:5,6
x,y:6,7 x,y:7,7
displayColumn: 5
x,y:7,1
x,y:6,2
x,y:6,3
x,y:6,4
x,y:6,5
x,y:6,6
x,y:7,7
displayColumn: 6

x,y:7,2
x,y:7,3
x,y:7,4
x,y:7,5
x,y:7,6

displayColumn: 7

//many many empty strings
displayColumn: 8

add debugging code to your program

@jsotola I'v tried to get print of x, y from some code parts in some times and I have no idea anymore. After step 6 I found nothing activating the pixel. So seems the pixel still acive after previous teps but why so and why one? My experience is too poor to get it.

This can't be correct: data = Text[i];  data <<= displayColumn;. The first assignment will be overwritten by the second. It also looks odd that you are also incrementing  displayColumn  in the loop() as well as left shifting it in function shownum(). It will get some weird values in it. The original code, if it worked,  would have shown a '0'. What are you attempting to do, scroll the '0' from right to left across the display?

@6v6gt The second statement shifts the value in data. It is not a simple assignment overwriting the first. In contrast, the first statement is necessary to set a defined value in data.

@6v6gt yes, kinda. I don't know it looks odd or not cause I'm newbee in Arduino. But I see no logical contradictions in the order of assignment and besides it works strange but almost properly. The first assignment sets next byte ("the display line") in data, the second shifts it to left, and every 0.2 sec displayColumn increases by 1 ("one display column"). I try to animate original code slightly to understand better how to cook displays

Oops. I did not look at the the operator too closely. To me the code looks OK. You could try slowing the multiplexing down and look for any odd effects. When I work with a matrix display, I find it easier to define an array which matches the display, load the array, then write it out. This way, there is an intermediate state you can check.

Your code looks fine to me, I checked the algorithm with debug prints, but no output to an LED matrix. -- Your wiring according to the drawing looks fine, too. -- Please [edit] your question to clarify: How long does this single erroneous LED light? Your code repeats endlessly. Does this happen?

@thebusybee done.

@6v6gt I'll try it but I found this way too verbose. I ran same code as you said for a 7-segments display experiment but the method with byte sequence looks more interesting and laconic for me, so I intend to figure out why I encountered the bug.

Does this phenomenon of the unwanted led remaining on show when the code is continually scrolling? Obviously, you stopped the cycle to make the pictures. With the way function Draw_point() is written, where the display is cleared and then a led is switched on, it is inevitable that if there is a pause anywhere, the last led switched on will remain on. As a crude test, you could add another clear() after the delay(1) in function Draw_point() or perhaps after show_num()  in the loop().

Please add debug prints like that: 1) For x and y in Draw_point() without line break. 2) println() after the for loop over j in show_num(). 3) For displayColumn after increment and rollover in loop() with line break. -- In my reproduction I added also a flag that avoids multiple outputs when displayColumn did not change, but the room here is limited. You might try to insert the same. -- Check that in the last round with displayColumn = 7 no output happens. It should be like that because your pattern has no bit 0 set.

Commonly you don't drive LEDs in reverse to switch them off. Instead you disable their driver, in case of the Arduino you will change the pin mode to input. However, I don't see how this could be an explanation to the effect you observe.

@thebusybee added and there's really no output after the seventh step. I also tried the flag as you said but this way cant draw symbol normally: LEDs just flash for a moment after every displayColumn chsnging. Looks like pin's state resets every loop iteration

@6v6gt the phenomenon is present when the scrilling stops at the final step too, no only when the scrolling is contineous. And yes, final clear() inside Draw_point turns the LED off, and now the code works as needed. Seems I understand your assertion about clear(), this function must be called before any row rendering. The original code draws static symbol so there clear() placed right. I just move it in show_num into first for as first line and now scrolling works correctly. You can write your comment as an answer little more detailed and I'll check it as correct

Good. I'm pleased it works now and it was an interesting puzzle. Maybe even another solution is simply to move the clear() from the beginning of Draw_point() to the end. That should also stop the unwanted led "lingering" for 200ms during the scroll. Anyway, I can't test it so I'll leave you to write up an answer and include the code in it that works best for you. Also note what @thebusybee  implied about making clear() more efficient. Feel free to mention my name in the answer.

I loaded your initial code into a simulator to try it. Unfortunately, the simulator does not have a raw 8x8 dot matrix and I can't spend too long creating one out of individual leds.
What I have done is modified Draw_point() to print out the time (ms) the last led was lit for (if > 5ms). It gives results like "xLast=7, yLast=6, on for 202 ms" and only that led which does not agree exactly with your statement "one LED (x=0, y=6) stays on.". Anyway, it is here: https://wokwi.com/projects/389152026616860673

@6v6gt seems in the original example circuit the display used in "landscape orientation" instead of "portrait" and its coordinate system is overturned. Thank you for helping very much!

As found out during the discussion,
the display must be cleaned before drawing any new row. And since the clear() calling was at the beginning of the Draw_point() and this function was not used in the last step, cleaning was not executed before the last step. This is correct for static rendering but for scrolling it will be correct to move the clear() to the end of the Draw_point() then the project works correctly.
#define MY_PERIOD 200

int displayColumn = 0;
uint32_t tmr1;

unsigned char Text[] = { 0x00, 0x1c, 0x22, 0x22, 0x22, 0x22, 0x22, 0x1c };

void Draw_point(unsigned char x, unsigned char y) {
  digitalWrite(x + 2, HIGH);
  digitalWrite(y + 10, LOW);
  delay(1);
  clear();
}

void show_num(void) {
  unsigned char i, j, data;
  for (i = 0; i < 8; i++) {
    data = Text[i];
    data <<= displayColumn;
    for (j = 0; j < 8; j++) {
      if (data & 0x01) {
        Draw_point(j, i);
      }
      data >>= 1;
    }
  }
}

void setup() {
  Serial.begin(9600);
  int i = 0;
  for (i = 2; i < 18; i++) {
    pinMode(i, OUTPUT);
  }
}

void loop() {
  show_num();
  if (millis() - tmr1 >= MY_PERIOD) {
    tmr1 = millis();
    displayColumn++;
    if (displayColumn > 7) {
      displayColumn = 0;
    }
  }
}

void clear() {
  for (int i = 2; i < 10; i++)
    digitalWrite(i, LOW);
  for (int i = 10; i < 18; i++)
    digitalWrite(i, HIGH);
}

Thanks to users @6v6gt and @thebusybee for their help in finding the solution.

As an addition to your answer, this is for future visitors who want to learn more.
1. Programming by Accident
Your analysis is correct, mine in an early comment is wrong.
The last LED of the second last "picture" is not cleared when the last "picture" is drawn. This is because you clear the matrix only, if you switch on an LED.
This is your original code:
void Draw_point(unsigned char x, unsigned char y) {
  clear();
  digitalWrite(x + 2, HIGH);
  digitalWrite(y + 10, LOW);
  delay(1);
}

In your solution you clear the complete matrix after the delay, which results in the expected effect.
However, you did not analyze the underlying to the end. You changed something after a random suggestion, and it "works." I have seen this so many times.
We know that Draw_point() handles only one LED. So we do not need to reset all pins to their respective off levels, 14 of the 16 are already fine. It suffices to do this for the single LED just switched on.
void Draw_point(unsigned char x, unsigned char y) {
  digitalWrite(x + 2, HIGH);
  digitalWrite(y + 10, LOW);
  delay(1);
  digitalWrite(x + 2, LOW);
  digitalWrite(y + 10, HIGH);
}

2. Driving the LEDs in Reverse
As I mentioned in a comment, you drive the LEDs of the matrix in reverse, when they are off. We all know that comments will not be read, mostly. So I add this here. ;-)
Most LEDs stand some voltage in reverse. According to the 788BS' data sheet it has 5V as absolute maximum rating. I would not dare to apply that really.
All professionals drive their LED matrices such that only forward current is applied. All other LEDs are not driven at all.
The solution here is to change the pin mode of the pins.
#define MY_PERIOD 200

int displayColumn = 0;
uint32_t tmr1;

unsigned char Text[] = { 0x00, 0x1c, 0x22, 0x22, 0x22, 0x22, 0x22, 0x1c };

void Draw_point(unsigned char x, unsigned char y) {
  pinMode(x + 2, OUTPUT);
  digitalWrite(x + 2, HIGH);
  pinMode(y + 10, OUTPUT);
  digitalWrite(y + 10, LOW);
  delay(1);
  pinMode(x + 2, INPUT);
  pinMode(y + 10, INPUT);
}

void show_num(void) {
  unsigned char i, j, data;
  for (i = 0; i < 8; i++) {
    data = Text[i];
    data <<= displayColumn;
    for (j = 0; j < 8; j++) {
      if (data & 0x01) {
        Draw_point(j, i);
      }
      data >>= 1;
    }
  }
}

void setup() {
}

void loop() {
  show_num();
  if (millis() - tmr1 >= MY_PERIOD) {
    tmr1 = millis();
    displayColumn++;
    if (displayColumn > 7) {
      displayColumn = 0;
    }
  }
}

You don't need to clear() in setup(), because all pins are initially in "input" mode already.
3. About Flicker
You tried with no delay() and see only a dim display. This is correct as the time the LED is on is short compared to the time of the rest of the program.
With delay(2) you experience flicker. Let's think about the timing here.
There are different "pictures" during the scroll, with the listed number of LEDs switch on:

displayColumn
Number of LEDs switched on

0
16

1
16

2
16

3
11

4
9

5
7

6
5

7
0

Because the Arduino is quite fast, we came approximate the calculations by neglecting the rest of the program.
Each single LED is shown for 2 ms according to delay(2), so a complete picture sums up to repetition periods between (nearly) 0 ms (displayColumn = 7) and 32 ms (displayColumn = 0 to 2). The reciprocal gives us the display frequency, many know the term "frames per second" or frame rate. The lowest frame rate is with the longest period: 1 / 0.032 s = 31.25 Hz. Our eyes see this as flickering. BTW, as soon as the "picture" has fewer LEDs, the display will stop flickering.
Commonly human eyes see no flicker if the frame rate exceeds about 50 to 60 Hz. With delay(1) the periods are only half as long as with delay(2), of course. The lowest frame rate is therefore 62.5 Hz, good enough for no flicker experience.
Please be aware that the frame rate drops with the number of LEDs switched on. If you want to have at least 50 Hz with delay(1), you cannot have more than 20 LEDs: 1 / 50 Hz = 20 ms, which corresponds to 20 LEDs.
The solution here is to show a complete row at the same time. Because then there are just 8 rows to sequence, you can raise to delay(2) again: 8 rows * 2 ms < 20 ms. The specific code is left as an exercise to the reader. Please be aware that you need to take electrical maximum ratings into account. The MCU of the Arduino has limits to the sourced current.
4. Final Note
You might wonder why the linked resource (the Keyestudio examples wiki) shows this "not-so-perfect" source code. Well, as we can see from the bad formatting of the example, it was hacked down in a hurry and without being aware that beginners will be misguided.
Take all such resources with a lot of caution. Unfortunately, this is absolutely necessary. (This includes my answer here, too.)

Just like that, I thought whatever my programm was far from optimum. I read your comment about mode switch but decided to search for materials on this topic because I never saw this method before, so thank you for the explaining with working example!
I also should to note that your first variant needs the clear() executed in the setup().
And one final question - why exactly does delay(1) work as it should? No delay - symbol is dim because we switch it on and off instantly, it's too little time. But the display begins to flicker when delay = 2 or higher. Why 1?


text:
EEPROM - Arduino
In my recent project, I want to store values permanently. So for that, I want to use the EEPROM. I searched for it and read about it. Now, I have some questions.
Questions:

How many locations are there in the EEPROM? (For Arduino Uno & Mega)
I read that an EEPROM has a limit of 100,000 write cycles per
  single location. That means if one location is used 100,000 times then
  we can use another after that? Or overall the EEPROM has a limit of 100,000 write cycles?
So, what about reading the contents of the EEPROM? Does it have the same limit?
And what is the starting location (address) of the EEPROM? (For Arduino Uno & Mega)

EDIT:1

Suppose I store the HIGH value of LED in one location and the LOW value of LED in another one. Then now read the value from that locations. Now how many times I can read this value? So what about write cycle? It just uses for only one time maybe?

Any better option for storing data permanently?

(1) How many locations are there in EEPROM? (For ARDUINO UNO & MEGA)

Read the datasheet for the chip on the board. It tells you how many bytes or kilobytes the chip has for EEPROM. For instance the ATMega328P on the Uno has 1024 bytes (1k).

(2) As I read out EEPROM has a limit of 100,000 write cycles per single location. That means If one location is used 100,000 times then we can use another after that? Or Overall EEPROM has a limit of 100,000 write cycle?

Each cell has at least a 100,000 write limit. Or more specifically a 100,000 erase limit (since a cell must be erased before writing).

(3) So, what about reading the content from EEPROM? Has it maybe same limit?

No, no limit - the limit as I mentioned is on erasing: you don't erase when reading.

(4) And what is starting location(address) of EEPROM? (For ARDUINO UNO & MEGA)

Zero.  It's not really part of any address space, it uses special instructions and registers to get at it.


text:
Detect where touch happened on a big capacitive electrode
I have a big-ish electrode (10cm x 10cm) that works fine for detecting touch over the whole electrode (as a boolean - simple touch vs. release) but I was wondering if there was a way to detect where on the electrode there was a touch, using filtered data or something? I saw this link where the person made a capacitive touch grid. All their copper tape rows/columns are touching. When I try to connect multiple clips to a single electrode though (more-or-less what they did) my MPR121 becomes unresponsive.
I'm using an Arduino Uno, a Sparkfun MPR121 capsense breakout, and this library for interacting with the MPR121.
Here's a basic program I have running at the moment just to check out an average of filtered data readings to see if there's a pattern. There isn't. The readings are anywhere between 250 and 580 no matter where the electrode is touched.
#include <MPR121.h>
#include "Wire.h"

int readingSum = 0;

void setup() {
  Serial.begin(9600);
  Wire.begin();
  MPR121.begin(0x5A);
  MPR121.setInterruptPin(2);

  MPR121.setTouchThreshold(50);
  MPR121.setReleaseThreshold(40);

  delay(1000);
}

void loop() {
  if (MPR121.touchStatusChanged()) {
    MPR121.updateAll();
    if (MPR121.isNewTouch(0)) {
      for (uint8_t i = 0; i < 8; i++) {
          readingSum += MPR121.getFilteredData(0);
      }
      Serial.println(readingSum / 8);
    }
    readingSum = 0;
  }
}

no, there is not

As @jsotola mentioned in the comments, no I don’t think there is a way to take a single electrode and turn it into a touchpad. Touchpads rely on a grid of addressable capacitance points to resolve a location.
I didn’t spend a lot of time investigating the link you referenced. However I wonder if you allowed for the adhesive backing on the copper tape when you attempted to replicate the example. It looks to me to be rows and columns of copper conductor separated by a thin layer of adhesive. Not the same thing as one big conductor.


text:
Input Oscillating Wildly
I'm trying to read an input from a switch but instead of getting 0 and 1 for closed/open, I'm getting 0 and a rapid series of 1s and 0s. Originally I tried (and failed) to simply read a rotary encoder but when I swap it for a standard rocker switch or even connect wires directly then it's the same.
This is my first time trying to get an input into an Arduino so I'm probably missing something quite straightforward.
I've got ground going to one pin of the switch and pin 2 to the other.
Here's the code I'm using to see if the switch is on or off.
void setup() {
  pinMode (2, INPUT);
  Serial.begin(9600);
}

void loop() {
 Serial.println(digitalRead(2));
}

In addition to @Bra1n's answer, this sort of problem can also usually be solved by grounding the switch via a resistor.

Your code also need a debounce method if its a hardware error and the button is damaged.
delay(20);

Pins configured as INPUT are in a high impedance state and very sensitive to electrical noise from the environment, especially with wires connected to them See Arduino Tutorial
Try using INPUT_PULLUP in your pinMode statement.
Additionally you might want to investigate switch debouncing methods for when your switch is operated.

Yes PULLUP has solved it, thanks!!


text:
Second I2C on Due RTClib, can't start
I am using SDA1, SCL1 for my DS3232 with RTClib on Due. It works on a Mega2560 on SDA, SCL.
I ran I2c_test with success after I inserted
#define Wire Wire1
However with ds3231.ino this define doesnot work. Looking at RTClib.cpp it looks like I can pass a parameter to Wire.begin(). I have tried sda1, scl1 and Wire1. They didnot work.
Thanks for the help.

Given you're talking about 5V and 3.3V Arduinos with what sounds like a single RTC breakout, it would be good to know exactly how you're hooking this up.  If ds3231.ino is one of the examples, you can show what changes you made to the example, then anyone with a Due and one of those modules can recreate your situation for testing.

What happens if you use the unmodified ds3231.ino example with line 333 of rtclib.h changed to reference &Wire1 rather than &Wire? (Ref https://github.com/adafruit/RTClib/blob/master/src/RTClib.h). Are you able to post your sketch and serial monitor output?

Does the unmodified ds3231.ino example sketch work if your RTC is connected to the Due Wire port (rather than Wire1)?

ds3231.ino is from RTClib. It does run on I2C port 1 (pins 20, 21), But not on port 2 (SDA1, SCL1) aka Wire1. I2C_Test.ino finds response at 0x50 and 0x68 meaning at least time keeping is working on the ds3231. Adding #define Wire Wire1 to ds3231 shows no effect. Examining RTCLib.cpp shows this define for  #ifdef AVR
#include <avr/pgmspace.h>
#elif defined(ESP8266)
#include <pgmspace.h>
#elif defined(ARDUINO_ARCH_SAMD)
// nothing special needed
#elif defined(ARDUINO_SAM_DUE)
#define PROGMEM
#define pgm_read_byte(addr) (*(const unsigned char *)(addr))
#define Wire Wire1
#endif

@Marlin Turbett, that's good, so ds3231.ino unmodified runs Ok on pins 20 and 21 (Wire). Are you able to try modifying line 333 of rtclib.h to reference &Wire1 and retry it on the Wire1 port? I'm not sure that simply #defining in your script is going to have a positive impact on the library behavior.

The unmodified RTCLib DS3231 sample code running on Arduino Due defaults to the Wire I2C connection on pins 20 SDA and 21 SCL.

To enable the same sketch to connect to a device connected to the Wire1 I2C connection on pins 70 SDA1 and 71 SCL1, I changed line 333 of RTClib.h to reference &Wire1 rather than &Wire.

Successful test output from the Wire1 connection is shown.

Update:
OP @Marlin Turbett pointed out that adding #define Wire Wire1 to RTClib.h also works. I agree. The modification of line 333 of RTClib.h which I suggested originally is I think the minimal change to get the desired behaviour. But using substitution to achieve the same change also works. A global change across the whole library may be a bigger hammer than might be desirable.
#define substitution works in single compilation units, so the #define needs to be in the same compilation unit as the text to be overwritten. In this case in the library, not the sketch.
The technique of using #define directives to overwrite which Wire port is referenced in RTClib is used selectively by the library depending on arduino architecture (see RTClib.cpp lines 46-73, below).
#include "RTClib.h"
#if defined(__AVR__) && !defined(TWCR) && defined(USICR)
#include <TinyWireM.h>
#define Wire TinyWireM
#else
#include <Wire.h>
#endif

#ifdef __AVR__
#include <avr/pgmspace.h>
#elif defined(ESP8266)
#include <pgmspace.h>
#elif defined(ARDUINO_ARCH_SAMD)
// nothing special needed
#elif defined(ARDUINO_SAM_DUE)
#define PROGMEM
#define pgm_read_byte(addr) (*(const unsigned char *)(addr))
#define Wire Wire1
#endif

#if (ARDUINO >= 100)
#define _I2C_WRITE write ///< Modern I2C write
#define _I2C_READ read   ///< Modern I2C read
#else
#include <WProgram.h>
#define _I2C_WRITE send   ///< Legacy I2C write
#define _I2C_READ receive ///< legacy I2C read
#endif

I don't know why the library code at lines 60 to 64 (for ARDUINO_SAM_DUE) was not effective, and I hope to do some more testing. Maybe others here can shed some light?
Update 2: Noting the link from @Edgar Bonet in the comments to the new example sketch customWire_DS3231onSAMD21.ino in RTClib 1.14.1 which specifically caters for multiple i2c ports. Nice one.

Thank you. That works. Lines 54 to 64 in RTClib.cpp looks like it substitutes Wire1 for Wire on Due. However, that is not working for me.

Great! If you can; please give the answer the tick to show it answers your question.

While tour fix works I put #define Wire Wire1 in RTClib.h. This works too. My opinion at this point is my Arduino setup for the Due can't fine the $defines that are already in the library.

I’ll have another look and see if I can replicate your result.

There’s an interesting discussion about compilation units on the Arduino forum that suggests that the sketch and the library are different compilation units and can’t share #defines. They discuss alternatives. https://forum.arduino.cc/t/compiler-not-detecting-external-header-file-with-defines/526633/8

Re “I don't know why the library code at lines 60 to 64 (for ARDUINO_SAM_DUE) was not effective”: This #define is vestigial from before the library allowed selecting a custom I2C interface. It serves no purpose anymore.

I just submitted a pull request to remove this confusing, dead pre-processor code.


text:
How to control continuous rotation servo via HC-12 rf module
I am working on a project to wirelessly control a continuous rotation servo...something like a wireless vending machine.
The problem I am having is controlling how many revolutions the servo is making. During testing I used a button and had no issues getting the delay to work properly. Now that it's connected to the HC-12 RF module I can't get the delay to control how many rotations the servo makes. The servo I'm using is the FS90R.
#include <SoftwareSerial.h>
#include <Servo.h>
SoftwareSerial mySerial(2, 3); // RX, TX
Servo badservo;

int pos = 92;
unsigned long last = millis();

void setup() {
  mySerial.begin(9600);
  badservo.attach(9);
  badservo.write(pos);
}

void loop() {
  if(mySerial.available() > 1){
    int input = mySerial.parseInt();//read serial input and convert to integer (-32,768 to 32,767)
    int servpos = badservo.read();
    if(millis() - last > 250){
      if(servpos == 92 && input == 1234){
        badservo.write(0);
        delay(470);
        //mySerial.println(8894);
      }
      else{
        badservo.write(pos);
        //mySerial.println(8894);
      }
    }
  mySerial.flush();//clear the serial buffer for unwanted inputs
  last = millis();
  }
  delay(20);//delay little for better serial communication
}

With the servo that I'm using has a stop position of 92, meaning when I do
servo.write(92);
it will stop the servo. Also, the 470 delay was tested with a button and was a single full rotation.
Now, with the HC-12 module, I can't get the servo to rotate less than 2.5 times.
Anyone have any idea what I'm doing wrong? The goal is to get the servo to rotate only once when the RF module receives the proper signal.

Feeling that adding a delay to a serial receive routine will result in "better serial communication" is pretty much always a bad idea, and indicates a severely broken underlying design.  You probably don't want to call flush() either - what you want, is sound event-driven code.

You can't rely on a specific delay being one rotation - especially when you are using SoftwareSerial. SoftwareSerial breaks many things, and anything that uses interrupts (such as the Servo library) gets broken by it. It's a real interrupt hog.
The proper way of doing it is to use a rotary encoder on the servo to report the position (or change in position) so that you know where the servo is. That's really the only reliable method of getting the servo to perform precise operations.
By the way:
mySerial.flush();//clear the serial buffer for unwanted inputs

does absolutely nothing. The operation of flush() changed when the Arduino API turned one. It is now supposed to wait until both the TX circular buffer and the UART TX FIFO are empty. It has nothing to do with emptying any inputs.  Instead you want:
while (mySerial.read() != -1);

Thanks for clearing that up! Which library would you recommend for communication with the HC-12 wireless device?

There are numerous alternatives to SoftwareSerial, and most of them are considerably better - but all software serial implementations suck. You really want to use hardware serial, but most small Arduino boards only have one UART which is used by the USB interface.

Ah. I should note that I'm using a Arduino Pro Mini for this project as everything has to be very compact. Can you point me to any resources that will help with this? There's a lot of info out there in the few Google searches I just did.

You might consider the Teensy-LC instead; I believe it has multiple hardware serial ports, and is quite small.  However, it introduces the complexity of its own IDE plugin.  It should be possible to get this to work, if awkwardly, with an ordinary Arduino and soft serial.