text:
How can I operate the leds and neopixel strips together (at the same time)?
Here's the code I wrote:
#include <Adafruit_NeoPixel.h>
#ifdef __AVR__
#include <avr/power.h> // Required for 16 MHz Adafruit Trinket
#endif

int latchPin = 8;
int clockPin = 12;
int dataPin = 11;

int numOfRegisters = 2;
byte* registerState;

long effectId = 0;
long prevEffect = 0;
long effectRepeat = 0;
long effectSpeed = 30;

#define LED_PIN    2
#define LED_COUNT 24

Adafruit_NeoPixel strip(LED_COUNT, LED_PIN, NEO_GRB + NEO_KHZ800);

void setup() {
  #if defined(__AVR_ATtiny85__) && (F_CPU == 16000000)
  clock_prescale_set(clock_div_1);
  #endif

  strip.begin();           // INITIALIZE NeoPixel strip object (REQUIRED)
  strip.show();            // Turn OFF all pixels ASAP
  strip.setBrightness(50); // Set BRIGHTNESS to about 1/5 (max = 255)

  //Initialize array
  registerState = new byte[numOfRegisters];
  for (size_t i = 0; i < numOfRegisters; i++) {
    registerState[i] = 0;
  }

  //set pins to output so you can control the shift register
  pinMode(latchPin, OUTPUT);
  pinMode(clockPin, OUTPUT);
  pinMode(dataPin, OUTPUT);
}

void loop() {
  do {
    effectId = random(6);
  } while (effectId == prevEffect);
  prevEffect = effectId;

  switch (effectId) {
  case 0:
    effectRepeat = random(1, 2);
    break;
  case 1:
    effectRepeat = random(1, 2);
    break;
  case 3:
    effectRepeat = random(1, 5);
    break;
  case 4:
    effectRepeat = random(1, 2);
    break;
  case 5:
    effectRepeat = random(1, 2);
    break;
  }

  for (int i = 0; i < effectRepeat; i++) {
    effectSpeed = random(10, 90);

    switch (effectId) {
    case 0:
      effectA(effectSpeed);
      break;
    case 1:
      effectB(effectSpeed);
      break;
    case 3:
      effectC(effectSpeed);
      break;
    case 4:
      effectD(effectSpeed);
      break;
    case 6:
      effectE(effectSpeed);
      break;
    }
  }

  // Fill along the length of the strip in various colors...
  colorWipe(strip.Color(255,   0,   0), 1); // Red
  colorWipe(strip.Color(  0, 255,   0), 1); // Green
  colorWipe(strip.Color(  0,   0, 255), 1); // Blue

  // Do a theater marquee effect in various colors...
  theaterChase(strip.Color(127, 127, 127), 1); // White, half brightness
  theaterChase(strip.Color(127,   0,   0), 1); // Red, half brightness
  theaterChase(strip.Color(  0,   0, 127), 1); // Blue, half brightness

  rainbow(1);             // Flowing rainbow cycle along the whole strip
  theaterChaseRainbow(1); // Rainbow-enhanced theaterChase variant
}

void colorWipe(uint32_t color, int wait) {
  for (int i=0; i<strip.numPixels(); i++) { // For each pixel in strip...
    strip.setPixelColor(i, color);          //  Set pixel's color (in RAM)
    strip.show();                           //  Update strip to match
    delay(wait);                            //  Pause for a moment
  }
}

void theaterChase(uint32_t color, int wait) {
  for (int a=0; a<10; a++) {  // Repeat 10 times...
    for (int b=0; b<3; b++) { //  'b' counts from 0 to 2...
      strip.clear();          //   Set all pixels in RAM to 0 (off)
      // 'c' counts up from 'b' to end of strip in steps of 3...
      for (int c=b; c<strip.numPixels(); c += 3) {
        strip.setPixelColor(c, color); // Set pixel 'c' to value 'color'
      }
      strip.show(); // Update strip with new contents
      delay(wait);  // Pause for a moment
    }
  }
}

void rainbow(int wait) {
  for (long firstPixelHue = 0; firstPixelHue < 5*65536; firstPixelHue += 256) {
    for (int i=0; i<strip.numPixels(); i++) { // For each pixel in strip...
      int pixelHue = firstPixelHue + (i * 65536L / strip.numPixels());
      strip.setPixelColor(i, strip.gamma32(strip.ColorHSV(pixelHue)));
    }
    strip.show(); // Update strip with new contents
    delay(wait);  // Pause for a moment
  }
}

void theaterChaseRainbow(int wait) {
  int firstPixelHue = 0;      // First pixel starts at red (hue 0)
  for (int a=0; a<30; a++) {  // Repeat 30 times...
    for (int b=0; b<3; b++) { //  'b' counts from 0 to 2...
      strip.clear();          //   Set all pixels in RAM to 0 (off)
      // 'c' counts up from 'b' to end of strip in increments of 3...
      for (int c=b; c<strip.numPixels(); c += 3) {
        // hue of pixel 'c' is offset by an amount to make one full
        // revolution of the color wheel (range 65536) along the length
        // of the strip (strip.numPixels() steps):
        int hue   = firstPixelHue + c * 65536L / strip.numPixels();
        uint32_t color = strip.gamma32(strip.ColorHSV(hue)); // hue -> RGB
        strip.setPixelColor(c, color); // Set pixel 'c' to value 'color'
      }
      strip.show();                // Update strip with new contents
      delay(wait);                 // Pause for a moment
      firstPixelHue += 65536 / 90; // One cycle of color wheel over 90 frames
    }
  }
}

void effectA(int speed){
  for (int i = 0; i < 16; i++) {
    for (int k = i; k < 16; k++) {
      regWrite(k, HIGH);
      delay(speed);
      regWrite(k, LOW);
    }

    regWrite(i, HIGH);
  }
}

void effectB(int speed) {
  for (int i = 15; i >= 0; i--) {
    for (int k = 0; k < i; k++) {
      regWrite(k, HIGH);
      delay(speed);
      regWrite(k, LOW);
    }

    regWrite(i, HIGH);
  }
}

void effectC(int speed){
  int prevI = 0;
  for (int i = 0; i < 16; i++) {
    regWrite(prevI, LOW);
    regWrite(i, HIGH);
    prevI = i;

    delay(speed);
  }

  for (int i = 15; i >= 0; i--) {
    regWrite(prevI, LOW);
    regWrite(i, HIGH);
    prevI = i;

    delay(speed);
  }
}

void effectD(int speed){
  for (int i = 0; i < 8; i++) {
    for (int k = i; k < 8; k++) {
      regWrite(k, HIGH);
      regWrite(15 - k, HIGH);
      delay(speed);
      regWrite(k, LOW);
      regWrite(15 - k, LOW);
    }

    regWrite(i, HIGH);
    regWrite(15 - i, HIGH);
  }
}

void effectE(int speed) {
  for (int i = 7; i >= 0; i--) {
    for (int k = 0; k <= i; k++) {
      regWrite(k, HIGH);
      regWrite(15 - k, HIGH);
      delay(speed);
      regWrite(k, LOW);
      regWrite(15 - k, LOW);
    }

    regWrite(i, HIGH);
    regWrite(15 - i, HIGH);
  }
}

void regWrite(int pin, bool state) {
  //Determines register
  int reg = pin / 8;
  //Determines pin for actual register
  int actualPin = pin - (8 * reg);

  //Begin session
  digitalWrite(latchPin, LOW);

  for (int i = 0; i < numOfRegisters; i++) {
    //Get actual states for register
    byte* states = &registerState[i];

    //Update state
    if (i == reg){
      bitWrite(*states, actualPin, state);
    }

    //Write
    shiftOut(dataPin, clockPin, MSBFIRST, *states);
  }

  //End session
  digitalWrite(latchPin, HIGH);
}

This comes up ALL THE TIME. Don't use delay. Do a Google search on "arduino blinkwithoutdelay" and read one of the various write-ups on the subject.
Here's a writeup that looks pretty good:
https://learn.adafruit.com/multi-tasking-the-arduino-part-1/using-millis-for-timing


text:
7 segment 4 digit not showing numbers 2,3 and 0
https://www.instructables.com/Using-a-4-digit-7-segment-display-with-arduino/
I used this link to make my circuit and I used this code also but some numbers like 2,3 and 0 doesn't display correctly.

So your answer given here is not quite accurate? https://arduino.stackexchange.com/questions/77524/4-digit-7-segment-display-not-showing-value-properly/80525#80525

It looks like you have the center segment and the top left vertical segment reversed. For the image you show, if you switched the on/off states of those 2 segments, you'd see 1230.
I don't know if the problem is in your code or in your wiring. The simplest fix would be to swap the pins for those 2 segments.

Thanks it works.

You should accept my answer if it solved your problem. That is a strong norm on this site. Up-voting helpful answers is optional (once you have enough reputation for that) but also considered good form.

source: Stack Exchange

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

sort: votes


text:
Communication between two nrf24l01
i can't figure this out, i have a task to get data from RX module that led has turned on.
The Idea. I press push button on TX part, and led diode turn on, on RX part. Then RX send's data to TX that led have been turn'd on and print "LED HAVE BEEN TURNED ON".
I have made turn on part, but i struggle with sending from rx to tx. When i add this part code just stops
 while (!radio.available()); {
   radio.read(&buttonState, sizeof(buttonState));
   if (buttonState == 0) {
     Serial.print("LED HAS BEEN TURNED ON");
     Serial.print("\n");

//RX
#include <SPI.h>
#include <nRF24L01.h>
#include <RF24.h>

#define led1 6
#define mot 5

int buttonState = 0;

bool ledbutton = 0;

RF24 radio(9, 8);
const byte address[][6] = {"00001", "00002"};

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

  pinMode(led1, OUTPUT);
  digitalWrite(led1, HIGH);

  pinMode(mot, OUTPUT);
  analogWrite(mot, HIGH);

  radio.begin();
  radio.setChannel(80);
  radio.setDataRate(RF24_250KBPS);
  radio.setPALevel(RF24_PA_HIGH);

  radio.openWritingPipe(address[0]); // 00001
  radio.openReadingPipe(1, address[1]); // 00002

  radio.setPALevel(RF24_PA_MIN);

}
void loop() {
  radio.startListening();
  if ( radio.available()) {
    while (!radio.available()); {
      radio.read(&buttonState, sizeof(buttonState));

      ledON();
      motON();
    }
    radio.stopListening();
    ledbutton = digitalRead(led1);
    radio.write(&ledbutton, sizeof(ledbutton));
  }
}

void ledON() {
  if (buttonState == 1) {
    digitalWrite(led1, LOW);
  }
  else  if (buttonState == 0) {
    digitalWrite(led1, HIGH);
    Serial.print("LED ON");
    Serial.print("\n");
  }

}

void motON() {
  if (buttonState == 3) {
    analogWrite(mot, 0);
  }
  else  if (buttonState == 2) {
    analogWrite(mot, 255);
    Serial.print("MOTOR ON");
    Serial.print("\n");
  }

}

//TX
#include <SPI.h>
#include <nRF24L01.h>
#include <RF24.h>

#define buttonPin1 7
#define buttonPin2 4

int buttonState1 = 0;
int buttonState2 = 0;

int ledbutton = 0;

RF24 radio(9, 8);
const byte address[][6] = {"00001", "00002"};

void setup() {
  pinMode(buttonPin1, INPUT_PULLUP);
  pinMode(buttonPin2, INPUT_PULLUP);

  Serial.begin(9600);

  radio.begin();
  radio.setChannel(80);
  radio.setDataRate(RF24_250KBPS);
  radio.setPALevel(RF24_PA_HIGH);

  radio.openWritingPipe(address[1]); // 00002
  radio.openReadingPipe(1, address[0]); // 00001

}
void loop() {
  radio.stopListening();
  buttonState1 = digitalRead(buttonPin1);
  buttonState2 = digitalRead(buttonPin2);

  LedControl();
  MotorControl();

  radio.write(&buttonState1, sizeof(buttonState1));
  radio.write(&buttonState2, sizeof(buttonState2));

  delay(5);
  radio.startListening();
  while (!radio.available()); {
    radio.read(&ledbutton, sizeof(ledbutton));
    if (ledbutton = 0) {
      Serial.print("LED HAS BEEN TURNED ON");
      Serial.print("\n");
    }
  }
}

void LedControl() {
  if (buttonState1 == 1) {
    buttonState1 = 1;
  }
  else  if (buttonState1 == 0) {
    buttonState1 = 0;
  }
  Serial.print(buttonState1);
  Serial.print("\n");
}
void MotorControl() {
  if (buttonState2 == 1) {
    buttonState2 = 3;
  }
  else  if (buttonState2 == 0) {
    buttonState2 = 2;
  }
  Serial.print(buttonState2);
  Serial.print("\n");
}

while (!radio.available()); {. Why do a while loop, when you just checked that there is radio-data available? Also, using a semi-colon and following that with a curly-bracket is terrible. I'm not sure what it is you want to do here. I think you could remove that line entirely (including the closing bracket 3 lines below).

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


text:
Connecting Seeeduino XIAO 3.3 V out to dual H-bridge driver module (L298N) with TTL compatible inputs
The H-bridge module uses TTL compatible logic, but the chip allows these values (based on the L298N data sheet):

Symbol
Parameter
Min.
Max.

ViL
Input Low Voltage (pin 5, 7, 10, and 12)
-0.3 V
1.5 V

ViH
Input High Voltage (pin 5, 7, 10, and 12)
2.3 V
VSS

Am I correct to assume that I do not need to step-up the logic signal (from 3.3 V to 5 V) for this to work, but can I connect straight to the input?
Schematic in mind:

You are you using the Seedstudio L298N board, right? not the bare L298N? That board have pull-up resistors on the it, that pull to 5V. Not sure what 5V through a 10kOhm resistor does the the IO pin on a 3.3V MCU. It's probably fine, and it's only an issue while the pin is an INPUT, which it only is till you run your code (only during bootloader and startup).

Am I correct to assume that I do not need to step-up the logic signal (from 3.3V to 5V) for this to work, but can connect straight to the input?

You are correct. The input has to be above 2.3V to register as HIGH and below 1.5V to register as LOW. You have 3.3V for HIGH and near 0V for LOW, which fits those criteria perfectly.

Thank you! I was trying to add "Seeeduino XIAO" as tag but do not have enough points, can you do that? I think it would help.

@MeSo2 No, I won't do that. If we added every board that existed as a tag we'd overload the database. Only the main Arduino boards and very common third party boards ones have tags. The Xiao isn't a common one - I have never heard of it.

Comparatively recent small form factor board using the same chip as the various "zero" boards.  XIAO, specifically, doesn't really enter into the actual question though where its role is just as a 3.3v logic level MCU.

@timemage So, it's YAABB...  Yet Another ARM Based Board...

Yes, though it seems to be gaining a following; it may eventually warrant a tag for dealing with its actual eccentricities.  Perhaps not yet.

@timemage Maybe I should add the tag "yaabb" ;)

Could not resist up-voting that. =)

@timemage "For general I/O pins: Working voltage of MCU is 3.3V. Voltage input connected to general I/O pins may cause chip damage if it' higher than 3.3V." found here: Seeeduino XIAO

@Majenko is there any issue with the Seedstudio L298N board having pull-up resistors to 5V.

@Gerben typically there's no problem. The resistor drops the current to 170uA which is far below the rating of most ESD protection diodes... (looking at the SAMD21 datasheet 1mA is the worst case minimum, and 720uA is below that.)

@MeSo2, I get that, but I'm unclear on why you're saying this to me.

@timemage I think he's confusing input and output....

@Majenko, if I had to guess, I'd say he may be under the impression that a XIAO is somehow different from an Arduino Zero (which uses the same microcontroller) with respect to the 3.3v signals; it isn't.

@timemage XIAO pin 1, 2, 8 - 11 will be used as outputs. I never used an Arduino, but got my feet wet using a propeller microcontroller back in 2014.


text:
Trying to use a gyro sensor and having issues
My setup is Arduino Mega.
I have a gyro sensor that I'm trying to use to measure the acceleration or G force in X axis (forward movement).
So far I'm trying to figure a way to use the value of Acc or Ax (acceleration X axis) in an if statement in order to activate a relay.
I tried everything and the example file the supplier sent is so confusing.
Please help. I'm attaching the main code and the header file too!
#include <Wire.h>
#include <JY901.h>
/*
Test on Uno R3.
JY901   UnoR3
TX <---> 0(Rx)
*/
void setup()
{
  Serial.begin(9600);
}

void loop()
{
  //print received data. Data was received in serialEvent;
  Serial.print("Time:20");Serial.print(JY901.stcTime.ucYear);Serial.print("-");Serial.print(JY901.stcTime.ucMonth);Serial.print("-");Serial.print(JY901.stcTime.ucDay);
  Serial.print(" ");Serial.print(JY901.stcTime.ucHour);Serial.print(":");Serial.print(JY901.stcTime.ucMinute);Serial.print(":");Serial.println((float)JY901.stcTime.ucSecond+(float)JY901.stcTime.usMiliSecond/1000);

  Serial.print("Acc:");Serial.print((float)JY901.stcAcc.a[0]/32768*16);Serial.print(" ");Serial.print((float)JY901.stcAcc.a[1]/32768*16);Serial.print(" ");Serial.println((float)JY901.stcAcc.a[2]/32768*16);

  Serial.print("Gyro:");Serial.print((float)JY901.stcGyro.w[0]/32768*2000);Serial.print(" ");Serial.print((float)JY901.stcGyro.w[1]/32768*2000);Serial.print(" ");Serial.println((float)JY901.stcGyro.w[2]/32768*2000);

  Serial.print("Angle:");Serial.print((float)JY901.stcAngle.Angle[0]/32768*180);Serial.print(" ");Serial.print((float)JY901.stcAngle.Angle[1]/32768*180);Serial.print(" ");Serial.println((float)JY901.stcAngle.Angle[2]/32768*180);

  Serial.print("Mag:");Serial.print(JY901.stcMag.h[0]);Serial.print(" ");Serial.print(JY901.stcMag.h[1]);Serial.print(" ");Serial.println(JY901.stcMag.h[2]);

  Serial.print("Pressure:");Serial.print(JY901.stcPress.lPressure);Serial.print(" ");Serial.println((float)JY901.stcPress.lAltitude/100);

  Serial.print("DStatus:");Serial.print(JY901.stcDStatus.sDStatus[0]);Serial.print(" ");Serial.print(JY901.stcDStatus.sDStatus[1]);Serial.print(" ");Serial.print(JY901.stcDStatus.sDStatus[2]);Serial.print(" ");Serial.println(JY901.stcDStatus.sDStatus[3]);

  Serial.print("Longitude:");Serial.print(JY901.stcLonLat.lLon/10000000);Serial.print("Deg");Serial.print((double)(JY901.stcLonLat.lLon % 10000000)/1e5);Serial.print("m Lattitude:");
  Serial.print(JY901.stcLonLat.lLat/10000000);Serial.print("Deg");Serial.print((double)(JY901.stcLonLat.lLat % 10000000)/1e5);Serial.println("m");

  Serial.print("GPSHeight:");Serial.print((float)JY901.stcGPSV.sGPSHeight/10);Serial.print("m GPSYaw:");Serial.print((float)JY901.stcGPSV.sGPSYaw/10);Serial.print("Deg GPSV:");Serial.print((float)JY901.stcGPSV.lGPSVelocity/1000);Serial.println("km/h");

  Serial.println("");
  delay(500);
}

/*
  SerialEvent occurs whenever a new data comes in the
 hardware serial RX.  This routine is run between each
 time loop() runs, so using delay inside loop can delay
 response.  Multiple bytes of data may be available.
 */
void serialEvent()
{
  while (Serial.available())
  {
    JY901.CopeSerialData(Serial.read()); //Call JY901 data cope function
  }
}

The header file:
#ifndef JY901_h
#define JY901_h

#define SAVE        0x00
#define CALSW       0x01
#define RSW         0x02
#define RRATE       0x03
#define BAUD        0x04
#define AXOFFSET    0x05
#define AYOFFSET    0x06
#define AZOFFSET    0x07
#define GXOFFSET    0x08
#define GYOFFSET    0x09
#define GZOFFSET    0x0a
#define HXOFFSET    0x0b
#define HYOFFSET    0x0c
#define HZOFFSET    0x0d
#define D0MODE      0x0e
#define D1MODE      0x0f
#define D2MODE      0x10
#define D3MODE      0x11
#define D0PWMH      0x12
#define D1PWMH      0x13
#define D2PWMH      0x14
#define D3PWMH      0x15
#define D0PWMT      0x16
#define D1PWMT      0x17
#define D2PWMT      0x18
#define D3PWMT      0x19
#define IICADDR     0x1a
#define LEDOFF      0x1b
#define GPSBAUD     0x1c

#define YYMM                0x30
#define DDHH                0x31
#define MMSS                0x32
#define MS                  0x33
#define AX                  0x34
#define AY                  0x35
#define AZ                  0x36
#define GX                  0x37
#define GY                  0x38
#define GZ                  0x39
#define HX                  0x3a
#define HY                  0x3b
#define HZ                  0x3c
#define Roll                0x3d
#define Pitch               0x3e
#define Yaw                 0x3f
#define TEMP                0x40
#define D0Status        0x41
#define D1Status        0x42
#define D2Status        0x43
#define D3Status        0x44
#define PressureL       0x45
#define PressureH       0x46
#define HeightL         0x47
#define HeightH         0x48
#define LonL                0x49
#define LonH                0x4a
#define LatL                0x4b
#define LatH                0x4c
#define GPSHeight   0x4d
#define GPSYAW      0x4e
#define GPSVL               0x4f
#define GPSVH               0x50

#define DIO_MODE_AIN 0
#define DIO_MODE_DIN 1
#define DIO_MODE_DOH 2
#define DIO_MODE_DOL 3
#define DIO_MODE_DOPWM 4
#define DIO_MODE_GPS 5

struct STime
{
    unsigned char ucYear;
    unsigned char ucMonth;
    unsigned char ucDay;
    unsigned char ucHour;
    unsigned char ucMinute;
    unsigned char ucSecond;
    unsigned short usMiliSecond;
};
struct SAcc
{
    short a[3];
    short T;
};
struct SGyro
{
    short w[3];
    short T;
};
struct SAngle
{
    short Angle[3];
    short T;
};
struct SMag
{
    short h[3];
    short T;
};

struct SDStatus
{
    short sDStatus[4];
};

struct SPress
{
    long lPressure;
    long lAltitude;
};

struct SLonLat
{
    long lLon;
    long lLat;
};

struct SGPSV
{
    short sGPSHeight;
    short sGPSYaw;
    long lGPSVelocity;
};
class CJY901
{
  public:
    struct STime        stcTime;
    struct SAcc         stcAcc;
    struct SGyro        stcGyro;
    struct SAngle       stcAngle;
    struct SMag         stcMag;
    struct SDStatus     stcDStatus;
    struct SPress       stcPress;
    struct SLonLat      stcLonLat;
    struct SGPSV        stcGPSV;

    CJY901 ();
    void StartIIC();
    void StartIIC(unsigned char ucAddr);
    void CopeSerialData(unsigned char ucData);
    short ReadWord(unsigned char ucAddr);
    void WriteWord(unsigned char ucAddr,short sData);
    void ReadData(unsigned char ucAddr,unsigned char ucLength,char chrData[]);
    void GetTime();
    void GetAcc();
    void GetGyro();
    void GetAngle();
    void GetMag();
    void GetPress();
    void GetDStatus();
    void GetLonLat();
    void GetGPSV();

  private:
    unsigned char ucDevAddr;
    void readRegisters(unsigned char deviceAddr,unsigned char addressToRead, unsigned char bytesToRead, char * dest);
    void writeRegister(unsigned char deviceAddr,unsigned char addressToWrite,unsigned char bytesToRead, char *dataToWrite);
};
extern CJY901 JY901;
#include <Wire.h>
#endif

why did you post this? ... is there a problem of some kind? ... do you have a question?

Gyro does not measure Acceleration like gravity.  Gyro measures rotation around an axis like a twist or rotation.  Maybe that is why your project is not working as you expect it to.

All your sketch do is print a lot of data, where is the code you said about "use the value of Acc or AX (acceleration X axis) in If function in order to activate a relay."? You said you want to "use the value of Acc", yet, there is a method shown in the header file GetAcc(); that you never bother to try. Read the source code if document is confusing and come back with some tangible question.


text:
Memory allocation on Arduino Due never returns NULL
I'm working on a project that uses quite a bit of RAM to store and analyze data that is sent from the PC. The program heavily relies on malloc/free, which normally works just fine. However, if the data set gets to big - which I can't tell beforehand - the Arduino just dies. Some analysis found that it has to do with memory management. Running a simple sketch which just does
void loop() {
  int SIZE_TO_TEST = (1024 * 10);
  int* mem = (int*)malloc(SIZE_TO_TEST);
  if (mem == nullptr)
  {
    // This never happens
    Serial.print("Allocation failed\r\n");
    return;
  }
  Serial.print("Allocation succeeded\r\n");
  Serial.print((int)mem, HEX); // this always prints 0x200712E0, regardless of the size
  Serial.println();
  for (int i = 0; i < SIZE_TO_TEST / 4; i++)
  {
    mem[i] = i;
  }

  for (int i = 0; i < SIZE_TO_TEST / 4; i++)
  {
    if (mem[i] != i)
    {
      // You better get a new board if this happens
      Serial.print("HARDWARE ERROR: Memory broken\r\n");
    }
  }
  free(mem);
}

works fine and repeatedly prints "Allocation succeeded". When I start increasing the SIZE_TO_TEST, the CPU crashes when the value is over the effective memory size of 96k. The weird thing is, that even when the value is 1000k (far beyond what the uP actually has), the pointer returned by malloc() is still the same memory address, not NULL, as one would expect. The crash also does not occur if the allocated memory is not used (if the two for loops are commented out), so I suspect the actual crash occurs because the program tries to write to memory that is not actually there.
How do I find out that the memory is exhausted? Why does malloc() never return NULL?
(Note: I know about the problems of memory fragmentation with small micro controllers, but I can work around that issue)

Just seen: The problem is also discussed here: https://forum.arduino.cc/index.php?topic=381203.0. No solution given, though.

The Arduino software is open source.  I'm sure a solution could be found.

I can give you an answer as to why it's failing.  But I can't tell you precisely what you should do about it.

Based on @timemage's answer, I'd suggest opening a bug report on Arduino and also on Newlibc.

On the ArduinoCore-sam project maybe.  I don't believe it's really Newlib's problem at all.

Why
This is a partial answer, for now, mostly with regard to:

Why does malloc() never return NULL?

So, the Due appears to use Newlib as its libc implementation; that is the systems C (standard and some non-standard) runtime that includes malloc(), or the greater part of malloc() anyway.  The Newlib malloc() relies on an  sbrk() function which is implemented by the specific system, the Due in this case.
This name and basic idea comes out of Unix; you can read about the interplay between malloc and sbrk some without it having to be in connection with Newlib or the Due specifically.  In short, sbrk extends the area that malloc has to work with and malloc divides that area into requested chunks.  Here is Newlib's documentation for sbrk and a sample implementation.
The Due (SAM) core for Arduino implements sbrk as:
extern caddr_t _sbrk ( int incr )
{
    static unsigned char *heap = NULL ;
    unsigned char *prev_heap ;

    if ( heap == NULL )
    {
        heap = (unsigned char *)&_end ;
    }
    prev_heap = heap;

    heap += incr ;

    return (caddr_t) prev_heap ;
}

This is a kind of degenerate implementation of _sbrk that just blindly says, "You want more memory, sure here you go" without limit.  If you look at the sample sbrk implementation for Newlib, you'll see it just calls abort() instead of a proper failure that would result in malloc returning NULL, which is admittedly not great, but at least it's not pretending that everything is fine.
There should be a condition somewhere in this code that check so see if there's any more space to be had and sets errno = ENOMEM and effectively does return -1 if there is not.
I modified this code to allow me to set a variable from the sketch that could force the next call to _sbrk to fail as described above.  And sure enough, on the next call to malloc() it returned NULL because _sbrk had indicated failure.
So the _sbrk implementation provided by the Due/sam core should be changed so that malloc fails when appropriate.  That said, I'm not precisely sure how that should be done.  So I'm going to hold off on making specific recommendations about it.  Maybe I look into it more I'll come back and update this with something more useful, addressing your other question of:

How do I find out that the memory is exhausted?

In rough terms though, the answer going to be that you modify that function so it returns -1 with ENOMEM under the right conditions.

How
This is the previously mentioned update with some details on the how:

How do I find out that the memory is exhausted?

So I've made something to give you an idea what the condition would look like.  I'm not strictly recommending you use it; for one thing it's barely been tested.
From the ATSAM3X8E's family datasheet:

SRAM0 is accessible over the system Cortex-M3 bus at address 0x2000 0000
and SRAM1 at address 0x2008 0000. The user can see the SRAM as
contiguous thanks to mirror effect, giving 0x2007 0000 - 0x2008 7FFF
for SAM3X/A8

The stack pointer starts near the top of memory 0x2008 7FFF and grows
downward.  The _end symbol marks the end of the mutable static storage
duration variables or the beginning of the heap.  Somewhere closer to
0x2007 0000; the fewer of these variables the closer.
On this system, which has a fairly common layout, the heap grows up with positive increments to sbrk as the stack pointer grows down with stack frames (local variables, return addresses etc).  So, "the end" of memory happens when the heap would otherwise allocate over the stack or the stack runs into the heap as your pushing things onto it.
So a typical thing to do is to check to see whether or not the sbrk's argument would cause the edge of the heap to get "too close" to the stack.
In the the /.arduino15/packages/arduino/hardware/sam/1.6.12/cores/arduino/syscalls_sam3.c, I've include some extra headers:
#include <errno.h>
#include <stdlib.h>

And put the following as a replacement _sbrk():
size_t __malloc_margin = 4 * (size_t)1024;
extern caddr_t _sbrk (int incr) {
    static const unsigned char *       heap      = (unsigned char *)&_end ;
    /****/ const unsigned char * const prev_heap = heap;

    if (incr > 0) {
        // Extra checks for stack growing

        if (incr >= 96 * (size_t)1024) {
            // The Due only has 96K of ram,
            // so any request for 96K or greater
            // is a failure out of the gate.
            errno = ENOMEM;
            return (caddr_t)-1;
        }

        unsigned char *stack_ptr;

        asm volatile(
            "mov %[sp_out], sp"
            : [sp_out] "=r" (stack_ptr)
            :
        );

        if (stack_ptr < heap) {
            // We're already in real trouble.
            abort();
        }

        if (stack_ptr - heap  <  incr + __malloc_margin) {
            // Not enough memory considering safety margin.
            errno = ENOMEM;
            return (caddr_t)-1;
        }
    }

    heap      += incr ;
    return (caddr_t) prev_heap ;
}

__malloc_margin was used as a variable name just because it's the name that avr-libc uses for the same purpose, namely to tune the minimum distance between the stack and heap during an allocation that the break to increase.  By the way, you can see this same kind of check happen in avr-libc's implementation of malloc (which also takes sbrk's role.)  Why is __malloc_margin 4K ?  No really scientific reason.  It's about 4% of memory, so it's not large, and it's not completely inconceivable to me that someone would try to put local variable(s) approaching 4k in a stack frame on a system that has 96kb total memory.  4K may not be an appropriate default though; more thought should go into that.  Having it in a variable like this allows it to be tuned at runtime; usually there would be a header that provides an extern declaration for it.
I may add more later to explain, but it short if the break is being increased, this sbrk looks to see if the new break would get within __malloc_margin of the stack pointer on a request, an if it would it returns the -1 value and errno = ENOMEM to cause malloc to behave correctly from the user's perspective.
Before anyone bothers to mention: Yes, I know you can take the address of a local to get a stack pointer value.  Yes, the check to see if the single allocation is larger than 96K is probably unnecessary.  Yup, it has Due specific stuff in it even though it's not strictly a Due; there are probably identifiers that could be used instead.  It should probably abort() if sbrk tries to go below 0 sized heap.  It's just a somewhat working illustration of what should be in _sbrk().  More thought and at least one change should be put into it before general use.
Regarding abort()
It occurs to me in some cases abort() may be an appropriate way to handle this.  If you believe that you can characterize the system (or the sketch if you like) at runtime so well that malloc() failing can be regarded as a major oversight, then calling abort() in sbrk() could make sense.  Or at least providing the option to do that.
In the comments you asked:

What does abort() exactly [do] on the Due?

Well, Newlib documentation says:

Before terminating your program, abort raises the exception SIGABRT
(using ‘raise(SIGABRT)’).

and then further down:

Supporting OS subroutines required: _exit and optionally, write.

The SIGABRT and _exit parts are more or less standard behaviour.  So it will call your signal handler for SIGABRT if you have one.
So then what does _exit do?  It loops forever.
I called abort() in a sketch and dumped the following via an arm version of the binutils objdump with -dS command-line options.
Here's the relevant abort() code:
00081b98 <abort>:
   81b98:   b508        push    {r3, lr}
   81b9a:   2006        movs    r0, #6
   81b9c:   f000 fb5c   bl  82258 <raise>
   81ba0:   2001        movs    r0, #1
   81ba2:   f7fe fec5   bl  80930 <_exit>
   81ba6:   bf00        nop

bl <raise> would in turn call your signal handler.  and bl <_exit> calls exit which displays as:
00080930 <_exit>:

extern void _exit( int status )
{
   80930:   e7fe        b.n 80930 <_exit>

00080932 <_kill>:

    for ( ; ; ) ;
}

It appears the optimizer has combined some things here, but essentially _exit has an instruction that jumps (branches) to itself, equivelent to for(;;);.
I half-expected the abort(); code to disable interrupts before calling _exit().  If you do plan on abort() in your _sbrk() that might be something to think about.  You may also want to provide a global flag that can be inspected from SIGABRT that allows the signal handler to do something diagnostically appropriate specifically for _sbrk() failures.
Perhaps sbrk should set a flag in a no-init data section and then set the watchdog timer and let it expire (or provide the SIGABRT handler with the information to do that).  Lots of things to consider.

Can you tell me in which file that implementation of _sbrk is to be found? Looks like a good analysis. Maybe my idea below might help with the missing condition?

It's linked to in the answer "Arduino implements sbrk".  That is syscalls_sam3.c  I'm about to update with some additional information though.

There's some more for you. I'm sure it'll get updated again to correct mistakes if nothing else.

Nice, I'll try this next. Pretty close to what I've been investigating as a workaround. What does abort() exactly on the Due?

I've updated the answer to address what abort() is does on the Due and a little of how that might interact with a replacement  _sbrk().

I think I found a workaround. It relies on the fact that on simple program architectures such as the one used on most microcontrollers, the heap grows upwards while the stack grows backwards.
const int MIN_FREE_STACK = 512;

void* mallocEx(int size)
{
  void* stackPtr = alloca(4); // This returns a pointer to the current bottom of the stack
  PrintAddress("StackPtr ", stackPtr);
  void* ptr = malloc(size);
  PrintAddress("NewInstance ", ptr);
  if ((byte*)ptr + size > ((byte*)stackPtr - MIN_FREE_STACK))
  {
    free(ptr); // This memory location is not really valid
    return nullptr;
  }
  return ptr;
}

The method checks, on each attempt to allocate memory, whether the newly allocated block would reach into the call stack (+ some safety margin). If so, the pointer is freed again and null is returned.
I tried with this a bit more demanding test, and it seems to work as expected (allocates a bunch of blocks until it fails at around 91k, then restarts)

void ValidateMemoryManager()
{
  const int oneK = 1024;
  const int maxMemToTest = 100; // the arduino due has 96k of memory
  void* ptrs[maxMemToTest];
  int idx = 0;
  int totalAllocsSucceeded = 0;
  while (idx < maxMemToTest)
  {
    void* mem = mallocEx(oneK);
    ptrs[idx] = mem;
    if (mem == nullptr)
    {
      break;
    }
    idx++;
  }

  // Happens in simulation
  if (idx == maxMemToTest)
  {
    idx--;
  }

  totalAllocsSucceeded = idx;
  while (idx >= 0)
  {
    free(ptrs[idx]);
    idx--;
  }

   Serial.print("Total usable memory: ");
   Serial.print(totalAllocsSucceeded * oneK, DEC);
   Serial.println();
}

Your answers deserves more love.  I'd considered using alloca() too because it seems like it would resist some unpredictable outcomes from the optimizer.  In the end in I decided to put a tiny chunk of inline assembly in there, but I'm still not sure it is the right choice; alloca might make more sense.  I haven't been through the rest of it to yet thuroughly, but I think I see what you're doing, and if I understand correctly this works almost identically as a non-invasive way of detecting the out-of-memory condition.

@timemage I didn't test this yet, but one point which doesn't work (at least not ouf of the box) with my approach is also correctly supporting new/delete. Could get a bit more complex, because they're not supposed to return null on failure, but throw exceptions. And these are not enabled by default on arduinos.

Right.  It now that I think about I used the term "invasive" with respect to the core.  With respect to your sketch it is.   There are no-throw versions of new and delete, but your point more or less stands.  You would have to replace their implementations to use your custom malloc.  Or alternately use your custom malloc function and then, use a placement-new and explicit destructor call.  If you wanted to go a bit off the rails with it you could define smart pointers that do nothing but that.  Fixing sbrk() is probably better.

@timemage Just tested it: With your fix, new returns null if there's not enough memory left. Seems they got that part right, after all.


text:
How do I resolve error message "assignment of function 'void digitalWrite (uint8_t, uint_8)"?
I am a beginner in using Arduino and programming in c/c++. I am trying to connect a 10-segment LED and a moisture sensor to my Arduino Uno, and when the moisture level is very low, the first 2 red LEDs will be turned on, when it is slightly higher, the next three orange LEDs will be turned on, when it is slightly higher the next three green LEDs will be turned on, and finally when the moisture level is above the threshold for the green LEDs, the final blue LED segment will turn on.   I have written a program that works, and I have tested both the moisture sensor and the 10 segment LED separately to ensure they are working. Although the program works how I intend it, about 30-40% of the time I am unable to run the program due to an error message in the process of uploading. To be clear, I do not change the code at all from the working state of the code to the error message appearing. I wanted to know why this message appears, and how to avoid/resolve this issue.   I have included my code below:
/*
   Arduino LED Bar Graph with Moisture Sensor
   Started June 25, 2020

   edited 6/28
    (added blue LED)
*/

int redLED = 13;
int yellowLED = 12;
int greenLED = 11;
int blueLED = 10;

#define SensorPin A0
float sensorValue = 0;
float moistureLevel = 0;

void setup()
{
  // put your setup code here, to run once:
  Serial.begin(9600);
  pinMode(redLED, OUTPUT);
  pinMode(yellowLED, OUTPUT);
  pinMode(greenLED, OUTPUT);
  pinMode(blueLED, OUTPUT);
}

void loop()
{
  if  (Serial.available() > 900)
  {
    moistureLevel = Serial.read();//set the var moistureLevel
    digitalWrite = (redLED, HIGH);
    digitalWrite = (yellowLED, LOW);
    digitalWrite = (greenLED, LOW);
    digitalWrite = (blueLED, LOW)
  }
  else if (Serial.available() > 750)
  {
    moistureLevel = Serial.read();//set the var moistureLevel
    digitalWrite = (yellowLED, HIGH);
    digitalWrite = (redLED, LOW);
    digitalWrite = (greenLED, LOW);

  }
  else(Serial.available() > 550)
  {
    moistureLevel = Serial.read();//set the var moistureLevel
    digitalWrite = (greenLED, HIGH);
    digitalWrite = (redLED, LOW);
    digitalWrite = (yellowLED, LOW);
    digitalWrite = (blueLED, LOW);
  }
  else(Serial.available() < 549)
  {
    moistureLevel = Serial.read();//set the var moistureLevel
    digitalWrite = (greenLED, HIGH);
    digitalWrite = (redLED, LOW);
    digitalWrite = (yellowLED, LOW);
    digitalWrite = (blueLED, HIGH);
  }
  for (int i = 0; i <= 100; i++)
  {
    sensorValue = sensorValue + analogRead(SensorPin);
    delay(1);
  }
  sensorValue = sensorValue / 100.0;
  Serial.println(sensorValue);
  delay(100);
}

And here is a copy of the exact error message:
/tmp/777165248/sketch_jun25a/sketch_jun25a.ino: In function 'void loop()':

/tmp/777165248/sketch_jun25a/sketch_jun25a.ino:33:33: error: assignment of function 'void digitalWrite(uint8_t, uint8_t)'

digitalWrite = {redLED, HIGH};

^

/tmp/777165248/sketch_jun25a/sketch_jun25a.ino:33:33: error: cannot convert '<brace-enclosed initializer list>' to 'void(uint8_t, uint8_t) {aka void(unsigned char, unsigned char)}' in assignment

/tmp/777165248/sketch_jun25a/sketch_jun25a.ino:34:35: error: assignment of function 'void digitalWrite(uint8_t, uint8_t)'

digitalWrite = (yellowLED, LOW);

^

/tmp/777165248/sketch_jun25a/sketch_jun25a.ino:34:35: error: cannot convert 'int' to 'void(uint8_t, uint8_t) {aka void(unsigned char, unsigned char)}' in assignment

/tmp/777165248/sketch_jun25a/sketch_jun25a.ino:35:34: error: assignment of function 'void digitalWrite(uint8_t, uint8_t)'

digitalWrite = (greenLED, LOW);

^

/tmp/777165248/sketch_jun25a/sketch_jun25a.ino:35:34: error: cannot convert 'int' to 'void(uint8_t, uint8_t) {aka void(unsigned char, unsigned char)}' in assignment

/tmp/777165248/sketch_jun25a/sketch_jun25a.ino:36:33: error: assignment of function 'void digitalWrite(uint8_t, uint8_t)'

digitalWrite = (blueLED, LOW)

^

/tmp/777165248/sketch_jun25a/sketch_jun25a.ino:36:33: error: cannot convert 'int' to 'void(uint8_t, uint8_t) {aka void(unsigned char, unsigned char)}' in assignment

/tmp/777165248/sketch_jun25a/sketch_jun25a.ino:41:36: error: assignment of function 'void digitalWrite(uint8_t, uint8_t)'

digitalWrite = (yellowLED, HIGH);

^

/tmp/777165248/sketch_jun25a/sketch_jun25a.ino:41:36: error: cannot convert 'int' to 'void(uint8_t, uint8_t) {aka void(unsigned char, unsigned char)}' in assignment

/tmp/777165248/sketch_jun25a/sketch_jun25a.ino:42:32: error: assignment of function 'void digitalWrite(uint8_t, uint8_t)'

digitalWrite = (redLED, LOW);

^

/tmp/777165248/sketch_jun25a/sketch_jun25a.ino:42:32: error: cannot convert 'int' to 'void(uint8_t, uint8_t) {aka void(unsigned char, unsigned char)}' in assignment

/tmp/777165248/sketch_jun25a/sketch_jun25a.ino:43:34: error: assignment of function 'void digitalWrite(uint8_t, uint8_t)'

digitalWrite = (greenLED, LOW);

^

/tmp/777165248/sketch_jun25a/sketch_jun25a.ino:43:34: error: cannot convert 'int' to 'void(uint8_t, uint8_t) {aka void(unsigned char, unsigned char)}' in assignment

/tmp/777165248/sketch_jun25a/sketch_jun25a.ino:47:3: error: expected ';' before '{' token

{

^

/tmp/777165248/sketch_jun25a/sketch_jun25a.ino:54:3: error: 'else' without a previous 'if'

else(Serial.available() < 549)

^~~~

/tmp/777165248/sketch_jun25a/sketch_jun25a.ino:55:3: error: expected ';' before '{' token

{

^

exit status 1

the error message occurs during code compilation, not during upload ... you always get that error, not only sometimes .... the obvious thing to do, is to review the digitalWrite command, to see if you made a mistake ... please do that

You have:
digitalWrite = (redLED, HIGH);

This is incorrect since digitalWrite is a function not a variable.  Instead you likely want:
digitalWrite(redLED, HIGH);

This calls the digitalWrite function with the two arguments.

please don't write Answer to syntax error questions. they are off-topic

@Juraj I'm having trouble finding where the site policy prohibits such questions or answers.  Please post a reference to it.  Thanks.

https://arduino.stackexchange.com/help/on-topic "Off topic:  General Coding: "

@Juraj. The coding question is very much Arduino related.  I think you're reading way more into the guideline than is there.

https://arduino.meta.stackexchange.com/questions/2667/trivial-questions-must-be-off-topic

Trivial for you is not trivial for a beginner.

lack of research is a closing reason too. basic examples show how to use digitalWrite.


text:
L298N motor driver problems
(edited)
So sorry my bad. To make it clear:
From the picture that I posted, I need to press the PBA (as Button1) so that both motors can run in forward (CW-clockwise)  and backward (CCW-counterclockwise) and  a stop.
While on the other hand, PBB (as button2) is for another condition  both motors can run in left, right, and stop.
Problems:

When I run my code, it appears glitching from my LCD display.

I able to achieve for PBB side but for PBA side, both motors don't move at all.

I had use potentiometer to adjust my speed. The potentiometer are doing fine.

I use debounce for both my buttons and I am not sure whether the debounce effect my void setmode(int Mode, int MotorMode1){}

////////////////////////////////////////////////////////////////////////////////[![enter image description here][1]][1]

boolean lastButton=LOW;
boolean currentButton = LOW;

boolean last1Button = LOW;
boolean current1Button = LOW;

boolean debounce(boolean last){
    boolean current = digitalRead(PBA);
    if (last != current) {
      delay(5);
      current = digitalRead(PBA);
      return current;
    }
  }

  boolean debounce1(boolean last1) {
    boolean current1 = digitalRead(PBB);
    if (last1 != current1) {
      delay(5);
      current1 = digitalRead(PBB);
      return current1;
    }
  }

  int Mode = 0;
  int motorMode1 = 0;

  void loop() {
    lcd.clear();
    lcd.setCursor(0, 0);
    lcd.print("SPEED:");
    lcd.setCursor(0, 1);

    // potentiometer LCD
    float inputValue = analogRead (pot);
    inputValue = map(inputValue, 0, 1023, 0, 100);
    lcd.setCursor(7, 0);
    lcd.print (inputValue);
    lcd.setCursor(12, 0);
    lcd.print ("%");

    //read values from potentiometer
    MotorSpeed = analogRead(SpeedControl);
    MotorSpeed = map(MotorSpeed, 0 , 1023 , 0 , 255);
    // adjust to prevent at low speed
    if (MotorSpeed < 8)MotorSpeed = 0;
    //set the motor speed
    //analogWrite (enA, MotorSpeed);
    //analogWrite (enB, MotorSpeed);
    // MotorLCD
    lcd.setCursor(0, 1);
    lcd.print("MOVE:");

    currentButton = debounce(lastButton);
    if (currentButton == HIGH && lastButton == LOW) {
      Mode++;
    }
    lastButton = currentButton;
    if (Mode == 3){
      Mode = 0;
    }

    current1Button = debounce1(last1Button);
    if (last1Button == HIGH && current1Button == LOW) {
      motorMode1++;

    }
    last1Button = current1Button;
    if (motorMode1 == 3){
      motorMode1 = 0;
    }

  setMode( Mode, motorMode1);

 }

  void setMode(int Mode, int motorMode1) {
    analogWrite (enA, MotorSpeed);
    analogWrite (enB, MotorSpeed);

    if (Mode == 1 ) {
      lcd.setCursor(5, 8);
      lcd.print("Forward");

      //MOTOR_A CLOCKWISE MAX SPEED
      digitalWrite(in1, HIGH);
      digitalWrite(in2, LOW);

      //MOTOR_B CLOCKWISE MAX SPEED
      digitalWrite(in3, HIGH);
      digitalWrite(in4, LOW);
    }
    if (Mode == 2) {
      lcd.setCursor(5, 8);
      lcd.print("Reverse");

      //MOTOR_A COUNTERCLOCKWISE MAX SPEED
      digitalWrite(in1, LOW);
      digitalWrite(in2, HIGH);

      //MOTOR_B COUNTERCLOCKWISE MAX SPEED
      digitalWrite(in3, LOW);
      digitalWrite(in4, HIGH);

    }

   if (motorMode1 == 1) {

      lcd.setCursor(5, 8);
      lcd.print("Right");
      //MOTOR_A CLOCKWISE MAX SPEED
      digitalWrite(in1, LOW);
      digitalWrite(in2, HIGH);
      //MOTOR_B COUNTERCLOCKWISE MAX SPEED
      digitalWrite(in3, HIGH);
      digitalWrite(in4, LOW);

    }
    if (motorMode1 == 2) {
      lcd.setCursor(5, 8);
      lcd.print("Left");
      //MOTOR_A COUNTERCLOCKWISE MAX SPEED
      digitalWrite(in1, HIGH);
      digitalWrite(in2, LOW);
      //MOTOR_B CLOCKWISE MAX SPEED
      digitalWrite(in3, LOW);
      digitalWrite(in4, HIGH);

    }
     if (Mode == 0 || motorMode1 == 0) {
      lcd.setCursor(5, 8);
      lcd.print("Stop");
      digitalWrite(in1, LOW);
      digitalWrite(in2, LOW);
      digitalWrite(in3, LOW);
      digitalWrite(in4, LOW);
    }
  }

If you want someone to help you, format your code properly and shorten it only to focus on the area where you think potentially  caused the problem.

There's a Tools/Auto Format menu option in the IDE for this.

BTW: What is the question? And, what do you mean with asynchronously and synchron? And, why do you use two names for A0 pin (pot, SpeedControl)? Why do you name output pins "inX"? Why do you set inX in the mode function first depending on the Mode variable and then overwrite it depending on the motorMode1 variable? But the most important question is: What do you want to achieve? Try to explain it, and perhaps you'll see yourself what's going wrong. We might help if we'd know what your goals are. Only looking at the code, I can not say what you are trying to do. ;-)

Hi peter, I had already upload a picture so that you can understand properly.

why do you use two names for A0 pin (pot, SpeedControl)?
I had declared twice with different function and that's cause confusion and I deleted it.

2.Why do you name output pins "inX"? Why do you set inX in the mode function first depending on the Mode variable and then overwrite it depending on the motorMode1 variable?
inX - for the Ln298 motor output
there are 4 inX outputs.
and 2 enX outputs under PWM.
Thanks for the comments. :D

I hope I understood you correctly. The best way would be to tell you how you can use states to get the problem solved. But that would cost me too much time.
I decided to edit your program. I have no hardware to try it. So it is just an example to show you the idea. Perhaps it works as it is.
Please check the comments. If you are really interested in understanding to problem and the solution and things are unclear,  you (or others) can ask with comments below. And of cause, if you find an error, I would be happy to know about it and correct it. ;-)
#include <Wire.h>
#include <LiquidCrystal_I2C.h>

// These are the different movement states
#define STATE_STOP 0
#define STATE_LEFT 1
#define STATE_RIGHT 2
#define STATE_FORWARD 3
#define STATE_BACKWARD 4

// always use expressive names

// The pin assignments
//////////////////////////////////////////////

// Analog
int pinPotiSpeed = A0;

// Motor A
int pinEnA = 9;
int pinInA1 = 8;
int pinInA2 = 7;

// Motor B
int pinEnB = 3;
int pinInB1 = 5;
int pinInB2 = 4;

// Buttons
const int pinBtnDir = 10;
const int pinBtnTurn = 11 ;

int stateMotors = STATE_STOP;
boolean flagBtnDirPressed = LOW;
boolean flagBtnTurnPressed = LOW;

int stateMotorsSpeed = 0;
int speedPercent = map( stateMotorsSpeed, 0, 255, 0, 100 );

LiquidCrystal_I2C lcd(0x27, 16, 2);

// I have not the time to think a lot about this debouncing, but
// I have a bad feeling. If the Arduino does not react on button presses
// or the mode change to quick please let me know. I'll have a look on it, if
// necessary. ;-)
boolean readButtonAndDebounce(int btnPin, boolean lastState)
{
    boolean actualState = digitalRead(btnPin);
    if (lastState != actualState)
    {
      delay(15);
      actualState = digitalRead(btnPin);
      return actualState;
    }

    // this return was missing in the original program
    return actualState;
}

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

    pinMode(pinEnA, OUTPUT);
    pinMode(pinInA1, OUTPUT);
    pinMode(pinInA2, OUTPUT);

    pinMode(pinEnB, OUTPUT);
    pinMode(pinInB1, OUTPUT);
    pinMode(pinInB2, OUTPUT);

    pinMode(pinBtnDir, INPUT);
    pinMode(pinBtnTurn, INPUT);

    digitalWrite(pinInA1,LOW);
    digitalWrite(pinInA2,LOW);

    digitalWrite(pinInB1,LOW);
    digitalWrite(pinInB2,LOW);

    lcd.init();
    lcd.backlight();

    lcd.clear();
    lcd.setCursor(0, 0);
    lcd.print("SPEED:");
    lcd.setCursor(0, 1);

    lcd.setCursor(7, 0);
    // convert 0-255 to 0%-100%
    lcd.print ("0 %");

    lcd.setCursor(0, 1);
    lcd.print("MOVE: Stop");
}

void loop()
{
    stateMotorsSpeed = map( analogRead( pinPotiSpeed ), 0, 1023, 0, 255 );
    if ( stateMotorsSpeed < 8 ) stateMotorsSpeed = 0;
    speedPercent = map( stateMotorsSpeed, 0, 255, 0, 100 );

    boolean flagBtnDirPressedOld = flagBtnDirPressed;
    flagBtnDirPressed = readButtonAndDebounce( pinBtnDir, flagBtnDirPressed );

    boolean flagBtnTurnPressedOld = flagBtnTurnPressed;
    flagBtnTurnPressed = readButtonAndDebounce( pinBtnTurn, flagBtnTurnPressed );

    // this is a bit tricky, because I don't know if i understood the problem correctly.
    // My problem is, what happens if both button are pressed, I decided to give
    // the Direction button the precedence
    if ( flagBtnDirPressed && ! flagBtnDirPressedOld )
    {
      switch( stateMotors )
      {
        case STATE_STOP:
          stateMotors = STATE_FORWARD;
          break;

        case STATE_FORWARD:
          stateMotors = STATE_BACKWARD;
          break;

        case STATE_BACKWARD:
          stateMotors = STATE_STOP;
          break;

        default:
          // this happens if a state from the other button is active
          // The table does not include a rule what to do in this case.
          // Perhaps you could count button click modulo 3 for each button
          // and then you can switch to the correct state
          stateMotors = STATE_STOP;
      }

    }
    else if ( flagBtnTurnPressed && ! flagBtnTurnPressedOld )
    {
      // this is only entered if press state of the direction button has not changed
      switch( stateMotors )
      {
        case STATE_STOP:
          stateMotors = STATE_RIGHT;
          break;

        case STATE_RIGHT:
          stateMotors = STATE_LEFT;
          break;

        case STATE_LEFT:
          stateMotors = STATE_STOP;
          break;

        default:
          // this happens if a state from the other button is active
          stateMotors = STATE_STOP;
      }
    }

    controlMotorAndUpdateLcd();
}

void setMotorSignals( boolean sigA1 , boolean sigA2, boolean sigB1, boolean sigB2 )
{
      //MOTOR_A
      digitalWrite(pinInA1, sigA1);
      digitalWrite(pinInA2, sigA2);

      //MOTOR_B
      digitalWrite(pinInB1, sigB1);
      digitalWrite(pinInB2, sigB2);
}

void controlMotorAndUpdateLcd()
{
    lcd.clear();
    lcd.setCursor( 0, 0 );
    lcd.print( "SPEED:" );
    lcd.setCursor( 0, 1 );

    // potentiometer LCD
    lcd.setCursor( 7, 0 );
    lcd.print ( speedPercent );
    lcd.setCursor( 12, 0 );
    lcd.print ("%");

    analogWrite ( pinEnA, stateMotorsSpeed );
    analogWrite ( pinEnB, stateMotorsSpeed );

    // MotorLCD
    lcd.setCursor(0, 1);
    lcd.print("MOVE:");

    lcd.setCursor(5, 8);
    switch( stateMotors )
    {
      case STATE_STOP:
        lcd.print("Stop");
        setMotorSignals( LOW, LOW, LOW, LOW);
        break;

      case STATE_FORWARD:
        lcd.print("Forward");
        setMotorSignals( HIGH, LOW, HIGH, LOW);
        break;

      case STATE_BACKWARD:
        lcd.print("Reverse");
        setMotorSignals( LOW, HIGH, LOW, HIGH);
        break;

       case STATE_LEFT:
        lcd.print("Left");
        setMotorSignals( HIGH, LOW, LOW, HIGH);
        break;

      case STATE_RIGHT:
        lcd.print("Right");
        setMotorSignals( LOW, HIGH, HIGH, LOW);
        break;
    }
}

Thanks for the help..
There is still some glitches on the LCD display. Do you have any idea why.? When I run void setup at the " welcome " part is still work fine until it reach the final state part where " Speed" and "Move". The wording is unclear and some have some glitches.

Sorry I don't understand what you mean by "glitches". Do you mean e.g the Speed value changes quickly. I can only help, if I know the error exactly. 2. I can not help you with the wording, but you can use texts that fits better for you.

It's okay Peter. I will try to solve it myself. Thanks a lot, Peter.


text:
How to upload code to atmega32u4?
I recently created a pcb with the atmega32u4 to use it as a development board. The controller is connected to a micro usb port. Should I install the arduino bootloader instead of the deafult one? Or keep the default boot loader and find another way of flashing hex files? But bottom line what is the process to flash a hex file to the atmega32u4 via usb?

do you want to upload Arduino sketches from Arduino IDE? why do you think there is some bootloader on the 32u4?

I'm pretty sure the 32u4 comes preloaded with a bootloader and yes I would like to use the Arduino IDE. @Juraj

Pull /HWB high and reset the chip - you're now in DFU mode. Use a DFU programmer to upload your code over USB.

@Majenko  As I read it you pull HWBE LOW during RESET not hight.  See page 341 @ https://ww1.microchip.com/downloads/en/DeviceDoc/Atmel-7766-8-bit-AVR-ATmega16U4-32U4_Datasheet.pdf

Maybe. I've never done it.

There are four ordering codes for the 32U4.  Three of them come with the DFU bootloader on it; one doesn't.  They also come with and without external oscillator fusing which may be relevant as well depending on how the board is designed and which programming method is used.  You should probably mention which ordering code you have and maybe more about the board.

Installing the Arduino bootloader would make it easier to upload you sketch from the Arduino IDE.
Installing the Arduino bootloader via DFU is probably the easiest method. Alternatively use ISP, but you'd need a programmer for that, or use a separate Arduino board with the ArduinoAsISP sketch running on it.


text:
Voltage, current measurement from solar panel using INA219 and ESP-12F
I recently started tinkering with ESP-12F thus I am a novice here. As a standard novice project, I am making a standalone weather station for my living room. I want to use solar panels to charge the batteries which power up the ESP-12F via USB. I am using ESP-12F as a controller and sending data to Rpi using MQTT.
I am using the following items:

ESP-12 F powered by USB
2.5W 5V solar panel ( I want to connected two in parallel but for now using only one )
RPi 3B
INA219A to measure voltage and current generated by solar panel.
IN4001 diode as blocking
DHT11 sensor for temp and humidity values
Battery pack to charge 2 x 2500mAh batteries ( This is not done yet )

I am quite confused by the connections to INA219 and the data its providing. Thus, ESP-12F is still connected to independent usb power source and my goal is for now to understand and monitor the voltage and current generated by solar panel.
The INA219 Vcc, GND, SDA, SCL are connected to ESP-12F. I can read the values and observe them on serial monitor or mqtt panel.
1. Below is the breadboard connection when INA219 Vin+ is NOT connected.

The voltage measurement sent via MQTT is as below:
Ignore graph, I was pluging in/out Vin wire too many times thus very bizzare lines.

Current connections are as below:
Solar Panel (-) --> INA219 Vin (-) and breadboard to power LED
Solar Panel (+) --> Only to breadboard to power LED [INA219 Vin+ NOT connected]
ESP-12F 3V --> INA219 Vcc
ESP-12F GND --> INA219 GND
ESP-12F D1 --> INA219 SCL
ESP-12F D2 --> INA219 SDA
ESP-12F is powered by separated USB power source
Code using which the values are computed:
I have used Adafruit_INA219 library.
  shuntvoltage = ina219.getShuntVoltage_mV();
  busvoltage = ina219.getBusVoltage_V();
  current_mA = ina219.getCurrent_mA();
  power_mW = ina219.getPower_mW();
  loadvoltage = busvoltage + (shuntvoltage / 1000);

I dont understand the values sent by INA219 and have no idea how to interpret them. At this point, INA219 is connected to ESP-12F 3V power (Vcc) and GND. It does not have any Vin. Why there is a load voltage of -1.9 and current?
2. When INA219 has Vin(+) and Vin(-) connected

When I connect the Vin+ and Vin- of INA219 I dont have any voltage/current on the breadboard. You can see the LED if OFF. I dont understand why this happens. The whole circuit on breadboard is redundant once I connect INA219 Vin pins to solar panel output pins.
Current connections are as below:
Solar Panel (-) --> INA219 Vin (-) and breadboard to power LED
Solar Panel (+) --> INA219 Vin(+) and breadboard to power LED
ESP-12F 3V --> INA219 Vcc
ESP-12F GND --> INA219 GND
ESP-12F D1 --> INA219 SCL
ESP-12F D2 --> INA219 SDA
ESP-12F is powered by separated USB power source
The voltage and current values at this point is shown below:

The load voltage increases and the difference which is approx 2.1V.
This delta voltage matches the voltage values from solar panel when measured by multimeter at this point. Thus, I would assume load voltage = current voltage generated by solar panel. But, current is unchanged and LED on breadboard if OFF the moment I connect INA219 Vin. Thus, I assume I have done wrong connections.
It will be great if you can point out my mistakes and make suggestions!
Thank you!

You had a long post, but yet missing a lot of critical information for diagnosis. It will be better to provide a schematic than the breadboard picture, as it doesn't even show the IN219 on it. Where is your current shunt? and do you have the pull-up resistors for the I2C? does your I2C works? simply your post and focus on one question that you want to ask or the thing that you need help.

Vshunt = Vin+ - Vin- and typically < 50mV or just a few mV, Vbus = Vin - GND and therefore should be around 5V in your case, Load Voltage should be very close to VBus. So all your data doesn't make any sense. For the current, the value return is integer for mA, so it need to divided by 1000. So it is better to show your schematic/connection diagram and your Arduino sketch.

You connected the V- and V+ probes of the INA module direct to the V- and V+ of the solar panel. That means you connect V+ with V- from solar panel  over a 0.1 Ohm resistor. That is like a short. The Solar panel gets overloaded and the voltage breaks down. Lucky you, the solar panel can not provide more current. If it could, then the shunt resistor would be grilled. RIP ;-). Try put the v+ and V- in series with the LED and LED_Resistor. e.g.
Solar+ --> IN4001 --> INA+ |no connection| INA- --> LED --> R(LED) --> Solar-

That would make more sense. It'll show you how much current is drawn by the LED.
If you want to know how much current the panel can deliver, you would have to build a circuit with a potentiometer and measure the Voltage between V+ and V- of the Panel. You can also use the INA to mesasure the current through the potentiometer. Begin with a high resistancy, then turn the poti towards lower resistance and check when the voltage breaks down. The INA shows you the current. But be aware that, the max current depent on the amount of light the panel is exposed to and on the age of the panel itselves. So the values will change as these conditions change.


text:
MFRC522 Communication Failure
I'm using TTGO ESP32 and I've got an MFRC522 from AliExpress.
I've soldered connector pins to the board itself (both for ESP32 and MFRC522) and I'm using jumper wires female-to-female to connect themselves.
However, using an example sketch (DumpInfo) from miguelbalboa's RFID library, it says communication failure and scanning 3 different key cards or the key fob doesn't output anything.
Firmware Version: 0xFF = (unknown)
WARNING: Communication failure, is the MFRC522 properly connected?

This is my current pinout scheme:
(MFRC - ESP32)
SDA (SS) -> 33
SCK -> 25
MISO -> 27
MOSI -> 26
RST -> 32

And, of course also GND to G and 3.3V to 3.3V.
I've also tried SDA and SCK to connect to 21 and 22, respectively but no luck.
Though I have a DS1307 RTC module and microSD card adapter module and connected accordingly and it's working fine, by using Dupont wires, with the same method.
A manufacturer's defect or still I'm making an error somewhere?
You can see TTGO's ESP32 pinout diagram and also a picture of MFRC522 here  wired using jumper wires. I may be using (again) the wrong pins. The red LED on the MFRC522 is stable, though.
Thank you in advance.

UPDATE!
The issue has been fixed, just after finding this stackoverflow answer by bat macumba. I'll leave the question here, in case someone stumbles into the same problem.


text:
'class Adafruit_SPIDevice' has no member named 'endTransaction'
So what I have done is followed all of the instructions in the following link:
https://learn.adafruit.com/adafruit-pygamer/setup
and have managed to get all the way up to https://learn.adafruit.com/adafruit-pygamer/arduino-libraries.
the board not has its own serial COM port and does work with a very basic blink example program which does not include any libraries at all. Shown on https://learn.adafruit.com/adafruit-pygamer/using-with-arduino-ide.
The next problem occuring is that now another error message is coming up within the code which I am not too sure it is trying to say:
Arduino\libraries\Adafruit_EPD\src\Adafruit_EPD.cpp: In member function 'void Adafruit_EPD::csHigh()':
and
libraries\Adafruit_EPD\src\Adafruit_EPD.cpp:649:12: error: 'class Adafruit_SPIDevice' has no member named 'endTransaction'.
Here is the github for the library I am using (its called adafruit arcada library), https://github.com/adafruit/Adafruit_Arcada.
Here is the code that I am trying to run using the adafruit_arcada library. I have checked it is installed in the right place in the arduino/library folder on the computer system.
Here is my code I am trying to run:
#include "Adafruit_Arcada.h"
Adafruit_Arcada arcada;

void setup(void) {
  Serial.begin(9600);
  Serial.print("Hello! Arcada TFT Test");

  // Start TFT and fill black
  if (!arcada.arcadaBegin()) {
    Serial.print("Failed to begin");
    while (1) delay(10);
  }
  arcada.displayBegin();

  // Turn on backlight
  arcada.setBacklight(255);
}

void loop() {
  arcada.display->fillScreen(ARCADA_RED);
#if defined(ADAFRUIT_MONSTER_M4SK_EXPRESS)
  arcada.display2->fillScreen(ARCADA_RED);
#endif

  delay(100);

  arcada.display->fillScreen(ARCADA_GREEN);
#if defined(ADAFRUIT_MONSTER_M4SK_EXPRESS)
  arcada.display2->fillScreen(ARCADA_GREEN);
#endif

  delay(100);

  arcada.display->fillScreen(ARCADA_BLUE);
#if defined(ADAFRUIT_MONSTER_M4SK_EXPRESS)
  arcada.display2->fillScreen(ARCADA_BLUE);
#endif

  delay(100);

  arcada.display->fillScreen(ARCADA_BLACK);
#if defined(ADAFRUIT_MONSTER_M4SK_EXPRESS)
  arcada.display2->fillScreen(ARCADA_BLACK);
#endif

  delay(100);
}

However, something is telling me that something is either out of date or I might have potentially installed something wrong because in the guide that was sent there is 5 examples within the adafruit arcada library. But with the one I have installed, there is lots of examples. The guide itself was not updated too long ago (6th November 2020). The arcada library I have installed is the one installed from the library manger and the version of the library is 2.5.0 and the one on the tutorial on https://learn.adafruit.com/adafruit-pygamer/arduino-libraries seems to be saying the library is version 1.0.0. Perhaps the library is too update on my computer to date compared to the one in the guide which potentially might be more out of date than the one I have on my computer.

The line in your error message seems to be referring to a library for "Adafruit E-paper displays".  Did I miss something in your question that should have clued me into why an e-paper display plays a role in this?

Well... I am not too sure if the screen is a E-paper display.

But I did look at the adafruit EPD driver and it seemed to be out of date so I updated it.

The display used on the board is described as "1.8" 160x128 Color TFT", "TFT" being an LCD technology.  Mostly I was wondering if you'd added anything or if there was a mini-display or battery indicator something of that sort that would account for it.  EPD library is mentioned as a dependency of Arcada, for what reason I don't know.  It'll be a while before I get a deeper look into it.

Don't worry I have solved it, all that I did was update the EPD driver and that was it.

Post what you did as an answer to your own question.


text:
Changing the servo motor operating direction using arduino
I want to turn the servo motor 90 degrees with the first double high inputs, then I want to turn the motor 180 degrees with double high inputs, but the motor turns 180 degrees with one high input.
thank you for all help
#include <Servo.h>
Servo myservo;
const int  buttonPin = 8;    // the pin that the pushbutton is attached to
const int ledPin = 13;       // the pin that the LED is attached to
int Newbuttoncounter;
int buttonPushCounter = 0;   // counter for the number of button presses
int buttonState = 0;         // current state of the button
int lastButtonState = 0;     // previous state of the button

void setup() {
  myservo.attach(9);
  myservo.write(90);
  delay(1000);
  pinMode(buttonPin, INPUT);

  pinMode(ledPin, OUTPUT);

  Serial.begin(9600);
}

void loop() {
  myservo.write(90);
  buttonState = digitalRead(buttonPin);

  if (buttonState != lastButtonState) {

    if (buttonState == HIGH) {

      buttonPushCounter++;
      delay(500); // darbeleri alması için nefesleme.bu olmasa her darbede yüksek olur
    }
    if (buttonPushCounter % 2 == 0) {
      myservo.write(0);   //sağa döner
      delay(500);
      myservo.write(90);
      delay(500);
      Serial.println("WHITE");
      Newbuttoncounter = buttonPushCounter;

    }

    else if (Newbuttoncounter % 2 == 0) {

        myservo.write(180); //sola döner
        delay(500);
        myservo.write(90);
        delay(500);

      }

      else {

        lastButtonState = buttonState;
      }
    }
  }

Please [edit] your question to add the code there, not in an answer. The code markup is three backticks, not [code] here. Look at the help in the editor in case of doubt.

What's a "double" high input?

double high input detection of the sensor


text:
IRremote sending only works once with Arduino Nano
I am trying to control a receiver, wich is not working. I believe i have to send the code at least three times... but after the first time the IR Led stays off. I am using the Arduino Nano with the LED connected to pin 13. The "Send" message keep printing.

I am using this lib: https://github.com/Arduino-IRremote/Arduino-IRremote
I tried multiple versions of the lib

My code:
#include <IRremote.h>

IRsend irsend;

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

const static unsigned int raw[68] = {8950,4450,550,550,600,550,600,500,600,550,550,550,600,500,600,550,600,500,600,1600,600,1600,600,1650,550,1650,550,550,600,1600,600,1600,600,1650,550,550,600,1600,600,1600,600,550,550,550,600,500,600,550,550,550,600,1600,600,550,550,550,600,1600,600,1600,600,1600,600,1600,600,1650,550};

void loop() {
  Serial.println("Send");
  for (int i=0; i<3; i++) {
    irsend.sendRaw(raw,68,38);
    delay(40);
  }
  delay(5000);
}

Works only again once when resetting the Arduino

In all the examples found in the project's github files the delay between transmissions is over an order of magnitude longer than 40ms. Maybe that would help.

I believe i have to send the code at least three times  ... then what is preventing you from repeating irsend.sendRaw(raw,68,38) two more times?

@st2000 40ms is about right for the NEC protocol. The RAW code looks a lot like NEC.

Are you saying you can't see the IR led light up three times in a row, or that it isn't repeating after the 5 second delay? The former is pretty unlikely for you to notice, as the led being off for 40ms is hard to notice for us humans.

Got it to work... Code is fine. Pin 13 was the problem, because for the Nano it actually is Pin 3.  I actually tested it earlier with another LED but my other one was for some reason really dark, so i  just missed it.


text:
Which Arduino-Board do I need?
I want to use a single Arduino board and link it to both the ANALOG CO2 GAS SENSOR (MG-811 SENSOR) and ANALOG PH SENSOR - METER KIT. I was wondering if the Uno Rev 3 had enough pins or do I have to go with the Mega.

They are hardly going to use 4 pin each . That means u could almost any Arduino u can find.

Nano board has a bunch of analog and digital pins. It does good and cheap. But for convenience UNO board is preferable for its large size easy handling and easy pin and wiring management.

Uno has enough pins. You'll probably need an analog pin for each measured quantity, and you might want a few digital pins to turn them on or off or make mode changes, if any. The next question is: what your project meant to do, and does the Uno have enough memory to accomplish it? You will probably go quite a way with an Uno before your project exceeds its capabilities, unless you have some unusually stringent requirements.

Thank you, I am a beginner to Ardunio and want the CO2 and Ph sensor to collect data for a science experiment over time together. Are there any resources you can direct me to regards attaching 2 sensors to an Arduino or articles to help me better understand arduino.

That's a pretty wide-open question! :-) You'll need to narrow it down some to keep it manageable. Try searching for "Introduction to Arduino" and follow a few of those leads. Try running a few of the the example programs from the Arduino IDE. Make small alterations to the examples to get some some hands-on experience with- and "ownership" of the compile/upload process. Find a few tutorials that demonstrate using a sensor & build them. Even if it's just to measure a resistor. By then you'll have some better-focused questions to search for or to bring back here. Have fun!


text:
Arduino Pro Mini PWM issue
I want to create a small LED strip driver/controller with 2 channels (Cold/Warm white) using Arduino Pro Mini (5V/16MHz). I have connected the parts per the following diagram
I have pins 5 and 6 setup as output, control them via analogWrite, and it all works great on Arduino UNO.
The problem comes with Arduino mini pro. When one channel is set to 255 and the other is 0, the LED strip does light only in one color, which is OK and when I swap the PWM channel's values, the other light color starts to shine. So far so good. When I set both to 0, the strip keeps on shining at about 30% (I don't have a scope, so I can't tell what the pwm signal is doing). Varying the channels' pwm in the range 0-255 does affect the light somehow but it never goes down to a complete off.
Looking at the arduino uno and pro mini I can't see anything obvious that should make them act differently from the hardware perspective so I'm guessing there's a problem in the libraries or perhaps my arduino pro mini (a clone) is somehow messed up.
Has anyone observed this kind of behavior in Arduino pro mini and has a solution for it?
Edit: Added some measurements per @Abel's request. I measured both DC and AC with and without the LED strip connected.
Connecting the LED strip really does mess things up, but WHY? UNO can handle it, but the pro mini can't! I thought mini was basically just shrunk down arduino uno (both have the same SMD version of MEGA328P), but apparently there are some differences.

check your led strip specs.  you may have to change the pwm frequency.

@Abel, does the pwm frequency differ between the UNO and the pro mini? Like I said in my question, the same code works just fine in an UNO board but doesn't on pro mini. I used pins 5 and 6 in both cases.

@Juraj - the problem is with pro mini  - a link to the particular board is in my question - click on the "clone" word.

theres a lot that can be wrong.  without led strip specs I can't determine.  1) frequency may be throwing off something in your strips own voltage regulation (you are basically swinging the "ground" side around). 2) pro mini logic voltage may be lower (people mix 3.3v and 5v all the time).  add in your pull to ground on the logic, and your power mosfets may not be reacting properly.  (shouldnt need to pull output logic)

@Abel the strip is this: https://www.aliexpress.com/item/33005175470.html (5050 CCT, 12V). With my first try I didn't use the MOSFETS. I used TIP120 Darlington transistor which did not have the 10k pull down and that's when I first observed the strange behavior. I didn't try it with the Arduino UNO back then and decided to switch to the MOSFETS. As for the variant of Arduino mini. I'm pretty sure I have the 5V (I checked voltage on pins and signage on the crystal). I tried to change the board type to 3.3V in the Arduino IDE - apart form the timing on the serial line, nothing changed.

if the crystal checks out, its most likely 5V.  if you have a meter, put it in AC mode and see what's happening on the pwm signals.  It'll report VRMS, but it's still better than nothing.  Compare what you see on uno vs mini pro.

Showing the actual wiring may reveal something.

Double check you wiring, and resistor values. Double check you solder joints on your pro-mini (assuming you soldered the headers yourself). Wiggle all you connections in your breadboard.

Thanks to comments I received from several people here I quadruple checked the wiring and eventualy found the problem. My recent Arduino Uno tests were done on a breadboard, but I had the Pro Mini prototype soldered on the prototyping board which has the holes connected in columns on the copper side. I made the cuts in all the necessary places ... but one! That one omission caused a short between pin 6 and the drain from the other channel's mosfet. The problem with these boards is that the parts are on one side and while flipping the board to the copper side, it is too easy to get lost in all the columns and miss something.
The morales of this story are: "Never be too certain about your wiring/soldering" and "Arduino is pretty resistent to my attempts to fry it :)".

Get a good digital O'scope. They are incredibly cheap these days, and pay for themselves pretty rapidly in reduced frustration and time spinning one's wheels.  I recently got a Hanmatek DOS1102 dual-channel 110MHz, and I haven't used my old analog Tek2236 since

Nice clean design! Let's determine for sure what voltage it is outputting to the MOSFETs. Write a very simple sketch that cycles a pin every few seconds and measure the voltage. You should get ground and VCC. If it is less than 4.5 volts (guard band included) your FETs will give you problems as they will not be properly enhanced.  Here is why: The IRF520 is a Power Mosfet with 9.2A collector current and 100V breakdown voltage. The mosfet has a low gate threshold voltage of 4V and hence commonly used with microcontrollers like Arduino for switching high current loads. You may have to get a different MOSFET with a lower gate threshold. Note there is some variation in the devices so they will not all but the same but will meet the specification. The 10K pull down resistors is a great addition and guarantees your state during reset until it is set up.


text:
Arduino freezing frequently
I'm using an Arduino Nano for programing an automatic hand sanitizer that has a thermometer. But after running for some time the board freezes and only restarting can solve the issue. While checking the serial monitor it suddenly stops working.
The program includes reading distance from an ultrasonic sensor and temperature from an IR thermometer (distance and ambient temperature are read continuously and the serial monitor will constantly display values). At random when the temperature is read and is displayed on the OLED screen, the board freezes (board freezes only at this time) and restarting can make it work 1 more time and then freezes again.
Question 1
Is it something to do with the code or is it a hardware issue?
Question 2
Does a clone version of NANO cause such problem? (I'm using a clone version)
This is my code:
#include <Wire.h>
#include <Adafruit_MLX90614.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>

Adafruit_MLX90614 mlx = Adafruit_MLX90614();
Adafruit_SSD1306 display(-1);
//Adafruit_SSD1306 display(128, 64, &Wire, -1);

#define trigPin 12 // Trigger pin
#define echoPin 11 // echo pin

float roomTemp; // ambient temperature
float objectTemp, stemp; // object temperature

int readcount = 0;
float threshold= 3.5 ;

int maximumRange = 15; // Maximum range needed
int minimumRange = 3; // Minimum range needed
long duration, distance; // Duration used to calculate distance
int dtime;
unsigned long rememTime;

// motor coding
int set_time;
float distance_cm;
unsigned long ultra_time;
int set_cm = 20;
int motor = 2; // Output for Motor drive
int flag = 0;

void setup() {
  Serial.begin(9600);// initialize serial communication at 9600 bits per second:

  pinMode (trigPin, OUTPUT);
  pinMode (echoPin, INPUT);
  pinMode(motor, OUTPUT);

  display.begin(SSD1306_SWITCHCAPVCC, 0x3C) ;
  delay(200);
  display.clearDisplay();
  display.setTextColor(WHITE);
}

void loop() {
  // temperature sensor coding
  digitalWrite(trigPin, LOW);
  delayMicroseconds(2);
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);

  duration = pulseIn(echoPin, HIGH);
  //Calculate the distance (in cm) based on the speed of sound.
  distance= duration * 0.034/2;

  // reading object and ambient  temperature
  objectTemp = threshold + mlx.readObjectTempC() ;
  roomTemp = mlx.readAmbientTempC() ;

  // print to Serial port
  Serial.println("Object:" + String(objectTemp) + ", Ambient:" + String(roomTemp));
  Serial.println(distance);

  // display on OLED
  display.clearDisplay();
  display.setTextSize(1);
  display.setCursor(0, 25);
  display.print("Dis:" + String(distance) + "cm");
  display.setCursor(65, 25);
  display.print("Room:" + String(roomTemp).substring(0, 4) + "C");
  display.display();
  display.setTextSize(2);
  display.setCursor(0, 0);

  if (distance < minimumRange) {
    display.print("TOO CLOSE!");
  }
  if ((distance >= minimumRange) && (distance <= maximumRange)) {
    if (readcount == 5) { // after reading 5 consecutive time
      disptemp();
    } else {
      display.print("HOLD ON"); // when in range, ask user to hold position
      stemp = stemp + objectTemp;
      readcount++; // until approx. 5 x 200 ms = 1 sec
    }
  } else { // if user is out of range, reset calculation
    dtime = 100;
    readcount = 0;
    stemp = 0;
  }
  display.display();
  delay(dtime);
  Serial.println("count  :"+String(readcount));
}

void disptemp() {
  objectTemp = stemp / 5; // get the average reading of temp
  display.setTextSize(1);
  display.print("YOUR TEMP:");
  display.setTextSize(2);
  display.setCursor(60,5);
  display.print(String(objectTemp).substring(0, 4) + "C");
  display.display();
  readcount = 0;
  stemp = 0;
  if (objectTemp >= 38) {
    play_alert();
  } else {
    play_ok();
  }
  ultrasonicRead();
  dtime = 5000; // wait for 5 seconds
}

void play_ok() {  // play three sequential notes when object temperature is below 37.5C
  tone(3, 600, 1000);  // pin,frequency,duration
  delay(200);
  tone(3, 750, 500);
  delay(100);
  tone(3, 1000, 500);
  delay(200);
  noTone(3);
}

void play_alert() { // beep 3x when object temperature is >= 37.5C
  tone(3, 2000, 1000);
  delay(1000);
  tone(3, 3000, 1000);
  delay(1000);
  tone(3, 4000, 1000);
  delay(1000);
  noTone(3);
}

void ultrasonicRead() {
  if (distance < set_cm) {
    digitalWrite(motor, HIGH);
    Serial.println("Motor On");
    delay(500);
    digitalWrite(motor, LOW);
    Serial.println("motor off");
  }
}

Remove all the String objects from your code.

You may want to consider using the watchdog timer to cause the board to automatically reset for this sort of thing.  To be clear, I'm not proposing this as a solution; you should still address the actual problem.  But the watchdog is often used to add a layer of protection against freezing up when deployed.

It should be a fun project. Since you did not give us a schematic (not a frizzy thing) I can only guess. It appears to me you are using the I2C interface and may be week on the pull up resistors. Also the early 1 wire library would hang up if a device missed an ACK. There are many small programs that display the amount of free memory, include that in your code and see if it is stable or slowly leaking memory.

You can put the following two lines at the top your sketch: void got_to_line(int n) {Serial.print(F("[Line:")); Serial.print(n); Serial.println(']'); Serial.flush();}  and #define GOT_HERE() got_to_line(__LINE__)   You can then litter your code with GOT_HERE(); moving them around until you find the exact line (or lines) where the freeze is happening.  If you do that, let us know the exact line (or lines) that it is freezing on.

Any allocation / de- or re-allocation of memory[1] during run time, will cause the heap (the pool of memory from which those allocations are made) to expand until the heap and the stack grow toward each other enough to collide, at which point one overwrites part of the other with unpredictable results.
Strings are allocated from the heap. Strings that are built up little by little, as with:
Serial.println("Object:" + String(objectTemp) + ", Ambient:" + String(roomTemp));
 cause allocation several allocation / de-allocations.
As a simple-to-implement test, comment out the statements that use the String object and just print the raw data. Your program should run without crashes.
To recreate what you're now doing with Strings, I'd suggest using snprintf() to build up your output into a fixed-size output buffer, which can be a local character array (allocated on the stack and de-allocated when the containing function exits). This should be equally stable as the abbreviated experiment I proposed above.
[1] *Unless allocated memory is de-allocated most-recent-first. And even that assumes foreknowledge of the memory allocation algorithm in use, and so, is non-portable).
One way around this is to write one's own memory allocator/de-allocator, which has a pre-assigned pool of fixed-length blocks, one of which it supplies for any memory request of any size, so long as:

there is a free block to allocate; and
the requested size can fit in (the data-space of) a pre-assigned block.

why not a series of Serial.print()?

A series of Serial.print() is perfectly acceptable; I suggested snprintf() as being semantically closer to concatenation of Strings as the OP had written.

In addition to some of the above comments;
Your Nano may not support the watchdog. Please check This post on the Arduino forum
If you are looking for "There are many small programs..." I'll just post the functions I use for getting free memory, heap and stack information below.

int freeRam()
{
    extern int __heap_start, *__brkval;
    int v;
    return (int)&v - (__brkval == 0 ? (int)&__heap_start : (int)__brkval);
}

uint8_t * stack()
{
  uint8_t * ptr;
  ptr = (uint8_t *)malloc(4);
  free(ptr);
  return ((uint8_t *)(SP));
}

uint8_t * heap()
{
       uint8_t * ptr;
       ptr = (uint8_t *)malloc(4);
       free(ptr);
       return(ptr);
}

"may not support the watchdog" is perhaps not the best way to put it.  Optiboot clears MCUSR and so WDRF, meaning you cannot tell that the watchdog timer was the cause of reset merely by inspecting MCUSR.  As a reset mechanism it otherwise works perfectly fine.  There are some ways to somewhat address the clearing of MCUSR also, beyond just fixing the bootloader that is.


text:
L293D motorshield with batteries doesn't power Arduino
Recently I came across a video about a guy building a remote Bluetooth-controlled Arduino car and I was quite amazed. So I decided I wanted to build it too. I have no Arduino or electronics experience at all other than being an IT professional.
So I bought the parts he used in the video (he advised a knockoff Arduino in the description).
After putting it all together the motors work through Bluetooth (yay!). But the issue is that the batteries connected to the motorshield don't give power to the Arduino at all (because the lights don't turn on).
When plugged in the laptop with the USB cable the Arduino gets powered and the motorshield light turns on just a bit, but not enough to make the motors and Bluetooth work.
So in short:
USB powered: Arduino works, motorshield light barely turns on, motors don't work, Bluetooth lights go on, but is not emitting a signal.
2x 18650 battery powered: motorshield light shines bright, Arduino doesn't work, Bluetooth lights don't flicker.
Both: everything works.
So for some reason, the batteries connected to the motorshield don't power the Arduino.
Video used:
https://youtu.be/Q36NbjPMV5k
Circuit diagram:

Knockoff arduino:

L293D motor shield (I'm aware that the ground of the power isn't plugged in)

Parts used:

Geekcreit UNO r3 ATmega16U2 AVR
L293D motor shield
Geekcreit HC-05 bluetooth
4 TT motor
2x 18650 3,7-4.2v 2200mah batteries

I really don't know what I did wrong, since I followed the video and did exactly what the person did. Maybe the batteries aren't powerful enough?

the yellow jumper is the first suspect ... remove it and short the pins with a screwdriver

@jsotola what would shorting the pins cause?

it would replace the jumper ... the yellow jumper itself may be missing the metal strip that shorts the two pins

That sadly didn't work.

Take your voltmeter and measure the voltage from the white wire to the black wire.  These are supposed to be +5V and GND.  But unless you measure them you won't know if they are or not.  Don't have a voltmeter?  It's time to get one.

@jwh20 i can get a voltmeter, but it'll take a while, cuz corona. What would my next steps be if it was correct or not correct?

If there is 5V present, then the problem is likely on the Arduino side.  If not, then your board may be the problem.

Would there be a way to rule the board or arduino out if said 5V is present or not?

After trying to short the pins again, i found out @jsotola was right. The jumper is a defect. It's working now

You're allowed to answer your own question.

The problem was that the 2 pins on which the jumper sits, the jumper or the board was broken (idk exactly). I might've caused that myself by turning on the batteries + powering it through usb at the same time.
I bought a new L293D board then made sure I didn't connect usb power to the arduino while the L293D was sitting on top of it. I uploaded the code, then disconnected the usb, put the L293D on top, powered it all and it works like a charm!

Nice project. The batteries are connected to the motor power which is correct but the motor shield does not output voltage to the 5V system.  Try connecting the batteries to the Vin on the board and all should work.


text:
Using Keyboard library for ISO-UK layout
I am creating a keyboard and the PC I use it with is configured for UK so the keyboard layout it expects is this

I've highlighted the ISO-UK vs ANSI-US differences but the only key I am having real problems with is the backslash key.
My physical layout is actually this (ortholinear "Planck") but it's essentially the same except with two logical layers and variation in positioning.

The above is a fully functional UK-layout keyboard with the exception of the "\" key.
The sketch I am using is too large and distracting to post here but the following test sketch
#include "Keyboard.h"

byte keylist[] = { '`', '2', '3', '\'', '#', '\\' };

void setup() {
  Keyboard.begin();
  delay(1000);

  // unshifted
  for (byte i = 0; i < sizeof(keylist); i++) {
    Keyboard.press(keylist[i]);      delay(100);
    Keyboard.release(keylist[i]);    delay(100);
  }

  Keyboard.press(KEY_RETURN);
  Keyboard.releaseAll();

  // shifted
  for (byte i = 0; i < sizeof(keylist); i++) {
    Keyboard.press(KEY_LEFT_SHIFT);
    Keyboard.press(keylist[i]);
    delay(100);
    Keyboard.releaseAll();
    delay(100);
  }
}

void loop() {
  delay(1000);
}

Creates this output (in a Notepad window)
`23'£#
¬"£@£~

I did try switching focus to a keyboard diagnostic tool - KeyHitter by Elite Keyboards which showed different results
12:31.0675 ` (0xDF, BIOS 0x29) DOWN
12:31.0771 ` (0xDF, BIOS 0x29) UP -> 100ms
12:32.0772 2 (0x32, BIOS 0x03) DOWN
12:32.0871 2 (0x32, BIOS 0x03) UP -> 100ms
12:33.0872 3 (0x33, BIOS 0x04) DOWN
12:33.0972 3 (0x33, BIOS 0x04) UP -> 100ms
12:34.0972 ' (0xC0, BIOS 0x28) DOWN
12:35.0072 ' (0xC0, BIOS 0x28) UP -> 100ms
12:36.0072 LShift (0x10, BIOS 0x2A) DOWN
12:36.0082 3 (0x33, BIOS 0x04) DOWN
12:36.0172 LShift (0x10, BIOS 0x2A) UP -> 100ms
12:36.0182 3 (0x33, BIOS 0x04) UP -> 100ms
12:37.0172 \ (0xDE, BIOS 0x2B) DOWN
12:37.0272 \ (0xDE, BIOS 0x2B) UP -> 100ms
12:38.0271 Enter (0x0D, BIOS 0x1C) DOWN
12:38.0273 Enter (0x0D, BIOS 0x1C) UP -> 2ms

...
So the Arduino Keyboard library translates '#' into shift+3 which is unhelpful for UK users but I'm mystified why Keyhitter sees that '\\' produces the expected \ but other programs see it producing #! I guess Keyhitter intercepts keystrokes at a lower level than normal applications - for example it correctly shows Win being pressed but prevents Windows opening a start-menu.
The result in Notepad is typical of the effect produced in normal applications. So that's probably more relevant.
I can work around the '#' producing a shift+3 since '\\' produces # but how then do I generate a \?

try for (byte i = 0; i <= 255; i++) { Keyboard.press(i) .......  .... one of the values should generate the desired character ... then use that value instead of '\\'

@jsotola: I'm a bit wary of inadvertently hitting sequences of special keys like Win followed by  say F1 - so I tried an app that I suspect captures keystrokes at a low level - but that wasn't too helpful. I may try your suggestion if I can work in some safeguards so that I have time to work out what's happening before the system descends into a frenzied chaos.

figure out the byte value that represents the Win key and exclude it ... if ( i != Win ) Keyboard.press(i);

@jsotola: I was sceptical but that approach worked. I had to use a button press to increment my index because you encounter a lot of function keys etc causing help windows and other weird things to happen that you need time to recover from with a real keyboard. Keyboard.press(0xEC) produces "" in Notepad and when used in conjunction with shift produces the expected "|".

The USB keyboard protocol has no concept of characters. It doesn't know and doesn't care what character a key represents. Instead each code represents the location of the key on the keyboard, and it's down to the software on the computer to map those locations into characters through its own keyboard map.
So the Arduino has to do the opposite when you want to "print" text through the keyboard - convert that text into the locations of the keys on the keyboard. And it does that through the _asciimap array in Keyboard.cpp.
To use any other keyboard layout than US you need to modify that map so that each ASCII value points to the correct location for that character as defined in your computer's keyboard map.
You can find the list of keyboard location codes (named in this document after the US keycap decals) here (page 53) which you can then use to map any changes.
For example in _asciimap a double quote is listed as:
     0x34|SHIFT,    // "

Which maps to Keyboard ' and " in USB. But for UK you want that to be shift-2, which is Keyboard 2 and @ in a US layout.  That entry is hex 1F.
So changing the quote to be a shifted 0x1F should give you the quote you desire:
    0x1F|SHIFT, // "

You would need to do the same to all other characters that need re-mapping (including ). Some may take a little trial and error to work out what the equivalent key on a UK keyboard is, since some keys are in physically different locations (most notably there is no key to the left of Z on a US keyboard, but there is an extra one to the right of ]).
Unfortunately the Arduino Keyboard library doesn't provide a way for a user to give their own keyboard map. Instead you have to modify the source code of the library itself.

This makes sense but there is more going on because, on my Arduino-based keyboard, shift+2 already produces " rather than @ - so there's some additional mapping in Windows that's already doing most of the work of making my keyboard behave like an ISO-UK keyboard. (If interested Keyboard.press(0xEC) is an effective UK "" key. This whole area seems a lot more complex than I remember back in the days of PC-XT keyboard scancodes and TSRs

For completeness I am posting this answer. You can produce a UK backslash keystroke event by using something like
#define KEY_BSLASH 0xEC

This was found rather more empirically than analytically so is not an especially informative result, but it might be of some use to others creating non-ANSI keyboard layouts using Arduinos.

If it works on ISO-UK, it is likely to work on every ISO layout (e.g. give “<” in AZERTY). And this makes your answer more generally useful.


text:
Can arduino nano drive two circuit
I am building a robot snake with a bunch of servos and ov7670. As I see, ov7670 operate with 3.3v and servos needs 5v. I will use Lipo battery for servos for this I need to connect ground pin of arduino and input of battery. But For ov7670, I already connect the ground pin of arduino. Can I connect ground with a jumper to another breadboard to connect with lipo battery and servos or I need two arduino nanos?

You can use a common ground in fact it's the normal thing to do with external circuits such as relays, servos etc

I am a beginner and do not know much about arduino. Thanks for your answer.