text:
getting SPI SSD1307 to work on Arduino Mega
After some time off, I decided to get back into my project after some help from this topic I started earlier Difference in pinout (types?) Uno/Mega. Unfortunately, even tho I have read multiple times what has been said about the SPI pins on a mega, the displays simply will not work. Both my LED strips and rotary encoder are working, so my code compiles and uploads as it should. The displays are ssd1307 using SPI.
Pinout from MEGA to displays
49 > RST for display1/display2/display3
50 > DC for display1/display2/display3
51 > SDA for display1/display2/display3
52 > SCK for display1/display2/display3

33 > CS for display1
34 > CS for display2
35 > CS for display3

Here is the code I am trying to use:
#include <Adafruit_NeoPixel.h>
#include "HCuOLED.h"
#include "SPI.h"

Adafruit_NeoPixel REVLEDS = Adafruit_NeoPixel(7, 2, NEO_GRB);
Adafruit_NeoPixel DASHLEDS = Adafruit_NeoPixel(3, 3, NEO_GRB);

#define SCK 52
#define SDA 51
#define DC 50
#define RST 49

HCuOLED HCuOLED_5(SSD1307, 33, DC, RST); // For SSD1307 displays (HCMODU0050 & HCMODU0052)
HCuOLED HCuOLED_4(SSD1307, 34, DC, RST); // For SSD1307 displays (HCMODU0050 & HCMODU0052)
HCuOLED HCuOLED_3(SSD1307, 35, DC, RST); // For SSD1307 displays (HCMODU0050 & HCMODU0052)

#define s1 6
#define s2 5
#define key 4

int newCounter = 0;
int oldCounter = 0;
int oldState;
int newState;
int rotated = 0;
int keyState = 0;
int keyReset = 0;

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

  REVLEDS.begin();
  REVLEDS.setBrightness(25);

  DASHLEDS.begin();
  DASHLEDS.setBrightness(25);

  pinMode(s1, INPUT);
  pinMode(s2, INPUT);

  oldState = 1;
  newState = oldState;

  HCuOLED_5.Reset();
  pinMode(53, OUTPUT);
}

void loop() {

  newState = digitalRead(s1);
  if(newState != oldState){
    if(digitalRead(s2)!= oldState){
      newCounter ++;
    } else {
      newCounter --;
    }
    if(newCounter == (oldCounter+2) ||newCounter == (oldCounter-2)){
      if(newCounter > oldCounter) rotateRight();
      else rotateLeft();
      oldCounter = newCounter;
    }
  }
  oldState = newState;

  keyState = digitalRead(key);
  //Serial.println(keyState);
  if(keyState == LOW && keyReset == 0){
    onButtonPress();
    keyReset = 1;
  } else if (keyReset == 1 && keyState == HIGH){
    keyReset = 0;
  }

  for(int i = 0; i < 7; i++){
  REVLEDS.setPixelColor(i, 0,255,0);}
  REVLEDS.show();

  for(int i = 0; i < 3; i++){
  DASHLEDS.setPixelColor(i, 0,0,255);}
  DASHLEDS.show();

  //display 5
  HCuOLED_5.SetFont(Terminal_8pt);
  HCuOLED_5.Cursor(44,0);
  HCuOLED_5.Print("Cpt");
  HCuOLED_5.Cursor(20,10);
  HCuOLED_5.Print("Fastlane");
}

void onButtonPress(){
  Serial.println("Pressed button");
}

void rotateLeft(){
  Serial.println("Rotated left");
}

void rotateRight(){
  Serial.println("Rotated right");
}

Now the question is, what am I missing?
TIA!

the SSD1307 supports SPI and I2C. you should provide a link to the display module. SDA and SCK are used to label I2C pins

Sorry forgot to add that this was the SPI version of the ssd1307.

Pin 53 is set to OUPUT as you can see in the code. In the link of my original post you can see that I already had these SPI display work on mu UNO, but not on my MEGA. The display in question are these:
https://nl.aliexpress.com/item/5pcs-7pin-0-96-White-OLED-module-0-96-OLED-New-128X64-OLED-LCD-LED-Display/32650457238.html?spm=a2g0s.9042311.0.0.6d864c4dvMy0SY
I am also planning on adding 2 bigger ones, which are these:
https://nl.aliexpress.com/item/1pcs-Blue-1-3-SPI-Serial-128X64-OLED-LCD-LED-Display-Module-for-Arduino-UNO-R3/32650144885.html?spm=a2g0s.9042311.0.0.6d864c4dvMy0SY

The displays do not use SPI MISO pin. It is 12 in Uno and 50 on Mega. On Mega you try to use pin 50 for DC pin of the displays and it creates a conflict with SPI. MISO should be an INPUT and DC is OUTPUT.

Found the problem... after my break, i forgot that the .refresh() command is actually the command that displays something on the screen, while I kept thinking it was to clear the screen. After adding that to my code together with .clearBuffer(), everything works with the following pinout:
Pinout from MEGA to displays
48 > RST for display1/display2/display3
49 > DC for display1/display2/display3
51 > SDA for display1/display2/display3
52 > SCK for display1/display2/display3

33 > CS for display1
34 > CS for display2
35 > CS for display3

With the following code to show different stuff on screen:
#include "HCuOLED.h"
#include "SPI.h"

#define SCK 52
#define SDA 51
#define DC 49
#define RST 48

HCuOLED HCuOLED_5(SH1106, 33, DC, RST); // For SSD1307 displays (HCMODU0050 & HCMODU0052)
HCuOLED HCuOLED_4(SH1106, 34, DC, RST); // For SSD1307 displays (HCMODU0050 & HCMODU0052)
HCuOLED HCuOLED_3(SH1106, 35, DC, RST); // For SSD1307 displays (HCMODU0050 & HCMODU0052)

int tCounter = 0;

void setup(){
  HCuOLED_5.Reset();
  //pinMode(53, OUTPUT);
}

void loop() {
  //display 3
  HCuOLED_3.SetFont(Terminal_8pt);
  HCuOLED_3.Cursor(44,0);
  HCuOLED_3.Print("Cpt");
  HCuOLED_3.Cursor(20,10);
  HCuOLED_3.Print("Fastlane");
  HCuOLED_3.SetFont(LCDLarge_24pt);
  HCuOLED_3.Cursor(20,30);
  HCuOLED_3.Print("3 - ");
  HCuOLED_3.Cursor(65,30);
  HCuOLED_3.Print(tCounter);
  HCuOLED_3.Refresh();
  HCuOLED_3.ClearBuffer();

  //display 4
  HCuOLED_4.SetFont(Terminal_8pt);
  HCuOLED_4.Cursor(44,0);
  HCuOLED_4.Print("Cpt");
  HCuOLED_4.Cursor(20,10);
  HCuOLED_4.Print("Fastlane");
  HCuOLED_4.SetFont(LCDLarge_24pt);
  HCuOLED_4.Cursor(20,30);
  HCuOLED_4.Print("4 - ");
  HCuOLED_4.Cursor(65,30);
  HCuOLED_4.Print(tCounter);
  HCuOLED_4.Refresh();
  HCuOLED_4.ClearBuffer();

  //display 5
  HCuOLED_5.SetFont(Terminal_8pt);
  HCuOLED_5.Cursor(44,0);
  HCuOLED_5.Print("Cpt");
  HCuOLED_5.Cursor(20,10);
  HCuOLED_5.Print("Fastlane");
  HCuOLED_5.SetFont(LCDLarge_24pt);
  HCuOLED_5.Cursor(20,30);
  HCuOLED_5.Print("5 - ");
  HCuOLED_5.Cursor(65,30);
  HCuOLED_5.Print(tCounter);
  HCuOLED_5.Refresh();
  HCuOLED_5.ClearBuffer();

  tCounter++;
}

and the pin 50?

Unused. However It also works if I don't set pin 53 to OUTPUT. Why is this?

SPI library does it in begin

was use of pin 50 as DC one of the reasons why it didn't work?


text:
avrdude ser_open() can't set com-state
When trying to upload the blink sketch to my (unofficial) Arduino Uno, I get the following error:
avrdude ser_open() can't set com-state for "\\.\COM3"

I have programmed this Arduino before using this same laptop, but not for quite some time.  I have not changed anything in the Arduino IDE in this time.
I have tried the following:

Reading answers for the following related questions:

avrdude: ser_open(): can't set com-state for "\\.\COM2"
avrdude: ser_open(): can't open device "\\.\COM3"?
Can't upload to my Arduino UNO
avrdude: ser_open(): can't open device "\\.\COM4": Access denied

Confirmed that COM3 was the correct port by going to device manager. I have only one port listed here, COM3, and it disappears when I unplug my Uno and reappears when I plug it back in again.  One strange thing to point out is that it is called RAMPS for some reason?
Tried 3 different USB cables
Tried 3 different USB ports
Restarting the computer
Uninstalled and reinstalled the Arduino IDE
Uninstalled the device from Device Manager
Tried a (previously untested) (also unofficial) Arduino Nano.  When I looked up this in Device Manager, it was also reported as RAMPS on COM3 (strange?)

None of the above fixed the issue and all gave the same error as shown above (except when trying different USB ports which showed the error just for different COM ports).
EDIT: Just tried both the Uno and Nano on another computer and both worked fine. This confirms that both the arduinos and cables I'm using are working properly.

Ch340 drivers solved the problem.

Maybe a Windows driver problem.
Do your uno and nano use a ch340? (It is the component translating USB to uart (serial pins of atmega328).
Windows has no software way to differenciate boards using this component. It is a common use on cheap clones to lower price.
Official arduinos use a second atmega (atmega16u2 natively supporting usb) instead of the ch340. Allowing windows to identify the arduino model.
You should try to update your ch340 driver as you have the same problem with the 2 boards. here is the download page of the manufacturer (ch341ser.exe is the package you want)
You can also try to connect your board to an usb2 port as some problems (and solutions to try) are posted here (arduino forum)
And even try to use an usb2 hub...

It was the driver.  For reference, I uninstalled the driver using Device Manager, then plugged the Uno in again and it installed the correct CH430 driver for me automatically, which is exactly what it must have done on the other computer since there has never been an Arduino plugged in to it before.

Worked for me as well, I just uninstalled the driver and scanned for changes

Exactly! A windows update can wipe out the existing CH341 driver, so re-installing it will fix it.  Just 1. uninstall from Device Manager, checking the box to include the driver, then 2. It will be automatically re-installed in a few seconds (or the next time you plug in the Arduino clone).

I had the same problem, open the port under COM and LPT in your device manager.
Then roll back driver so the PC uninstalls all updates to the driver. At this point uploading the code will give the "Windows does not recognize driver" or some error like that. Now just unplug and plug the UNO back in and update driver.
This solved the problem for me.
Hope this helps :)

For the records, the default/vanilla drivers should be by FTDI. They can be installed automatically by Windows, but it's not bundled with them out of the box (so you must be online, and have updates enabled).

I had the same problem. I was able to upload a simple Blink example, but not my own program. And I thought there's no problem in my program, since I successfully tested it on other Arduino before. But actually, that was the problem. I had this in my program (for console logs):
void setup() {
  Serial.begin(9600);
}

Then I read that different Arduinos use different baud rates. Originally I tested it on Arduino Mega, but this time I wanted to upload it to "unofficial" Arduino Nano (for which you have to use ATmega328P (Old Bootloader) option when uploading).
Since I didn't need debug logs in my program anymore, I removed these 'Serial' commands completely. Then it got uploaded without problems.
A short article on this topic

I have the same problem.  I found it related to the card and not the PC.  The offending card uses processor ATMEGA328P_U_TH (Image 1).  The successful card uses a different processor ATMEGA328P_U (Image 2).
I have NOT found a way to use the ATMEGA328P_U_TH card.  It will not correctly connect to a PC and allow code to download from IDE to card.
Image 1

Image 2

the way more important difference is the USB chip. one has a FTDI chip or CH340, the other has Atmega16u2

Juraj, Thank you.  The issue that I am experiencing is that the card with FTDI does not link to any PC.  I made sure the CH340G driver code was loaded.  Still unsuccessful.  I'd like to find out why and make corrections.   But, I do not have the time to go through the troubleshooting steps on my own.

source: Stack Exchange

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

sort: votes


text:
I need help with code with two IR sensors using ATMega16
I'm working on a ball-counting project using two IR sensors to detect balls entering and exiting a room, but I'm currently stuck. I need help refining the logic in my while loop. Here's how I want it to function:
The first sensor detects a ball.
The first sensor stops detecting.
The second sensor detects the ball.
The second sensor stops detecting.
The counter should increase or decrease depending on which sensor detected the ball first.
Right now, my code only works when both sensors detect an object at the same time.
if (!(PINA & (1<<PA0))) { //Check S1

    while (!(PINA & (1<<PA0)));

    // Now check if S2 is detecting
    if (!(PINA & (1<<PA1))) {

        while (!(PINA & (1<<PA1)));

        // Increment the visitor count
        visitor_count++;
    }
}

// Check if S2 is detecting
if (!(PINA & (1<<PA1))) {
    while (!(PINA & (1<<PA1)));

    // Now check if S1 is detecting
    if (!(PINA & (1<<PA0))) {
        // Wait for S1 to stop detecting
        while (!(PINA & (1<<PA0)));

        // Decrement the visitor count
        visitor_count--;
    }
}

The first sensor detects
The second sensor detects
The first sensor stops detecting
The second sensor stops detecting
Counter increases or decreases
But sensors are not close enough and will never detect a ball at the same time. I tried asking ChatGPT, but it keeps giving me the same answer. I thought you’ll understand better my problem.
I will appreciate any advice.
Edit: There is just one entrance, with two sensors.

You need to implement a state machine. A state machine is such a common solution that if you do not know what one is, now would be a great time to learn.

A common method to count objects (balls or people) in a space with only 1 opening (entrance / exit) is to use 2 beam interruption detectors placed close enough such that the object of interest will, at some point while entering or exiting the space, block both beams at the same time. Specifically, one beam will be blocked, then both and finally the other beam will be blocked. To detect the object's direction (entering or exiting) a well understood method called quadrature decoding is used. As this is a common solution, it is likely what the AI assumed was requested.
In the above case, a simple 4 state machine can be implement to detect direction of travel. Let's call the beams A and B. The 4 states are simply 1) no beams blocked, 2) only beam A blocked, 3) both beam B & A blocked & 4) only beam B blocked. The object counter can be incremented or decremented depending on the direction of travel of the object. Assumptions are made that only 1 object will pass the detector at a time and that the object will completely pass the detector without changing direction.
If the detectors are spaced far enough apart that they both can not be blocked by the same object at the same time, the solution can remain identical to the above. However, we will not be able to know for sure which of 2 of the above stats (no beams blocked and both beams blocked) we are in. So we need to make an additional assumption. There can only be 1 object between the 2 detectors at any given time. If true, we sill only need 4 states. But the state where both beams are blocked will need to be changed to be identical to the state where no beams are blocked. They will be identical except one of these identical states will represent no object between the detectors and the other an object between the detectors.
To conclude, the 1st design is more robust and and harder to confuse in the real world (where assumptions are often disregarded). The 2nd design is less robust and can be confused easily in the real world.

The issue lies in the order of operations and the logic that checks the sensors. You want the logic to handle cases where a ball could be detected by one sensor first and the other sensor shortly after, depending on the direction of travel. You can modify the code like this:
// Variables to keep track of the sensor states
bool s1_detected = false;
bool s2_detected = false;

if (!(PINA & (1<<PA0))) { // Check if S1 detects first
    s1_detected = true;

    // Wait for S1 to stop detecting
    while (!(PINA & (1<<PA0)));

    // Now check if S2 detects after S1
    if (!(PINA & (1<<PA1))) {
        s2_detected = true;

        // Wait for S2 to stop detecting
        while (!(PINA & (1<<PA1)));

        // Increment the visitor count
        if (s1_detected && s2_detected) {
            visitor_count++;
        }

        // Reset detection states
        s1_detected = false;
        s2_detected = false;
    }
}

// Check if S2 detects first
if (!(PINA & (1<<PA1))) {
    s2_detected = true;

    // Wait for S2 to stop detecting
    while (!(PINA & (1<<PA1)));

    // Now check if S1 detects after S2
    if (!(PINA & (1<<PA0))) {
        s1_detected = true;

        // Wait for S1 to stop detecting
        while (!(PINA & (1<<PA0)));

        // Decrement the visitor count
        if (s2_detected && s1_detected) {
            visitor_count--;
        }

        // Reset detection states
        s1_detected = false;
        s2_detected = false;
    }
}

When S1 detects a ball, the code waits until S1 stops detecting. Then it checks if S2 detects the ball next. If it does, and then S2 stops detecting, it increments the counter.
If S2 detects the ball first, the code waits for S2 to stop detecting, then checks if S1 detects next. If so, the counter is decremented.
Hopefully, this method will work. If you also need guidelines regarding how to interface IR sensors with ATmega16, you can check here:
https://www.pcbway.com/project/shareproject/Interfacing_IR_Sensor_Module_with_Arduino_Nano_31dcd7c1.html

That is exactly the code snippet, that OP posted in their question. You haven't modified anything, besides some comments.

Thanks. Edited.

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


text:
Using Software Serial on Arduino Mega
So Im using this sensor:
https://wiki.dfrobot.com/Serial_6_Axis_Accelerometer_SKU_SEN0386 with this library https://github.com/DFRobotdl/DFRobot_WT61PC
Im using 2 sensors but got poor frequency on Arduino Uno and decicded to switch to Mega since it supports multiple communications at once.
This code works perfectly fine on Uno, but doesnt on Mega. Of course I tried using this method: https://docs.arduino.cc/built-in-examples/communication/MultiSerialMega and I know I shouldnt be using Software Serial on Mega but this library has been written using Software Serial and I cant use a different method (or at least thats how I understand it).
Here is the reason.
SoftwareSerial mySerial(10, 11);
DFRobot_WT61PC sensor(&mySerial);

So I tried multiple variations of pins (ones supporting UART, pcint, TX/RX) https://docs.arduino.cc/learn/built-in-libraries/software-serial and nothing seems to we working. Also tried removing the SD card reader, tried the original example code. I also tried Hardware Serial as it should be but again, it doesnt support this sensor and ends up resulting in errors(or vice versa). Nothing.
Here is the working Uno code:
#include <DFRobot_WT61PC.h>
#include <SoftwareSerial.h>
#include <SPI.h>
#include <SD.h>

#define FILE_BASE_NAME "Pomiar"
#define VCC2 7

const uint8_t CS_PIN = 4;

SoftwareSerial mySerial(2, 3);
SoftwareSerial mySerial2(5, 6);
DFRobot_WT61PC sensor(&mySerial);
DFRobot_WT61PC sensor2(&mySerial2);

File myFile;
File file;

const uint8_t BASE_NAME_SIZE = sizeof(FILE_BASE_NAME) - 1;
char fileName[] = FILE_BASE_NAME "00.txt";

void setup()
{

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

  //Use Serial as debugging serial port
  Serial.begin(9600);
  Serial.print("Initializing SD card...");

  if (!SD.begin(4)) {
    Serial.println("initialization failed!");
    while (1);
  }
  Serial.println("initialization done.");

  while (SD.exists(fileName)) {
    if (fileName[BASE_NAME_SIZE + 1] != '9') {
      fileName[BASE_NAME_SIZE + 1]++;
    } else if (fileName[BASE_NAME_SIZE] != '9') {
      fileName[BASE_NAME_SIZE + 1] = '0';
      fileName[BASE_NAME_SIZE]++;
    } else {
      Serial.println(F("Can't create file name"));
      return;
    }
  }

  //Use software serial port mySerial as communication seiral port
  mySerial.begin(9600);
  mySerial2.begin(9600);
  //Revise the data output frequncy of sensor FREQUENCY_0_1HZ for 0.1Hz, FREQUENCY_0_5HZ for 0.5Hz, FREQUENCY_1HZ for 1Hz, FREQUENCY_2HZ for 2Hz,
  //                        FREQUENCY_5HZ for 5Hz, FREQUENCY_10HZ for 10Hz, FREQUENCY_20HZ for 20Hz, FREQUENCY_50HZ for 50Hz,
  //                        FREQUENCY_100HZ for 100Hz, FREQUENCY_125HZ for 125Hz, FREQUENCY_200HZ for 200Hz.
  sensor.modifyFrequency(FREQUENCY_10HZ);
  sensor2.modifyFrequency(FREQUENCY_10HZ);
}

void loop()
{

  long timestamp = millis();

  float acc1;
  float acc2 ;
  float acc3 ;
  float gyro1 ;
  float gyro2 ;
  float gyro3;
  float angle1;
  float angle2;
  float angle3;

  float acc12 ;
  float acc22 ;
  float acc32 ;
  float gyro12;
  float gyro22 ;
  float gyro32 ;
  float angle12 ;
  float angle22;
  float angle32;

  mySerial.listen();
  if (sensor.available()) {

    acc1 = sensor.Acc.X;
    acc2 = sensor.Acc.Y;
    acc3 = sensor.Acc.Z;
    gyro1 = sensor.Gyro.X;
    gyro2 = sensor.Gyro.Y;
    gyro3 = sensor.Gyro.Z;
    angle1 = sensor.Angle.X;
    angle2 = sensor.Angle.Y;
    angle3 = sensor.Angle.Z;

  }

  mySerial2.listen();
  if (sensor2.available()) {

    acc12 = sensor2.Acc.X;
    acc22 = sensor2.Acc.Y;
    acc32 = sensor2.Acc.Z;
    gyro12 = sensor2.Gyro.X;
    gyro22 = sensor2.Gyro.Y;
    gyro32 = sensor2.Gyro.Z;
    angle12 = sensor2.Angle.X;
    angle22 = sensor2.Angle.Y;
    angle32 = sensor2.Angle.Z;

  }

  myFile = SD.open(fileName, FILE_WRITE);

  if (myFile) {
    myFile.print(timestamp);
    myFile.print("|");
    myFile.print(acc1);
    myFile.print("|");
    myFile.print(acc2);
    myFile.print("|");
    myFile.print(acc3);
    myFile.print("|");
    myFile.print(gyro1);
    myFile.print("|");
    myFile.print(gyro2);
    myFile.print("|");
    myFile.print(gyro3);
    myFile.print("|");
    myFile.print(angle1);
    myFile.print("|");
    myFile.print(angle2);
    myFile.print("|");
    myFile.print(angle3);
    myFile.println("");

    myFile.print(timestamp);
    myFile.print("|");
    myFile.print(acc12);
    myFile.print("|");
    myFile.print(acc22);
    myFile.print("|");
    myFile.print(acc32);
    myFile.print("|");
    myFile.print(gyro12);
    myFile.print("|");
    myFile.print(gyro22);
    myFile.print("|");
    myFile.print(gyro32);
    myFile.print("|");
    myFile.print(angle12);
    myFile.print("|");
    myFile.print(angle22);
    myFile.print("|");
    myFile.print(angle32);
    myFile.println("");

    myFile.close();
  } else {
    Serial.println("error opening test.txt");
  }
}

I also found this question: Arduino Mega 2560 SoftwareSerial Not Working.
The guy has exact problem as I do but nooone found a solution to it.
I also want to note that the manufacturer states that this library and sensor works fine on Mega. Really need your help.
cheers
@edit
So I did some tests and the only code that actually shows something in monitor is:
#include <DFRobot_WT61PC.h>

DFRobot_WT61PC sensor(&Serial);

void setup()
{
  //Use Serial as debugging serial port

  //Use software serial port mySerial as communication seiral port
  Serial.begin(9600);
  sensor.modifyFrequency(FREQUENCY_10HZ);
}

void loop()
{
  if (sensor.available()) {
    Serial.print("Acc\t"); Serial.print(sensor.Acc.X); Serial.print("\t"); Serial.print(sensor.Acc.Y); Serial.print("\t"); Serial.println(sensor.Acc.Z); //acceleration information of X,Y,Z
    Serial.print("Gyro\t"); Serial.print(sensor.Gyro.X); Serial.print("\t"); Serial.print(sensor.Gyro.Y); Serial.print("\t"); Serial.println(sensor.Gyro.Z); //angular velocity information of X,Y,Z
    Serial.print("Angle\t"); Serial.print(sensor.Angle.X); Serial.print("\t"); Serial.print(sensor.Angle.Y); Serial.print("\t"); Serial.println(sensor.Angle.Z); //angle information of X, Y, Z
    Serial.println(" ");
  }
}

But as you see the output is corrupted.

When you can provide a serial instance to the library to use, then it is not written for SoftwareSerial only. Please show how you tried with HardwareSerial and the resulting errors

Quoted from SoftwareSerial Library, "Not all pins on the Mega and Mega 2560 boards support change interrupts, so only the following can be used for RX: 10, 11, 12, 13, 14, 15, 50, 51, 52, 53, A8 (62), A9 (63), A10 (64), A11 (65), A12 (66), A13 (67), A14 (68), A15 (69)", your code not using those pins.

@hcheung I tried them, the code I provided working code for uno so there is proof I didnt make a mistake anywhere

Also I took a look at the library you mentioned, there is no reason why HardwareSerial not work, if it is causing errors, it is something else, probably not instantiates the Serial1 or Serail2 correctly.

If you have problem in Mega, shows the code that doesn't work in Mega, not the code that work in Uno.

@hcheung How can I initialize serial when I first need to initialize my sensor? And providing Hardware serial to the DFRobot_WT61PC sensor(&mySerial); function causes errors

Show the code that doesn't work, not the code that works. How will that help?

Well the code that isn't working is exactly the same @NickGammon

How is the sensor connected to the Mega?

As hcheung said SoftwareSerial on the Mega does not support pins 2, 3, 5, 6 so I don't see how you can expect it to work.

Which pins should I use then to make it work?

Avoid SoftwareSerial whenever you can. It is very fragile: there are so many ways it can break your code... It can be useful on the Uno only because on this board you have little choice. The Mega, however, has four hardware serial ports. SoftwareSerial on the Mega makes no sense at all.

@EdgarBonet how can I use this library then?

@Aivion2000: Use Serial1, Serial2 or Serial3 instead of mySerial.

It's quick and dirty but you can make it Mega compatible by deleting the line #include <SoftwareSerial.h>, and replacing the lines
SoftwareSerial mySerial(2, 3);
SoftwareSerial mySerial2(5, 6);

with
#define mySerial Serial1
#define mySerial Serial2

replacing Serial1 and Serial2 with whichever of the Mega's serial ports you wish to use for mySerial and mySerial2, and connecting your DFRobot sensor signals to the correct pins for your chosen hardware serial ports.

Thx king it worked, also we connected tx to rx and rx to tx. We don't know why it's working, but it is.

There are three fairly major issues in your code:

The Mega does not support SoftwareSerial on pins 2, 3, 5, 6 because those pins do not support change interrupts. Thus it simply can't work on those pins. This itself is a show-stopper.

Your code to read data is flawed. You test if a single byte is available (sensor.available()) and then proceed to read 9 bytes. There is no guarantee that 8 of them are actually there.

I'm confused about what you are doing in your second block of code. You are telling the sensor library to get its data from Serial, which is where you type stuff. All that would do is echo what you type, bearing in mind my point directly above.

I used an example from this library, I changed nothing in the code, just the way I initialize the sensor. I don't know how to use the sensor.available differently.

there are always 9 bytes comming out of the sensor, we tested it on Uno and it worked perfectly, why would the sensor work differently on Mega?

The bytes don't come out instantly. They take time. If you check for 1 byte then you can't guarantee that 9 bytes have arrived. Try changing to if (sensor.available() >= 9).

why would the sensor work differently on Mega - because it doesn't support those pins. How many times do we need to make this point?

You are ignoring the most likely explanation for your problem.

But I tried every possible pin combination, not only 2,3 or 5,6.

You said "Well the code that isn't working is exactly the same" - not exactly, if you tried different pin combinations, eh? Show code that uses supported pins.


text:
Adafruit feather helium integration
So I have an adafruit feather M0 LoRa 900 MHz and try to connect it to a helium hotspot (add to my helium console). For that I use the official helium documentation provided by helium and I get to the point of uploading the sketch to the board, but (as stated guide) if I open the serial monitor afterwards I only get an error message called: EV_JOIN_FAILED with a seemingly random number behind the error message. The output of the serial monitor looks like this:
22924969: EV_JOIN_FAILED
24125790: EV_JOIN_FAILED
25510651: EV_JOIN_FAILED
26731900: EV_JOIN_FAILED
28546725: EV_JOIN_FAILED
29506788: EV_JOIN_FAILED
30549623: EV_JOIN_FAILED
31955928: EV_JOIN_FAILED
33169043: EV_JOIN_FAILED
34528464: EV_JOIN_FAILED
36263160: EV_JOIN_FAILED
37424536: EV_JOIN_FAILED
38958548: EV_JOIN_FAILED
40127470: EV_JOIN_FAILED
40996827: EV_JOIN_FAILED

I made sure to edit the config file of LMIC and also triple checked that I entered the correct AppKey, Device EUI and App EUI into the test program.
My goal is to connect my adafruit feathe M0 to the helium console and send a Hello World packet and get developing.
Help would be apreciated.
Edit: Here is a screenshots of the adafruit feather M0 itself

Can you please include the number behind the error message? Does it change or does it stay the same? Did you make sure to attach antennas and flip the jumper as stated in the guide?

the number is always changing and I will include a an example of the output of the monitor in a minute. The antenna is properly installed and the jumper should be as well but I will include a photo of the board just in case.

Okay, the number that you see is the "timestamp" of the device or the ticks number. Your setup looks right. Could you please include the serial monitor output right after you flash? It should at least tell you it tried to join the network. Also, you've unlinked the guide you used - now it just points to the image of the board.

Okay, it´s good to know that the setup is right. I included the official helium documentation again, sorry for messing that up. The problem is that this is really the only output that the serial monitor displays. It doesn´t tell me that it tried to join the network or anything.

It might be also worth mentioning that, since I´m in the EU, I tried to modify the lmic config.h file to, instead of using the #define CFG_us915 1 line, use the #define CFG_eu868 1 line. That just gives me the following error while compiling:
'LMIC_selectSubBand' was not declared in this scope; did you mean 'LMIC_setupBand'?

Looking on GitHub, could you try commenting out that function? What happens when you do that?

I have the same issue!! I’m connecting to AU_915 so had to change frequency in the lorabase.h file. I can see the join attempt and the join accept on helium console, but my feather M0 doesn’t seem to hear the response. This means I get ‘EV_JOIN_FAILED’ over and over.


text:
Arduino programming attiny13a
Hello I want to program an Attiny13a with Arduino code. I always have this error  when I add repository "no file board.txt" in path.
How to successfully configure IDE to able burn on it?
I use :
Link 1
And :
Link 2
But nothing changed .
I am using IDE Arduino v1.6.7.
Finally I import ATTiny13 (link) now these errors appear:
Board attiny13:avr:attiny13 doesn't define a 'build.board'
preference.Auto-set to: AVR_ATTINY13

Board attiny13:avr:attiny13at4 doesn't define a 'build.board' preference. Auto-set to: AVR_ATTINY13AT4

Board attiny13:avr:attiny13at9 doesn't define a 'build.board' preference. Auto-set to: AVR_ATTINY13AT9

Warning: platform.txt from core 'Attiny13' contains deprecated compiler.path={runtime.ide.path}/hardware/tools/avr/bin/, automatically converted to compiler.path={runtime.tools.avr-gcc.path}/bin/. Consider upgrading this core.

Warning: platform.txt from core 'Attiny13' contains deprecated tools.avrdude.cmd.path={runtime.ide.path}/hardware/tools/avr/bin/avrdude, automatically converted to tools.avrdude.cmd.path={path}/bin/avrdude. Consider upgrading this core.

Warning: platform.txt from core 'Attiny13' contains deprecated tools.avrdude.config.path={runtime.ide.path}/hardware/tools/avr/etc/avrdude.conf, automatically converted to tools.avrdude.config.path={path}/etc/avrdude.conf. Consider upgrading this core.

Warning: platform.txt from core 'Attiny13' contains deprecated recipe.ar.pattern="{compiler.path}{compiler.ar.cmd}" {compiler.ar.flags} {compiler.ar.extra_flags} "{build.path}/{archive_file}" "{object_file}", automatically converted to recipe.ar.pattern="{compiler.path}{compiler.ar.cmd}" {compiler.ar.flags} {compiler.ar.extra_flags} "{archive_file_path}" "{object_file}". Consider upgrading this core.

@Gerben Please, give him a break, he's non-native english speaker.

Could you please include the actual error message exactly as it was displayed in the IDE?

I want to apologize Gerben if my english is bad but i write it after 16h in work . I will try to edit post when i sleep a little.

@MichałGałkowski The "errors" (they're warnings) should not matter. It should still compile and upload.

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


text:
Cannot find crtatmega328p
I have just installed the arduino IDE on my gentoo laptop. I then installed the toolchain with the following command:
crossdev -s4 avr

This does a stage 4 install of the toolchain, with all its dependecies etc.
I am following a tutorial, with my arduino uno, which I am assuming is using the Amtel ATmega328 chipset. This tutorial is simply going to turn an led on and off.
I click the verify button and I get the following errors:
/usr/libexec/gcc/avr/ld: cannot find crtatmega328p.o: No such file or directory

/usr/libexec/gcc/avr/ld: cannot find -latmega328p

collect2: error: ld returned 1 exit status

I downloaded the source files "avr-libc" compiled them and noticed inside the directory
/avr-libc-1.8.1/avr/lib/avr5/atmega328p

That the compiled module is named crtm328p.o which is available on my pc under the directory:
/usr/avr/lib/

I dont understand what is wrong and why this is not working. The only posts relating to missing files are over 5 years old and those solutions are not working.

The IDE should already have the toolchain in it - no need to compile and install anything else.

@Majenko this is not the case when you install it on gentoo.

It's in the tar file - that has nothing to do with the OS you are using it on. How are you trying to install it?!

I installed it with "emerge -av arduino" This installs the package "dev-embedded/arduino-1.0.5-r1::gentoo" which is the java version. Arduino IDE. It then tells me during the install that avr is missing and i have to install it by entering crossdev -s4 avr on the command line

1.0.5 is ancient. You want 1.6.7 from https://www.arduino.cc/en/Main/Software

mmm... let me update it.. i know it install avr-libc version 1.8.1

Just download the tar,xz file, extract it, then run the arduino program from within it - that will give you everything you need without any more installation needed.

I do not use Gentoo, but I can tell you how things work on Ubuntu 14.04,
which also installs Arduino 1.0.5. I assume Gentoo should not be that
different... The dependency tree is like this:

The package named "arduino", version 1.0.5, contains the IDE. It
depends on Java and on arduino-core.
arduino-core, version 1.0.5 also, has the Arduino core libraries. It
depends on gcc-avr, avrdude and avr-libc.
gcc-avr comes as version 4.8, avr-libc is version 1.8.0.

When you compile a program for an Uno, on the link stage avr-g++ gets
called, and it is asked to link your object files with libcore.a (the
Arduino core) and -lm (the math library). avr-g++ in turn calls the
linker (collect2) and asks it to link together
/usr/lib/avr/lib/avr5/crtm328p.o (the C runtime), your object files,
libcore.a, -lgcc (the GCC support libraries), -lm and -lc (avr-libc).
Notice that there is no crtatmega328p.o, it's called crtm328p.o instead.
And there is no -latmega328p.
For diagnosing your problem, you can set an IDE preference so that it
shows you the exact command lines it runs for compiling your program.
You can then copy and paste the last command (link stage) on a terminal.
If you add the -v option (meaning “verbose”), you will see what gcc is
asking the linker to put together.
You may be able to fix your problem with a simple symlink from
crtm328p.o to crtm328p.o. If you are using vanilla Gentoo packages, you
should then file a bug to the packager. On Ubuntu, you type
sudo apt-get install arduino and it just works.

FYI: Using sudo apt-get install arduino gets you an ancient version of Arduino IDE, it is much better idea to download the latest from Arduino's site.

@Avamander: I tried that, but the install is a mess: it completely ignores all the standard conventions of a Linux file system. I am a lot happier with an ancient core (I do not use the IDE) that is at least cleanly installed.

What do you mean by standard conventions of a Linux file system? The install is fairly clean, it keeps it's stuff where the IDE was unpacked and only uses the Sketchbook what you've set. It's similar to Steam, not the most elegant but it works and you don't have to compile anything yourself and the developers have a standard set of libraries.

I mean mostly the Filesystem Hierarchy Standard. After unpacking the IDE, I did a regular install of the AVR development toolchain, and ended up with lots of duplicates. This is the Arduino package completely ignoring good practices of putting stuff in the right place and correctly identifying its dependencies.

Uhh, the toolchains are bundled with the IDE so that there would be no need to install dependencies, plus many things are not redistributable through a repository due to licence issues. It ain't ignoring, it can't do what you hope. There are issues related to updating the package open on Github.

@Avamander: arduino-core is just the Arduino libraries, doc and examples. The toolchain is not bundled, it's listed as dependencies.

My mistake. I fixed it.

But still, it's the best currently possible.

I had the same error, but I did everything as says in arduino wiki: https://wiki.gentoo.org/wiki/Arduino#Install_the_toolchain_using_crossdev
and solved it, after read this discussion: https://wiki.gentoo.org/wiki/Talk:Arduino
helped: build the avr toolchain without '--stable' part of crossdev command line :
USE="-openmp -hardened -sanitize -vtv" crossdev -s4 --portage --verbose --target avr

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


text:
How do I reset to servo position everytime I excecute a particular sequence
I'm trying to make a prosthetic hand that can play rock, paper, scissors with a human. It is based on the premise that you push a button and it randomly selects a move to play. After each move, I'd like for it to return to a normal state after a few seconds delay, the human can then decide whom is victorious.
Code I have so far. It doesn't even stop after the degrees I've set, it just keeps turning. I have a cardboard prototype and it has come close to breaking because the servos just keep turning.
#include <Servo.h> //servo library

//Define servos
Servo servo1;
Servo servo2;
Servo servo3;
Servo servo4;

int pos = 0;

void setup()
//define servo signal inputs [digital PWM 2, 3, 4, 5]
{
  servo1.attach(2);
  servo2.attach(3);
  servo3.attach(4);
  servo4.attach(5);

}

void loop()
{
  void rEADY();
  //void rock();
  //void scissors();
  //void paper();
}

void rEADY()
{
  servo1.write(20);
  servo2.write(20);
  servo3.write(20);
  servo4.write(20);
  servo1.write(0);
  servo2.write(0);
  servo3.write(0);
  servo4.write(0);

}

void rock()
{
  servo1.write(180);
  servo2.write(180);
  servo3.write(180);
  servo4.write(180);
  servo1.write(0);
  servo2.write(0);
  servo3.write(0);
  servo4.write(0);
}

void scissors()
{
  servo1.write(180);
  servo2.write(180);
  servo3.write(0);
  servo4.write(0);
  servo1.write(0);
  servo2.write(0);
  servo3.write(0);
  servo4.write(0);
}

void paper()
{
  servo1.write(0);
  servo2.write(0);
  servo3.write(0);
  servo4.write(0);
  servo1.write(20);
  servo2.write(20);
  servo3.write(20);
  servo4.write(20);

}

do you realize that loop() repeats several thousand times every second? .... think about what your code is doing each iteration of loop()

@jsotola Thanks for replying :) I was working on it today and I did realise that I shouldn’t loop it. But i’m still a bit stuck on how to execute one off moves. Not sure if I’m looking at it the right way.

looping is ok ... look for blinkWithoutDelay sketch in the examples in the arduino IDE ... you can run a subroutine in the loop() block only once quite easily ... in setup(), set a flag ... in loop(), if flag is set, then run code and clear flag ... that's it ... the program will continue looping, but it will run the code only the first time through, because the second time through, the flag is no longer set .... you can easily add code that sets the flag every 10 seconds ... that will make the flag set at the begining of loop() again for a single repeat of the code once every 10 seconds


text:
Not getting input from sensor using timer
I wrote a code to move linear actuator and lights up and down using timer. But its not getting Sensor input please help me in this.
#include <avr/sleep.h>//this AVR library contains the methods that controls the sleep modes
#define interruptPin 2 //Pin we are going to use to wake up the Arduino
int uv1 = 7; //light
int uv2 = 8; // light
int mot1 = 5; //motion down
int mot2 = 6; // motion up
int buzz=39;
const int speaker = 27;
int led = 9;
int ledState = LOW;
int inputPin = 10;               // choose the input pin (for PIR sensor)
int pirState = 0;            // variable for reading the pin status, we start, assuming no motion detected
long previousMillis = 0;
long interval = 2000;
long OnTime = 30000;
long SenseDel = 8000;           // milliseconds of on-time
long OffTime = 8000;
unsigned long timestart = 0;
const int ply = 23; // relay to reset the sound
const int stp = 35; //relay to puase sound
bool sound = false;
long time_taken = 0;
int start_delay = 3000;
int audio_time = 8000;
int audio_time1 = 8000;
int audio_time3 = 8000;
void setup()
{
pinMode(led, OUTPUT);
pinMode(uv1, OUTPUT);
pinMode(uv2, OUTPUT);
pinMode(mot1, OUTPUT);
pinMode(mot2, OUTPUT);
pinMode(led, OUTPUT);      // declare LED as output
pinMode(inputPin, INPUT);     // declare sensor as input
digitalWrite(mot1, HIGH);
digitalWrite(mot2, LOW);
digitalWrite(led, LOW);
pinMode(interruptPin,INPUT_PULLUP);//Set pin d2 to input using the buildin pullup resistor
Serial.begin(9600);
pinMode(ply, OUTPUT);
pinMode(stp, OUTPUT);
pinMode(speaker, OUTPUT);
// TIMER 1 for interrupt frequency 300.0018750117188 Hz:
cli(); // stop interrupts
TCCR1A = 0; // set entire TCCR1A register to 0
TCCR1B = 0; // same for TCCR1B
TCNT1  = 0; // initialize counter value to 0
// set compare match register for 300.0018750117188 Hz increments
OCR1A = 53332; // = 16000000 / (1 * 300.0018750117188) - 1 (must be <65536)
// turn on CTC mode
TCCR1B |= (1 << WGM12);
// Set CS12, CS11 and CS10 bits for 1 prescaler
TCCR1B |= (0 << CS12) | (0 << CS11) | (1 << CS10);
// enable timer compare interrupt
TIMSK1 |= (1 << OCIE1A);
sei(); // allow interrupts
digitalWrite(speaker,LOW);
audio_message();
delay(200);
}
ISR(TIMER1_COMPA_vect)
{ //interrupt commands for TIMER 1 here
pirState = digitalRead(inputPin);
}
void loop()
{
unsigned long currentMillis = millis();
while ((pirState == HIGH) && (currentMillis-previousMillis >=SenseDel))
{
//previousMillis = currentMillis;
Serial.println("Motion detected!");
digitalWrite(mot2, LOW);
digitalWrite(mot1, LOW);
digitalWrite(uv1, HIGH);
digitalWrite(uv2, HIGH);
//delay(SenseDel);
//Go_To_Sleep();
}
// We only want to print on the output change, not state
//pirState = HIGH;
while ((pirState == LOW) && (currentMillis-previousMillis >= OnTime))
{
previousMillis = currentMillis;
Serial.println("Moving Down");
digitalWrite(mot2, HIGH);
digitalWrite(mot1, HIGH);
digitalWrite(uv1, LOW);
digitalWrite(uv2, LOW);
pirState = HIGH;

}
while ((pirState == LOW) && (currentMillis-previousMillis >=  OffTime))
{
//previousMillis = currentMillis;
Serial.println("Stay There!");
digitalWrite(mot2, HIGH);
digitalWrite(mot1, LOW);
digitalWrite(uv1, LOW);
digitalWrite(uv2, LOW);
pirState = HIGH;

}
while ((pirState == LOW) && (currentMillis-previousMillis >=  OnTime))
{
//previousMillis = currentMillis;
Serial.println("Moving Up!");
digitalWrite(mot2, LOW);
digitalWrite(mot1, LOW);
digitalWrite(uv1, LOW);
digitalWrite(uv2, LOW);
tone(buzz,2000);
delay(1000);
noTone(buzz);
delay(1000);
 pirState = HIGH;

}
}
void Go_To_Sleep()
{
sleep_enable();//Enabling sleep mode
attachInterrupt(0, wakeUp, LOW);//attaching a interrupt to pin d2
set_sleep_mode(SLEEP_MODE_PWR_DOWN);//Setting the sleep mode, in our case full sleep
sleep_cpu();//activating sleep mode
Serial.println("just woke up!");//next line of code executed after the interrupt
audio_message();
}
void wakeUp()
{
Serial.println("Interrrupt Fired");//Print message to serial monitor
sleep_disable();//Disable sleep mode
detachInterrupt(0); //Removes the interrupt from pin 2;
}
void stop_button()    // func to act as stop sound
{
digitalWrite(stp, LOW);
delay(200); //100
digitalWrite(stp, HIGH);
}
void play_button()  // // func to act as play sound
{
digitalWrite(ply, LOW);
delay(140);//100
digitalWrite(ply, HIGH);
}
void audio_message()
{
digitalWrite(speaker, HIGH);
play_button();
sound = true;
delay(100);
//digitalWrite(speaker, LOW);
Serial.println("Speaker On");
play_button();
//time_taken = millis();
delay(audio_time1);
delay(audio_time);
//delay(audio_time3);
//Do something.....
play_button();
stop_button();
sound = false;
digitalWrite(speaker, HIGH);
Serial.println("Speaker Closed");
delay(1000);
}

First, please format your code properly (standard Markdown rules apply). Secondly, what sensor isn't it receiving the input from? What hardware do you have, how is it wired up, and how do you expect it to behave?

reduce your code to only read the sensor and print its value ... your sketch has a lot of code that is unrelated to the sensor

pirState needs to be declared volatile


text:
Conversion from string to char array
I know this is Arduino Forum but I think this question is related to programming, I am using ESP8266 for the project. I need to convert the  string incoming on the serial through UART lines and receiving those using the below code. Also I am converting the received string to char array as i need to insert some more characters in between hence I need the conversion.
I have used 3 different commands to convert the above string into char array as you can see below

#include <SoftwareSerial.h>
#include <Arduino.h>

#include <stdio.h>

#include <string.h>

SoftwareSerial s; //RX TX
using namespace std;
String str= "";
String str_tx;

const char* c;
double buff[24];
unsigned long int str_len = 0;
double val;
char* token;
//char* rest = char_array;
int i=0;
void setup() {
  // put your setup code here, to run once:
  Serial.begin(115200);
  s.begin(115200, SWSERIAL_8N1, 13, 15, false, 256); //115200, SWSERIAL_8N1, 13, 15, false, 512
  pinMode(13, INPUT);
  pinMode(15, OUTPUT);

  Serial.println("in setup 1");
  Serial.println("in setup 2");
  Serial.println("in setup 3");

}

void loop() {
  // put your main code here, to run repeatedly:2
 while(s.available() >0)
 {

  char ch=s.read();
  str.concat(ch);
  if( ch =='\n' )
  { str.trim();
    Serial.println(str);
    str_tx = str;
    Serial.println(str_tx);

    str_len = str_tx.length()+1;
    Serial.println(str_len);
    //char char_array[sizeof(str_tx)];
    char char_array[str_len];
    //strcpy(char_array, str_tx.c_str());
    //str_tx.toCharArray(char_array, str_len);
    std:copy(str_tx.begin(),str_tx.end(),char_array);
    Serial.println(char_array);
    char_array[sizeof(str_tx)] = '\0';
    //char_array[65] = 0;
    str="";
    str_tx = "";
    Serial.println("------------------------------------");
  }
  /*
  str = "";
  str = s.readStringUntil('\n');
  str.trim();
  Serial.println(str);
  str_tx = str;
  Serial.println(str_tx);

  str_tx = str;
  str_tx.replace("\n","");

  str_len = str_tx.length();
  Serial.println(str_len);
  Serial.println(str_tx.c_str());*/

}

}

The output of the above code comes as below, you can see the first time conversion occurs but the next time only empty string shows up, in all the 3 cases its showing the same hence I need to find out what exactly this issue is caused by, would appreciate if anyone could thro some light on it.
Thankyou

this is not a forum ... it is a Q&A site

insert more Serial.print() statements in your code for debugging purposes ... find out if variables have the value that you expect

use readBytesUntil

It's not clear what you are trying to achieve. Avoid String objects if you can: see Reading Serial on the Arduino. If you really need a String object, see String::toCharArray() or, if you know what you are doing, String::c_str().

What are these lines for ? These seem to be syntax errors or just don't do anything.
//char char_array[sizeof(str_tx)];
char char_array[str_len];

@jsotola Noted. Thanks for the suggestion.

@Edgar Bonet Yes thats why I tried using both, thanks for the link I will go through it and let you know!


text:
Why does the potentiometer act as an on/off switch in my program?
I'm using an HC-SRO4 Ultrasonic Sensor and a D10K Potentiometer. So, I was just messing around with the potentiometer in the program and then tried to change the brightness of the LED which turns on if a certain condition is met, but the potentiometer acts like an ON/OFF switch instead. I'd like to know why this happens and how can I change the LED's brightness normally in this situation.
long duration;
int distance;
int trigPin = 9;
int echoPin = 10;
int buzzer = 11;
int LED = 3;
boolean detected = false;
#define pot 0
int val = 0;

void setup() {
  pinMode(LED, OUTPUT);
  pinMode(trigPin,OUTPUT);
  pinMode(echoPin,INPUT);
  pinMode(buzzer,OUTPUT);
  Serial.begin(9600);
}

void loop() {
  digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
duration = pulseIn(echoPin, HIGH);
distance= duration*0.034/2;
val  = analogRead(pot);
val  = map(val, 0, 1023, 0, 255);
Serial.println  (distance);

if(distance < 50 && distance != 0){ // distance != 0  because sometimes the distance's first value is sometimes 0 which ruins the purpose of
 // the program
  analogWrite(LED, val);
  alarm();
  detected = true;
}
else if(detected){
  digitalWrite(LED,LOW);
  alarm();
}
}

void alarm(){
  tone(buzzer, 450);
  delay(100);
  tone(buzzer, 1000);
  delay(100);
  }

Write a sketch with pot and led only.

Well, I did and it works fine. I can change the brightness of the LED. But what I don't understand is why it doesn't do so in the code above. @Juraj

because the analogWrite is conditional to distance sensor reading

Thing is can't I change the brightness while that condition is true? Well, when I make the condition true, (putting some object in front of the sensor) I turn the potentiometer and it still acts like an ON/OFF switch.

The answer is very simple. You use pin 12 for LED. Pin 12 can't do analogWrite(). This pin doesn't support PWM on Arduino UNO (Atmega 328)
Pin 3 is not OK either. Use of tone() function disables PWM on pin 3. From reference: "Use of the tone() function will interfere with PWM output on pins 3 and 11".

I'm sorry. I had changed my LED pin to 12 (I'll edit it to 3 now) because I was messing around with it. It was originally a PWM pin when this problem happened

@ArmanSamma: Please make sure that whatever code you post is always relevant to the question.

I don't understand. How and why does the tone() function disable PWM on pin 3? @Juraj

"tone()" in answer is a link. Read the reference of the tone function.


text:
Need help with a program for a button to change the display on an OLED display
So I am programming an OLED display from my Arduino Uno. I am trying to have a button that switches the different words on the display. (The words are just placeholders for programs as of now.) My program has a button that changes a counter, and an if test to see what the counter is so it can display the appropriate word. The problem is, whenever I press the button, the display turns black and doesn't do anything anymore. When I start/reset the Arduino, it displays TEMPERATURE, but it should say TIME.
#include <OLED_I2C.h>

OLED  myOLED(SDA, SCL, 8);

extern uint8_t SmallFont[];
extern uint8_t MediumNumbers[];
extern uint8_t BigNumbers[];

//constants:
const int buttonPin = 2;

//variables:
byte oldButtonState = HIGH;
int screenNumber = 0;
byte buttonState = 0;

void setup()
{
  myOLED.begin();
  myOLED.setFont(SmallFont);
  pinMode(buttonPin, INPUT_PULLUP);
}

void loop() { //myOLED.print formats with (string, text_placement,     pixel_location)
  // read the pushbutton input pin:
  buttonState = digitalRead(buttonPin);

  // Test if the button is being pressed
  if (buttonState == HIGH) {
    myOLED.clrScr();
    myOLED.update();
    oldButtonState = buttonState;
    if (screenNumber != 2) {
      ++screenNumber;
    }
    else {
      screenNumber = 0;
    }
    //delay a little to avoid bouncing
    delay(200);
    }

  //Test for the screenNumber variable and change to the
  //according screen
  if (screenNumber == 0) {
    myOLED.print("TIME", CENTER, 16);
    myOLED.update();
  }
  else if (screenNumber == 1) {
    myOLED.print("TEMPERATURE", CENTER, 16);
    myOLED.update();
  }
  else if (screenNumber == 2) {
    myOLED.print("DIRECTION", CENTER, 16);
    myOLED.update();
  }
  else {
    myOLED.print("ERROR", CENTER, 16);
    myOLED.update();
  }
}

What is your question? What is your sketch doing that it's not suppose to be doing?

have a close look at your code and try to figure out why it is displaying screen #1

I didn't see a problem in the code - but maybe I overlooked something.
Maybe your code is not the problem but your hardware. Did you make sure the input is connected to GND if it the button is not pressed?
Notes and Warnings
If the pin isn’t connected to anything, digitalRead() can return either HIGH or LOW (and this can change randomly).
https://www.arduino.cc/reference/en/language/functions/digital-io/digitalread/
I suggest you use serial to show the value of buttonState after this line
buttonState = digitalRead(buttonPin);

Maybe it is not what you expect it to be.

this doesn't apply. he has INPUT_PULLUP

I changed the input mode to INPUT and added the Serial.print(buttonState); but it only prints 0 even when I am pressing the button. Any clue why that might be?

So I switched the side that the wire connecting to PIN 2 was and now it says 1 when I am not pressing it and 0 when I am.

Good that you found the problem. Sometimes we forget to double check the little things (they connections) and concentrate only on the code...

You have pinMode(buttonPin, INPUT_PULLUP); so I assume, you connected the button between pin and ground. With pull-up the pin will read HIGH if it is not grounded. If the button is pushed, grounding the button pulls it LOW. So you should test if the button is pressed with comparing to LOW.
We have this misleading idea in our heads that active is HIGH and not active is LOW. But you can see it this way:

button pushed down (low) is LOW
button not pushed is up (high) reading HIGH

I fixed the problem. It turned out that the value being returned by the button was 1 when it was not being pressed and 0 when it was being pressed. My new code is:
#include <OLED_I2C.h>

OLED  myOLED(SDA, SCL, 8);

extern uint8_t SmallFont[];
extern uint8_t MediumNumbers[];
extern uint8_t BigNumbers[];

//constants:
const int buttonPin = 2;
const int debug = 0;

//variables:
int screenNumber = 0;
byte buttonState = 0;

void setup()
{
  myOLED.begin();
  myOLED.setFont(SmallFont);
  pinMode(buttonPin, INPUT);
  myOLED.clrScr();
  myOLED.print("TIME", CENTER, 16);
  myOLED.update();
  Serial.begin(9600);
}

void loop() { //myOLED.print() formats with (string, text_placement, pixel_location)
  // read the pushbutton input pin:
  buttonState = digitalRead(buttonPin);
  Serial.println(buttonState);
  if (debug == 1) {
    myOLED.clrScr();
    myOLED.print("Start", CENTER, 16);
    myOLED.update();
    delay(debugDelay);
  }
  // compare the buttonState to its previous state
  if (buttonState == 0) {
    if (screenNumber < 2) {
      screenNumber = screenNumber + 1;
    }
    else {
      screenNumber = 0;
      }
    //delay a little to avoid bouncing
    delay(100);
    }

  //Test for the screenNumber variable and change to the
  //according screen

  if (screenNumber == 0) {
    myOLED.clrScr();
    myOLED.print("TIME", CENTER, 16);
    myOLED.update();
  }
  else if (screenNumber == 1) {
    myOLED.clrScr();
    myOLED.print("TEMPERATURE", CENTER, 16);
    myOLED.update();
  }
  else if (screenNumber == 2) {
    myOLED.clrScr();
    myOLED.print("DIRECTION", CENTER, 16);
    myOLED.update();
  }
  else {
    myOLED.clrScr();
    myOLED.print("ERROR", CENTER, 16);
    myOLED.update();
  }
}

and what did I write in my answer? you accepted the wrong answer

Edgar told me to use the Serial.print() to find out what the value of the button was. That helped me more. If you had just said it is the inverse of what I expected it would have made more sense.


text:
Arduino SD card cannot write (writes crap files and then I get error)
I am developing a very simple project to measure some temperatures and store them in an SD card. I have a problem trying to write. No matter what I do the SD card always ends up with content like this:

And in read only mode. I have formatted it in FAT16, FAT32, in Windows an Ubuntu and always the same. I have changed between two different Arduino UNO boards, two different SD modules connected like this:

and extremly simple codes like this example and I always get the same.
Detailed example of what I do and what I get
I have wrote this simple code to test:
#include <SD.h>
#define CHIP_SELECT_PIN 10
/* CIRCUITO ----------------
* SD card attached to SPI bus as follows:
* MOSI - pin 11
* MISO - pin 12
* CLK - pin 13
* CS - pin 10. */
File archivo;
char cadena[20];
char c;
void setup(void) {
Serial.begin(9600);
while (!Serial) {;} // Esperar a que se inicialice la comunicacion serial
      while (Serial.read() >= 0) {;} // Limpiar el buffer
// INICIALIZAR LA MEMORIA ----------------------------------------
Serial.print("Initializing SD card... ");
pinMode(CHIP_SELECT_PIN, OUTPUT);
if (!SD.begin(CHIP_SELECT_PIN)) {
  Serial.println("Unable to initialize. Remove the card.");
  while (1);
}
Serial.println("OK!");
// ABRIR UN ARCHIVO PARA ESCRIBIR --------------------------------
if (SD.exists("ARCHIVO.TXT")) {
  Serial.println("Deleting existing file with the same name. ");
  SD.remove("ARCHIVO.TXT");
}
Serial.print("Creating new file... ");
if (!(archivo = SD.open("ARCHIVO.TXT", FILE_WRITE))) {
  Serial.println("Unable to create the file. Remove the card.");
  while (1);
}
Serial.println("File successfully created. ");
Serial.print("Send a string to store in the card... ");
while (Serial.available() == 0); // Nos quedamos esperando a que nos manden el numero
leerCadena('\n', cadena, 19);
Serial.print("The following string was received: \" ");
Serial.print(cadena);
Serial.println("\"");
archivo.print(cadena);
archivo.close();
Serial.println("The string was successfully stored in the card. ");
// Lectura de los datos guardados en la memoria ------------
Serial.print("Preparing to read data in card... ");
if (!(archivo = SD.open("ARCHIVO.TXT", FILE_READ))) {
  Serial.println("Cannot open file to read. Remove the card. ");
  while(1);
}
Serial.print("The string stored in memory is: \"");
while ((c = archivo.read()) >= 0) {
  Serial.print(c);
}
Serial.println("\"");
archivo.close();
Serial.println("Remove the card.");
while(1);
}
void loop(void) {}
void leerCadena (char corte, char* cadena, byte n_bytes) {
  byte n_leidos;
  n_leidos = Serial.readBytesUntil(corte, cadena, n_bytes);
  cadena[n_leidos] = '\0';
  delay(100);
  while (Serial.read() >= 0) {;}
}

and what I am doing and getting is:

First I format my SD card in FAT32 using Gparted (the same happens if I format it in FAT16 or 32 both in Ubuntu and Windows).
I test the SD card in my computer.  It works perfectly. I can remove it and plug it again and the data is there. Everything OK.
I put the card in the SD slot connected to Arduino and run the above program. What I get through the serial monitor is
Now I remove the card from Arduino and insert it into my computer. This is its content:  The file "readme.txt" contains the same text as before. The file "ARCHIVO.TXT" is empty. The binary files vary in size, e.g. the second one is 3 GB and fourth one is 774 MB.
Now I try to modify the content in "readme.txt" and I get this:  I cannot delete files either.
I remove the SD card from my computer and insert it again into Ardino. Reset the board and through the serial port I get:
Now the content of the card seen in the computer is different:  and the file "ARCHIVO.TXT" is not present.
If I put the card again in Arduino and reset the board everything repeats from step number 3. I mean, it creates the file "ARCHIVO.TXT" among with the other strange files, in the next time I put it into Arduino it deletes the file "ARCHIVO.txt", and so on.

If after all this I format the SD card in my computer, we are back in step number 1.
I am about giving up with Arduino and the SD module and go to a Raspberry. But it is much more expensive for this extremly simple task I need to do...

The problem was magically solved. I think the cables were the causing this issue. I was using cables of about 15 cm, now changed them to 5 cm and is working perfectly.

I change voltage from 5V to 3.3V and move GND to the GND pin near the 3.3V. Now I can write and read a text file on a SD card.

-Did you change the CS pin in the code to 10?
-It can be a problem with the SD card, try another and tell us.
-After the "dataFile.close();" put: "if(dataFile)Serial.println("not closed");" and watch the serial monitor window.

Thanks for your answers. I have tried almost everything. I have added more information to the question. I am waiting for a new SD card. After that I run out of ideas about what could be the problem...

You have to guarantee that the file.txt is not opened before you shutdown the power or take the SD card off. I recomend you firstly, to do a "for" loop to stop in "X" iterations. If it works, you can put then a push-button in your project to stop any time.

I had the same problem (using a UNO with the MH-SD module directly connected to the arduino). The module apparently correctly initialised and I could list the files that were already there but when I attempted to create a single blank file ready for reading, a whole bunch of random named files were created many of which were enormous (according to my PC, although it said they all corrupted and couldn't open any of them). And then the card wasn't recognised when I tried using it again and had to be reformatted. I eventually found that one of the wires I was using, specifically the one to GND adjacent to MISO, was faulty. I suspect the length of the cables is irrelevant, I think that user171780 had a faulty cable in the same position.

I think maybe the problem comes from the SD module you use. I have used the SD module just like you.And I can not write or read data successfully. More seriousely, my card broken and the damage is permanent.This connect is the new SD module I use, and I use successfully. You can dry by yourself.
https://www.qutaojiao.com/8515.html?fbclid=IwAR0T9dFoAOyJhTCSOHeDWQTE_Iuq8l5eGN9ByYth2uPmIyzC2bHLdt0_cKk

This is essentially a "link only" answer (and to a foreign language site). You should provide the (translated, English) important parts of the answer directly here, not link to them.


text:
How to install Adafruit motorshield library in arduino-cli
I need to install this library using the arduino-cli software. I don't know what name to use for the library. Using
arduino-cli lib install <library_name>

I have tried Adafruit_MotorShield, Adafruit_MotorShield_V2, and other random combinations and in all cases it cannot found it. In the library manager of the graphical interface it is this one:

check the name in library.properties

How do I find the properties of a library?

I found it on GitHub over arduinolibraries.info and it is in the library's folder too if you have it installed elsewhere. And the More Info link in IDE Library Manager goes to GitHub too

Are you talking about this? Where is the name to use?

Thanks, now I found the library.properties file.

As pointed out by Juraj♦ in the comments, the name to use can be found in the library.properties file. There we find name=Adafruit Motor Shield V2 Library so the command to install the library is:
arduino-cli lib install Adafruit\ Motor\ Shield\ V2\ Library

Note the white spaces are escaped.

quotes didn't work?

Don't know, I tried at once with that command, which worked.


text:
Using a keypad to play an audio file on Arduino Mega and Adafruit VS1053?
I am trying to use a keypad to trigger an audio file using an Arduino Mega and Adafruit VS1053 Music Maker. I have gotten the music files to play independently, and when the correct number is entered into the keypad a red LED flashes to green, but I have no idea how to make the music file play as a result of my combination.
What works is that the music file plays, but the problem is that it plays automatically and not upon a combination input.
I have tried putting musicPlayer.playfullfile("track002.mp3") in the loop with an if statement, and when I press the keypad the serial reader tells me it is playing the music file, but nothing is actually playing :
char key = keypad.getKey();
if (key) {
  Serial.println(key);
  if (key =='9') {
      playMusic("track001.mp3");
  }
}

I've done experiments with playmusic outside of the loop and it works fine and finds the file no problem. So the problem occurs when I try and put it into the loop as part of a keypad combination, it returns immediately without playing.
This is from the Serial reader:
>Playing music file 9
>Playing music file 9
>Playing music file 9
>Playing music file

Any help would be tremendously appreciated.
My full code is below:
#include <Keypad.h>
#include <SD.h>
#include <SPI.h>
#include <Adafruit_VS1053.h>

#define SD_ChipSelectPin 53

String password = "123";
String answer = "";
int position = 0;
const byte ROWS = 4;
const byte COLS = 4;
char keys[ROWS][COLS] = {
  {'1','2','3','A'},
  {'4','5','6','B'},
  {'7','8','9','C'},
  {'*','0','#','D'}
};

byte rowPins[ROWS] = { 51, 49, 47, 53 };
byte colPins[COLS] = { 45, 43, 41, 39 };
Keypad keypad = Keypad( makeKeymap(keys), rowPins, colPins, ROWS,
COLS);
int R = 27; // 3rd yellow wire in GROUND
int G = 29;

// define the pins used
//#define CLK 13       // SPI Clock, shared with SD card
//#define MISO 12      // Input data, from VS1053/SD card
//#define MOSI 11      // Output data, to VS1053/SD card
// Connect CLK, MISO and MOSI to hardware SPI pins.
// See http://arduino.cc/en/Reference/SPI "Connections"

// These are the pins used for the breakout example
#define BREAKOUT_RESET  9      // VS1053 reset pin (output)
#define BREAKOUT_CS     10     // VS1053 chip select pin (output)
#define BREAKOUT_DCS    8      // VS1053 Data/command select pin
(output)
// These are the pins used for the music maker shield
#define SHIELD_RESET  -1      // VS1053 reset pin (unused!)
#define SHIELD_CS     7      // VS1053 chip select pin (output)
#define SHIELD_DCS    6      // VS1053 Data/command select pin
(output)

// These are common pins between breakout and shield
#define CARDCS 4     // Card chip select pin
// DREQ should be an Int pin, see
http://arduino.cc/en/Reference/attachInterrupt
#define DREQ 3       // VS1053 Data request, ideally an Interrupt pin

Adafruit_VS1053_FilePlayer musicPlayer =
  // create breakout-example object!
  //Adafruit_VS1053_FilePlayer(BREAKOUT_RESET, BREAKOUT_CS,
BREAKOUT_DCS,
DREQ, CARDCS);
// create shield-example object!
Adafruit_VS1053_FilePlayer(SHIELD_RESET, SHIELD_CS, SHIELD_DCS, DREQ, CARDCS);

void setup() {
  if (! musicPlayer.begin()) {
    // initialise the music player
    Serial.println(F("Couldn't find VS1053, do you have the right pins defined?"));
    while (1);
  }
  Serial.println(F("VS1053 found"));
  if (!SD.begin(CARDCS)) {
    Serial.println(F("SD failed, or not present"));
    while (1);  // don't do anything more
    // Set volume for left, right channels. lower numbers == louder volume!
    musicPlayer.setVolume(20,20);
    pinMode(R, OUTPUT);
    pinMode(G, OUTPUT);
  }
  musicPlayer.playFullFile("track003.mp3");
}

void loop() {
  char key = keypad.getKey(); // init. variable key keypad is non blocking
  while (key == NO_KEY) {
    // we got no key press? -> do again
    key = keypad.getKey();
    delay(100);
  }
  answer.concat(key); // add key to answer
  if (answer.equals(password)) {
    //password OK
    musicPlayer.playFullFile("track002.mp3");
    Serial.println(F("Playing track 001"));
    LockedPosition(false);
    answer="";
  } else {
    LockedPosition(true);
  }
  if (answer.length() > password.length()) {
    // answer is different and bigger than password
    // can't become the right answer
    answer = "";
  }
  if (key == '*' || key == '#') {
    LockedPosition(true);
    answer="";
  }
}

void LockedPosition(int locked) {
  if (locked) {
    digitalWrite(R, HIGH);
    digitalWrite(G, LOW);
  } else {
    digitalWrite(R, LOW);
    digitalWrite(G, HIGH);
    delay(10000);
    digitalWrite(G,LOW);
  }
}

Hey @josecanuc, that part is from a previous code attempt to show what I've tried so far. What I was trying to do with that attempt was get the audio to play when I press '9' using the code below. The serial reader read Playing Music File, but did not actually play anything:  char key = keypad.getKey();
if (key) {
Serial.println(key);
if (key =='9') {
playMusic("track001.mp3");
}
}

I've narrowed down the circumstances where this happens. I put "SD.exists("file")" at the top of the loop and it consistently returns true until the first time the keypad is used. From that point on it returns false, which explains why the musicPlayer doesn't play it. It just can't find it. Any thoughts how how the keypad could be interfering with SD?

The sketch has a pins conflict.
SD card is on SPI bus. SPI pins on Arduino Mega are pins 50, 51, 52 and 53. These pins are available on the ICSP/SPI header too. Mega compatible shields use the SPI pins on the ICSP header. Pin 53 must be set as output if the Mega is SPI master and is usual to use it as CS pin for a slave.
According to sketch the SD CS pin is 53.
According to sketch the keypad uses pins 51 and 53. 51 is SPI pin used by the shield and pin 53 is CS pin for SD card.


text:
How to properly run four DC motors with an Arduino?
I am working on a project where I have four DC motors that are controlled by two L293D motor drivers. Two of the motors act as the wheels of the robot, and the other two act as a mop.
The Arduino board is powered through the USB port. The DC motors are powered by the L293D motor driver through the 5 V pin on the Arduino.  Alongside the motors, an ultrasonic sensor and a water sensor are also using the 5 V pin.
This is what the robot should be doing:
The robot will move forward. If it senses an obstacle through the ultrasonic sensor, it will turn right. If it senses water through the water sensor, the robot will stop moving and the mop will start spinning. After cleaning the water spillage, it will move forward again, just like what it did before.
It seems like the motors are not getting enough power, because whenever I place it on the floor, it doesn't move.
The base / platform of the robot is plywood, which is heavy for the robot, and I think this is a factor that affects the spinning of the wheels.
I also have a 9 V battery, which I think could power the motors, but I don't know how to connect it. How am I supposed to connect it to the L293D motor driver? I think I should connect the positive side of the 9 V battery to the VCC 2 pin of the L293D motor driver. But, where should I connect the negative side of the 9 V battery?

Try A power buss as the main power distribution source

With out knowing the demands of the motors (how much current they need under a given load) it is difficult to answer your question.  But, in most Arduino designs:

Motors are powered independently of the Arduino.  And when Arduino Uno is powered through its USB port it should be realized that most common USB power sources are only obliged to offer up to 500mA of current.
The motor's power source likely needs to be capable of providing several Amps. A common 9 Volt battery only contains about 500mAh and will likely drain in 10s of minutes if it works at all.

Consider the power pack used in common portable electric power tools.  This should give you a perspective of the type of power you will need in order to create a robot with multiple motors.


text:
Can't use uint16_t in library
I wonder why the following minimal example sketch doesn't compile (unknown type name 'uint16_t'):
sketch_does_not_compile.ino:
#include "myheader.h"

void setup() {
  char a[]="hello world";
  uint16_t l=str_len(a);
  Serial.println(l);
}

void loop() {}

myheader.c:
uint16_t str_len(char* input_string) {
  uint16_t i=0;
  while (input_string[i++]!='\0');
  return i;
}

myheader.h:
#include "myheader.h"

uint16_t str_len(char* input_string);

Compilation fails with:
myheader.c: At top level:
myheader.c:3:1: error: unknown type name 'uint16_t'
 uint16_t str_len(char* input_string);
 ^
exit status 1
unknown type name 'uint16_t'

Using uint16_t in the .ino-file directly like in the sketch below compiles fine.
sketch_compiles.ino:
uint16_t str_len(char* input_string) {
  uint16_t i=0;
  while (input_string[i++]!='\0');
  return i;
}

void setup() {
  char a[]="hello world";
  uint16_t l=str_len(a);
  Serial.println(l);
}

void loop() {}

What am I missing?

#include <stdint.h>

Why is the declaration of str_len() in the .c file and the implementation in the .h file?

Using #include <Arduino.h> in your myheader.h will also include <stdint.h> and probably solve this.
The Arduino IDE automatically includes Arduino.h in the sketch itself, but apparently not for external stuff.


text:
End stops for stepper motor
I need to add some end stops to this stepper motor code. I'm using one axis of a joystick to control a carriage that goes back and forth on a long screw. I have hall switches for both ends, I just want it to stop going in that direction when it triggers the switch.
I didn't write this code but it would work great if I could just add the end stops. If I have the switches connected to pins 2 and 3.
How could I write something like: if pin 2 goes high, stop motor in that direction, and then the same for pin 3 in the opposite direction?
#include <AccelStepper.h> // accelstepper library
AccelStepper stepper(1, 8, 9); // direction Digital 9 (CCW), pulses Digital 8 (CLK)

//Pins
const byte Analog_X_pin = A0; // x-axis readings
const byte enablePin = 7;

//Variables
int Analog_X = 0;             //x-axis value
int Analog_X_AVG = 0;         //x-axis value average
  //----------------------------------------------------------------------------
void setup() {
  Serial.begin(9600);
  //----------------------------------------------------------------------------
  //PINS
  pinMode(Analog_X_pin, INPUT);
  pinMode(enablePin, OUTPUT);
  //----------------------------------------------------------------------------
  InitialValues(); // averaging the values of the 3 analog pins (values from potmeters)
  //----------------------------------------------------------------------------
  // Stepper parameters
  // setting up some default values for maximum speed and maximum acceleration
  stepper.setMaxSpeed(2000);     //SPEED = Steps / second
  stepper.setAcceleration(1000); //ACCELERATION = Steps /(second)^2
  stepper.setSpeed(1000);
  delay(1000);
}

void loop() {
  ReadAnalog();
  stepper.runSpeed(); // step the motor (this will step the motor by 1 step at each loop indefinitely)
}

void ReadAnalog() {
  if (abs(Analog_X-Analog_X_AVG) > 50) {
    digitalWrite(enablePin, HIGH);  // enable the driver
    stepper.setSpeed(5*(Analog_X-Analog_X_AVG));
  } else {
    digitalWrite(enablePin, LOW);   // disable the driver
    stepper.setSpeed(0);
  }
  // Reading the potentiometer in the joystick:
  Analog_X = analogRead(Analog_X_pin);
  // if the value is 25 "value away" from the average (midpoint), we allow the update of the speed
  // This is a sort of a filter for the inaccuracy of the reading
  if (abs(Analog_X-Analog_X_AVG) > 50) {
    stepper.setSpeed(5 * (Analog_X-Analog_X_AVG));
  } else {
    stepper.setSpeed(0);
  }
}

void InitialValues() {
  //Set the values to zero before averaging
  float tempX = 0;
  //----------------------------------------------------------------------------
  // read the analog 50x, then calculate an average.
  // they will be the reference values
  for (int i = 0; i<50; i++) {
    tempX += analogRead(Analog_X_pin);
    delay(10); //allowing a little time between two readings
  }
  //----------------------------------------------------------------------------
  Analog_X_AVG = tempX/50;
  //----------------------------------------------------------------------------
  Serial.print("AVG_X: ");
  Serial.println(Analog_X_AVG);
  Serial.println("Calibration finished");
}

This is what I came up with. Note that the ReadLimits function is called after ReadAnalog and before runSpeed. In that order the stepper will not move in the direction of the limit switch, if it is pressed.
PS since you used setAcceleration, don't you need to call run instead of runSpeed?
void loop()
{
  ReadAnalog();
  ReadLimits();
  stepper.runSpeed(); //step the motor (this will step the motor by 1 step at each loop indefinitely)
}

void ReadLimits()
{
  if( digitalRead(2)==LOW && stepper.speed()>0 )//read input, assuming they have pull-up resistors.
  {
    stepper.setSpeed(0);
  }

  if( digitalRead(3)==LOW && stepper.speed()<0 )//read input, assuming they have pull-up resistors.
  {
    stepper.setSpeed(0);
  }
}

edit to avoid some confusion; here is the entire code with my suggestion embedded:
#include <AccelStepper.h> // accelstepper library
AccelStepper stepper(1, 8, 9); // direction Digital 9 (CCW), pulses Digital 8 (CLK)

//Pins
const byte Analog_X_pin = A0; // x-axis readings
const byte enablePin = 7;

//Variables
int Analog_X = 0;             //x-axis value
int Analog_X_AVG = 0;         //x-axis value average
  //----------------------------------------------------------------------------
void setup() {
  Serial.begin(9600);
  //----------------------------------------------------------------------------
  //PINS
  pinMode(Analog_X_pin, INPUT);
  pinMode(enablePin, OUTPUT);
  //----------------------------------------------------------------------------
  InitialValues(); // averaging the values of the 3 analog pins (values from potmeters)
  //----------------------------------------------------------------------------
  // Stepper parameters
  // setting up some default values for maximum speed and maximum acceleration
  stepper.setMaxSpeed(2000);     //SPEED = Steps / second
  stepper.setAcceleration(1000); //ACCELERATION = Steps /(second)^2
  stepper.setSpeed(1000);
  delay(1000);
}

void loop()
{
  ReadAnalog();
  ReadLimits();
  stepper.runSpeed(); //step the motor (this will step the motor by 1 step at each loop indefinitely)
}

void ReadLimits()
{
  if( digitalRead(2)==LOW && stepper.speed()>0 )//read input, assuming they have pull-up resistors.
  {
    stepper.setSpeed(0);
  }

  if( digitalRead(3)==LOW && stepper.speed()<0 )//read input, assuming they have pull-up resistors.
  {
    stepper.setSpeed(0);
  }
}

void ReadAnalog() {
  if (abs(Analog_X-Analog_X_AVG) > 50) {
    digitalWrite(enablePin, HIGH);  // enable the driver
    stepper.setSpeed(5*(Analog_X-Analog_X_AVG));
  } else {
    digitalWrite(enablePin, LOW);   // disable the driver
    stepper.setSpeed(0);
  }
  // Reading the potentiometer in the joystick:
  Analog_X = analogRead(Analog_X_pin);
  // if the value is 25 "value away" from the average (midpoint), we allow the update of the speed
  // This is a sort of a filter for the inaccuracy of the reading
  if (abs(Analog_X-Analog_X_AVG) > 50) {
    stepper.setSpeed(5 * (Analog_X-Analog_X_AVG));
  } else {
    stepper.setSpeed(0);
  }
}

void InitialValues() {
  //Set the values to zero before averaging
  float tempX = 0;
  //----------------------------------------------------------------------------
  // read the analog 50x, then calculate an average.
  // they will be the reference values
  for (int i = 0; i<50; i++) {
    tempX += analogRead(Analog_X_pin);
    delay(10); //allowing a little time between two readings
  }
  //----------------------------------------------------------------------------
  Analog_X_AVG = tempX/50;
  //----------------------------------------------------------------------------
  Serial.print("AVG_X: ");
  Serial.println(Analog_X_AVG);
  Serial.println("Calibration finished");
}

Thanks for responding, I tried what you sent, if I touch either pin 2 or 3 to gnd. or 5V still nothing happens the motor doesn't stop in either direction. I don't know much about coding, I tried to hire someone to do it and after 2 days of trouble shooting and revising the code it still doesn't work. The code works perfectly except I can't seam to add the end stops. Any help would be greatly appreciated.

Have you added pull-up resistors, or used pinMode(2, INPUT_PULLUP); pinMode(3, INPUT_PULLUP);?

Why did you add ReadAnalog();  stepper.runSpeed(); at the end of the ReadLimits function I provided?

See my edit above.

I think that's it, if I have pins 2 and 4 connected to 5v it runs normally, when I connect the jumper wire to gnd instead or + it stops the motor in that direction. Forgive me I really don't know what I'm doing when it comes to this stuff. So I have hall switches for the stops do I include pinMode(2, INPUT_PULLUP); pinMode(3, INPUT_PULLUP); or do I need pullup resistors? if so what value please? I am very grateful for your help maybe now I can finish this.

Got it, added input pull ups works perfectly,

It depends on the hall effect sensors. Some require a pull-up resistor. INPUT_PULLUP enables the pull-up resistor that's inside the Arduino chip. There is no difference between enabling this pull-up resistor in software, or having a physical (35kOhm) pull-up resistor on the pin. The value of the resistor doesn't really matter in this case.


text:
How often does a mpu6050 gyro sonsor need calibration?
I want to use it in my real car for daily use to measure yaw angle when needed.
Is is ok to only calibrate it once at first then use it every day when driving without any problem? if not, how often should I recalibrate it?

Sorry for asking, but many 1st time posters get accelerometer, gyroscope and magnetometer mixed up. It depends on the manufacture.  But many accelerometers and gyroscopes work with only a small amount of calibration if any.  And I can not think of a good reason to calibrate them a second time.  A magnetometer needs calibration the 1st time and every time afterwards should conditions change.  And magnetometers do not work well near metal objects.  Like cars. (BTW, a MPU6050 has an accelerometer and gyroscope but no magnetometer.)

Most accelerometers and gyroscopes need little if any calibration.  Consult the manufactures specification sheets.  If any calibration is made and correction values found, then it is assumed those values may be used in the future for the same accelerometer / gyroscope.
This analog.com document goes into gyroscope calibration details.
Deriving the angle of the car (the "yaw") at any given moment will likely be problematic.  Errors from integrating the gyroscope's axis which is perpendicular to the ground will accumulate over time.  Which is the main problem when using dead reckoning.
Consider using a magnetometer & accelerometer along with the gyroscope in order to mitigate the accumulated errors from only using the gyroscope.

I just want it to find the 45 angle when parallel park. when car is fixed to adjacent car, reset it to zero then go reverse to reach 45 degree. I reset sensor's current position by a button as zero position.  Is it wrong? what is your idea?

The longer the interval of time over which a maneuver is tracked the more likely errors will creep into your calculations. You will have to be the judge as to how much error your application can tolerate and what is a reasonable amount of time for you to make the maneuver.  My ideas deal with longer car trips and integrating a tilt compass to aid in correcting any accumulated gyroscope errors. I don't think that is necessary for this case.

I don't want to use compass in my car anyway. because it needs calibration every time I want to parallel park. The time for reaching a 45 angle in parallel park is about 10 seconds or less. At that moment the sensor's work is finished. The sensor is going to be used once a day by average.

Excuse me, a micro question! Can I reset the sensor (x, y, z) to (0, 0, 0) logically using code (not calibrate)? because calibration takes much time.

Most gyroscopes are zero at rest and fluctuate when rotated.  It is normally up to the hosting processor to translate that into an angle.  Some gyroscopes can be written to to adjust / calibrate the gyroscope output.  But these values can be kept as part of the hosting processors program so that raw un-calibrated values are read from the gyroscope.


text:
Modifying the alert-like popup in ESPAsyncWebServer authenticate() function
So, ESPAsyncWebServer library is using the Digest MD5 Authentication by default, and I want to use this feature in my webserver, but there is a problem, I don't like the ugly prompt box, and I don't want to write a form for authentication, because is sends the password in clear text. I have searched all files in the Src folder of the ESPAsyncWebServer library, Yet I had no luck up to my beginner programming knowledge. So, how can I do this? it is something totally browser side and I cannot change it?
Update: I was able to get the following from the Wireshark.
Hypertext Transfer Protocol
    GET /openthefdoor HTTP/1.1\r\n
        [Expert Info (Chat/Sequence): GET /openthefdoor HTTP/1.1\r\n]
            [GET /openthefdoor HTTP/1.1\r\n]
            [Severity level: Chat]
            [Group: Sequence]
        Request Method: GET
        Request URI: /openthefdoor
        Request Version: HTTP/1.1
    Host: 192.168.1.3\r\n
    Connection: keep-alive\r\n
    Cache-Control: max-age=0\r\n
     [truncated]Authorization: Digest username="admin", realm="asyncesp", nonce="d13ba3040a4ed5c661a47d28c08554f4", uri="/openthefdoor", response="ca8806aa058dda66838784e784e67f8b", opaque="90ba2cd8a2870065f4daa582fd57105a", qop=auth, nc=0000
         username="admin"
         realm="asyncesp"
         nonce="d13ba3040a4ed5c661a47d28c08554f4"
         uri="/openthefdoor"
         response="ca8806aa058dda66838784e784e67f8b"
         opaque="90ba2cd8a2870065f4daa582fd57105a"
         qop=auth
         nc=00000002

2nd update: based on this question I guess the popup is coming up from the browser and I was looking in a wrong place!

searched all files in the Src folder ... what did you search for?

If you write a nice webpage to login, why can't you do the login exactly the same way, with a webrequest from the browser through javascript? Why would that be any less encrypted than doing it directly?

@chrisl Can I implement Digest MD5 Authentication? also I don't have enough memory on my esp8266.

@jsotola for theauthenticate() and requestDigestAuthentication() and WWW-Authenticate and to my knowledge I couldn't find anything useful to me.

try searching for HTML tags ... if you can determine the HTML code for the login popup, it may help to search for the tags in the popup

@jsotola based on this question I guess it's coming up from the browser and I was looking in a wrong place!

I don't know about a specific authentication method. I wanted to point out, that there is no functional difference if you make the web request by typing the address in your browser and hitting enter, or by writing a web request in the javascript code of a website.

@chrisl the form that I wrote is a login form, so I has to use an authentication method.,or the username and password will be sent in clear text form!

The authentication dialog, that you get, is provided by the browser. You cannot change this, since it is part of the browser software.

I don't want to write a form for authentication, because is sends the password in clear text.

That is false. How exactly the data is send depends on how you implement your login/action site. You can also tap into the forms submit event and use javascript with something other than Basic Authentication, like the Digest Authentication, that you mentioned. So your webpage, that gets served from the ESP, would contain the nice looking HTML form and javascript code, that uses the submit event of the form and does a webrequest to the ESP for the /openthefdoor endpoint, providing the credentials as digest (hashes).
From the ESPs (aka webservers) perspective, it is functionally irrelevant, if the login webrequest is done by typing in the login address in the address bar, or by javascript code embedded inside the served website. Both are just simple webrequests. You don't need to submit data from a form directly (unencrypted)
I cannot give you a ready made example of such javascript code and this is off topic for this Arduino site. Though you should be able to find example code online. Maybe by searching for something like "javascript digest authentication" or similar.
Note: Digest authentication transmits hashes of the credentials. That is not the same as encryption, especially with an easy hash standard like MD5. Better than plain text, but with a hash table an attacker would still be able to read the credentials. For encryption you would need TLS (https).


text:
Why is conversion time 10 times slower in my ESP32-WROOM-32U?
The following code is used to show conversion time and maximum sampling frequency. The code is from this GitHub page for a spectrum analyzer based on the ESP32. The author in his YouTube video shows that his reading is around 10 μs for the conversion time and around 100000 Hz as maximum sampling frequency.
Here is my case:
Conversion time: 93.54 uS
Max sampling frequency: 10690.92 Hz

It is 10 times slower! What is the problem?
#define AUDIO_IN_PIN 35

int analogValue;
unsigned long newTime;

void setup() {
  Serial.begin(115200);
  Serial.println("START");
}

void loop() {
  newTime = micros();

  // Do 1 million reads and record time taken
  for (int i = 0; i < 1000000; i++) {
    analogValue = analogRead(AUDIO_IN_PIN);

  }

  float conversionTime = (micros() - newTime) / 1000000.0;
  Serial.println("END");
  Serial.print("Conversion time: ");
  Serial.print(conversionTime);
  Serial.println(" uS");

  Serial.print("Max sampling frequency: ");
  Serial.print((1.0 / conversionTime) * 1000000);
  Serial.println(" Hz");
}

Edit: Sorry my bad, I added yield() to see what happens, but nothing has changed.
Edit: I have tried the @thebusybee recommandation and the result is the same!
void loop() {

  newTime = micros();
  //delay(10);
  //delay(100);
  delay(1000);
  // Do 1 million reads and record time taken
  for (int i = 0; i < 1000000; i++) {
    analogValue = analogRead(AUDIO_IN_PIN);

  }

  float conversionTime = (micros() - newTime) / 1000000.0;
   Serial.println("END");
  Serial.print("Conversion time: ");
  Serial.print(conversionTime);
  Serial.println(" uS");

  Serial.print("Max sampling frequency: ");
  Serial.print((1.0 / conversionTime) * 1000000);
  Serial.println(" Hz");
}

No luck yet! But I have found a better solution for my case esp32_is2_adc_reading

Probably that yield() as it might introduce task switching and so

In the github project, that you linked, the author doesn't yield

Yeah, I added yield() to see what happens, but nothing has changed!

Try removing the println("START"); from setup(). Serial interrupts while transmitting data during the sampling stage might slow it down.

I added the start and end print to calculate the time, it wasn't there in the beginning, yet nothing changes.

Delay before the loop reading the analog values, to make sure that no serial transmission takes place. You have some 60 to 70 characters per test, these need about 6ms at 115200 baud. Start with delay(10); to see what happens. -- Please [edit] your question to add your then current code and results.

@the busybee no luck mate!

Next try: Toggle a port pin in the acquiring loop and use the oscilloscope to see what's really happening.

Read this: Slower ADC Sampling rate using firmware versions 2.0.6, 1.0.6, or 1.0.5 compared to version 1.0.4. Earlier versions of the ESP32 Arduino Core might have had a much shorter ADC conversion time.

Also see here on Electronics StackExchange: Why doesn't the sampling rate of the ESP32 go any higher than 10 kHz?. No solutions however.

If you have found a solution, please write an actual answer that is self-contained and mark it. This is the way this site is intended to work. You can and probably should provide the link to the external resource. However, the answer shall have enough details to understand it without visiting that resource.


text:
Arduino if, else if conditions being overlooked
Hi Im very new to coding and I'm struggling to fix a problem. I want the user to input a yes or no answer to a question and based on the answer I want the right text to show on the serial monitor and a LCD as well as the right LED light to light up. However it seems like the if and else if statements are ignored and no matter what the user input is the last else statement is the only thing that shows up.
My second problem is with the switchLead. The LED that shows the condition of the switchLead does not turn off when the switchLead is open.
This is just school work so it has to be basic. Please let me know where I made a mistake! Also this is my first post so let me know how I could make this more clear. Thanks!
#include <Wire.h>
#include <LCD.h>
#include <LiquidCrystal_I2C.h>

LiquidCrystal_I2C lcd(0x27, 2, 1, 0, 4, 5, 6, 7, 3, POSITIVE);

String input;                   // Declate string variable to hold user input

const int whiteLead = 2;
const int switchLED = 13;
const int RED1 = 9;
const int YELLOW1 = 8;
const int GREEN1 = 7;

int switchLead = 0;

void setup() {
  Serial.begin(9600);          // Serial transmission activated baud rate 9600 bits per sec
  lcd.begin(16,2);             // Initialise I2C LCD 16 columns with 2 rows
  lcd.backlight();

pinMode(whiteLead,INPUT);
pinMode(switchLED,OUTPUT);
pinMode(RED1,OUTPUT);
pinMode(YELLOW1,OUTPUT);
pinMode(GREEN1,OUTPUT);

switchLead = digitalRead(whiteLead);       // Read the state of the switchLead value
if (switchLead == HIGH) {                  // Begin if; if whiteLead is open do;
  digitalWrite(switchLED, LOW);
  digitalWrite(RED1,LOW);
  digitalWrite(YELLOW1,LOW);
  digitalWrite(GREEN1,LOW);

}                                          // End if
else {                                     // Begin else; Check if the switchLead is closed, turn LED ON
  digitalWrite(switchLED, HIGH);           // Turn switch LED ON
}                                          // End else
}                                          // End void setup

void loop() {                               // Void loop begins
  Serial.println("Is the room in use? ");   //Prompt user to input answer
  while (Serial.available()==0) {}          // Wait for user input
  input = Serial.readString();              // Read user input and store it in variable input

   if (input == "Yes") {               // Begin if: if user input is yes

    lcd.setCursor(0,0);
    lcd.print("In use");
    Serial.print("The room is ");
    Serial.println("in use");
    digitalWrite(switchLED,HIGH);
    digitalWrite(RED1,HIGH);
    digitalWrite(GREEN1,LOW);
    digitalWrite(YELLOW1,LOW);
  }
  else if (input == "No") {

    lcd.clear();
    lcd.setCursor(0,0);
    lcd.print("Empty");
    Serial.print("The room is: ");
    Serial.println("empty");
    digitalWrite(switchLED,HIGH);
    digitalWrite(GREEN1,HIGH);
    digitalWrite(RED1,LOW);
    digitalWrite(YELLOW1,LOW);
  }
    else {                                // Begin else

    lcd.clear();                        // Clear LCD display
    lcd.setCursor(0,0);                 // Set LCD cursor to column 0, row 0
    lcd.print("Preparing");             // Print message enclosed in brackets on LCD
    Serial.print("The room is ");       // Print message enclosed in brackets to computer monitor
    Serial.println("being prepared");   // Print message enclosed in brackets to computer monitor
    digitalWrite(YELLOW1,HIGH);         // Turn YELLOW1 ON
    digitalWrite(GREEN1,LOW);           // Turn GREEN1 OFF
    digitalWrite(RED1,LOW);             // Turn RED1 OFF
  }                                     // End else
}                                       // End void loop

because readString returns "Yes\n"

tip:  lcd.setCursor(0,0); is always executed ... it should be placed before the first if statement .... same with the Serial.print("The room is ");

Try to use this command
input = Serial.readStringUntil('\n');

Instead of input = Serial.readString();
and also use while (Serial.available() > 0)
Instead of while (Serial.available()==0)
and where you used int switchLead = 0;
Try to use bool switchLead;
I hope these changes in the code will help you