text:
I cannot get my code to play music in a or manner. I have to open one switch then the other. Music should play with either door open
Problem is if I open the necklaceDoor first, nothing happens. I have to open the ringDoor first. That turns everything on. Then with the necklaceDoor open, the stepper motor will turn off and the lights and music will continue to play. But I want to be able to open the necklaceDoor first and play the music with the lights. I do not want it to matter which one is opened first. I also realized that if I can get an or statement to work within an and statement I could do away with the fourth if statement completely. Both ringDoor open and necklaceDoor open, as well as ringDoor closed and necklaceDoor open have the same outcome. Now if I switch the door states in the third if statement, I get necklaceDoor only plays audio after closed(original problem) but if both doors are open and then ringDoor is closed, the music will shut off after the stepper timer is done and then start again after necklaceDoor is closed?!?!?!?
#include <SD.h>
#include <TMRpcm.h>
#include <Stepper.h>
TMRpcm tmrpcm;

const int stepsPerRevolution = 2048;   //Number of pulses per revolution
const int ringDoor=2;                  //Ring door
const int necklaceDoor=7;              //Necklace door
const int relayPower=22;               //Turn relay on

Stepper myStepper = Stepper(stepsPerRevolution, 8, 10, 9, 11);

void setup() {
  Serial.begin(9600);                         //Start connection with computer

  if (!SD.begin(53))                         //Chip pin on card
  {
    Serial.println("failed!");                //SD card did not read
    return;
  }

  tmrpcm.speakerPin = 46;                      //Speaker output pin
  myStepper.setSpeed(5);                       //Stepper speed
  pinMode(ringDoor,INPUT);                     //Check state of ring door magnetic switch, NO
  pinMode(necklaceDoor,INPUT);                 //Check state of necklace door magnetic switch, NO
  pinMode(relayPower,OUTPUT);                  //Relay enable for 12V LED
  digitalWrite(ringDoor,HIGH);                 //Make door closed read high on start up
  digitalWrite(necklaceDoor,HIGH);             //Make door closed read high on start up
  digitalWrite(relayPower,LOW);                //Make relay off on start up
}

void loop() {

  if ((digitalRead(ringDoor)==HIGH)&&(digitalRead(necklaceDoor)==HIGH))
  {                                                                                //ring door and necklace door is closed, everything is off
    digitalWrite(relayPower,LOW);
  }

  if ((digitalRead(ringDoor)==LOW)&&(digitalRead(necklaceDoor)==HIGH))
  {                                                                                //ring door is open and necklace door is closed, lights on, stepper motor spinning, music playing
    digitalWrite(relayPower,HIGH);
    tmrpcm.play("music.wav");
    myStepper.step(stepsPerRevolution);
    delay(500);
    myStepper.step(-stepsPerRevolution);
    delay(500);
  }

  if ((digitalRead(ringDoor)==LOW)&&(digitalRead(necklaceDoor)==HIGH))
  {                                                                                //ring door closed and necklace door open, lights on, stepper motor off, music playing
    digitalWrite(relayPower,HIGH);
    tmrpcm.play("music.wav");
  }

  if ((digitalRead(ringDoor)==LOW)&&(digitalRead(necklaceDoor)==LOW))
  {                                                                                //ring door and necklace door open, lights on, stepper motor off, music playing
    digitalWrite(relayPower,HIGH);
    tmrpcm.play("music.wav");
  }
}

Please and thank you to any and all who help. It is greatly appreciated.
Yes, I asked the the original question and the answer I received not only did not work, somehow neither latch worked anymore.

The code you've presented should not even compile. Some of what looks like code is in comments, line endings are apparently missing, and lines extend far out across the page. Is this what you tried to run or did it get mangled when you posted it? If it's the latter, please repost the code you actually compiled.

I don't know what happened to your code when you copy-pasted it, but please reformat it entirely and paste it in here again. It's entirely unreadable, and definitely should not compile as it is. Once you paste it, highlight it all and click the "Code Sample" button in the editor to get the editor to treat it as a code block (as it is now already).

Updated. Thank you, I had not realized it messed up.

Did you intend for the two middle if statements to have the exact same condition?  Or should one have been for the other door?

all you need is two if statements to cover the open doors ... if either door is open then lights on and play music .... if ring door is open then run motor ... run them one after the other

I have tried two if statements.I have tried else if statements. I have tried just about everything imaginable to me. No matter what, what I cannot get the lights to turn on with just the necklace door open. And, I need the motor to stop if the necklace door is opened at any point. Thanks for the help but I think I am going to have to pay someone to look at it.

First of all, you have to find out how your magnetic switches work. Are they opened or closed if you attach a magnet to them? Do they behave the same or is one closed and the other opened if you attach a magnet?
Your code above is written for active LOW switches i.e. if the respective door is closed the switch is opened and therefore the logic level of the pin is HIGH. The level is LOW if the door is opened (activated; hence active LOW).
In order your code had a chance to work, the switches must be connect the right way: on one side connect them to GND and on the other side to the respective Arduino pin. If this is not the case, the code must be changed or the switches must be conneted the right way. You did not show us your schematic, so I can not check it for you.
Here is some code to try: But first find out if the switches you use are LOW or HIGH active. I also have no access to an IDE at the moment, so I can not try out the code. Take it as a hint on how to do it.
And one tip from a guy that does the job for 30 years now: Don't comment variables if their names say it all:
//  this sort of comments makes the code unreadable --V
const int ringDoor=2;                          //Ring door

I know it is a common behavior in the Arduino community, but don't write comments after a statement. In your code above I did realize that there are comment for the if statements only when I copied the code in my answer. Comments are only usefull if they say something new and can be read without problems.
#include <SD.h>
#include <TMRpcm.h>
#include <Stepper.h>
TMRpcm tmrpcm;

const int stepsPerRevolution = 2048;
const int ringDoor = 2;
const int necklaceDoor = 7;
const int relayPower = 22;

Stepper myStepper = Stepper( stepsPerRevolution, 8, 10, 9, 11 );

void setup()
{
  Serial.begin( 9600 );
  if ( ! SD.begin( 53 ) )
  {
    Serial.println( "failed!" );
    return;
  }

  tmrpcm.speakerPin = 46;
  myStepper.setSpeed( 5 );
  pinMode( ringDoor, INPUT );
  pinMode( necklaceDoor, INPUT );
  pinMode( relayPower, OUTPUT );

  digitalWrite( ringDoor, HIGH );
  digitalWrite( necklaceDoor, HIGH );

  digitalWrite( relayPower, LOW );
}

void loop() {

  // the following code works if both switches are LOW active
  // (i.e. LOW if the door is open)
  // if the "ringDoor-switch is HIGH active change
  // digitalRead( ringDoor ) == LOW to
  // digitalRead( ringDoor ) == HIGH
  // if the "necklaceDoor-switch is HIGH active change
  // digitalRead( necklaceDoor ) == LOW to
  // digitalRead( necklaceDoor ) == HIGH
  // and
  // digitalRead( necklaceDoor ) == HIGH to
  // digitalRead( necklaceDoor ) == LOW

  if ( ( digitalRead( ringDoor )     == LOW ) ||
       ( digitalRead( necklaceDoor ) == LOW ) )
  {
    // one of the doors is open
    digitalWrite( relayPower, HIGH );
    tmrpcm.play( "music.wav" );
    if ( digitalRead( necklaceDoor ) == HIGH )
    {
      // only the ring door is opend
      myStepper.step( stepsPerRevolution );
      delay( 500 );
      myStepper.step( -stepsPerRevolution );
      delay( 500 );
    }
  }
  else
  {
    digitalWrite( relayPower, LOW );
  }
}

So your code works almost perfect. Thank you very much! I do apologize for the notes. The arduino page forum asked for them as did my first post here. The only issue I am having now is that if I open necklace door first no music will play until I close that switch? Then music will play? I am trying to figure out how to add picture of my schematic. Be gentle with me, I don't have CAD so I drew it in MultiSim. ( A program I still have from college). I just edited original post with the schematic.

@VincentLedbetter You're welcome. There is no reason to apollogize. The schematic is fine. The switches connect GND to the sensor pins so the first part of the program (e.g. activating the pull up resistors) seems to be correct. Theres one thing I can not check, and that's: Are the switches close if the doors are close or are they open? See the comment in the code above. If you can not find out, make the HIGH/LOW changes I suggest in the comment and find out if that works better. There could also be an issue with the needed power. The Mega might not be able to drive all the current you need.

So the 12v Power supply has a splitter. One side goes to the arduino and I am only running the sd card reader, the relay enable and the audio pin. Then the other side of the 12v power supply is ran through the relay. The LED's plug in before the voltage regulator and the stepper motor is powered after the voltage regulator. So my high amperage draw is coming straight from the power source and not through the board.

@VincentLedbetter The 3.3V Pin has a maximum current of 50mA. How much current draws the SD Card Module? The IO Pins can deliver 40mA. How much draws the Buzzer? The 5V can deliver the minimum of the possible Power Supply current and 500mA (controlled by a thermofuse). From that you have to subtract the current that's drawn from the other pins: 3.3V, IO Pins, the pullups on the switches draw current ...  It was just an idea if nothing else makes sense. The other idea, that the switches might not behave as expected, is more important to me.


text:
SIM900 module connects then disconnects from carrier soon after
I have an Arduino Mega 2560 with an ESP8266 built into it, and a SIM900 shield, which I am building a project with.
The shield is powered by an external adjustable 3-12V, 2A supply set at 6V so power is not an issue.
I have managed to get serial to work, and can issue commands to the device. My issue is the following;

I fire up the shield.
Shield reports back CREG = 2 which means ME is looking for an operator to connect to.
Shield reports back CREG = 1 which means it has connected to an operator.

Running AT+COPS? returns my provider, as long as CREG = 1.

Seconds in, CREG = 4, which means Unknown.

I don't see why it keeps disconnecting me, I have gone through 4 different SIM cards and the problem persists.
Has anyone else had this problem and if you did, how did you manage to work around it?
17:29:25.000 -> NORMAL POWER DOWN
17:29:25.000 ->
17:29:25.000 -> +CREG: 3
17:29:27.993 -> ?????????? (SHIELD TURNS ON, GARBAGE OUTPUT)
17:29:29.520 -> RDY
17:29:29.520 ->
17:29:29.520 -> +CREG: 2
17:29:29.520 ->
17:29:29.520 -> +CREG: 0
17:29:29.520 ->
17:29:29.553 -> +CFUN: 1
17:29:29.553 ->
17:29:29.553 -> +CPIN: SIM PIN
17:29:33.506 -> AT+CPIN=1234
17:29:33.506 ->
17:29:33.506 -> OK
17:29:34.503 ->
17:29:34.503 -> +CREG: 2
17:29:36.528 -> AT+COPS?
17:29:36.528 ->
17:29:36.528 -> +COPS: 0
17:29:36.528 ->
17:29:36.528 -> OK
17:29:38.022 ->
17:29:38.022 -> Call Ready
17:29:39.550 -> AT+COPS?
17:29:39.550 ->
17:29:39.550 -> +COPS: 0
17:29:39.550 ->
17:29:39.550 -> OK
17:29:41.044 ->
17:29:41.044 -> +CREG: 1
17:29:42.572 -> AT+COPS?
17:29:42.572 ->
17:29:42.572 -> +COPS: 0,0,"CYTAMOBILE-VODAFONE"
17:29:42.572 ->
17:29:42.572 -> OK
17:29:44.565 -> AT+COPS?
17:29:44.565 ->
17:29:44.565 -> +COPS: 0,0,"CYTAMOBILE-VODAFONE"
17:29:44.598 ->
17:29:44.598 -> OK
17:29:47.587 -> AT+COPS?
17:29:47.587 ->
17:29:47.587 -> +COPS: 0,0,"CYTAMOBILE-VODAFONE"
17:29:47.620 ->
17:29:47.620 -> OK
17:29:49.580 ->
17:29:49.580 -> +CREG: 4
17:29:50.111 -> AT+COPS?
17:29:50.111 ->
17:29:50.111 -> +COPS: 0
17:29:50.111 ->
17:29:50.111 -> OK

6 V on barrel jack or Vin of Mega is not enough

The mega is powered by the USB cable connected to my laptop. It's the SIM900 shield that is connected to the power supply.

source: Stack Exchange

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

sort: votes


text:
Using different processors when it comes to arduino
I decided to learn Arduino in this quarantine so I am still a newbie when it comes to micro controllers. Basically I been doing all my projects based on the ATMEGA328P-PU:

I even converted my breadboard designs to custom PCBs like this one:

I am running out of Atmega328P-PU processors and I am about to buy more. But instead of going with the traditional Atmega328P should I buy other processors?
This are my alternatives:

They all are about the same price. For example the ESP32 is 10 times faster and it was a lot more sram and pins. Anyways this are my questions:

Why do people buy the Atmega328P when there are faster and more powerfull processors for the same price?

I been saving a lot of money by buying the Atmega328P processor by itself and then building Arduino using the crystal, ceramic capacitors etc. There are so many tutorials on how to build that such as on THIS LINK and many more. But how can I build an ESP32 running arduino code on a breadboard? I have not been able to find that tutorial. All the tutorials I find use the ESP32 already soldered to a PCB. I want to build my custom PCB using a ESP32 for example. Where can I find that tutorial?

If I decide to buy the ESP32 or ESP8266 should I build my code using the arduino IDE? I will have to add stuff to arduino IDE so it works with the ESP32. What are the benefits of using other IDEs?

I am thinking about the ESP32 and ESP8266 because I see a lot of people using them on the internet and they are much more powerfull than the Atmega328P for the same price. What other processors do you guys recommend?

did you see Teensy 4?

Forget the esp8266. The IO is to restrictive. ESP32 if far far better.

I love the 8266, mostly because of the price and the esp-01's size. ESP's don't really do breadboards. If you want small and cheap, look for "wroom esp32" modules, but keep in mind the pin spacing is unlike breadboards. I use 10cm M+F dupont cables to run from MCU pins to breadboards. The nodeMCU boards have so many vcc+gnd pins that I can often "dead bug" sensors and outputs w/o a breadboard or pcb using F+F dupont cables. I would look into the "blue pill" arm boards, which now have official arduino support. Lastly, there's a way to run a 328 w/o a crystal, at 8Mhz, might interest you.

For learning it really doesn't matter much of which MCU to choose from. For actually embedded project development, it really depends on what you want to do with your dev board. I thought that I would just offers some of my thoughts and experiences here as a reference, there is no right or wrong answers. I'm sure many people have their own favourites and considerations when picking their MCU.

Why do people buy the Atmega328P when there are faster and more powerfull processors for the same price?

ATmega328p get popular for its long history (it is 2-decades old) and Arduino, personally I feel that there are better MCU with compatible features, memory size, etc. even within the AVR series to replace ATmega328p, I actually developed an ATtiny3217-based Arduino board last month, it is cheaper (on chip BOM cost) and it does not need crystal for running at 20MHz with decent accuracy, it offers almost similar I/O pins, memory size, UART/I2C/SPI as ATmega328, but it is a much modern chip with many features that are not available in ATmega328 (such as DAC, touch support, event system, etc.). ATmega3208/4809 is another interesting candidate for my next project.

All the tutorials I find use the ESP32 already soldered to a PCB. I want to build my custom PCB using a ESP32 for example. Where can I find that tutorial?

ESP32 (and ESP8266 like ESP-12F as well) come with a compact form factor that is ready to be integrated into your design, most of the design needs are USB-interface, power supply and some peripheral (such as auto-reset circuitry, power and blinking LEDs, etc.). You can take a look at Adafruit HUZZAH ESP8266 which is basically based upon an ESP-12E module with added circuit for reset, voltage regulator.

If I decide to buy the ESP32 or ESP8266 should I build my code using the arduino IDE? I will have to add stuff to arduino IDE so it works with the ESP32. What are the benefits of using other IDEs?

Arduino IDE is not the only IDE for programming an Arduino, PlatformIO is one of the alternatives IDE for Arduino programming, one of the main benefits is better project and dependency(libraries) management and the flexibility on compiling/building process (e.g. pull in the floating point supports on AVR chips). Take a look at these two YouTube videos to see how it looks like and how to set it up:

A Better Arduino IDE – Getting Started with PlatformIO
PlatformIO – Using External Libraries

I am thinking about the ESP32 and ESP8266... What other processors do you guys recommend?

As I mentioned at the beginning, it really depend on your selection criteria. ESP8266 and ESP32 is generally the choice for its WiFi capability, however, you won't chose ESP8266 for anything related to ADC because it has only one ADC with a reference voltage of 1v. ESP32 looks great for for its faster CPU, it however generated a lot of noise when you want to reading sensor data even though it offers 12-bit ADC resolution versus 10-bit in ATmega328p. Its ADC also has non-linear issue on some of the old batch of ESP32 chips.
On the question of "what other processors do you guys recommend"? If no requirements for wireless connectivity, I personally like STM32F103 Blue Pill, for its better ADC (12-bit), more memory, and multiple UARTs, and cheap but there are things that you need to be aware of (such as fake STM32 chip and design faults).
Whatever you decided for your next choice of MCU, I'm sure it won't be your last one, as your experience grow and your project get more complex, you will know that there is no perfect MCU that fit it all.

Sometimes faster and more powerful is not needed. If you just needed a simple timer, and it needed to be battery operated, a processor like the ATmega328 would be the better choice. It really depends on the application.

The ESP32 is a great device. But the A/D converter on it is less than stellar. It is not as consistent compared to the A/D in the Atmega328P.

The ESP32 is more fussy about the power supply requirements compared to the Atmega328P. Lots of people get themselves into trouble when they use poor design practices with the ESP32/ESP8266 modules. Poor practices that worked well enough for lower power and lower speed processors like the Atmega328P. Most people don't bother with reading the datasheet for the processors. They just try and copy stuff they fine on the Internet. And the Internet is full of poor quality information by people who don't really understand much of what they are working with.

If you want to start using the ESP32, then do yourself a favor and buy a working board with a power supply and not just buy a module. It will save you many hours of grief.

The Arduino IDE makes it easy to get stuff working. There also is Python, but it is less popular. There is a lot more information available for the Arduino IDE, and available libraries. And that makes development a lot easier. There are other ways, but the learning curve is much steeper.

The "Blue Pill" STM32F103C8T6 based board is a lot of capability for little money. The CPU runs on 3.3 volts like the ESP devices. It has gain a lot of popularity in the last few years but there isn't as much information as for the Atmega328P.

The STM32F103C8T6 and the ESP devices are 3.3 volt based designs. And they require 3.3 volt devices to interact with. There are some devices that are mostly 5 volt only devices. Like a character LCD. It is easier to interface that to a 5 volt processor.
There is lots that I could still say but it would take hours. But what you should do before deciding on a part is to decide what the needs of the project are. That will often guide you towards the part you should use.
One more note. The ESP devices are running a lot of code on top of the Setup and Loop functions. There is lots of stuff going on in the background to support the WiFi capability. And you don't have the kind of control that you could have with a non-ESP device. But if you want that part then you need to accept that limitation.

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


text:
Linux can not open arduino IDE - java.lang.NullPointerException
I use arch linux. I installed arduino ide with pacman. When I try to run it, loading window will show for few socends and than program crashes. There are logs:
john@arch-thinkpad ~ [1]> arduino
Picked up JAVA_TOOL_OPTIONS:
Set log4j store directory /home/john/.arduino15
java.lang.NullPointerException
    at processing.app.Base.rebuildProgrammerMenu(Base.java:1705)
    at processing.app.Base.<init>(Base.java:286)
    at processing.app.Base.main(Base.java:150)
john@arch-thinkpad ~ [255]>

john@arch-thinkpad ~> arduino --version
Picked up JAVA_TOOL_OPTIONS:
Loading configuration...
Initializing packages...
Preparing boards...
Arduino: 1.8.13

What should I do to fix it ?
Thank you for your help

Delete your preferences.txt file.

I had to install arduino-avr-core package:
sudo pacman -S arduino-avr-core

Now it works fine

The first thing to do is delete your preferences.txt file. This is the most common cause of startup issues - some corruption or an invalid setting in that file can break the IDE completely.
rm ~/.arduino15/preferences.txt

If that doesn't fix it then you can delete your entire Arduino working directory, which will remove all installed cores and boards and give you a fresh installation:
rm -rf ~/.arduino15

There was some corruption to the package_index.json a little while ago - mid July - perhaps the OP was affected by that, even though it though the post phrasing suggests that they have only just installed the Arduino IDE. Anyway, the fix for that issue was to remove file ~/.arduino15/package_index.json and remove folder ~/.arduino15/cache - which would be worth trying before deleting the preferences file or entire settings directory if it is an old/configured install.

Thank you for your answer but it did not change anything and issue still remains.


text:
ESP32 send data to another ESP32 without establishing a wifi connection
Originally I was creating a project consisting of the Atmega328P and NRF24L01 to create multiple arduinos that could talk to each other.  Basically I was creating something like this:

As the network grows I am starting to run out of memory when using the atmega328P. I have to be careful about allocating memory and more. So I will like to replace the NRF24L01 with the ESP32.  The price of the ESP-WROOM-32 by itself is also cheaper than buying an NRF24L01 + the atmega328.

Question
How can I send data from one ESP32 to another ESP32 without establishing a WiFi connection? Just like the NRF24L01 where you specify a writting pipe where you want to send the data and the other NRF24L01 is listening on that pipe.

I know I can do that with ESP-NOW. This video explains how. The problem with ESP NOW is that I have to know in advance the mac address of the ESP32 where I intend to send a message. I plan to be able to keep adding smart home devices without having to know the mac address.
My algorithm with NRF24 that I already created is as follows:

There is a master node listening on address 2
If I add a new  node A to the network it listens on address 1.
Master discovers all devices that have address 1 every few seconds.
So eventually node A receives a discovery packet message that comes from master. Node A listens now on a random address and replies to master with that random anddress.
So node A is now connected to the network.

The cool thing about this algorithm is that I can keep adding new nodes to the network without knowing in advance its address. I will like to do the same thing with the ESP32. How can I send a simple message betweenn 2 ESP32 modules?

You should check out mesh mode...

if they have constant power, you could connect to wifi on boot, fetch a "phone book" from a server, then disconnect wifi and start esp-now. If they only talk one-way like my light switches(buttons), you don't need to ever change config to add more units.

Finally I found a way how to do it. If you use the mac address FF:FF:FF:FF:FF:FF that works as a broadcast address. This is the working code on how to send a message from the master to another esp32 without knowing its mac address. Later the slave can reply with its real mac address:
Code for master (tx)
#include <Arduino.h>
#include <esp_now.h>
#include "WiFi.h"

uint8_t broadcastAddress[] = {0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF};

void OnDataSent(const uint8_t *mac_addr, esp_now_send_status_t status) {
  Serial.println(status == ESP_NOW_SEND_SUCCESS ? "Delivery Success 1" : "Delivery Fail 1");
  if (status ==0){
    Serial.println("Delivery Success 2");
  }
  else{
    Serial.println("Delivery fail 2");
  }

  Serial.println();
}

void setup()
{

  Serial.begin(115200);

  Serial.println("Starting...\n");

  // Set device as a Wi-Fi Station
  WiFi.mode(WIFI_STA);

  Serial.println(WiFi.macAddress());

  // Init ESP-NOW
  if (esp_now_init() != ESP_OK) {
    Serial.println("Error initializing ESP-NOW");
    for(;;) {      delay(1);  } // do not initialize wait forever
  }

  Serial.println("initialized ESP-NOW");

  // Once ESPNow is successfully Init, we will register for Send CB to
  // get the status of Trasnmitted packet
  esp_now_register_send_cb(OnDataSent);

   // Register peer
  esp_now_peer_info_t peerInfo;
  memcpy(peerInfo.peer_addr, broadcastAddress, 6);
  peerInfo.channel = 0;
  peerInfo.encrypt = false;

   // Add peer
  if (esp_now_add_peer(&peerInfo) != ESP_OK){
    Serial.println("Failed to add peer");
    for(;;) {      delay(1);  } // do not initialize wait forever
  }
}

int dataToSend = 1;
void loop()
{
    dataToSend++;

    // Send message via ESP-NOW (size of an int is 4 bytes on ESP32)
    esp_err_t result = esp_now_send(broadcastAddress, (uint8_t *) &dataToSend, 4);

    if (result == ESP_OK) {
      Serial.println("Sent with success");
    }
    else {
      Serial.println("Error sending the data");
    }

    //Serial.println(WiFi.macAddress());
    delay(1000);
}

Code for slave (Rx)
#include <Arduino.h>
#include <esp_now.h>
#include "WiFi.h"

// Callback when data is received
void OnDataRecv(const uint8_t * mac, const uint8_t *incomingData, int len)
{
  int dataReceived;
  memcpy(&dataReceived, incomingData, sizeof(dataReceived));

  Serial.print("Data Received: ");
  Serial.println(dataReceived);

  Serial.println();
}

void setup()
{

  Serial.begin(115200);
  delay(100);

  Serial.println("Starting...\n");

  // Set device as a Wi-Fi Station
  WiFi.mode(WIFI_STA);

  // print our mac address
  Serial.println(WiFi.macAddress());

  // Init ESP-NOW
  if (esp_now_init() != ESP_OK) {
    Serial.println("Error initializing ESP-NOW");
    for(;;) {      delay(1);  } // do not initialize wait forever
  }

  Serial.println("initialized ESP-NOW");

  // Register for a callback function that will be called when data is received
  esp_now_register_recv_cb(OnDataRecv);

}

void loop()
{
}

You can also reply back on the receiver code if you want. It will be the same code.

google OSI model data link layer for additional info about the osi model layer 2 ... there are multiple communication protocols available ... i do not know which are implemented by the esp32 module

You don't even need to set the macAddress to FF:FF:FF:FF:FF:FF, the esp_now_send() function allows you to pass in a NULL as the macAddress for broadcasting esp_now_send(NULL, *data, len). See documentation.

For peers, you also don't need to use the physical macAddress, you can simply assign a local-administrated peer address to each peers. The advantages of doing so is not only save the trouble from finding each peer's macAddress,  when you swap out a peer and replace another one in future, you don't even need to change the peer list of macAddresses in your master code.


text:
Detecting different objects closeness
iam currently working on a new project, where i would like to detect the existence/closeness of several objects around the arduino up to like 1 meter. I was thinking about an rfid setup, but as the objects could have different sizes like 5 centimetre tall and only 3 centimetre wide, i think this won't work for the max distance. I was also thinking about a ble beacon, but as this one has to be activley powered all the time, it wouln't be the perfect solution. As the base could be fully customized, it may have some kind of sensors/wires overall the surface, but iam a bit lacking of a good idea for this.
I hope someone might had a similar setup, or a good idea to go.
PS: When i think about it twice, it would be better, if it can be differentiate between some areas within the one meter and the different objects, entering each area. I've added some image, hope this helps to understand, what i want to archive at the end.

Thank you and greetings,
Sebastian

why would an RFID solution be dependent on object size?

hey @jsotola thanks for the feedback, yes my mistake, just had a quick view into rfid setups and thought it  have some dependency for the range, but just the reader seems to be a bit more expensive. But when i think about it twice, it would be better, if it can be differentiate between some areas within the one meter and the different objects, entering each area. I have added some image, hope this helps to understand, what i really want to archive. Thanks a lot!

The image confuses me. Why have you put the map of germany under your Arduino there? What are you trying to achieve? As you may have noticed, measuring the position (in this case with direction and distance) of multiple objects is not an easy task. A description of what you are actually trying to build might give us better information to suggest a fitting solution

@chrisl it should be a smart table top game and in this case "germany" just represents the field and in different areas should different situations recognized as soon as a object (character) enters the different areas

I want to detect specific small objects, which could be moved around in specific areas (one square meter), so not a "just detect somthing in front of xyz" and also not "depending on the range" detection. Does any has a suggestion so far? Thanks and Greetings,
Sebastian

As you might have already seen, a position sensing system can be really complex. Here I will list some possibilities, that come to my mind and might be fitting for your case or not.

Matrix based solutions: Here I mean sensors a some sort arranged in a matrix underneath the game table, which can sense the object placed on them. As you know from your wiring, where a specific sensor is located, you know from the triggered sensor, where the object was placed. The resolution directly corresponds to the numbers of sensors, that you place. You can use different sensors, which will give you different information, but are also very different in handling and costs:

Reed switches and magnets on the bottom of the objects. The magnet on the object would close the reed switch. A read switches are rather cheap (have seen 40 pieces for about 10€ on amazon; on aliexpress or others you might get them even cheaper) and can be easily placed in an electrical matrix or (depending on the number and places of object at any time) checked via shift registers, which are also not very pricey.

Hall sensors and magnets on the bottom of the objects. You would measure the magnetic field of the magnets with the hall sensors. You could use different magnet strengths to get different readings and thus directly distinguish between different object types. The hall sensors will be not that easy to read. Mostly they have an analog output, thus you would need extra ADCs and multiplexers to read them all.

RFID readers and RFID chips in each object. Very pricey and rather low resolution. Also very difficult to read from all of them with the Arduino. But you could go for the reed switch version and use a single RFID reader to first tell the Arduino, which object you are placing. In the game you would first hold the object to the reader, then place it on the board.

Lidar system: A Lidar scanner could scan over your board (it measures the distance in a circle around it). Each object would be a negative peak in the measured distance distribution. From the angle and the distance, you could calculate the position on the board. Though you would need to carefully place the sensor, as one object might hide the other behind it. You can tackle that with an additional Lidar scanner, but the processing will also be rather complex. And Lidar scanners are rather expensive.

Ultrasonic sensors out the board: If you place enough ultrasonic sensors around the board and measure with one after the other, you might also get fitting results. But I would guess, that you won't get good positioning results with them, especially for the rather small objects and distances used on a game table.

Computer Vision: Away from Arduino you could use OpenCV on a Raspberry Pi together with a small camera above your board to detect objects. General object detecting is rather easy with OpenCV and python; getting it's position in the camera image is trivial then (from where you can calculate the position on the board easily). With more work it should also be possible to detect the object themselves (meaning distinguishing between different objects). We might need to train OpenCV with top-down images of the objects for that. If you don't get good results with the normal camera mode, you could try the IR camera mode (by removing the IR filter of the Pi's camera) and put some good IR reflective stuff on the top of the objects. Then OpenCV only has to find the bright spots in the image. All that is possible, though I cannot help you with that and also it is off-topic on this site.

If you can have a board with fixed positions, you could make direct electrical connections between the objects and the board. Though that means, that you would have metal contacts all over the board. I recently used such electrical connections to distinguish between different objects, which can be put into a small number of bays. I have 7 pins on each object, one of them ground. On the object I connected some of the other pins to the ground pin to create a binary pattern. The pins of each bay get read by a shift-in register. All registers are chained together and connected to the Arduino with a total of 4 pins.

Depending on your needs you could combine some of these options. I would try the OpenCV solution, or alternatively the reed switch with one RFID reader solution.

You should use the HC-SR0 ultrasonic sensor. It has good accuracy and range. If you don't want to use that, you can use an infrared distance sensor. If these don't work, please tell me why.


text:
How to convert my Arduino setup to a PIC setup?
I have an arduino setup with LCD, RTC, EEPROM, Reed Switch, AC/DC Buck Converter, 4X4 Keypad.
What PIC IC will let me connect with all these(40 Pins), and yet accept Arduino Code.
I don't want to rewrite the code. I learn Arduino only recently, So shifting to another coding language is near impossible, since am not a coder.

so, you go to an Arduino site to ask how to not use an Arduino? ... go to a Microsoft website and ask how to stop using Microsoft software ... see how they like your question

voting to close because the question is not about an Arduino

There is a pinguino project which allows you to program PIC MCUs on Arduino IDE like an Arduino.

There are also many chipKit-based boards that can be run under the Arduino IDE environment.

I am the head honcho for for current chipkit designs. It sounds like the MAX32 is what you want. Equivalent to the Mega. The uC32 may have enough pins too which is an uno equivalent. You should check them out. All PIC32 based.

@jsotola, I think this question is perfectly acceptable for this site. I support expanding beyond Arduino. Very few of the users here, no doubt, are using genuine Arduino boards which give money to Arduino anyway. The goal isn't to have a pure Arduino site, it's to have a site inspired by Arduino which opens up multiple avenues of creativity and productivity.

And yes, some PIC boards can be programmed like Arduino. Arduino has inspired a lot of progress in the industry as a whole, and literally changed the world of programmable electronics.

@hindisong.cc, Why do you want to use a PIC anyway? What are you seeking?

The PIC32 has full (or nearly full) support for the Arduino API through the chipKIT project.  If you want to use one of the smaller PIC chips (PIC16 / PIC18 etc) then you're out of luck. There just isn't a freely available C++ compiler for those chips, so the Arduino API can never really be ported to them.
I have, in the past, cobbled together an Arduino-style API layer for a handful of selected PIC18s which uses structs to emulate a couple of the Arduino C++ objects, but it only worked in a very basic way with no function overloading for things like Serial.print().
One of the problems from a low-end user's perspective is that the PIC32 only comes in harder to use TQFP and QFN etc packages in anything larger than 28 pins. That means you can't breadboard without a development board. Fortunately there are some breadboard friendly options in the chipKIT ecosystem, such as the Fubarino series of boards. For more pins though you'd be wanting one of the bigger boards, such as the MAX32 which is in a Mega footprint (but with even more pins).
It's important to note though that the PIC32 is a 3.3V device and, owing to physical differences in the way that some of the internals work, there are incompatibilities in some of the libraries and functionality (such as no "LOW" or "CHANGE" interrupt support, only "RISING" and "FALLING").


text:
Assigning value to a struct byte order
So i have struct:
typedef struct sendPacketStruct {
  byte header = headerByte;//0x55
  unsigned int time;//2 bytes
  int height;//2 bytes
};

And i do this:
    sendPacketStruct sendPacket;

    sendPacket.time = 84;//0x54
    sendPacket.height = 100;//0x65

    Serial.write((byte*)&sendPacket, sizeof(sendPacket));

But when i receive it at the other end the hex bytes are:
55 54 00 64 00
So the first byte is correct as the header 0x55, but the 2x 2 byte values time and height are there but shifted.
eg it should be 00 54 not 54 00

it should be 00 54 not 54 00 ... why? ... is it causing a problem? ... the bytes are not shifted

Because if i read out the 2nd and 3rd byte to make the int I would get 0x5400 which is 21504  not 84 (0x54)

see 'endiannes' in wikipedia. this is why it is better to send text between systems.

read out the 2nd and 3rd byte to make the int ... how are you making the int? ... are you reading the bytes separately?

I would be reading the serial data a byte at a time as that arrive into an buffer array. When I detect a full packet in the buffer I would convert the various bits into the data. This is in a mobile app.

OK so it's actually acting correct for a little endian system, which I didn't know it was, I'm just only experienced in big endian network protocols. Thanks @Juraj

Either agree on an endian-ness (for transmission) among all systems sharing this data, or include an endian-ness indicator in the packet, and all receiver's agree to receive accept either one.

Note that today most CPUs, including AVR, ARM and x86-64, are little endian.

The answer is that arduino is little endian, so the byte order is correct. I was just expecting big endian order as ive seen in some other network protocols. If that is desired instead I can just do some bit shifting and re-arranging.

The endianness of a protocol is defined by the protocol. In C there are functions htons() ntohs() etc for "Host to Network Short" and so on that set the correct endianness for the protocol.


text:
Which Arduinos support ATOMIC_BLOCK?
Is there a definitive list of which Arduino architectures support the ATOMIC_BLOCK() macro, and a list of #defines for each architecture?
I've tried searching through the Arduino cores on GitHub to see where ATOMIC_BLOCK is used. If it's not used in a core, I've assumed it's not supported. I generated this list based upon that assumption, but how accurate is it?
ArduinoCore         Supported       Archived    #define
-------------------------------------------------------
  samd
  avr                  Yes                      __AVR__
  arc32
  sam                  Yes
  primo                               Yes
  megaavr              Yes
  API
  nRF528x-mbedos
  mbed

I would like to write some code, something like this (edited in response to comments):
#define ATOMIC_BLOCK_SUPPORTED (__AVR__ || __MEGAAVR__ || __SAM__)
.
.
.
#if ATOMIC_BLOCK_SUPPORTED
    ATOMIC_BLOCK(ATOMIC_RESTORESTATE)
    {
#endif

        // Do not disturb.

#if ATOMIC_BLOCK_SUPPORTED
    }
#endif

For architectures that don't support ATOMIC_BLOCK, I would like to write my own code to save, disable and restore the global interrupt flag, something like this.
    asm
    {
        // Save interrupt flag.
    }
    // Clear interrupt flag.
    // Do not disturb.
    // Restore interrupt flag.

Potential Solution?
#ifdef __AVR__
#include <util/atomic.h>
#elif defined(__ARCH2__)
#define ATOMIC_BLOCK(/* for architecture 2 */)
#elif defined(__ARCH3__)
#define ATOMIC_BLOCK(/* for architecture 3 */)
// etc
#endif
.
.
.
#ifdef ATOMIC_BLOCK
    ATOMIC_BLOCK(ATOMIC_RESTORESTATE)
    {
#endif

        // Do not disturb.

#ifdef ATOMIC_BLOCK
    }
#endif

Is there a definitive list of code that saves, disables and restores the global interrupt flag for every Arduino architecture that could be dropped into each #elif branch?

Have you tried #ifdef ATOMIC_BLOCK?

Or even: #ifndef ATOMIC_BLOCK /* define your own ATOMIC_BLOCK here */ #endif

Have you found any one that doesn't support it?

@user253751, thanks for your suggestions. I think most architectures don't support ATOMIC_BLOCK. I've added a potential solution. Do you know of any code that saves, disables and restores the global interrupt flag each Arduino architecture?

Have you actually tried it on all those architectures?

No, but I could only find it defined in 3 of the cores on GitHub. Is my assumption wrong?

Note that, on AVR, ATOMIC_BLOCK is not provided by the Arduino core, but by the avr-libc.

Please note that your idea of concatenating #defined symbols and use #ifdef on that will not work. Better try to #define X (defined(A) | defined(B) | defined(C)) and check with #if X.

Thanks @edgar-bonet and @the-busybee. I'm currently reading Identifying... and Platform Specification. Seems to be a perennial issue that no-one has yet holistically addressed. Thinking I might have to data-scrape all the Arduino forums for #defines...

@tim, see if my answer provides what you need. This is a topic I've studied a lot about.

This answer covers: Which Arduinos support ATOMIC_BLOCK? And how can I duplicate this concept in C with __attribute__((__cleanup__(func_to_call_when_x_exits_scope))) and in C++ with class constructors and destructors?.
Which Arduino's support the ATOMIC_BLOCK macros?

Which Arduinos support ATOMIC_BLOCK?

Only AVR (ATmel AVR architecture) microcontrollers support the ATOMIC_BLOCK macros, because these macros are part of the avr-libc library, which, you guessed it!, supports only AVR microcontrollers.
AVR-based Arduinos include those based on the ATmega328 microcontroller (Arduino Uno, Nano, Mini, etc.), ATmega2560 (Arduino Mega 2560), ATmega32U4 (Arduino Leonardo, Pro Micro), etc.
How are the ATOMIC_BLOCK macros implemented in C with the gcc compiler, and where can I see their source code?
avr-libc is available for download here: https://www.nongnu.org/avr-libc/ --> "source code and documentation" link under the "Downloads" section. Ex: here is the tarball for v 2.0.0: http://download.savannah.gnu.org/releases/avr-libc/avr-libc-2.0.0.tar.bz2.
The entire source code for the ATOMIC_BLOCK macros is contained in avr-libc-2.0.0/include/util/atomic.h.
ATOMIC_BLOCK is an ingenious macro written in C and relying upon the gcc "cleanup" attribute C extension which can call a function you define when a variable goes out of scope. Essentially, this is identical to a C++ class destructor which gets called when an instance of a class in C++ goes out of scope. The gcc "cleanup" attribute extension is a way to get C++-like behavior in C.
Here is the official gcc documentation: https://gcc.gnu.org/onlinedocs/gcc/Common-Variable-Attributes.html. It states:

cleanup (cleanup_function)
The cleanup attribute runs a function when the variable goes out of scope. This attribute can only be applied to auto function scope variables; it may not be applied to parameters or variables with static storage duration. The function must take one parameter, a pointer to a type compatible with the variable. The return value of the function (if any) is ignored.
If -fexceptions is enabled, then cleanup_function is run during the stack unwinding that happens during the processing of the exception. Note that the cleanup attribute does not allow the exception to be caught, only to perform an action. It is undefined what happens if cleanup_function does not return normally.

Its format is like this:
int x __attribute__((__cleanup__(func_to_call_when_x_exits_scope))) = 0;

You use it like this:
RUN A REAL EXAMPLE OF THIS CODE IN C ONLINE HERE.
static __inline__ void cleanup_my_byte(uint8_t *my_byte_p)
{
    Serial.print("my_byte is going out of scope! Its value is ");
    Serial.println(*my_byte_p);
}

void setup()
{
    uint8_t my_byte __attribute__((__cleanup__(cleanup_my_byte))) = 7;
} // The following function call occurs automatically here as `my_byte`
  // exits its scope!:
  //    `cleanup_my_byte(&my_byte);`

Studying the avr-libc-2.0.0/include/util/atomic.h file referenced above, you can see how the ATOMIC_RESTORESTATE macro is implemented, using this attribute. I've put just the relevant pieces from that file here:
#include <avr/io.h>
#include <avr/interrupt.h>

#define ATOMIC_BLOCK(type) for ( type, __ToDo = __iCliRetVal(); \
                           __ToDo ; __ToDo = 0 )

static __inline__ uint8_t __iCliRetVal(void)
{
    cli();
    return 1;
}

#define ATOMIC_RESTORESTATE uint8_t sreg_save \
    __attribute__((__cleanup__(__iRestore))) = SREG

static __inline__ void __iRestore(const  uint8_t *__s)
{
    SREG = *__s;
    __asm__ volatile ("" ::: "memory");
}

Note that cli() clears (turns off) interrupts, and sei() sets (turns on) interrupts.
So, you can see that ATOMIC_RESTORE_STATE gets replaced by uint8_t sreg_save __attribute__((__cleanup__(__iRestore))) = SREG, which backs up the global interrupt state from the AVR SREG 8-bit register into sreg_save, then calls this function call when sreg_save exits its scope: __iRestore(&sreg_save);. That function call to __iRestore() then sets the SREG register back to where it was, restoring the interrupt state (turning it ON if it was ON before, or OFF if it was OFF before).
The official documentation for ATOMIC_BLOCK is here: https://www.nongnu.org/avr-libc/user-manual/group__util__atomic.html. An example usage is this:
ATOMIC_BLOCK(ATOMIC_RESTORESTATE)
{
    my_var_copy = my_var;
}

The ATOMIC_RESTORESTATE part backs up the SREG register and sets up the call for __iRestore(&sreg_save); to occur when sreg_save exits this block scope, as we've already discussed, and the ATOMIC_BLOCK part gets converted into this: for ( ATOMIC_RESTORESTATE, __ToDo = __iCliRetVal(); __ToDo ; __ToDo = 0 ). This means that the entire block is now an ingenious for loop which runs only once! Prior to entering the for loop block, __iCliRetVal() is called once, clearing (turning OFF) interrupts, and __ToDo is set to 1, or true, so the for loop runs at least once, and then at the end of the first run it is set to 0, or false, to stop the for loop after one single run! As we've already gone over, the sreg_save variable now goes out-of-scope at the closing brace and the call to __iRestore(&sreg_save); is made, via the gcc extension, to restore the interrupt state! Ingenious!
How could you implement the ATOMIC_BLOCK functionality in Arduino in C++ (as opposed to avrlibc's gcc C version)?
In C++ (Arduino is C++, so we don't have to be limited to just C plus gcc extensions, as was the constraint in the avrlibc ATOMIC_BLOCK macros), you can get a similar effect using destructors in structs or classes (or, just use the avrlibc pattern shown above if you like, as that gcc C code is also perfectly valid gcc C++ code!).
Option 1: example to create a usage style similar to C++'s std::lock_guard
This, for example, would implement a form of ATOMIC_BLOCK(ATOMIC_FORCEON) {}, using a simple class in C++:
It relies on Arduino's built-in functions interrupts() (same as avrlibc's sei() function) and noInterrupts() (same as avrlibc's cli() function). I wish that Arduino also had built-in saveInterrupts() and restoreInterrupts() functions, but unfortunatley they don't. Someone will have to go file a feature request and request them, or implement them themselves and do a Pull Request (PR) on GitHub to try to get them back into the main Arduino branches.
RUN A REAL EXAMPLE OF THIS CODE IN C++17 ONLINE HERE.
#define ATOMIC_BLOCK_FORCEON AtomicBlockForceOn atomicBlockForceOn_

class AtomicBlockForceOn
{
public:
    // Constructor: called when the object is created
    inline AtomicBlockForceOn()
    {
        noInterrupts(); // turn interrupts OFF
    }

    // Destructor: called when the object is destroyed (ex: goes
    // out-of-scope)
    inline ~AtomicBlockForceOn()
    {
        interrupts(); // turn interrupts ON
    }
};

That's it! Now use it like this:
uint16_t my_var_copy;
{
    ATOMIC_BLOCK_FORCEON;
    // now do whatever you want here, with interrupts disabled; ex:
    my_var_copy = my_var;
} // the `atomicBlockForceOn_` object's destructor is called here
  // and interrupts are automatically turned back ON!

Pretty cool!
This, I imagine, is probably exactly how C++'s std::lock_guard is implemented! Its usage is very similar:
void safe_increment()
{
    const std::lock_guard<std::mutex> lock(g_i_mutex);
    ++g_i;

    std::cout << std::this_thread::get_id() << ": " << g_i << '\n';

    // g_i_mutex is automatically released when lock
    // goes out of scope
}

Option 2: example to create a usage style similar to avrlibc's ATOMIC_BLOCK macros
To obtain a usage style of ATOMIC_BLOCK(ATOMIC_FORCEON) { } in C++ one can definitely use the gcc C style which avrlibc uses, since that is also valid C++, but let's continue with the C++ class style shown just above instead, with just a few tweaks. We will add a couple more helper macros and a couple more functions to the class to make this work. Here it is, with a usage example shown at the end which is identical to how avrlibc's ATOMIC_BLOCK can be used! I think this is pretty cool too.
RUN A REAL EXAMPLE OF THIS CODE IN C++17 ONLINE HERE.
#define ATOMIC_BLOCK(type) for(type; type##_OBJECT_NAME.run(); \
    type##_OBJECT_NAME.stop())
#define ATOMIC_FORCEON_OBJECT_NAME atomicBlockForceOn_
#define ATOMIC_FORCEON AtomicBlockForceOn ATOMIC_FORCEON_OBJECT_NAME

class AtomicBlockForceOn
{
public:
    // Constructor: called when the object is created
    inline AtomicBlockForceOn()
    {
        noInterrupts(); // turn interrupts OFF
    }

    // Destructor: called when the object is destroyed (ex: goes
    // out-of-scope)
    inline ~AtomicBlockForceOn()
    {
        interrupts(); // turn interrupts ON
    }

    // Can we run? Returns true to run the `for` loop or
    // `false` to stop it.
    inline bool run()
    {
        return run_now;
    }

    // Tell the `for` loop to stop
    inline void stop()
    {
        run_now = false;
    }

private:
    bool run_now = true;
};

Use it like avrlibc's ATOMIC_BLOCK() { } macro!
Usage example:
uint16_t my_var_copy;
ATOMIC_BLOCK(ATOMIC_FORCEON)
{
    // now do whatever you want here, with interrupts disabled; ex:
    my_var_copy = my_var;
} // the `ATOMIC_FORCEON_OBJECT_NAME` (`atomicBlockForceOn_`) object's
  // destructor is called here and interrupts are automatically
  // turned back ON!

Further reading:

Nick Gammon's excellent "Interrupts" page, which is how I first got started learning about interrupts in 2012~2014 or so: https://gammon.com.au/interrupts.
Other answer's I've done about interrupts, locks/guards, and things:

global volatile variable not being updated in ISR
My own race condition problem: https://stackoverflow.com/questions/36381932/c-decrementing-an-element-of-a-single-byte-volatile-array-is-not-atomic-why
My own race condition solution, demonstrating 3 (or 4, depending on how you look at it) ways to enforce "atomic access guards" on AVR-based 8-bit Arduinos: https://stackoverflow.com/questions/36381932/c-decrementing-an-element-of-a-single-byte-volatile-array-is-not-atomic-why/39693278#39693278

What's that weird type##_OBJECT_NAME thing I did in the macro anyway? Read more about macro token concatenation using the ## preprocessor operator in the official gcc C++ user manual here: https://gcc.gnu.org/onlinedocs/cpp/Concatenation.html. Note: this also works in C of course.
gcc inline or __inline__, and static inline or static __inline__ rules:
https://gcc.gnu.org/onlinedocs/gcc/Inline.html

Thanks. That's a great answer. I'd previously read some of your Further Reading (points 1 & 2i-iii) while researching the issue. I was about to collate it, but you've saved me the job by creating an excellent reference post. The macro with the for  loop and Option 1 & 2 with the class are what I was looking at implementing, so thanks for a clear explanation of them. Now need to figure out what to put in the macro __iRestore and the class constructure/destructor to save/restore the global interrupt flag for each architecture.

Correct. You have to figure out how to disable/enable interrupts now for each architecture, then put the appropriate code into the constructor/destructor. Here's how to do it on STM32, for instance, which is used in the Arduino "professional" line such as the $103 Portenta H7, based on the STM32H7 microcontroller: prim = __get_PRIMASK();, __disable_irq();, if (!prim) { __enable_irq(); }. That's using the low-level CMSIS libraries.

You can also use a half dozen other techniques, including the STM32 core libraries and the FreeRTOS libraries (if using the FreeRTOS real time operating system). I have personal notes on it all that I need to publish on my website someday. 32-bit microcontrollers are beasts. I have no idea how to do it on Atmel/Microchip 32-bit SAM or SAMD microcontrollers, such as the Zero or Due, but there are ways for all chips, you just have to figure them out.


text:
Problems connecting nodemcu esp8266 on my laptop
I have a new laptop and didn't run any development boards on it except some Arduino boards.
But now, I have only nodemcu esp8266 and maple mini boards and trying to connect them but I get error connection message.
esptool.FatalError: Failed to connect to ESP8266: Timed out waiting for packet header
I tried to find solutions but apparently I'm stuck here and I can't do anything.
I tried to re-flash the nodemcu with the flasher but I can't get the addresses. This is what I got:

The flashing started but can't get the AP MAC and STA MAC. I don't know what is the problem now, I used to flash it before but on my old Dell laptop. I started to think that there are some problems with usb ports of my msi gaming laptop, they are 3.0, I think that could be a problem.
The board is recognized in device manager and in Arduino IDE COM ports.
My question is how to solve this problem ?

I have a problem connecting my dev boards with Arduino IDE. I don't know if it's a hardware or software problem.

I edited the post

Is the correct USB-to-Serial port driver installed correctly on your laptop? Do you use the correct COM port and the correct settings (baud rate, SPI mode) in the Flasher?

@StarCat Yep, I configured all these stuff, same COM ports and same baud rate. The driver is installed by default. I deleted it and installed it again. Same problem ! Really strange, it's working perfectly on my desktop which is not around right now.


text:
EEPROM Arduino library for ESP8266 is not working
I am trying to use EEPROM library from Arduino framework for my ESP8266 project (NodeMCU). I am using Atom with Platformio.
Initialization of EEPROM is attempted at void setup() in main.cpp:
EEPROM.begin(80);

The compiler throws an error at this line with:
request for member 'begin' in '0', which is of non-class type 'int'

This is strange as I just follow a simple example from GitHub.
I include <EEPROM.h> just as <Arduino.h> and many others (<ESP8266WiFi.h>, <ESP8266WebServer.h>, <ESP8266mDNS.h>). Platformio has created .pio\build\nodemcuv2\lib32c\EEPROM directory with EEPROM.cpp.o inside but compilation fails.
How can I make it work and what else should I check to find the problem?

run the example code that is in the Arduino IDE

Instead of describing your code, show your code.

@Majenko, it's almost 2.5K lines. Not easy to bring the relevant part quickly.

Then write some code that is only a few lines and demonstrates the problem.

Exactly what @Majenko said - if this is a problem then it should be easy to demonstrate in 10 lines of code. If you can't reproduce it in 10 lines of code then you have a very large clue as to what's going on.

you have not the right EEPROM library.

Have you tried compiling one the examples supplied with the ESP8266 Arduino BSP (after adding #include <Arduino.h> to the top, of course) - maybe the eeprom_write one? If that works, you will be able to narrow it to something else in your code. Otherwise, you've probably got a corrupt install, or wrong platformio.ini configuration. You didn't add EEPROM to the lib_deps, did you? As you should be using the espressif8266 platform provided EEPROM library.

Thank you all for your help. At first I thought it's about the library I use (just as @Juraj supposed). Then your advices to try pure examples (which proved to work fine) led me to search for conflicts.
Eventually I found an external lib that had #define EEPROM (nothing to do with Arduino, it's for other MCUs to communicate).
I was misguided by a vague compiler error. Normally for a direct naming conflict (as in this case) it says clearly: "redefinition of ..."
So be warned, this type of error should be considered as a conflict to look for.
Once again, many thanks for everyone's help!

The problem here is that these symbols exist in different layers. The problem one was a "preprocessor macro" which gets replaced verbatim in a first pass through the code. Only once that is done is the code compiled - so first off all references to EEPROM get replaced with 0 (I guess) and then it's compiled, which leaves you with 0.begin(80); that of course fails to compile. There's no redefinition to report an error on.


text:
How can i develop a fish tank automation using arduino
As a part of my final year Engineering project I would like to develop a  fish tank automation system. In my project I need to check the quality  of water concurrently and also I need to check the sedimentation of my fish tank. Which are the different types of sensors  used for this?
How can i connect it to my arduno uno?

Have you tried googling for corresponding sensors? What were the results and how exactly didn't they help you? What have you already tried to design your project?

what does quality of water mean? ... what factors are you checking? ... what does sedimentation mean? ... what are you checking?

you can check turbidity with a shielded light sensor and a light emitter; like an analog beam interruption sensor.

You can try water temperature controlling idk if you are in a winter season having zone in earth like auto turning on the heater, can auto turn on UV light when dark etc.or may be filter status by connectivity measurements or pH level you have to draw a diagram of what you will do before going to electronic programming.what will you do so on

You're starting from the wrong end of the problem (the electronics).
First, you need to decide the requirements for your system.

Write down what your system is supposed to do: measure something? When & how often? Save or display the measurements? Control something based on the data? How precise must that control be (e.g. +/- .5 degC) (precision can be expensive)? Control something based on something other than measurements (except, perhaps, time?

Once you understand the requirements, then you can write down the steps the system should take to meet them; it doesn't need to be code (and probably shouldn't be, just yet).

Decide on what to measure and how to measure it. Can't figure out a sensor for something? Maybe you can infer it from something you can sense. Or perhaps learn how quickly or how often that 'something' goes out of spec and restore it without a measurement (e.g. you presumably already know how often and how much to food to dispense).

Now you can start thinking about electronics, sensors, and code, having a pretty good idea of what you will need to know, to acquire, and to create, to build your project (whether or not you'll be expected to actually build one).

This is an Engineering approach to design and it is almost certain your project is intended to show that you know how to do this, much more than to show you can run a fish tank.


text:
Can we control other servos with common servo code Arduino
I am trying to control MG996R using code for a typical servo (SG90)
I used an external power supply, 5V,2A
I connected the servo signal line to Arduino slot 7,
servo positive to external power supply positive,
servo ground to external power supply ground,
while leaving the Arduino power supply and ground unconnected.
I tried the below code.
it works for SG90, while MG996R is not moving at all.

#include <Servo.h>
Servo myservo;

void setup()
{
  myservo.attach(7);  //pin 7 is the one control servo

}

void loop()
{

  for (int pos=0; pos<=60; pos++)
  {
    myservo.write(pos);
    delay(15);
  }

}

Is it because the different servos need different code?

the two servos use the same control signal ... if one works, then the other should work also ... recheck your power and ground connections ... make sure that servo ground is connected to arduino ground ... confirm that the power supply stays at 5 V under load ... measure the voltage while trying to move the servo ... if the voltage holds at 5 V, then the servo is suspect

there is no reason to have a for loop ... all you need is myservo.write(45); delay(1000); myservo.write(135); delay(1000); ... the servo will cycle between those two angles

They work with same control signal, so the same code should work for both of them
You need make sure the ground of servo is both connected with the Arduino ground and the power supply ground (power supply ground for power supply positive, Arduino ground for the signal line)
I think SG90 worked even not connecting the Arduino ground is because the difference in design.
But you should always connect Servo ground to the Arduino ground.

@jsotola's comment is the answer, so I'll just quote it here:

the two servos use the same control signal ... if one works, then the other should work also ... recheck your power and ground connections ... make sure that servo ground is connected to arduino ground ... confirm that the power supply stays at 5 V under load ... measure the voltage while trying to move the servo ... if the voltage holds at 5 V, then the servo is suspect

Also, make sure you're using the pin you set with myservo.attach(). Your comment says pin 9 but your code says pin 7, which is confusing. This code is using pin 7 as the servo signal:

myservo.attach(7);  //pin 9 is the one control servo

I note on the manufacturers website for the MG996R that it has an operating voltage of 4.8V to 6.6V.
Your problem could be that your voltage (at the motor) is below the minimum voltage of 4.8V.
Try driving the motor with 6V.
Also make sure you are testing the motor with no load connected to the output.

The operating current (running current for the MG996R (~650 mA) is higher than SG90 (~220 mA) but definitely well in the capacity of a 5 V, 2 A. Unless there is a mechanical load on the servo motor, the motor is not limited by the current supply.

The MG996R is a power beast. it is good idea to consider rechecking the supply voltage as well as trying with the supply greater than ~5 V.
PS: The code is definitely fine.
Here is the simulation for the code you have posted which works fine with an emulator


text:
Better way for connecting to Arduino pins to a sensor than jumper cable
Well I have an dht21 and arduino mega. Dht21 leads look like this

If I use jumper cable and soldering dht21 leads with jumper cable than plug-in my arduino's socket. it looks like this below image. It dont looks safe. If the device falls to the ground or something, the cables may come out of place or the place may loosen over time. If I solder the cables under the arduino, it will be hard and looks like ugly. What is the best solution to plug-in a sensor to arduino board.

There is also the option of a Prototyping Screw Shield which converts the Arduino pins into terminal screw blocks. This makes a more permanent connection without being completely permanent.

Remember the Arduino is a prototyping system and it should be easy to plug, unplug and move around connectors.
If you want a permanent solution, you should make your own PCB and you will have a huge choice of connectors suited for all imaginable purposes (for example the JST family of connectors).
There are some connectivity systems like the Grove connector that have attempted to standardize connectivity on Arduino and related platforms.

One option you have is to solder your sensor leads to a set of header pins. The friction of multiple pins secured in a header will be greater than that of individual jumpers. When soldering to the header pins, use a method to secure the pins from movement, as the heat of the soldering iron may soften the plastic holding the pins.
The image below, from Digikey, is representative and does not imply correct spacing or fit for an Arduino.

Arduino solder shields are also available. This is a complete circuit board, akin to StarCat's recommendation of a custom PCB, but off-the-shelf. It allows access to all pins on the specific Arduino for which it was designed. I consider this option excessive for three connections, but include it for completeness.


text:
Animation of led strip with ESP32 does not work when WiFi is in use
I am using the ESP32 for a simple project. I know how to animate an led strip using atmega328p with arduino but when I animate it on the ESP32 it does not work that great. It will be nice if I can use the same ESP32 to run my entire project without having to include another MCU. Has someone managed to be able to animate an led strip meanwhile using wifi on the ESP32 ?
This is the code I use to animate an LED stip meanwhile using wifi. I wrote this code myself so maybe I am doing something wrong. It works better than any of the libraries I have found online. The library that works best is esp32WS2811-master. But still this code works better than that library in my case.
#include <Arduino.h>
#include "WiFi.h"
#include <Adafruit_NeoPixel.h>

// we will runt the task that animates led strip on a separate core of arduino
TaskHandle_t Task1;

// where led pin is connected and number of leds to animate
#define PIN 32
#define NUM_LEDS 80

Adafruit_NeoPixel strip = Adafruit_NeoPixel(NUM_LEDS, PIN, NEO_GRB + NEO_KHZ800);

// mutex that helps enter critical sections meanwhile we animate led strip
portMUX_TYPE mux = portMUX_INITIALIZER_UNLOCKED;

// it will run on core 0 of esp32. Responsible for animating led strip.
void loop2(void *parameter)
{
   uint32_t _color = strip.Color(0, 0, 0);

   for (;;) // infinite loop
   {
      _color = strip.Color(0, 0, 255);

      // animation 1
      for (uint16_t i = 0; i < strip.numPixels(); i++)
      {
         strip.setPixelColor(i, _color);

         //portDISABLE_INTERRUPTS();      // arternative to portENTER_CRITICAL
         portENTER_CRITICAL(&mux);        /* start critical section */

         strip.show();

         //portENABLE_INTERRUPTS();       // alternative to portEXIT_CRITICAL
         portEXIT_CRITICAL(&mux);         /* end critical section */

         vTaskDelay(15);                  // one tick delay (15ms) in between reads for stability
      }

      // animation 2
      _color = strip.Color(0, 255, 0);
      for (uint16_t i = 0; i < strip.numPixels(); i++)
      {
         strip.setPixelColor(i, _color);

         //portDISABLE_INTERRUPTS();      // arternative to portENTER_CRITICAL
         portENTER_CRITICAL(&mux);        /* start critical section */

         strip.show();

         //portENABLE_INTERRUPTS();       // alternative to portEXIT_CRITICAL
         portEXIT_CRITICAL(&mux);         /* end critical section */

         vTaskDelay(15);                  // one tick delay (15ms) in between reads for stability
      }
   }
}

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

   // disabling wifi helps but we need it
   // WiFi.mode(WIFI_OFF);

   // init led strip
   strip.begin();
   strip.setBrightness(4);
   strip.show(); // Initialize all pixels to 'off'

   // create a task that runs on core 0 of esp32
   xTaskCreatePinnedToCore(
       loop2,
       "Task_1",
       1000,
       NULL,
       2, // priority of 0 is the lowest.
       &Task1,
       0 // use core 0. Core 1 is the default core
   );

   // continue running code on default core 1 of esp32

   // Set WiFi to station mode and disconnect from an AP if it was previously connected
   WiFi.mode(WIFI_STA);
   WiFi.disconnect();

   Serial.println("Setup done");
}

// on main loop scan network just to show how led strip does not work great when wifi is in use
// This code I copied and pasted from the WiFi examples of the esp32
void loop()
{
   Serial.println("scan start");

   // WiFi.scanNetworks will return the number of networks found
   int n = WiFi.scanNetworks();
   Serial.println("scan done");
   if (n == 0)
   {
      Serial.println("no networks found");
   }
   else
   {
      Serial.print(n);
      Serial.println(" networks found");
      for (int i = 0; i < n; ++i)
      {
         // Print SSID and RSSI for each network found
         Serial.print(i + 1);
         Serial.print(": ");
         Serial.print(WiFi.SSID(i));
         Serial.print(" (");
         Serial.print(WiFi.RSSI(i));
         Serial.print(")");
         Serial.println((WiFi.encryptionType(i) == WIFI_AUTH_OPEN) ? " " : "*");
         delay(10);
      }
   }
   Serial.println("");

   // wait 5 seconds for next network scan
   auto end = millis() + (unsigned long)5000;
   while(millis() < end)  {
      vTaskDelay(1);
   }

}

When I run this code the first led flickers. The other LEDs animate great 99.99% of the time. When I disable WiFi this code works great. I still need portENTER_CRITICAL(&mux); or portDISABLE_INTERRUPTS(); for it to work even if I disable WiFi. Has anyone managed to be able to animate an led-strip with the ESP-32 successfully meanwhile using WiFi?
If I am required to use a separate micro controller which one do you guys recommend? The ATtiny85?

it's not the wifi, it's your delay calls and while statements that are stopping the show.

The delay is part of the animation. If I disable the wifi the animation works great @dandavis. I need to animate one led every 15 milliseconds.

well, I know that i can push rgb values over wifi to an esp32 at 30FPS on a 64 pixel strip. If wifi blocked this would look really jerky, but it doesn't, except for occasional hiccups which fix themselves. I didn't even mess with interrupts or explicit flow control. Make your animation routine async (think blink w/o delay) to allow more than one thing at once to happen. For me, this required rewriting the adafruit lib to move the loops into stand-alone callable functions that did a single iteration worth of work at the right time, as determined by the loop()'s logic and millis().

Doesn't all the WiFi management software run on core 0? If you run on core 1 does it improve?

@danvis are you using an addressable led strip?  are you animating your LED by changing the color of one led at a time? If I use a none addressable led strip it works.

@Majenko if I use core 1 it works better. I just get some flickering once every 5 seconds. But the LEDs animate great its just the flickering that I have to somehow figure out how to solve.

I used the FastLed library and it works now. For some reason the adafruit library only works when I am not using the WiFi. This code works:
#include "Arduino.h"
#include <FastLED.h>
#include "WiFi.h"

// we will runt the task that animates led strip on a separate core of arduino
TaskHandle_t Task1;

#define LED_PIN 32
#define NUM_LEDS 108
#define BRIGHTNESS 10
#define LED_TYPE WS2811
#define COLOR_ORDER GRB
CRGB leds[NUM_LEDS];

#define UPDATES_PER_SECOND 100

// scan the network every 5 seconds
void loop2(void *parameter)
{
    for (;;)
    {
        Serial.println("scan start");

        // WiFi.scanNetworks will return the number of networks found
        int n = WiFi.scanNetworks();
        Serial.println("scan done");
        if (n == 0)
        {
            Serial.println("no networks found");
        }
        else
        {
            Serial.print(n);
            Serial.println(" networks found");
            for (int i = 0; i < n; ++i)
            {
                // Print SSID and RSSI for each network found
                Serial.print(i + 1);
                Serial.print(": ");
                Serial.print(WiFi.SSID(i));
                Serial.print(" (");
                Serial.print(WiFi.RSSI(i));
                Serial.print(")");
                Serial.println((WiFi.encryptionType(i) == WIFI_AUTH_OPEN) ? " " : "*");
                delay(10);
            }
        }
        Serial.println("");

        vTaskDelay(5000);
    }
}

void setup()
{

    Serial.begin(115200);

    delay(1000); // power-up safety delay
    FastLED.addLeds<LED_TYPE, LED_PIN, COLOR_ORDER>(leds, NUM_LEDS).setCorrection(TypicalLEDStrip);
    FastLED.setBrightness(BRIGHTNESS);

    // Set WiFi to station mode and disconnect from an AP if it was previously connected
    WiFi.mode(WIFI_STA);
    WiFi.disconnect();

    // create a task that runs on core 0 of esp32
    xTaskCreatePinnedToCore(
        loop2,
        "Task_1",
        1000,
        NULL,
        2, // priority of 0 is the lowest.
        &Task1,
        1 // use core 0. Core 1 is the default core
    );

    Serial.println("Setup done");
}

void loop()
{

    // red
    for (int i = 0; i < NUM_LEDS; i++)
    {
        leds[i] = 0xFF0000;
        FastLED.show();
        FastLED.delay(25);
    }

    // green
    for (int i = 0; i < NUM_LEDS; i++)
    {
        leds[i] = 0x00FF00;
        FastLED.show();
        FastLED.delay(25);
    }

    // blue
    for (int i = 0; i < NUM_LEDS; i++)
    {
        leds[i] = 0x0000FF;
        FastLED.show();
        FastLED.delay(25);
    }

    // rgb red green blue

    //ChangePalettePeriodically();
    //FillLEDsFromPaletteColors( startIndex);
}

Please accept your own answer so it doesn't pop up over and over again


text:
How to ssh via USB Ethernet adapter
For a few days now, I have been connecting to my board which is hooked up to my router through a clutter of wires, over Wi-Fi. To spare my family from the risk of tripping, or hogging the extension cords all to myself, I'm looking for a way to establish an ssh connection directly from my computer (either via a USB Ethernet or a Thunderbolt Ethernet adapter).
My question is what address will I be looking for? Is it something like arduinoname.local?

Ehhm, so your Arduino is connected to your Wifi network and you are asking, what IP it has to reach it from your PC? Have you looked at the webinterface of your router? Normally there you can find a list of connected devices with their IP addresses. When your Arduino uses DHCP, the router is the one, who sets the device to a specific address. So you should look there

No, no, no! I have been connecting over Wifi, but I want to be able to connect over cable instead (computer-to-board instead of computer-to-router-to-board)

ssh root@[arduinoname].local

does the trick. Just replace [arduinoname] with your board's name: ssh root@myboard.local
Seems to take a minute or two to initialize, so if it doesn't work immediately don't give up right away!
This however won't allow you to access your internet, so I'll still have to connect to my router if I'm going to be downloading anything.


text:
4-digit 7-segment display not showing value properly
I'm trying to add a 4-digit 7-segment display to an existing project (a temperature & relative humidity sensor) to show the temperature on the display.
I bought the display a long time ago and I it doesn't have any ID and I don't have any reference to a schematic, so I followed this article to find out both if it's a common cathode or anode and the pinout.
It turns out it's a common cathode display and the pinout goes like this (numbered from upper left):
1 -> D1
2 -> A
3 -> F
4 -> D2
5 -> D3
6 -> B
7 -> E
8 -> D
9 -> DP
10 -> C
11 -> G
12 -> D4
Where D{1,2,3,4} are the digit control pins and the rest are the segments.
So I added the SevSeg library to my project. And the sketch compiles, but when I upload it to my Arduino Uno all the LEDs in the digits 1 and 4 light up and digits two and three remain off.
I checked the pinout twice, with the same results and the display doesn't seem to be damaged. Do you see any issue on my code?
Thanks in advance!

isolate the area of failure ... switch the digit pin wires ... see if the problem is with the display, or with program

Be sure, that you don't connect anything to the pins used by the ethernet shield

https://www.instructables.com/Using-a-4-digit-7-segment-display-with-arduino/ This maybe helpful... I used this and this worked.

What caused the problem of the digit that driven by pin 12 is quite obvious to me. You use pin 11, 12, 13, 14 for driving the 7-segment digits. While SPI library by default uses pin 10, 11, 12, 13 as SS, MOSI, MISO and SCK, and set pin  12 (MISO) as INPUT which is in conflict with your pin 12 (as an OUTPUT) for driving the digit.
Pin 13 is also used by the interval blinking LED (i.e. BUILTIN_LED) when defined as a digital i/o.
Your code uses quite a few libraries, and those libraries could uses some of the I/O pins, I would suggest you reduce your code to only the code related to SevSeg, set the display to all '8888', and add each library one by one back to find out what caused the problem.

Your issue could be in code or in your hardware.
To work out which one, try running one of the example sketches like the testWholeDisplay.ino that comes with the library you are using. This way you have known working code and you are testing that your hardware is wired up correctly. If this step doesn't work, then you need to look into your wiring and/or setup.
If using the example sketch works, then you can start looking into your sketch. Divide it into chunks and test each chunk independently. If any chunk doesn't work then work out what is different from the example sketches compared to your code.

You're right, I used the example and the display works fine. The problem may be what @hcheung says, so I'll try to free the pins 11, 12, 13, 14 and use the analog pins as digital pins instead. Another option would be to use a LED driver.

Reverse engineering your code, which is generated by https://examples.blynk.cc, I have found that you are using:

an Arduino Uno
W5100 Ethernet shield (or Arduino Ethernet Rev3)
DHT11
4-digit 7 segment display

Your Blynk example code looked something like this.
For the 7 segment display you are using pins 3, 5, 6, 7, 8, 9, 11, 12, 13, A0, A1, A2.
byte digitPins[] = { 11, 12, 13, A2};
byte segmentPins[] = {3, A0, 5, 6, 7, 8, 9, A1};

However, the W5100 Ethernet controller uses pins 10, 11, 12 and 13 as seen on the Arduino Ethernet webpage:

NB: Pins 10, 11, 12 and 13 are reserved for interfacing with the Ethernet module and should not be used otherwise. This reduces the number of available pins to 9, with 4 available as PWM outputs.

Pins 2 & 4 are used for the DHT11 and SD card chip select respectively.
All you have to do is change the wiring of the seven segment display to not use pins 11, 12 and 13, and then adjust your sketch accordingly. For example, you could use A3, A4 & A5.


text:
Reading SNMP V2 OID from ESP8266/ESP32
i need to read from my ESP32/ESP8266 some SNMP V2 OID values from my home printer: it exists a library/method that can do that?
I've seen some SNMP agents, but they works only with the devie as server and not as SNMP client.
Any thoughts?

SNMP agents are servers. In the SNMP world, clients are called managers.

Not sure if you found it, but there I created an SNMP Manager: https://github.com/shortbloke/Arduino_SNMP_Manager
There is also an SNMP Agent: https://github.com/0neblock/Arduino_SNMP
I know this is a bit later than when you requested this info. But posting here in case it's still helpful to you or others that stumble over this question.


text:
Heart Pulse sensor analog value doesn't change even if sensor pressed by finger
I have recently bought a Heart Pulse Sensor. Then, to check whether the sensor is working correctly or not, I uploaded this below code:
void setup() {

 Serial.begin(9600);
}

void loop() {
 int sensorValue = analogRead(A0);

 Serial.println(sensorValue);
 delay(1);        // delay in between reads for stability
}

I know, that this code doesn't calculate the actual BPM. It sends 380-400 sensor value through
the Serial monitor, while the sensor is not being pressed by my finger. But when I press it with
my finger, the sensor value doesn't even come out of the range 380-400. But the sensor value was supposed to jump over 500 when a beat happened.
I think, that probably means my sensor is unable to detect beats. And now, my question is, why
my sensor is unable to detect beats?
After looking at some forums, I learned that this sensor can be a clone. After looking at my sensor
carefully, I found some little differences in my sensor than the sensors other people used in their
tutorials. And, the most spottable differences were:
*the colors of my sensor's pre-soldered jumper wires were different than other sensors.
*"pulsesensor.com" was written in the other sensors, but it wasn't written on my sensor
There were also some other differences. I have given three pictures of my pulse sensor below.

My final questions:-

Why my pulse sensor is unable to detect beats?
Is my pulse sensor a clone or not?
If it is a clone, can it be fixed somehow?
Do I need to buy another one?

That's all I know. Can anyone help me! Any help appreciated.
Thanks a lot!

how is it wired to the Uno?

Pulse sensor + to Arduino 3.3v (Also tried with 5v), Pulse sensor - to Arduino GND, and finally, pulse sensor Signal pin to Arduino A0 pin

Serial.print takes time to execute ... print only if sensorValue > 500

Use 5v, if you use 3.3v, your ADC Vref will be wrong.

Have you looked at the pulsesensor.com/ site for more information about your sensor? Especially note this page: https://pulsesensor.com/pages/getting-advanced  which recommends using 115200 baud "or you won't see anything". I don't know this sensor - have you tried touching either side? Tried the sample code from the site (though your code looks fine to me...).

Why my pulse sensor is unable to detect beats?
Chances are something wrong.  The only way to tell what specifically is to keep debugging.  If you don't have access to an Oscilloscope or Multimeter, this will involve checking your wiring and altering code.  To check wiring, make sure:

Minus (-) is to ground
Plus (+) s to your + voltage
S is to the A0.

Is my pulse sensor a clone or not?
It is likely.  Open-Source Hardware tends to have many clones.
If it is a clone, can it be fixed somehow?
Clones sell repeatedly if they work.  There is little point making a clone sensor that does not- if scamming was the point, one could ship empty envelopes.  If two different people make the exact same electronics, we hope that they behave very similarly regardless of who made them.
Do I need to buy another one?
Possible but unlikely.  If you can prove your sensor is defective, a seller might be willing to ship a replacement.
Try the following code to test the sensor.  My guess is that you are missing something due to Serial spamming.  Beyond that, taking a pulse may be tricky - the unskilled can easily pronounce some of the living as dead from just the wrist.  I suggest putting it to your throat to be on the safe side.

int minSV;
int maxSV;
unsigned int Frame;

void setup() {
 minSV=500;
 maxSV=0;
 Serial.begin(9600);
}

void loop() {
 int sensorValue = analogRead(A0);
 if(sensorValue > maxSV) maxSV = sensorValue;
 if(sensorValue < minSV) minSV= sensorValue;
 Frame = Frame +1;
 if(Frame > 10000) //would be 1s if frame takes 0.1 ms
 {
  //might want to reset min and max here after debug is complete and sensor is verified to work.  Until then, reset the arduino to reset min and max.
  Frame =0;
  Serial.print("Min: ");
  Serial.print(minSV);
  Serial.print("; Max: ");
  Serial.println(maxSV);
 }
 // removed: delay(1);        // delay in between reads for stability
}


text:
Whats the best way to keep an Arduino in a waterproof junction box and prevent overheating?
I am trying to make an automatic garden gate unlock that runs on a timer. I plan on running an arduino uno 24/7 with a software timer that activates a motor to release a bolt lock. I am going to fit all the electronics and extension cord into a waterproof junction box. Will this cause over heating? Is there a need for some kind of waterproof cooling system? Has anyone ever built outdoor electronics and ran into this problem?

Arduinos don't generate that much heat - except maybe the 5V regulator. Use an efficient switching regulator instead of relying on the 5V regulator on board and there will be little to no heat.

If you do need to actively cool something then use a metal enclosure and thermally connect that component to the casing.

I wouldn't worry all that much about the Arduino itself, but, depending on what you use, the power supply and especially the motor driver may generate some heat. It won't be on often, or for very long, though. Somebody somewhere could do the math given your exact set-up; speaking for myself, I would just try it and experiment.

@Majenko good point I'll look into that.

@ocrdu no the motors won't be on often likely twice a day for a couple of seconds, but the arduino will be running always but not performing any tasks until the time

I'd be more worried about the sun heating the box, than the Arduino board.

You also might consider using sleep mode.

I can't remember where I found it, but one person I saw had actually just protected the battery and battery charger and left the Arduino Nano out in the elements. He said they are so robust they just work regardless of the elements, and as soon as they dry out from the rain they just start working again. He said he had been doing it for years and had many Nanos just living out in the wild outside of enclosures and doing fine. This leads me to believe that enclosing cheap Arduino Nano-based projects perfectly is less important than I once thought.

The linear regulator on an Arduino works by converting excess voltage to heat. If you power it with 12V and draw a full amp from it it will turn (12-5)*1a or 7 watts of power to heat, and quickly overheat even if it's not in a box.
If you power it from 6.5V and only draw 300mA from it, it will turn (6.5-5)*.3, or a little under half-a-watt. While the Arduino is idling it will probably only draw 50mA, so less than 1/10th of a watt of heat.
For infrequent, short bursts of a few seconds you can probably get away with drawing 500mA of power without overheating.
Or skip the internal regulator and use a buck style voltage regulator. Those generate a LOT less heat.
Edit:
For a project I did recently, I used an external 5V regulated supply for everything. I cut a USB cable and soldered the red and black (+5V and ground) to the 5V supply, and plugged that into the Arudino's USB connector. That feeds 5V into the Arduino.

I normally use a SEPIC converter and low RDSon MOSFETs. I usually set the output of the converter to about 8 volts. I am assuming the motor is powered by another power supply not the one on the Arduino. I typically use the plastic Euro boxes without any problems. Keep it out of the sun and you will be OK.

"I usually set the output of the converter to about 8 volts." Wait, what? You then feed the converter into the VIN and still drive the Arduino's voltage regulator? Why not set your converter to 5V and use it's output to power the Arduino directly?

If you use a converter to generate 8 volts and feed that into the Arduino's VIN, you'll still turn 2V to heat.

Sorry, you'd convert THREE volts (and whatever current is drawn through the Arduino's regulator) to heat.

Using the Vin adds additional filtering and stability and it is free. I do not like inductive loads or lines leaving the enclosure to be on the same power supply as the microprocessor, they are great antennas. That is a lot less heat with an 8V feed then with a 12V feed. The proper choice of MOSFETS will have a big impact on the heat. Most of my designs do not use heat sinks, Low RDSon FETs cost more but are generally much cheaper for me then installing heat sinks.

The simplest selection is Aluminum water proof box.
You can make it yourself, using aluminum U profiles,
and mount arduino heat generator parts on the internal surface of the box.


text:
what library should I #include when using switch-case statement
I receive an error code of: 'switch' was not declared in this scope
The code is correct so I assume that the necessary library was not included.
Please tell me the correct #include to use.
swith(pwm){
  case 0:   Serial.print(pwm); Serial.print("   ");_delay_ms(2000);
            break;
  case 31:  Serial.print(pwm); Serial.print("   ");_delay_ms(100);
            break;
  case 63:  Serial.print(pwm); Serial.print("   ");_delay_ms(100);
            break;
  case 95:  Serial.print(pwm); Serial.print("   ");_delay_ms(100);
            break;
  case 127:  Serial.print(pwm); Serial.print("   ");_delay_ms(100);
            break;
  case 159:  Serial.print(pwm); Serial.print("   ");_delay_ms(100);
            break;
  case 191:  Serial.print(pwm); Serial.print("   ");_delay_ms(100);
            break;
  case 124:  Serial.print(pwm); Serial.print("   ");_delay_ms(100);
            break;
  case 156:  Serial.print(pwm); Serial.print("   ");_delay_ms(100);
            break;
  case 188:  Serial.print(pwm); Serial.print("   ");_delay_ms(100);
            break;
  case 220:  Serial.print(pwm); Serial.print("   ");_delay_ms(100);
            break;
  case 252:  Serial.print(pwm); Serial.print("   ");_delay_ms(100);
            break;
  default:  break;
}

spelling error.  switch not swith

I receive an error code of: 'switch' was not declared in this scope ... no, you don't get that error ... look at the message again ... next time copy and paste the message ... you cannot trust yourself to correctly type in what it says

It seems you have a syntax error: write switch instead of swith.


text:
how to convert the following code into one using direct port manipulation
Following is the program for scanning a keyboard for MIDI transfer.
At present the code works fine, but it could be faster.
I need to know how to use direct port manipulation inside the for loop.
boolean keypressed[6][6]; //for storing key states
int midinote[6][6] ={ 60 ,61 ,62 ,63 ,64 ,65
                 ,66 ,67 ,68 ,69 ,70 ,71
                 ,72 ,73 ,74 ,75 ,76 ,77
                 ,78 ,79 ,80 ,81 ,82 ,83
                 ,84 ,85 ,86 ,87 ,88 ,89
                 ,90 ,91 ,92 ,93 ,94 ,95  }; //code for various midi notes C3 to C6

void setup() {

   Serial.begin(38400);
   for(int i=0; i<6; i++){
      pinMode(i+2,OUTPUT);
      digitalWrite(i+8,HIGH);
   }
   for(int i=0; i<6; i++){
      pinMode(i+8,INPUT);
      digitalWrite(i+8,HIGH);
   }
   for(int i=0; i<6; i++){
      for(int j=0; j<6; j++){
          keypressed[i][j] = false;
          }
      }
   }
void loop() {

   for(int i=0; i<6; i++){
      digitalWrite(i+2, LOW);
      for(int j =0; j<6; j++){
         if ((digitalRead(j+8) == LOW) && !keypressed[i][j]){
            Serial.write(0x91);
            Serial.write(midinote[i][j]);
            Serial.write(127);
            keypressed[i][j] = true;
           }
         if ((digitalRead(j+8) == HIGH) && keypressed[i][j]){
            Serial.write(0x91);
            Serial.write(midinote[i][j]);
            Serial.write(0);
            keypressed[i][j] =false;
         }
      }
digitalWrite(i+2, HIGH);
   }

 }

You need to download the data sheet of the AVR and look up the port registers. Then you can access (read or write) all bits of a port with a single instruction. You will need to change your keyboard scanning algorithm accordingly. -- Having said this, I'm not sure that the Arduino libraries don't have methods to do this already.

I do not think that direct port access increases the speed of your program remarkably. If you natively read a PORT you have to store the value in a CPU register and then check its bits in the loop. There is a difference in reading a IO register compared to an internal CPU register, but its not that much compared to the time you need to send the midi note. And that's limited to the midi speed. (Wich is 31250 bps, as far as i know - not 38400 as I saw in your code). But if the receiver understands, it's OK ;-). So, I would say the midi speed is he bottleneck not the keyboard scanner algorithm.

Ah, if you don't need any wise ( dumb ;-) ) talk. Here is a link that answers yout question. So you can decide whether it is worth it, to change your program.  https://www.arduino.cc/en/Reference/PortManipulation

I doubt if you gain anything with it, as Serial will be the bottleneck. But if you must, I'd suggest something like the digitalWriteFast library.

It is better to use interrupts instead of pooling pins.
but this is related to your arduino controller.
what is you arduino core controller?
if you can select I prefer "Nano 33 IoT " which has 9 pins (2, 3, 9, 10, 11, 13, 15, A5, A7) available for interrupt.
this page may be usable:
https://playground.arduino.cc/Main/PinChangeInterrupt/

I'm not sure how useful interrupts are on a button matrix.

polling force cpu to check i/o ports in loop that cause waste cpu time and code is a cascaded for loop.
where using interrupts lets cpu doing its normal code and interrupt with its input Vector make every thing ready for you, by some bit-wise operations you can find changed port and send correct output.

That’s a very common newbie trap.  But go ahead.


text:
What is the maximum size of Static Json Document in Arduino JSON?
I'm trying to do serial communication between Arduino mega and a esp8266, and having issues with determining the size of the JSON document. I have read that the receiver buffer size should be greater than the sender buffer, but what's the maximum buffer size we can use for the JSON document?

The Arduino Mega has 8 KB of RAM, all of which you could use in a StaticJsonDocument.
The ESP8266 has 80 KB of RAM, but the core limits the stack to 4 KB. If you need something bigger, switch to a DynamicJsonDocument.
In both cases, you need to leave a lot of room for other variables and libraries. As an example, I wouldn't create a StaticJsonDocument bigger than 6 KB on the Mega, and 2 KB on the ESP8266.
By the way, I heard this library is very well documented, did you have a look?
Do you know you can use the ArduinoJson Assistant to help you decide the capacity of the JsonDocument?

so you heard? :-)

Thanks and I checked the links earlier, but I have an issue, is the size we give when creating the static json document is in bytes? ex StaticJsonDocument<450> doc; is it 450 bytes?

Yes, it's the capacity of the memory pool, in bytes.