text:
ESP32-CAM, Failed to connect to ESP32
I am trying my ESP32-CAM for project but I am having problems with uploading script/code to the ESP. I am using CP2102 to connect ESP and my laptop. I tried connecting it to 3.3V and even 5V but none seem to be working as I always get the same error:
"A fatal error occurred: Failed to connect to ESP32: Timed out waiting for packet header"

Did you connect GPIO0 to Ground when powering up the ESP32Cam, before starting the upload?

Yes, I connected it exactly like this :
https://i1.wp.com/randomnerdtutorials.com/wp-content/uploads/2019/12/ESP32-CAM-FTDI-programmer-5V-supply.png?w=750&quality=100&strip=all&ssl=1
Don't know if it helps but when I connected it of the two LEDs on this USB-UART (TXD and RXT) only TXD was blinking.

i bet the 3.3v isn't strong enough to power the ESP32

Well as I said, I tried 5V too, meanwhile I tried using Arduino Mega as "programmer" so I could be sure it isn't in UART-USB and it did the same thing. I am wondering if the ESP isn't damaged, any ideas how to test it?

For future references.
So after some time I was finally able to upload my code into ESP32-CAM. I don't know if I had just bad luck with "faulty" ESP but here is what helped me.

Don't use CP2102, it just doesn't work for me, use other programmer or Arduino as I did.

If you have been using scheme like this scheme and wasn't able to fix your problem try to connect all other things that need GND on some breadboard and use just one GND pin from ESP. I noticed that GNDs on ESP has (or atleast mine have ) 0.5V difference between them. Right now I am using the GND pin that was connected to IO0 as "main" GND and its works.

Hope this helps someone and thanks for all replies.

Thanks for posting your solution. Please note that whatever your problem was, it might very well come down to power supply issues. In my experience, not all commonly available USB Serial->TTL converters are powerful enough for an ESP32Cam (either at 3.3V or 5V), especially once the ESP32 is starting up, connecting to Wifi and powering up its camera.


text:
Problem Using pins A4 and A5 for input and output I2C
Hardare used:
Arduino nano ( old Bootloader )
Oled Monochrome Display ( 4 pins, 128 x 32 )
MPU 6050
Both display and MPU use A4 and A5 as I2C communication protocol, They interfere, as the MPU is used 2-way and the Display 1-way.

How can I change those 2 pins( does not matter witch Display/Sensor )
Can this method ( the one you propose ) be used for more cases like this? ( ex 3 sensors )

There is what I tried so far:
#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>

#define SCREEN_WIDTH 128 // OLED display width, in pixels
#define SCREEN_HEIGHT 32 // OLED display height, in pixels

#define OLED_RESET     4 // Reset pin # (or -1 if sharing Arduino reset pin)
#define SCREEN_ADDRESS 0x3C ///< See datasheet for Address; 0x3D for 128x64, 0x3C for 128x32
Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, OLED_RESET);

#include "I2Cdev.h"
#include "MPU6050_6Axis_MotionApps20.h"
#if I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE
    #include "Wire.h"
#endif
MPU6050 mpu;

#define OUTPUT_READABLE_YAWPITCHROLL
#define OUTPUT_READABLE_REALACCEL

// MPU control/status vars
bool dmpReady = false;  // set true if DMP init was successful
uint8_t mpuIntStatus;   // holds actual interrupt status byte from MPU
uint8_t devStatus;      // return status after each device operation (0 = success, !0 = error)
uint16_t packetSize;    // expected DMP packet size (default is 42 bytes)
uint16_t fifoCount;     // count of all bytes currently in FIFO
uint8_t fifoBuffer[64]; // FIFO storage buffer

// orientation/motion vars
Quaternion q;           // [w, x, y, z]         quaternion container
VectorInt16 aa;         // [x, y, z]            accel sensor measurements
VectorInt16 aaReal;     // [x, y, z]            gravity-free accel sensor measurements
VectorInt16 aaWorld;    // [x, y, z]            world-frame accel sensor measurements
VectorFloat gravity;    // [x, y, z]            gravity vector
float euler[3];         // [psi, theta, phi]    Euler angle container
float ypr[3];           // [yaw, pitch, roll]   yaw/pitch/roll container and gravity vector

#define INTERRUPT_PIN 2  // use pin 2 on Arduino Uno & most boards
volatile bool mpuInterrupt = false;
void dmpDataReady() {
  mpuInterrupt = true;
}

void setup() {
  volatile bool mpuInterrupt = false;     // indicates whether MPU interrupt pin has gone high

  if(!display.begin(SSD1306_SWITCHCAPVCC, SCREEN_ADDRESS)) {
    Serial.println(F("SSD1306 allocation failed"));
   for(;;); // Don't proceed, loop forever
  }

  // Clear the buffer
  display.clearDisplay();

  delay(150);

  #if I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE
        Wire.begin();
        Wire.setClock(400000); // 400kHz I2C clock. Comment this line if having compilation difficulties
    #elif I2CDEV_IMPLEMENTATION == I2CDEV_BUILTIN_FASTWIRE
        Fastwire::setup(400, true);
    #endif

    Serial.println(F("Initializing I2C devices..."));
    mpu.initialize();
    pinMode(INTERRUPT_PIN, INPUT);

    // verify connection
    Serial.println(F("Testing device connections..."));
    Serial.println(mpu.testConnection() ? F("MPU6050 connection successful") : F("MPU6050 connection failed"));

    delay(50);

    // load and configure the DMP
    Serial.println(F("Initializing DMP..."));
    devStatus = mpu.dmpInitialize();

  if (devStatus == 0) {
        // Calibration Time: generate offsets and calibrate our MPU6050
        mpu.CalibrateAccel(6);
        mpu.CalibrateGyro(6);
        mpu.PrintActiveOffsets();
        // turn on the DMP, now that it's ready
        Serial.println(F("Enabling DMP..."));
        mpu.setDMPEnabled(true);

        // enable Arduino interrupt detection
        Serial.print(F("Enabling interrupt detection (Arduino external interrupt "));
        Serial.print(digitalPinToInterrupt(INTERRUPT_PIN));
        Serial.println(F(")..."));
        attachInterrupt(digitalPinToInterrupt(INTERRUPT_PIN), dmpDataReady, RISING);
        mpuIntStatus = mpu.getIntStatus();

        // set our DMP Ready flag so the main loop() function knows it's okay to use it
        Serial.println(F("DMP ready! Waiting for first interrupt..."));
        dmpReady = true;

        // get expected DMP packet size for later comparison
        packetSize = mpu.dmpGetFIFOPacketSize();
    } else {
        // ERROR!
        // 1 = initial memory load failed
        // 2 = DMP configuration updates failed
        // (if it's going to break, usually the code will be 1)
        Serial.print(F("DMP Initialization failed (code "));
        Serial.print(devStatus);
        Serial.println(F(")"));
    }

  Serial.begin(9600);
}

void loop() {
  if (!dmpReady) return;
    // read a packet from FIFO
    if (mpu.dmpGetCurrentFIFOPacket(fifoBuffer)) { // Get the Latest packet

        #ifdef OUTPUT_READABLE_YAWPITCHROLL
            // display Euler angles in degrees
            mpu.dmpGetQuaternion(&q, fifoBuffer);
            mpu.dmpGetGravity(&gravity, &q);
            mpu.dmpGetYawPitchRoll(ypr, &q, &gravity);
            /*
            data.gyro_data[0] = ypr[0] * 180/M_PI;
            data.gyro_data[1] = ypr[1] * 180/M_PI;
            data.gyro_data[2] = ypr[2] * 180/M_PI;
            */
        #endif

        #ifdef OUTPUT_READABLE_REALACCEL
            // display real acceleration, adjusted to remove gravity
            mpu.dmpGetQuaternion(&q, fifoBuffer);
            mpu.dmpGetAccel(&aa, fifoBuffer);
            mpu.dmpGetGravity(&gravity, &q);
            mpu.dmpGetLinearAccel(&aaReal, &aa, &gravity);
            /*
            data.acc_data[0] = aaReal.x;
            data.acc_data[1] = aaReal.y;
            data.acc_data[2] = aaReal.z;
            */
        #endif
    }

    display.print(String(ypr[0] * 180/M_PI));
    display.print('/');
    display.print(String(ypr[1] * 180/M_PI));
    display.print('/');
    display.print(String(ypr[2] * 180/M_PI));
    display.print("\n\n");
    display.print(String(aaReal.x));
    display.print('/');
    display.print(String(aaReal.y));
    display.print('/');
    display.print(String(aaReal.z));

    //display.print(String(data.id));
    display.display();

    delay(500);
}

Now I know this looks like a bunch of code thrown together with the hope to work, But it is composed from 2 other of my codes separately for MPU and Display, those work fine.

They interfere, as the MPU is used 2-way and the Display 1-way. -- No, that's nonsense. I2C is bidirectional half duplex regardless. Even if you only think you use one direction you're actually always using both. You have described everything except the actual problem  You say they "interfere" but don't actually tell us how you think they interfere with each other or what the symptoms actually are.

Several devices can share an I2C bus, unless they have the same address (which is unlikely with a display and an MPU).

There are many aspects of your code that don't make any sense. Such things as the whole of the interrupt system (which appears to do nothing at all).

#include "I2Cdev.h" #include "MPU6050_6Axis_MotionApps20.h" take care of communication with the MPU, and through previous tests the interrupt pin stabilises the z-axis. I used this as a reference. Then what I mean by interference is that normally the display would show 0.00/0.00/0.00 on two lines, ( as there is no data). But with the MPU added it just shows some random pixels on.

So after repeated tests I found several problems, software and hardware.

The cables I used on the breadboard where facing each other. The metal parts where touching ( from a defect of the cables ). Turned them 90*.

The Oled display was NOT Initialized properly. When using display.write() or display.print() you must first put the cursor at (0;0) by display.setCursor(0,0). Furthermore for more compatibility in Setup(){} you have to add display.setTextSize(1) and display.setTextColor(WHITE).

Power control. I found the best, either adding a capacitor on the VCC and GND lines when using them to power 2 Sensors at the same time, or ad a 5 mls delay in the first function. delay(5)

source: Stack Exchange

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

sort: votes


text:
Arduino mega ethernet Udp client randomly failing
I have a keyestudio board identical to the arduino mega 2560. I use the matching keyestudio ks0156 W5100 ethernet shield. My code uses the following library for ethernet paulstoffregen/Ethernet@0.0.0-alpha+sha.9f41e8231b
I have the following code (initialization and "loop" code):
const int port_broadcast{27333};
char udp_packet_buffer[UDP_TX_PACKET_MAX_SIZE + 1];

const byte mac[] = {0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED};

EthernetUDP udp;

void init_ethernet() {
  if (Ethernet.begin(mac) == 0) {
    Serial.println("Error initializing Ethernet using DHCP");

    if (Ethernet.hardwareStatus() == EthernetNoHardware) {
      Serial.println("Ethernet shield was not found.");

      while (true) {
        delay(1);
      }
    }

    if (Ethernet.linkStatus() == LinkOFF) {
      Serial.println("Ethernet cable is not connected.");
    }

    Ethernet.begin(mac, ip, dns);
  } else {
    Serial.print("DHCP assigned IP ");
    Serial.println(Ethernet.localIP());
  }

  udp.begin(port_broadcast);
}

void update_time() {
  int packet_size = udp.parsePacket();
  if (packet_size > 0) {
     const auto num_read = udp.read(udp_packet_buffer, UDP_TX_PACKET_MAX_SIZE);
    Serial.print("Received ");
    Serial.print(num_read);
    Serial.println(" bytes: ");
    if(num_read > 0) {
      udp_packet_buffer[num_read] = '\0';
      Serial.println(udp_packet_buffer);
    }
  }
}

On my Windows device in the same network I have a service that every 2 seconds posts the current time in the format 2021-09-19 15:37:30 over UDP broadcast to my local network. This works quite well until suddenly the board starts receiving wrong values. Here is a sample output from the board:
DHCP assigned IP 192.168.1.120
Received 19 bytes:
2021-09-19 19:59:37
Received 19 bytes:
2021-09-19 19:59:39
Received 19 bytes:
2021-09-19 19:59:41
Received 19 bytes:
2021-09-19 19:59:43
Received 19 bytes:
2021-09-19 19:59:45
Received 19 bytes:
2021-09-19 19:59:47
Received 19 bytes:
2021-09-19 19:59:49
Received 19 bytes:
2021-09-19 19:59:51
Received 19 bytes:
2021-09-19 19:59:53
Received 19 bytes:
2021-09-19 19:59:55
Received 19 bytes:
2021-09-19 19:59:57
Received 19 bytes:
2021-09-19 19:59:59
Received 19 bytes:
2021-09-19 20:00:01
Received 19 bytes:
2021-09-19 20:00:03
Received 19 bytes:
2021-09-19 20:00:05
Received 19 bytes:
2021-09-19 20:00:07
Received 19 bytes:
2021-09-19 20:00:09
Received 19 bytes:
2021-09-19 20:00:11
Received 19 bytes:
2021-09-19 20:00:13
Received 19 bytes:
2021-09-19 20:00:15
Received 19 bytes:
2021-09-19 20:00:17
Received 19 bytes:
2021-09-19 20:00:19
Received 19 bytes:
2021-09-19 20:00:21
Received 19 bytes:
2021-09-19 2
Received 19 bytes:
␒0"1    0
Received 19 bytes:
2021-09-19 20:00:␒7
Received 19 bytes:
2021-09-1        ␒0
Received 3 bytes:
2
Received 24 bytes:
20:00␚3!␁B��

As you can see suddenly the output makes no sense anymore. There is no sensor attached, no input happening or anything else going on, it just randomly starts outputing wrong values. Also when it starts outputing wrong values it does not continue for long before completely stopping to receive anythin alltogether. According to Wireshark the windows service keeps posting the right data, so I can rule out that it has something to do with the service.
So my question is, why would my board suddenly stop receiving data over UDP without any apparent reason or interaction from the outside? Reseting the board will immediately continue to print more data, but until then it stopped. It got adequate power supply and the LAN cable is very short. Am I doing something wrong in my code? Does it look like an issue with the Ethernet shield?
For completeness sake this is the C# code from the service that is sending to the UDP broadcast:
        private UdpClient _time_broadcaster;
        private readonly IPEndPoint _broadcast = new IPEndPoint(IPAddress.Parse("192.168.1.255"), 27333);

        private void timer_elapsed(object source, ElapsedEventArgs args) {
            var now = DateTime.Now;
            var year = now.Year;
            var month = now.Month;
            var day = now.Day;

            var hour = now.Hour;
            var minute = now.Minute;
            var second = now.Second;

            var result = $"{year:D4}-{month:D2}-{day:D2} {hour:D2}:{minute:D2}:{second:D2}";
            var data = Encoding.ASCII.GetBytes(result);
            _time_broadcaster.Send(data, data.Length, _broadcast);
        }

seems like a buffer is getting cumulatively overfilled ... possibly by not retrieving all data from buffer at each read .... does the program always fail at the same location?

Yea, I thought something similar too, so I also checked that and sometimes it fails after a few seconds, sometimes after a minute, sometimes even more. What did make a change is changing the windows service to send to 192.168.1.120 (the assigned IP) instead of 192.168.1.255 (broadcast), it has been running for 30 minutes now without any interruption. I need to do some more testing there.

that probably eliminates the buffer overflow idea ... possible bug in the library

does not necessarily eliminate overflow- depends on what you are listening for.  it may also be a feature related to monitoring network traffic between other devices rather than a bug.  try reverting to old settings and having network of only 2 devices.

did you try the Ethernet library from Library Manager?

I am using PlatformIO, I will check out which one is the official one from Library Manager in Arduino IDE and try to find that one in PIO.

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


text:
Where are these junk characters (from serial) coming from?
I currently have 2 Arduinos both hooked up to HC-12s and have successfully got them communicating. But I am now trying to be able to process the data sent across and store it as a variable so as to make comparisons. But I'm getting junk data that comes over with the code, which prevents me from being able to do these comparisons.
For example, from one arduino when I sent "stop" I received
stop<⸮=l⸮⸮⸮

I cant figure out what this junk is from, also, I've limited the receivedChars to a size of 4, why am I getting more than 4 characters?
The code from the sender
#include <SoftwareSerial.h>

SoftwareSerial HC12(3, 2); // HC-12 TX Pin, HC-12 RX Pin

void setup() {
  Serial.begin(9600);             // Serial port to computer
  HC12.begin(9600);               // Serial port to HC12
  Serial.print("Checking HC-12 module: ");
  HC12.write("AT");               //Check for response(this is sending data to the HC, the SET pin must be low for this to work)
  delay(1000);
  HC12.write("AT+RX");            //Gets configs of HC-12
}

void loop() {
  while (HC12.available()) {        // If HC-12 has data
    Serial.write(HC12.read());      // Send the data to Serial monitor
  }
  while (Serial.available()) {      // If Serial monitor has data
    HC12.write(Serial.read());      // Send that data to HC-12
  }
}

The simplified receiving code
    #define BYTELENGTH 4 //Limited to 4 chars
       #define ENDMARKER '\n'  //To know when stop stop reading serial

       SoftwareSerial HC12(3, 2); // HC-12 TX Pin, HC-12 RX Pin

  Serial.begin(9600); //Fastest it can be on the nano
  HC12.begin(9600); // Serial port to HC12s

      char receivedChars[BYTELENGTH - 1];
      int byteIndex;
      char curChar;

      while (HC12.available()) {        // If HC-12 has data
        curChar = HC12.read();
        if(curChar != ENDMARKER){
          receivedChars[byteIndex] = curChar;
          byteIndex++;
        }
      }
      if(strcmp(receivedChars,"") != 0){
        Serial.println(receivedChars);
        receivedChars[0] = 0;
      }

Btw: 9600 baud is not the fastest, that the Nano can get. The HardwareSerial interface Serial can also work with baudrates of up to 2 Megabaud. The problem with these baudrates is only, that you cannot provide the data in that speed. But 9600 baud is rather slow, even for the Nano. The real bottleneck here is the SoftwareSerial library. I think it can handle up to 38400 baud without problems. 11520 baud might also work, though I think that is very hard at the limit.

The software serial is temporary, just for testing. I did have everything at 115200 baud but was running into issues. That would explain that one!

I would say you are printing data outside of your char array, because you didn't terminate the C-string in it and the size of your array is too small.
You have
#define BYTELENGTH 4 //Limited to 4 chars
char receivedChars[BYTELENGTH - 1];

so your char array is only 3 elements big. When you want to save a string in that array, you always need to terminate it with a null character \0 (which is also zero in decimal representation). So in that char array you only have space for 2 characters. But your message "stop" is 4 characters long, so you need a char array with at least 5 elements. If you are not in an extreme tight memory situation I would suggest using a buffer with a bit headroom above your biggest message (to be sure, that nothing breaks, if you later use messages that are a bit longer). So more like this:
#define BYTELENGTH 10 //Limited to 4 chars
char receivedChars[BYTELENGTH + 1]; // message length + null character termination

And then you need to change your receiving code to add a null character at the end of the message. Also you might want to actually use the newline character \n as message delimiting (which you are currently not doing):
bool full_message_received = false;

void loop(){
    while (HC12.available()) {        // If HC-12 has data
        curChar = HC12.read();
        if(curChar != ENDMARKER){
          receivedChars[byteIndex] = curChar;
          byteIndex++;
        } else {
          receivedChars[byteIndex] = '\0'; // terminating the c-string
          full_message_received = true; // marking the message as fully received
        }
    }
    if(full_message_received){
        Serial.println(receivedChars);
        receivedChars[0] = 0;
        full_message_received = false;
    }
}

What happens, if I don't terminate the string with a null character? All the functions, that handle C-strings (like strcmp() or also Serial.print()) use the null character to determine, at which point the string is at its end. They don't know the size of your array, so they just read byte after byte, until they reach the null character. They even read more data than is in your array. The junk characters are most likely exactly, what currently is placed in the memory directly after your array. Serial.print() doesn't know, that they don't belong to the C-string, since you didn't use the null character to tell it that. It just keeps printing characters, until it reaches a byte, that is zero.
You even wrote data to memory outside of the array. Depending on what comes directly after your array in the memory this can be without any problems, but you might also overwrite some other data, without knowing, what that data is. That can lead to very weird and hard to debug problems. Be sure to never write outside of your array. You might break things in weird ways.

So when ENDMARKER is reached (in this case \n), you are telling it to terminate the rest of the array. Then when I print it out or do anything with it, I shouldn't be reaching into additional memory spaces. But then I'm not even seeing the \n because the array length is too short.
So to fix it, I need to make sure my array can fit at least 4 chars, + the \n (which should be sent by the other Arduinos serial monitor right?), then have my code searching for it and terminate the array after it. Am I understanding correctly?

nearly correct.  You need your array to fit 4 chars + the terminating null character. In my code above I don't include the \n in the array. Normally you don't need that character in there, since it is only used for delimiting individual messages on the serial interface. And the \n is also read and printed, if your array is too small. But then this data overwrites the memory space after the array, which can be very bad.

So for preventing writing and reading outside the array you need to make the array big enough for every possible message, that you might get. You read until the \n to only read one full message at a time (each individual message delimited by the \n on the serial interface). And for using the received data as a c-string (for example for printing) you need to terminate it with a null character.

It appears you have a baud rate problem. I am surprised you are getting anything. You need software to start the serial port such as SoftwareSerial mySerial(rxPin, txPin) then in setup  mySerial.begin(9600); You need that in each application and the baud rates need to be the same.
I have used SC16IS750 I2C/SPI-to-UART devices as an external UART, they work great and have many nice features such as a 64 bytes of transmit and receive FIFOs. Some versions of this have been obsoleted but they are still available and work fine. You get 8 additional I/Os as well.

I do have it, just excluded it to avoid posting all my code. Just made the edit. Im guessing there is either something about serial or the char array that im missing thats adding the extra junk

The softwareserial operates in half duplex. It is interrupt driven and if other interrupts are occuring that can cause problems. Here is a link/discussion that may help you a lot. https://electronics.stackexchange.com/questions/23265/arduino-software-serial-full-duplex. The more information given generally the better. If there is additional hardware connected post a schematic with links showing technical information on the devices.

That is actually an issue I've noticed, I'm hoping to get rid of software serial altogether. It just made programming simpler for the time being, but it seems to be causing some issues so I might need to expedite moving over.

According to this vidéo in French it appeared that the problems comes from the SoftwareSerial library which if not reliable enough to provide accurate timings for your transmission. There are alternate software serial libraries (like AltSoftSerial), which use hardware timers, but I can't tel you more because I didn't try to use it.
All I can say, is that I my case removing SoftwareSerial to use the defaut hardware serial port solved the problems I had.
Alternatively, you can use I²C ⇒ UART IC like MAX3100, in order to provide aother hardware UART (With MAX3100 you'll need to add a 3.6468 or 1.8234 MHz crystal and 2×22pf capacitors) - I also didn't try it yet (Chip and crystal are ordered though. Or also you should be able to make the i2c ⇒ UART conversion with one more Arduino.

SoftwareSerial is ok at 9600 baud. the accepted answer explains the true problem.

This is not true, @Juraj. It largely depends on transmission speed. Even at 9600 bps, I got character losses, when I didn't add delays to slow it down. This didn't arises with the hardware port.


text:
Why are the pin numbers of the diagrams and of the code different?
If I search Google for "arduino nano pin numbers", all results show that the pin number of D2 is 5. But that did not work. I searched for some sample codes, and they were 3 for D3 and 5 for D5, etc. So, in codes, the pin number for Dn is n. Then what are the numbers in these diagrams?

are you referring to the physical pin numbers of the module? ... they start at 1 and wrap around

Every chip datasheet (and also the Arduino boards) uses 2 different ways to refer to the pins:

Counting the physical pins in the order as they appear on the chosen package of the chip
Referring to the pins by their function

The first way is only for referring to specific pin positions from the outside, for example when you are building the actual circuit. This also includes special pins like Vcc, GND and Reset. Those pins cannot be referenced by the code (wouldn't make much sense). Also the microcontroller on the inside of its package doesn't know in which package it got stuck by the manufacturer. Each package has a different pin order and form factor. So this counting only makes sense in the context of placing this specific package of the chip into a circuit (like where is Vcc, where ground and where do I need to connect to that specific digital pin), but makes no sense to use for the code inside the controller.
For referring to pins from inside the controller (aka in the code) we use the function of the pins. On an Arduino you have mainly digital and analog pins, which can be controlled. So for the convenience of beginners (which are targeted by the Arduino framework) the digital and analog pins are just numbered. Those are the numbers, that are normally written only the Arduino board. So D2 means the third digital pin inside the Arduino framework. A0 is the first analog pin. Where that pin is physically located on the board isn't interesting for the code, nore does the code know the actual location. For the code its just the third digital output hardware and so on.
TL;DR: For building the circuit we must refer to pin positions (like where is Vcc, where is ground) to connect the chip/microcontroller correctly. But the internal code doesn't know, where the physical pins are located and the actual location can also depend on the packaging. So internally we use a different counting system based on the pin function. The Arduino way of counting the digital and analog pins just hides away complexity for the beginner. As reference the numbers are also printed on the Arduino board itself.

In case you want to go deeper into the rabbit hole:
Actually the microcontroller has different hardware for different functions incorporated. For example: The analog pins can be used by the ADC (Analog to Digital Converter) to measure an analog voltage. But they also each have digital input and output hardware, just like any other digital pin. Most pins of a microcontroller are multi purpose. The code has to decide, what hardware gets to be connected to the respective pins. When I use pinMode(2, OUTPUT) I tell the microcontroller to connect the third digital output hardware to its respective physical pin. When I use analogRead(A1) I tell it to connect the second analog channel of the ADC to its respective pin and read an analog voltage through the ADC.
That means, that the code only knows of the function hardware and that it can be connected to their respective pins (whichever these pins are on the outside world). The numbering in digital and analog pins is only an additional abstraction layer to hide the complexity from beginners. Actually the code controls the hardware functions via Special Function Registers (SFR). These are special pieces of memory, which are physically hardwired to the respective hardware in the microcontroller. For the digital output hardware the pins are sorted into groups of up to 8 pins. These groups are called Ports, and are numbered with characters. When you look at this pinout of the Arduino Nano, you see, that the Arduino pin D2 is also named PD2, which means PortD third pin (counting from zero up). Arduino pin D8 is also named PB0, so PortB first pin. Functions like pinMode(), digitalWrite() and digitalRead() all just manipulate the SFRs for the wanted port to set the respective pin. Refer to the Documentation on Port Manipulation for learning how to do it yourself. For beginners it is just easier to use the markings on the board - the Arduino pin number - instead of bearing with the ports and their SFRs directly.

Might be clearer to tell all four levels at the start: 1) The pin number of the breakout board, which are numbered 1-30 here  2) The Arduino name for the pin, such as D3  3) The microcontroller datasheet name for the pin, such as PA4   4) The microcontroller package pin number

The additional abstraction is not just to make life easier for beginners. As @RedGrittyBrick notes in their answer, it makes the code more portable. To a lesser degree, it's also makes the code more readable, though some may not agree. And if you're using one of the commercial boards where the pins are marked with the Arduino labels, it's certainly easier to get the wires on the right pin.

There are at least four ways of referring to pins on any Arduino board:

Board-order: Simple numeric order (1,2,3 ...) of physical location of pins on printed circuit board anticlockwise from the USB end (or some arbitrary end)
Arduino-name: Names used in Arduino source code and/or PCB silk-screen annotation (D1,D2 ... A0,A1 ...).
IC-order: Simple numeric order of corresponding pin on IC according to numbering used on manufacturers data sheet.
IC Function name: Names for functions available on pin (RESET, VCC, INT0, PB0,PB1,PB2 ...) as described in data sheet for IC.

For example:

Nano PCB Pin#
Arduino Name
ATMega328 TQFP Pin#
ATMega328 DIP Pin#
ATMega328 function

1
D13
17
19
PB5, SCK, PCINT5

2
3V3
N/A
N/A
N/A

3
REF
20
21
AREF

4
A0
23
23
PC0, ADC0, PCINT8

5
A1
24
24
PC1, ADC1, PCINT9

etc

There are lots of different Arduino and Arduino-like boards that use the ATMega328, some use different ATMega328 packages (DIP, TQFP, etc) with different pin arrangements. Many arrange the physical PCB pins differently. This is why there isn't a fixed one to one relationship and it is partly why the Arduino IDE provides for it's own simplified naming that it attempts to apply consistently and portably across a variety of different microcontrollers.

(c) PigHixx w/o permission.

Why are the pin numbers of the diagrams and of the code different?

Because the Arduino designers chose to re-use the name "pin" for the chip's programmable signal lines, despite it's more common and already existing use to mean any of the protruding external connections to the device.


text:
Adafruit MPU-6050 and adafruit I2C Multiplexer

I have 3 adafruit MPUs hooked up to adafruit I2c Multiplexer. All of which is hooked up to a Arduino uno.
Attached is also my code.
/* Assign a unique ID to this sensor at the same time */

/*Adafruit_HMC5883_Unified mpu1 = Adafruit_HMC5883_Unified(1);
Adafruit_HMC5883_Unified mpu2 = Adafruit_HMC5883_Unified(2);*/

#define TCAADDR 0x70

#include <Adafruit_MPU6050.h>
#include <Adafruit_Sensor.h>
#include <Wire.h>
Adafruit_MPU6050 mpu1 = Adafruit_MPU6050();
Adafruit_MPU6050 mpu2 = Adafruit_MPU6050();
Adafruit_MPU6050 mpu3 = Adafruit_MPU6050();

void displaySensorDetails(Adafruit_MPU6050 *mpu)
{
sensor_t sensor;
mpu->getGyroSensor();
Serial.println("------------------------------------");
Serial.print ("Sensor: "); Serial.println(sensor.name);
Serial.print ("Driver Ver: "); Serial.println(sensor.version);
Serial.print ("Unique ID: "); Serial.println(sensor.sensor_id);
Serial.print ("Max Value: "); Serial.print(sensor.max_value); Serial.println(" uT");
Serial.print ("Min Value: "); Serial.print(sensor.min_value); Serial.println(" uT");
Serial.print ("Resolution: "); Serial.print(sensor.resolution); Serial.println(" uT");
Serial.println("------------------------------------");
Serial.println("");
delay(500);
}

void setUpMPU(Adafruit_MPU6050 *mpu)
{
  mpu->setAccelerometerRange(MPU6050_RANGE_8_G);
  Serial.print("Accelerometer range set to: ");
  switch (mpu->getAccelerometerRange()) {
  case MPU6050_RANGE_2_G:
    Serial.println("+-2G");
    break;
  case MPU6050_RANGE_4_G:
    Serial.println("+-4G");
    break;
  case MPU6050_RANGE_8_G:
    Serial.println("+-8G");
    break;
  case MPU6050_RANGE_16_G:
    Serial.println("+-16G");
    break;
  }
  mpu->setGyroRange(MPU6050_RANGE_500_DEG);
  Serial.print("Gyro range set to: ");
  switch (mpu->getGyroRange()) {
  case MPU6050_RANGE_250_DEG:
    Serial.println("+- 250 deg/s");
    break;
  case MPU6050_RANGE_500_DEG:
    Serial.println("+- 500 deg/s");
    break;
  case MPU6050_RANGE_1000_DEG:
    Serial.println("+- 1000 deg/s");
    break;
  case MPU6050_RANGE_2000_DEG:
    Serial.println("+- 2000 deg/s");
    break;
  }

  mpu->setFilterBandwidth(MPU6050_BAND_21_HZ);
  Serial.print("Filter bandwidth set to: ");
  switch (mpu->getFilterBandwidth()) {
  case MPU6050_BAND_260_HZ:
    Serial.println("260 Hz");
    break;
  case MPU6050_BAND_184_HZ:
    Serial.println("184 Hz");
    break;
  case MPU6050_BAND_94_HZ:
    Serial.println("94 Hz");
    break;
  case MPU6050_BAND_44_HZ:
    Serial.println("44 Hz");
    break;
  case MPU6050_BAND_21_HZ:
    Serial.println("21 Hz");
    break;
  case MPU6050_BAND_10_HZ:
    Serial.println("10 Hz");
    break;
  case MPU6050_BAND_5_HZ:
    Serial.println("5 Hz");
    break;
}
}

void tcaselect(uint8_t i) {
if (i > 7) return;
Wire.beginTransmission(TCAADDR);
Wire.write(1 << i);
Wire.endTransmission();
}

void setup(void)
{
while (!Serial)
    delay(10); // will pause Zero, Leonardo, etc until serial console opens
Serial.begin(115200);
Serial.println("HMC5883 Magnetometer Test"); Serial.println("");
Serial.println("HMC5883 Magnetometer Test"); Serial.println("");

/* Initialise the 1st sensor */
tcaselect(0);
mpu1.setAccelerometerRange(MPU6050_RANGE_8_G);
Serial.print("Accelerometer range set to: ");
switch(mpu1.getAccelerometerRange()) {
case MPU6050_RANGE_2_G:
  Serial.println("+-2G");
  break;
case MPU6050_RANGE_4_G:
  Serial.println("+-4G");
  break;
case MPU6050_RANGE_8_G:
  Serial.println("+-8G");
  break;
case MPU6050_RANGE_16_G:
 Serial.println("+-16G");
  break;
}
mpu1.setGyroRange(MPU6050_RANGE_500_DEG);
Serial.print("Gyro range set to: ");
switch (mpu1.getGyroRange()) {
case MPU6050_RANGE_250_DEG:
  Serial.println("+- 250 deg/s");
  break;
case MPU6050_RANGE_500_DEG:
  Serial.println("+- 500 deg/s");
  break;
case MPU6050_RANGE_1000_DEG:
  Serial.println("+- 1000 deg/s");
  break;
case MPU6050_RANGE_2000_DEG:
  Serial.println("+- 2000 deg/s");
  break;
}
mpu1.setFilterBandwidth(MPU6050_BAND_21_HZ);
Serial.print("Filter bandwidth set to: ");
switch (mpu1.getFilterBandwidth()) {
case MPU6050_BAND_260_HZ:
  Serial.println("260 Hz");
  break;
case MPU6050_BAND_184_HZ:
  Serial.println("184 Hz");
  break;
case MPU6050_BAND_94_HZ:
  Serial.println("94 Hz");
  break;
case MPU6050_BAND_44_HZ:
  Serial.println("44 Hz");
  break;
case MPU6050_BAND_21_HZ:
  Serial.println("21 Hz");
  break;
case MPU6050_BAND_10_HZ:
  Serial.println("10 Hz");
  break;
case MPU6050_BAND_5_HZ:
  Serial.println("5 Hz");
  break;
}

/* Initialise the 2 sensor */
tcaselect(1);
mpu2.setAccelerometerRange(MPU6050_RANGE_8_G);
Serial.print("Accelerometer range set to: ");
switch(mpu1.getAccelerometerRange()) {
case MPU6050_RANGE_2_G:
  Serial.println("+-2G");
  break;
case MPU6050_RANGE_4_G:
  Serial.println("+-4G");
  break;
case MPU6050_RANGE_8_G:
  Serial.println("+-8G");
  break;
case MPU6050_RANGE_16_G:
 Serial.println("+-16G");
  break;
}
mpu2.setGyroRange(MPU6050_RANGE_500_DEG);
Serial.print("Gyro range set to: ");
switch (mpu1.getGyroRange()) {
case MPU6050_RANGE_250_DEG:
  Serial.println("+- 250 deg/s");
  break;
case MPU6050_RANGE_500_DEG:
  Serial.println("+- 500 deg/s");
  break;
case MPU6050_RANGE_1000_DEG:
  Serial.println("+- 1000 deg/s");
  break;
case MPU6050_RANGE_2000_DEG:
  Serial.println("+- 2000 deg/s");
  break;
}
mpu2.setFilterBandwidth(MPU6050_BAND_21_HZ);
Serial.print("Filter bandwidth set to: ");
switch (mpu1.getFilterBandwidth()) {
case MPU6050_BAND_260_HZ:
  Serial.println("260 Hz");
  break;
case MPU6050_BAND_184_HZ:
  Serial.println("184 Hz");
  break;
case MPU6050_BAND_94_HZ:
  Serial.println("94 Hz");
  break;
case MPU6050_BAND_44_HZ:
  Serial.println("44 Hz");
  break;
case MPU6050_BAND_21_HZ:
  Serial.println("21 Hz");
  break;
case MPU6050_BAND_10_HZ:
  Serial.println("10 Hz");
  break;
case MPU6050_BAND_5_HZ:
  Serial.println("5 Hz");
  break;
}

/* Initialise the 3rd sensor */
tcaselect(2);
mpu3.setAccelerometerRange(MPU6050_RANGE_8_G);
Serial.print("Accelerometer range set to: ");
switch(mpu1.getAccelerometerRange()) {
case MPU6050_RANGE_2_G:
  Serial.println("+-2G");
  break;
case MPU6050_RANGE_4_G:
  Serial.println("+-4G");
  break;
case MPU6050_RANGE_8_G:
  Serial.println("+-8G");
  break;
case MPU6050_RANGE_16_G:
 Serial.println("+-16G");
  break;
}
mpu3.setGyroRange(MPU6050_RANGE_500_DEG);
Serial.print("Gyro range set to: ");
switch (mpu1.getGyroRange()) {
case MPU6050_RANGE_250_DEG:
  Serial.println("+- 250 deg/s");
  break;
case MPU6050_RANGE_500_DEG:
  Serial.println("+- 500 deg/s");
  break;
case MPU6050_RANGE_1000_DEG:
  Serial.println("+- 1000 deg/s");
  break;
case MPU6050_RANGE_2000_DEG:
  Serial.println("+- 2000 deg/s");
  break;
}
mpu3.setFilterBandwidth(MPU6050_BAND_21_HZ);
Serial.print("Filter bandwidth set to: ");
switch (mpu1.getFilterBandwidth()) {
case MPU6050_BAND_260_HZ:
  Serial.println("260 Hz");
  break;
case MPU6050_BAND_184_HZ:
  Serial.println("184 Hz");
  break;
case MPU6050_BAND_94_HZ:
  Serial.println("94 Hz");
  break;
case MPU6050_BAND_44_HZ:
  Serial.println("44 Hz");
  break;
case MPU6050_BAND_21_HZ:
  Serial.println("21 Hz");
  break;
case MPU6050_BAND_10_HZ:
  Serial.println("10 Hz");
  break;
case MPU6050_BAND_5_HZ:
  Serial.println("5 Hz");
  break;
}

/* Display some basic information on this sensor */
tcaselect(0);
displaySensorDetails(&mpu1);
tcaselect(1);
displaySensorDetails(&mpu2);
tcaselect(2);
displaySensorDetails(&mpu2);
}

void loop(void)
{
/* Get a new sensor event */
sensors_event_t a, g, temp;
tcaselect(0);
mpu1.getEvent(&a, &g, &temp);
/* Display the results (magnetic vector values are in micro-Tesla (uT)) */
Serial.print("Sensor #1 - ");
//Serial.print("X: "); Serial.print(event.magnetic.x); Serial.print(" ");
//Serial.print("Y: "); Serial.print(event.magnetic.y); Serial.print(" ");
//Serial.print("Z: "); Serial.print(event.magnetic.z); Serial.print(" ");Serial.println("uT");
Serial.print("Acceleration X: ");
Serial.print(a.acceleration.x);
Serial.print(", Y: ");
Serial.print(a.acceleration.y);
Serial.print(", Z: ");
Serial.print(a.acceleration.z);
Serial.println(" m/s^2");

tcaselect(2);
mpu2.getEvent(&a, &g, &temp);
/* Display the results (magnetic vector values are in micro-Tesla (uT)) */
Serial.print("Sensor #2 - ");
Serial.print("X: "); Serial.print(event.magnetic.x); Serial.print(" ");
Serial.print("Y: "); Serial.print(event.magnetic.y); Serial.print(" ");
Serial.print("Z: "); Serial.print(event.magnetic.z); Serial.print(" ");Serial.println("uT");
Serial.print("Acceleration X: ");
Serial.print(a.acceleration.x);
Serial.print(", Y: ");
Serial.print(a.acceleration.y);
Serial.print(", Z: ");
Serial.print(a.acceleration.z);
Serial.println(" m/s^2");
delay(500);
}

In this configuration All of my mpu sensors are sending back unreasonable numbers for acceleration and temperature. Am I initializing my mpus correctly in my code?

It seems like you would need to call .begin() on your Adafruit_MPU6050 instances, like the examples do.
So, following the pattern, in setup() you would need to:
 tcaselect(0);
 if (!mpu1.begin()) {
    Serial.println(F("Failed to find MPU6050 chip 1"));
    while (1) {
      delay(10);
    }
 }

 tcaselect(1);
 if (!mpu2.begin()) {
    Serial.println(F("Failed to find MPU6050 chip 2"));
    while (1) {
      delay(10);
    }
 }

 tcaselect(2);
 if (!mpu3.begin()) {
    Serial.println(F("Failed to find MPU6050 chip 3"));
    while (1) {
      delay(10);
    }
 }

I see you're removing some repetition with functions.  I'm guessing you just haven't gotten to doing that with the repeated switch statements for printing frequencies and such. You may want to put your mcu1/mcu2/mcu3 into an array instead for similar reasons.
An array of Adafruit_MPU6050:
Adafruit_MPU6050 mpus[3];

The code for calling begin() could look something like:
size_t index = 0;
for (auto &an_mpu: mpus) {
  tcaselect(index);
  if (!an_mpu.begin()) {
    Serial.print(F("Failed to find MPU6050 chip, mpu["));
    Serial.print(index);
    Serial.println(']');
    Serial.println(F("Halting..."));
    while (1) {
      delay(10);
    }
  }

  ++index;
}

Thanks for the nice and helpful answer :), usually people are pretty condescending

You don't need the I2C multiplexors at all - I currently have seven MPU6050 modules being managed by one Teensy 3.5 chip.  Four MPU6050's are on one of the T3.5's I2C busses, and the remaining three are on another.  I could run them all from just one I2C bus, but I split them just for wiring convenience.  The 'trick' is to replace the I2C address of each MPU6050 in turn in the setup() routine, as shown by the code associated with the blog post referenced below
See this post and related ones on my blog site 'Paynter's Palace'.
I've been using this technique for quite a while now, so let me know if you have any additional questions.
22 Sept 21 edit:
Here's the function that handles address initialization for the four MPU6050's on the Wire2 I2C bus:
bool InitWire2Sensors()
{
  delay(1000);
  Serial.printf("Initializing VL53L0X Sensor Array Elements on Wire2\n");
  bool retval = true;

  //Put all sensors in reset mode by pulling XSHUT low
  digitalWrite(LF_XSHUT_PIN, LOW);
  digitalWrite(LC_XSHUT_PIN, LOW);
  digitalWrite(LR_XSHUT_PIN, LOW);
  digitalWrite(Rear_XSHUT_PIN, LOW);

  //left-front
  //input w/o pullups sets line to high impedance so XSHUT pullup to 3.3V takes over
  pinMode(LF_XSHUT_PIN, INPUT);
  delay(10);

  if (!lidar_LF.init())
  {
    Serial.println("Failed to detect and initialize LF sensor!");
    retval = false;
  }
  else
  {
    Serial.printf("lidar_LF successfully initialized at %x\n", lidar_LF.getAddress());
    lidar_LF.setMeasurementTimingBudget(20000);
    lidar_LF.startContinuous();

    lidar_LF.setAddress(DEFAULT_VL53L0X_ADDR + 4);
    Serial.printf("lidar_LF. address is now 0x%x\n", lidar_LF.getAddress());
  }

  //now bring lidar_LC only out of reset and set it's address
  //input w/o pullups sets line to high impedance so XSHUT pullup to 3.3V takes over
  pinMode(LC_XSHUT_PIN, INPUT);
  delay(10);

  if (!lidar_LC.init())
  {
    Serial.println("Failed to detect and initialize LC sensor!");
    retval = false;
  }
  else
  {
    Serial.printf("lidar_LC successfully initialized at %x\n", lidar_LC.getAddress());
    lidar_LC.setMeasurementTimingBudget(20000);
    lidar_LC.startContinuous();

    lidar_LC.setAddress(DEFAULT_VL53L0X_ADDR + 5);
    Serial.printf("lidar_LC. address is now 0x%x\n", lidar_LC.getAddress());
  }

  //now bring lidar_LR only out of reset and set it's address
  //input w/o pullups sets line to high impedance so XSHUT pullup to 3.3V takes over
  pinMode(LR_XSHUT_PIN, INPUT);
  delay(10);

  if (!lidar_LR.init())
  {
    Serial.println("Failed to detect and initialize LR sensor!");
    retval = false;
  }
  else
  {
    Serial.printf("lidar_LR successfully initialized at %x\n", lidar_LR.getAddress());
    lidar_LR.setMeasurementTimingBudget(20000);
    lidar_LR.startContinuous();

    lidar_LR.setAddress(DEFAULT_VL53L0X_ADDR + 6);
    Serial.printf("lidar_LR. address is now 0x%x\n", lidar_LR.getAddress());
  }

  //now bring lidar_Rear only out of reset and set it's address
  //input w/o pullups sets line to high impedance so XSHUT pullup to 3.3V takes over
  pinMode(Rear_XSHUT_PIN, INPUT);
  delay(10);

  if (!lidar_Rear.init())
  {
    Serial.println("Failed to detect and initialize Rear sensor!");
    retval = false;
  }
  else
  {
    Serial.printf("lidar_Rear successfully initialized at %x\n", lidar_Rear.getAddress());
    lidar_Rear.setMeasurementTimingBudget(20000);
    lidar_Rear.startContinuous();

    lidar_Rear.setAddress(DEFAULT_VL53L0X_ADDR + 7);
    Serial.printf("lidar_Rear. address is now 0x%x\n", lidar_Rear.getAddress());
  }
  //input w/o pullups sets line to high impedance so XSHUT pullup to 3.3V takes over
  pinMode(LR_XSHUT_PIN, INPUT);
  delay(10);

  if (!lidar_LR.init())
  {
    Serial.println("Failed to detect and initialize LR sensor!");
    retval = false;
  }
  else
  {
    Serial.printf("lidar_LR successfully initialized at %x\n", lidar_LR.getAddress());
    lidar_LR.setMeasurementTimingBudget(20000);
    lidar_LR.startContinuous();

    lidar_LR.setAddress(DEFAULT_VL53L0X_ADDR + 2);
    Serial.printf("lidar_LR. address is now 0x%x\n", lidar_LR.getAddress());
  }

  return retval;
}

Frank

Good point:  Here's the 'essential' code snippet:

Wow I was really confused about the Teensy 3.5 chip name, I thought you just meant a small chip. Thanks for the helpful answer :)


text:
Arduino Due generate 400KHz sine waze
I new in Arduino environment.
Found some code generate sine wave but frequency between 14kHz to 84kHz. URL is https://www.instructables.com/SineWave-Generator-for-Arduino-DUE/
I need to generate sine waze 400kHz frequency.
Output should be on DAC0 or DAC1.
Any one can help to solve my problem.

Sorry, but how should we help you with that? You didn't give us any information. Show the code, that you have found. And also provide a detailed description of what your actual problem is.

I get some sample for generate sine wave in this link
I need to generate sine wave with frequency 400KHz. Base on link above, I dont have any idea how can I write code to get freq 400KHz.
Sorry I new student to learn arduino. @chrisl

Please add this information to your question by editing it. It should be able to stand for itself, without important information in the comments. I'm no expert in the Due (never used it), but I don't think that will work for you. The sketch is just pumping out the samples by software as fast as it can. For the 84kHz it only uses 20 samples. So for 400kHz you would have only about 4 samples. Thats not really a sine wave anymore. Maybe a pure hardware wave generation would be better.

Googling gave me for example this site, which explains how to generate a sine wave using a 555 timer chip. They seem to go up to 250kHz. By changing the values of the components further, you might get to 400kHz. Though this is not my expertise field. You could ask a question about this at electrical stackexchange

For the STM32 there is app note AN4566 about Extending the DAC performance by disabling internal output buffer and using external one, and then they can go several times higher than usual 1Msps, but I'm not sure if microchip's SAM3X8E has this possibility too

The Due's DAC can go up to, and I quote direct from the datasheet:

Up to 350ksps conversion rate

That means you can set up to 350,000 data points on your waveform per second. With two datapoints (giving you a square wave or, more realistically, a waveform with a sharks fin shape) the maximum you could get is (350,000/2) 175kHz.
Given that you stipulate you want a sine wave you're going to need many more than just 2 data points in your waveform. Assuming a (reasonable) minimum of 32 data points (more would give a smoother waveform) you'd be looking at a maximum frequency of about 10kHz. Sacrificing waveform fidelity you could increase that, but the higher you go the less and less it resembles a sine wave.

I think you may be overestimating the capabilities of the Due DAC. My understanding and experimentation is that waveform generating code (e.g., https://forum.arduino.cc/t/funkgenie-a-wavetable-based-function-generator/214938) can generate consistent output waves up to “a few kHz”. After which the wave shapes suffer from distortion.
If wave shape is not critical (though you did mention you specifically needed a sine wave) you may be able to push further using PWM outputs (e.g., https://forum.arduino.cc/t/due-high-frequency-waveform-up-too-500khz/423392).
However, I think you may need to design a suitable electronic circuit to generate the wave you’re seeking. That may be a topic for the Electrical Engineering stack exchange though? There is an introduction to wave generation circuit options going up into the RF frequencies here.


text:
Setup Due counter
How do I setup a Due to count rising edges on a pin automatically without having to waste time on an ISR?
I have some wheel encoders, the simplist implementation is direction less where you only count rising edges.
I went the Due to count rising edges automatically and an ISR on a timer will periodically pole the current count

what does this mean? ... waste time on an ISR

what does this mean? ... timer will periodically pole

encoder questions have been asked, and answered many times ... this site is not a tutorial forum, so please do research first, then ask questions about any problems that you encounter

From what I understand the Due has a counter with internal circuity instead of an ISR using to count.

Have you a reference for that claim?

Normally I would set up a timer/counter to use an external clock. Looks like the atsamd does it differently and uses a "count on event" setting. Read the datasheet and see if you understand it (I don't from a cursory glance).

Actually I was looking at the SAMD21 not the SAM3X of the Due. That seems to have TCLK0-TCLK2 as clock inputs to timers. Chapter 36 of the datasheet details them.

You need to pick a timer that isn't being used for anything else and configure it as a simple counter with the clock source set to the external clock pin for that timer.

At block level, input clock signals of each channel can either be connected to the external inputs TCLK0, TCLK1 or
TCLK2, or be connected to the internal I/O signals TIOA0, TIOA1 or TIOA2 for chaining by programming the TC
Block Mode Register (TC_BMR). See Figure 36-2.
Each channel can independently select an internal or external clock source for its counter:

External clock signals(1): XC0, XC1 or XC2
Internal clock signals: MCK/2, MCK/8, MCK/32, MCK/128, SLCK
This selection is made by the TCCLKS bits in the TC Channel Mode Register (TC_CMR).

I am not personally familiar with the peripherals of the Due, but chapter 36 of the SAM3X datasheet details the workings and registers that you need to set.
Your encoder signal then connects to that clock input pin and the counter then counts every incoming pulse until you reset the count from your other periodic timer ISR.


text:
Timer to send a periodic pulse
I am looking for a very low power, small component (perhaps an arduino) that will send a pulse 3.3V logic HIGH pulse once every X seconds to another system.  I want to be able to configure X (maybe a trim pot or something) based on the use case the most rapid use case would be about once per second and the slowest would be once per hour. The duration of the pulse doesn't really matter much as long as it's one second or less.
Adafruit sells an item (PRODUCT ID: 3573) based on a Texas Instruments TPL5110 chip that sort of does this but it's a timed constant HIGH signal, not a pulse.  I am an electronics noob and am not sure what category of component this falls under but I have tried googling and reading tutorials on timers.

There are a lot of 555 (NE555) circuits published on the web that will probably do what you want. You might search for a 555 pulse generator and pick a circuit you can build with the parts on hand.

thanks!  I will try looking for "pulse generators"

there is no "arduino" in your question

You could do that with an Arduino: that would make the question on-topic here. Then use a sleep mode and port your code to an ATtiny85 (there are Arduino cores for it): that would make the component small and low power.

As Edgar Bonet commented, you can do this using an ATtiny85 IC in an 8-pin DIP package which is available for about $1 and can be programmed using the Arduino IDE.
You have to tell the Arduino software about the ATtiny85 by installing a "core" for it such as Spence Konde's
You will need a device to transfer the program into the ATtiny85, either a $5-$15 AVR programmer or something like an Arduino Uno using the Arduino-as-ISP sketch .
Writing the software will be extremely easy by Arduino standards.
One advantage of the ATtiny85 over the same sized NE555 is that the ATtiny85 needs no external components (resistors capacitors etc) and so is a lot simpler to use. You can run this ATtiny85 on a 3.3 Volt supply (anything from 2.7 → 5.5 V will work).
If you want an ATtiny85 on a pre-assembled PCB (like that Adafruit TPL5110 product), try a Digispark or a $1 Digispark clone, it can be plugged directly into a USB port for programming with the Arduino IDE. I haven't tried running one on 3.3V but I suspect that should be possible by connecting the 3.3V supply to the "5V" pin to bypass the Digispark's 5V regulator.

See https://wokwi.com/arduino/projects/310458692893934146

I was also able to run it on a cheap Digispark clone from a 3V3 supply

The only advantage over a bare ATtiny85 is that you don't need any programming hardware, just a USB port on a PC.

Awesome idea!  this is perfect. I hadn't thought of an Arduino as a subcomponent of another arduino! I also appreciate the really thorough answer with the great links, sketch, and even picture. Really helpful and I appreciate it

Do you have thoughts about making this sleep between pulses since I'd need that to be low power?

@rfii: That's a different question, there may be some answers to similar questions here. You need to put the device into a low-power sleep-mode and set an interrupt-timer to wake it. There's a really good example project at David Johnson-Davies's blog - he has many projects that use low-power sleep to extend battery life. He does tend to use a more serious coding style though.

Thanks! I found code from Sparkfun at https://learn.sparkfun.com/tutorials/h2ohno/all which has sleep functions.  I inserted sleep periods in and it works


text:
Arduino, generating smaller frequency than 31Hz
I'm controlling a car instrument panel with Arduino using the tone() function, however with Arduino Uno's minimum 31Hz frequency I can only set the speedometer at ~12mph or more.  I'd like to be able to set the speed from 0, which would require around 10Hz I believe. Are there any code tricks I could use? Maybe I should use hardware timer, or a different board?

What frequency range would you like to cover?

Let's say 10-400Hz, I don't have an exact number because each instrument cluster is different, but 10-400Hz should cover most of them

can't you toggle the pin on and off in loop() so as to lower the pulses per second from 30? It might not be as accurate, but your slow-reacting speedometer won't mind a 200us jitter.

try the Timer1 library

For this, I would consider using Timer 1 in mode 14 (fast PWM, with TOP
value controlled by ICR1), with the prescaler set to 64. The timer would
then be clocked at 250 kHz, giving you the following specs:

timer frequency: 250 kHz (time resolution = 4 µs)
minimum frequency: 3.81 Hz (exact period = 218 µs = 262,144 ms)
maximum frequency: 125 kHz (period = 8 µs)

As the time resolution is constant, the frequency resolution worsens as
you increase the frequency. At 400 Hz the resolution is about 0.16%, or
0.64 Hz.
This is not the only possible solution. Toggle mode would work also, and
also other prescaler values, which would give different frequency ranges
and resolutions.
Check the datasheet to see how to set the configuration bits (basically:
non-inverting PWM on either OC1A or OC1B, waveform generation mode = 14,
prescaler = 64). You may be able to find libraries to do this if you
prefer that approach, I have not checked this possibility.


text:
Mounting an Arduino inside a PC
I want to mount an Arduino Pro Micro inside my PC, hooked up to the PC's USB.
I don't want to have external cables for this, but have it neatly cabled inside.
My motherboard has USB connectors with 9 pins (5+5 grid, 10th pin key), like these:

These connectors would take a cable that looks like this:

But how would I connect this to the Arduino that has Micro USB?
I've been looking everywhere, but 9-pin USB to USB Micro does not seem to exist?
The closest I could find is a cable that goes from USB micro to a 5-pin header:

What is the preferred way to hook up an Arduino Micro with internal cabling?
Why does the 9-pin to USB-micro not exist?

why 9 pin USB to USB? .... top picture shows two USB cables

@jsotola I don't understand what you mean. Top picture is of a motherboard with 2 USB connectors. Middle pic is of a connector that would fit it. Bottom pic is of a cable that I found to be available. What is missing is a cabled that is 9-pin one end, and micro usb at the other end.

sorry, 2nd picture shows two separate usb cables

@Bram, @jsotola is highlighting in the comments that the example photo you show with a 9 pin keyed  two row connector has two usb cables connecting to it. USB connections often have four wires each. The standard wire color coding is:

(Source Wikipedia - USB)
Board manufacturers are often looking for a simple way to connect multiple panel mount USB ports to the PCB and this could have been a cheap and convenient way to connect two USB ports per pcb connector.
Some suggestions:

Research the specific motherboard online to see if a schematic or connector layout is available. It’s quite likely to be laid out like this:

Experiment by making your own connector, and use a multimeter to figure out which are the power and which are the data wires.
If the old USB ports which used to connect to the PCB are still available, investigate further until you’re more confident about how they were wired.
An adapter may help you experiment further to understand the PCB connections further.

A micro-USB breakout board may help you experiment with connections on the Arduino side.

no need to experiment.  5th pin in micro is for otg ID: https://electronics.stackexchange.com/questions/35462/why-does-micro-usb-2-0-have-5-pins-when-the-a-type-only-has-4

Thank you! My local electronics shop had the breakout board in stock! I don't know yet what to do with pin ID, though. I think it is needed to specify which side is device, and which side is host.

I think the PC as host would be a could configuration to try first.

@Bram, checkout @Abel’s link in the comment above for more information about the ID pin.


text:
how to detect when a transmitter is turned off?
Using the nrf24l01 wireless module I want to control a led with the sketch below.
The transmitter automatically sends data at intervals of one second continuously and when the receiver counter reaches 2, it turns on the LED at the desired time and then turns it off.
but what I want is when I turn off the power of the transmitter when 2 counts are detected from the transmitter, the led does not light up.
I want to turn the led on and off when I turn off the power of the transmitter after sending 2 signals from the transmitter.
Thank you for all the information you provide.
#include "nRF24L01.h"
#include "RF24.h"
#include "SPI.h"
int ReceivedMessage[1] = {000}; //  NRF24L01 tarafından alınan değeri saklamak için kullanılır
RF24 radio(3, 4); //  NRF24L01 SPI pimleri. uno'daki Pin 8 ve 9
const uint64_t pipe = 0xE6E6E6E6E6E6; // 2 NRF24L01 arasındaki iletişim için aynı olması gerekir

int led = A7;

bool flag = false;
bool ledflag  = false;
unsigned long  previous1 = 0;
unsigned long  interval1 = 5000;

unsigned long  previous2 = 0;
unsigned long  interval2  = 2000;
int button1PushCounter = 0;

void setup () {

  radio.begin(); // NRF24L01'i başlatın

  radio.openReadingPipe(1, pipe); // NRF24L01'i almaya hazır hale getirin

  radio.startListening(); // Bilginin alınıp alınmadığını görmek için dinleyin

  Serial.begin(9600);

  pinMode(led, OUTPUT);

}

void loop () {

  unsigned long currentmillis = millis();
  while (radio.available())
  {
    radio.read(ReceivedMessage, 1); // NRF24L01'den bilgileri okuyun

    if (ReceivedMessage [0] == 111) //  switch'e basıldığını gösterir
    {

      button1PushCounter++;
      Serial.println( button1PushCounter);
      delay(700);
    }

    if ( button1PushCounter == 2) {

      flag = true;
      previous1 =  currentmillis;

    }

    if ( flag ) {
      if (currentmillis - previous1 >= interval1  ) {

        digitalWrite(led, HIGH);
        ledflag  = true;
        previous2 =  currentmillis;
        flag = false;
        button1PushCounter = 0;
      }
    }

    if ( ledflag && (currentmillis - previous2 >= interval2  )) {
      digitalWrite(led,  LOW);
      ledflag  = false;

    }
  }
}

what problem are you seeing?

@ -jsotola when i turn off the power of the transmitter, the receiver does not light the led with the detecting data

it seems to me that you used a lot of words to ask how to detect when a transmitter is turned off?

This is what happens when the problem is not knowing the language

you already have the code ... just rearrange it a bit ... basically implement a watchdog timer ... when signal is received, store the value of millis ... if the difference between stored value and millis() is more than 1 second, then the signal did not arrive

I don't know how to do it with watchdog unfortunately

no, not a hardware watchdog timer ... just use software

I did as you said, but failed.It works when the power supply is on. It does not work when I turn off the power supply.

your code only runs if while (radio.available()) ... i am guessing that radio.available() may be false when the transmitter is turned off

Unfortunately, I couldn't run it according to this library.

I fixed the problem with the for loop

I found solution as below:-
if ( button1PushCounter == 3 ) {

  for (int i = 0; i < 5; i++)
  {
    delay(1000);
    Serial.println(i);
    a = HIGH;
  }
}

if ( a == HIGH ) {

  digitalWrite(led, HIGH);
  delay(1000);
  digitalWrite(led,  LOW);
  a = LOW;
  button1PushCounter = 0;
}


text:
reading data from server arduino and gsm900a
I am facing a problem in reading data from thingspeak server
after each AT command, I get the right response from the gsm
However, after
AT+HTTPPARA = "URL","thingspeak.com/channels/channelNumber/fields/1/last.txt"
AT+HTTPACTION=0
AT+HTTPREAD

I always get the response as HTML code so not as content
I really need your help and will appreciate any suggestions.
Thanks in advance.


text:
How to correctly use SSL certs with the Adafruit SIM800H
I am trying to use a Adafruit Sim800H to connect to Azure using MQTT with an SSL certificate. My first step is trying to put a new SSL certificate onto the board. To do this I am using this example here: https://github.com/vshymanskyy/TinyGSM/ ... etCert.ino . This seems to follow the typical suggested steps on how to set the SSL - by using AT command to create and write to a file, which is then set as the certificate.
The code I am running is the same as what is in the Github repo - except I have added extra print commands, getting a better idea of where it has broken. Here is an excerpt:
  SerialMon.println(F("Select..."));
  modem.sendAT(GF("+SSLSETCERT=\"" CERT_FILE "\""));
  SerialMon.println(F("cert file on.."));
  if (modem.waitResponse() != 1) return;
  if (modem.waitResponse(5000L, GF(GSM_NL "+SSLSETCERT:")) != 1) return;
  SerialMon.println(F("begin retCode"));
  const int retCode = modem.stream.readStringUntil('\n').toInt();

When I monitor my Arduino, I see "Select" and "cert file on.." printed out. However, then it hangs for a long time, and I get an error saying the command is not available.
Can anyone help me follow up on what may be the cause of this?
I have explored trying to update the firmware. I have downloaded a newer firmware (B11), and have the software needed to shift it to the board. However, it doesnt seem to recognise the board is connected over USB. In this situation, the cable is connected to the SIM800H board USB - is this correct?
Thanks.


text:
How to send AT commands to the ubox modem on MKR NB 1500
I am trying to send AT commands to the modem to keep the modem always active. I tried the File > Examples > MKRNB > Tools > SerialSarapassThrough example, but that gave me a +CME ERROR: operation not supported. Here is the output for the commands I sent via serial monitor:
AT
OK
AT+UPSV=0
+CME ERROR: operation not supported

Is there a built in code or any other code which I could use to send that command?

I'm not familiar with that modem, but if the firmware tells you, that is doesn't support that command, then it doesn't support it. Are you sure, that the modem is capable of what you want?

yes i am sure, I read the documentation of the modem and it specifies that sending commands will set it up according to my requirement

Please link to that part of the documentation

https://www.u-blox.com/sites/default/files/SARA-R4_ATCommands_UBX-17003787.pdf

The command is : AT+UPSV=0

You have to try SerialSARAPassthrough.ino from examples menu under MKRNB.
If it works properly, you can start writing AT in serial monitor line. You must see answer as OK. Then you can look at the u-blox commands document that is shared above


text:
Leonardo with hm-10 doesn't work
I have a hm-10 module attached to Arduino Leonardo board, I'm using a bluetooth terminal app to send some text.
The problem is I can send data from the Serial monitor to my phone but when I send from my phone, there is no output in the serial monitor.
It works fine if I test it on Arduino Uno.
I'm struggling with something that should be simple.
Can someone please help me?
Here is my code:-
#include <SoftwareSerial.h>

SoftwareSerial BTSerial(4, 5);

void setup(){
  Serial.begin(115200);
  Serial.println("Hello!");
  BTSerial.begin(115200);
}

void loop(){
  while (BTSerial.available()){
    byte data = BTSerial.read();
    Serial.write(data);
  }

  while (Serial.available()){
    byte data = Serial.read();
    BTSerial.write(data);
  }
}

Leonardo has Serial1. You don't need to use SoftwareSerial

I GOT IT!! It was problem with the pin settings.
According to SoftwareSerial library documentation, only pins 8,9,10,11,14,15,16 can be used for RX pin. But i used pin 4 for RX.


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

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

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

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

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

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

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

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

Successful test output from the Wire1 connection is shown.

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

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

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

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

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

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

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

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

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

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

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


text:
avrdude: stk500v2_ReceiveMessage(): timeout error for bluetooth arduino
I am trying to link the Bluetooth module to my arduino UNO in order to wirelessly program a robot. The only issue that I am having is that the bluetooth module does not seem to pick up the arduino.
Here is how the bluetooth module is wired up to my arduino:

The bluetooth module is paired to my PC via a bluetooth dongle. I know that the bluetooth module is working on port COM7. The LED then on the bluetooth module blinks quickly. After this I set the port to the correct port that the bluetooth module uses:

One thing that I found strange was that the name of the arduino board does not come up just like when I use a USB to upload the program.
When I open up the serial monitor the LED on the bluetooth module begins to blink more slowly possibly indicating it is connected. I afterwards try to send an AT command via the serial monitor to the arduino by typing in AT to the serial input at the top of the serial monitor and hitting enter and nothing happens. I then tried to send 3 different pieces of code separately to the arduino one at a time:
First code sample:
void setup() {

 Serial.begin(9600);

while (!Serial) {
   ; // wait for serial port to connect. Needed for native USB port only
 }

 Serial.println("ASCII Table ~ Character Map");
}

int thisByte = 33;

void loop() {

 Serial.write(thisByte);

 Serial.print(", dec: ");
 Serial.print(thisByte);

 Serial.print(", hex: ");
 Serial.print(thisByte, HEX);

 Serial.print(", oct: ");
 Serial.print(thisByte, OCT);

 Serial.print(", bin: ");
 Serial.println(thisByte, BIN);

 if (thisByte == 126) {
   while (true) {
     continue;
   }
 }
 thisByte++;

}

Second code sample:
#include <SoftwareSerial.h>
SoftwareSerial BTSerial (2,3);
void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
  Serial.println("Enter AT Commands");
  BTSerial.begin(9600);
}

void loop() {
  // put your main code here, to run repeatedly:
  if(BTSerial.available()){
    Serial.write(BTSerial.read());
  }
  if(Serial.available()){
    BTSerial.write(Serial.read());
  }
}

Third code sample:
char inputByte;
void setup() {
 Serial.begin(9600);
 pinMode(13,OUTPUT);

}

void loop() {
while(Serial.available()>0){
  inputByte= Serial.read();
  Serial.println(inputByte);
  if (inputByte=='Z'){
  digitalWrite(13,HIGH);
  }
  else if (inputByte=='z'){
  digitalWrite(13,LOW);
  }
  }
}

(The following situation occurs for all 3 samples of code I copied from online). When I set the port to COM7 and then click upload to the board, the IDE says "Uploading" and the LED begins to blink more slowly just like as I was mentioning before with the serial monitor. After a while eventually the following error messages came up:
avrdude: stk500v2_ReceiveMessage(): timeout
avrdude: stk500v2_getsync(): timeout communicating with programmer

I looked online for answers. The internet suggested to use a larger baud rate so I switched it from 9600 to 57600 and also at the same time switch from Newline to Both NL and CR. Still nothing happened and I got the following error message. One final suggestion I saw on the internet was to put a resistor divider/voltage divider across the RX pin (I haven't done this as I don't see how this could make a difference, I could be wrong about it though and it could make the whole difference).

You have no method to reboot the Arduino into the bootloader. You can't just slap a bluetooth interface on and hope it works. You need to have some way of triggering a reset like the USB interface does through the DTR signal.

Also you have to manually configure the HC05's baud rate to match the baud rate of the bootloader (115200 baud IIRC) which you can only do through its serial interface pins.

@Majenko Only problem is that I am not that experienced...

Then you need to read, read, read. Read how the HC-05 works. If there's something you don't understand then read up about that aspect. Keep reading until you understand it all.

@Majenko Is there a way I could use the reset pin on the arduino to solve the problem?

If you can come up with some way of remotely toggling it through the bluetooth connection, yes. Or tap the reset button at the right moment, but I guess that kind of negates the whole point of the bluetooth...

One thing that I found strange was that the name of the arduino board does not come up ... why should it? ... the name comes from the USB driver

@jsotola To be fair I was thinking that.

I am not sure how comfortable you are with soldering, but checkout this video where somebody showed how to reset the Arduino from the Bluetooth module: https://youtu.be/6GD3aNFrJ9I?t=401

The Bluetooth range is small so the robot can't be far from the computer for upload.

To solve the reset for the Bluetooth you could add a reset button on the robot and use it while avrdude attempts to upload the sketch. Baud rate on HC-05 must be set to 115200 baud.

As an alternative you could have USB connector on the robot. You can use a short USB extension cable as internal cable from the USB connector of the Arduino to the outer shell of the robot.


text:
What is the simplest way to emulate the original gameboy's cpu using Arduino?
My initial question assumes it is possible to emulate the original GameBoy system using an Arduino board.
Additional information in non-technical terms: I am looking to create an Arduino based device that accepts cartridges as input devices (in some cases they will also function as output devices) I am interested primarily in the Hexadecimal/pixel based "logic" which gameboy games uses to display game data.
What is the simplest way to emulate the original gameboy's hexadecimal based pixel logic to fetch, decode, and execute data using Arduino?
Before flagging this question, please comment so that I may clarify as this is a complex question to ask and I am willing to re word it as necessary.

never assume anything

hexadecimal based pixel logic makes no sense ... it is all binary data

On an Arduino? No chance. On something more powerful? Sure. I've seen Z80 (and other) emulation running on an ESP32 (see FabGL), and the Sharp LR35902 the gameboy uses is very similar to the Z80.

There are multiple open-source emulators. Do your research, and read their documentation and code. You will quickly find that an 8-bit AVR cannot emulate a GB in real-time. (Note: Many years ago I wrote a GB emulator for a 68000 CPU (16/32 bit system) with 16 MHz. It runs common games with 1/4 to 1/10 of their original speed, and had no sound emulation.)

@jsotola you are correct at the machine level all operations are binary, but a 1 with 15 leading zeros can be interpreted the same as a 1 with no leading zeros that leaves 15 unique locations available for data manipulation. i'm sorry if it does not make sense to you. imagine a 16 by 16 grid of squares. each one is able to be "colored in" if any square is filled in then it is treated as a 1 rather than a 0 . the placement of these squares along with other factors can be used to store information. the compressed form is seen as hexadecimal code which when uncompressed becomes binary data.

@Majenko I am not looking to use it to play games, just utilize hex based addressing that functions similarly to how a gameboy game might store and retrieve data from a game cartridge. I believe the frame rate could be much much less than what a typical game would need to be. I would not necessarily need to play sound, though I recall how pokemon each had unique "sounds" or cries when appearing on screen, so sound is still something I am still researching. I will check out the z80 I believe that the docs i read used a teensy 4.0 which worked with most arduino peripherals.

@thebusybee I will continue researching and hopefully in a few days I can re word this question to better suit my needs. I also read that the esp32 has a dual cores with 240 mhz clock speed for each processor. I may eventually try using this if possible. To clarify I would like to Specifically be able to emulate only a game operating almost identically to Pokemon.

@PeopleCallMeAdam hexadecimal notation is simply for human readability of binary data ... it is not a compressed version of binary data ... there is no hex based addressing ... it is all binary addressing at machine level ... when the processor retrieves a value of 0x48F4, it is actually retrieving 0100100011110100 ... it knows nothing about 0x48F4

@jsotola again I am aware that the data is binary at the machine level, I view hexadecimal notation as a form of "lossless compression" humans speak many languages, when you translate between them you often lose part of the meaning in that translation. if binary code is the meaning and hardware the "speaker" think of software as people some people/software speak spanish and some speak english. if hexadecimal allowed for a lossless compression of some meaning in english then later uncompressed in spanish with nothing lost during translation with 100% success rate would what i said make sense?

@PeopleCallMeAdam No, that makes no sense at all (regarding your comment asking, “If hexadecimal allowed for a lossless compression … meaning in English uncompressed in Spanish… would what I said make sense?”).

(Assembling an answer from the comments)
The consensus is that there is no "simple way to emulate the original gameboy cpu using Arduino". That a more powerful platform is required.
Multiple commenters expressed difficulty with the novel concept of "hexadecimal/pixel based logic". It is suggested that this concept may be without merit.


text:
Convert String to const unsigned char
String abc ="0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff";

const unsigned char displaydata={reinterpret_cast<const unsigned char*>(abc.c_str())};

display.drawBitmap(displaydata, startX, startY, bmpWidth, bmpHeight, GxEPD_WHITE);

Get error: invalid conversion from 'const unsigned char' to 'unsigned char' [-fpermissive]*
When I write like this
String abc ="0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff";

display.drawBitmap(reinterpret_cast<const unsigned char*>(abc.c_str()), startX, startY, bmpWidth, bmpHeight, GxEPD_WHITE);

No error but black screen no display image
When I write like this
const unsigned char displaydata[]={ 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff};

display.drawBitmap(displaydata, startX, startY, bmpWidth, bmpHeight, GxEPD_WHITE);

It is working
The string data coming from the server is returning to me as stirng, I am trying to reflect it on the screen. I want to convert a string data to const unsigned char with code
So I'm trying to convert

How exactly is the server giving you the binary data? Please include an example string from the servers answer to the request. Is it really in the format of your first string?

With const unsigned char displaydata={reinterpret_cast<const unsigned char*>(... you're assigning a pointer to a single character.  Or more importantly, part of a pointer to a character, which if the memory address (pointer value) was larger than 0xFF would be pretty useless. So, the problems start here with a missing pointer declarator (a *)  There's not much Arduino to the question. Fairly squarely a C++  question, unless I'm missing something.

String is a custom Arduino class, so could be classed as an arduino question (pun intended) on that merit.

Step one: Split the String into chunks using the comma delimiter. Step B: convert each chunk from its textual representation into its numeric value. Step Delta: place that value into the array. Step 0: forget const, that's irrelevant.

@Majenko, I didn't feel strongly enough about it to close-vote it.

That string is literally the characters 0xff ... while the array is the bytes 0xff...
Where the string contains 4 bytes to say 0,x,f,f (followed by comma and space) the array will have 1 byte the 255 (and no need for a comma or space to delimit).
If you are looking to convert the text hex string to bytes, look at a combination of How to convert an hex string to an array of bytes? and looping through the string.


text:
Why the unsigned long is overflowing?
I want to convert hour to seconds but unsigned long is overflowing, here's the code:
#include <Wire.h>
#include <DS3231.h>

RTClib myRTC;
unsigned long seconds;
char timestr[9];

void setup() {
  Serial.begin(250000);
  Wire.begin();
}

void loop() {
  DateTime now = myRTC.now();

  snprintf(timestr, 9, "%02d:%02d:%02d", now.hour(), now.minute(), now.second());
  seconds = (now.hour() * 3600);
  Serial.println(timestr);
  Serial.println(seconds);
  delay(100);
}

And the console output is:
16:33:36
4294959360

Why is this happening?

It's not the unsigned long that's overflowing but the calculation that you're assigning to it.
3600 is a signed integer (by default), and now.hour() is an unsigned byte. The unsigned byte gets promoted to match the "largest" type in the calculation - a signed integer - and then the calculation is performed, resulting in a signed integer.
That signed integer is then assigned to an unsigned long and, if the result is negative (as it may well be - 10*3600 > 32767) you end up with a massive number.
The simple "cure" is to ensure that one value in the calculation is an unsigned long. And the best way of doing that is to make your constant an unsigned long: by appending "UL" to it:
seconds = (now.hour() * 3600UL);


text:
ESP32 AP Automatic Web Page
I've often encountered WiFi networks that require you to sign in through a web page that automatically opens after connecting to the access point, such as hotels. I'd like to implement something similar with an ESP32, where a web page opens automatically after connecting to the AP. Is this doable? This seems to be difficult to Google, because I just get a bunch of introductory tutorials on setting up an AP.
Here's some project context in case it helps. I'm making an IoT device that needs to connect to the user's WiFi network, so the user needs to specify the login credentials. The solution I'm trying to implement is having the ESP32 set up a temporary AP, where the user can connect to that and enter their home WiFi credentials. As it stands now, the user has to manually type in the IP address of the ESP32 after connecting to the AP, but it'd be much more user friendly if the web page opened automatically like hotel WiFi networks sometimes do.
I've tinkered with this WiFi Manager library that appears to do what I want, but I'd like to implement mine from scratch.

I think you didn't find anything, because you searched for the wrong terms. What you want is a "captive Portal". I think there are some tutorials available on the web about that. Please try a search with that term. Something like "ESP32 captive portal".

Yeah, I figured that out as I was writing the question. I decided to post it anyways, since I'm guessing others may be in the same boat as me. I've already posted an answer with that info, but thanks for the help anyways!

Of course, as soon as I linked that WiFi Manager library in my question, I figured it out. The term I was missing was "captive portal" and I was able to figure it out from there. But I decided to post the question anyways, since it might help someone else stuck in the same situation.
Here's my understanding of how it works: when your device connects to a new network, it tries to ping a server to see whether it has internet access. With the ESP32, you can set up a DNS that redirects that ping to a web server running on the ESP32, which opens up the browser on the device.
I found this tutorial helpful for me to understand how that works, along with example code. This should be enough for me to get it working.
https://iotespresso.com/create-captive-portal-using-esp32/


text:
How can I make my code Thread-Safe?
So I made a post yesterday running into an issue on my ESP32 using both cores on the microcontroller (with wifi enabled, incase that is important).
I'm using both cores to control two Neopixel strips individually. I'm making a music visualizer, and I want the neopixels to react to the change in music as quickly as possible, so I felt like having one for every individual core was the best way for that to happen. The issue I am running into is that when audio is playing, the Music Visualizer function either in the primary core (Core 1), or secondary core (Core 0) will just completely freeze. I tried troubleshooting with some Serial.Print statements to understand where the code breaks, and it seems to happen around the setPixelColor command. I think my code is being thread locked, and I wanted to know what I could do to make it thread safe.
void musicVisualizer(void) {
  middle_strip.clear();
  upper_strip.clear();

  middle_strip.show();
  upper_strip.show();

  // Add code to tell Core 0 to wait until LED's are cleared.
  while (vu_meter) {
    tweeter_prev = tweeter;
    if (analogRead(tweeter_sample) <= 490)
      tweeter_adc = 0;
    else {
      tweeter_adc = (analogRead(tweeter_sample) - 490);
      if (tweeter_adc < 0)
        tweeter_adc = 0; // Filter for changing reference voltage
      else if (tweeter_adc > MIDDLE_LED_COUNT)
        tweeter_adc = tweeter_prev; // Filter for if there are intermittent spikes in the adc
    }
    tweeter_filter.Filter(tweeter_adc);
    tweeter = tweeter_filter.Current() * 6;  // 6 scaler is for when Alexa is at Volume Level 4

    //    /* Changing LED Number to improve efficency when turning on LED's */
    //    if (tweeter > 43)
    //      LED_COUNT = 65;
    //    else if (tweeter > 21)
    //      LED_COUNT = 43;
    //    else if (tweeter <= 21)
    //      LED_COUNT = 21;

    /* LED's turning on and off in response to audio */
    if ((tweeter > tweeter_prev) && (tweeter <= MIDDLE_LED_COUNT)) {
      for (int x = tweeter_prev; x < tweeter; x++) {
        //        middle_strip.setPixelColor(x, color);
        middle_strip.setPixelColor(x, 0, 0, middle_strip.gamma32(brightness));
        middle_strip.show();
      }
    }
    else if (tweeter_prev > tweeter) {
      for (int x = tweeter_prev; x >= tweeter; x--) {
        middle_strip.setPixelColor(x, 0, 0, 0);
        middle_strip.show();
      }
    }
  }

  /* Leaving VU Meter, returning to current lamp color set */
  if (led_on) {
    if (!color_white) {
      for (int i = 0; i < LOWER_LED_COUNT; i++) {
        lower_strip.setPixelColor(i, color);
        lower_strip.show();
      }
      for (int i = 0; i < MIDDLE_LED_COUNT; i++) {
        middle_strip.setPixelColor(i, color);
        middle_strip.show();
      }
      for (int i = 0; i < UPPER_LED_COUNT; i++) {
        upper_strip.setPixelColor(i, color);
        upper_strip.show();
      }
    }
    else {
      for (int i = 0; i < LOWER_LED_COUNT; i++) {
        lower_strip.setPixelColor(i, 0, 0, 0, lower_strip.gamma32(brightness));
        lower_strip.show();
      }
      for (int i = 0; i < MIDDLE_LED_COUNT; i++) {
        middle_strip.setPixelColor(i, 0, 0, 0, middle_strip.gamma32(brightness));
        middle_strip.show();
      }
      for (int i = 0; i < UPPER_LED_COUNT; i++) {
        upper_strip.setPixelColor(i, 0, 0, 0, upper_strip.gamma32(brightness));
        upper_strip.show();
      }
    }
  }
  else {
    upper_strip.clear();
    middle_strip.clear();
    lower_strip.clear();

    upper_strip.show();
    middle_strip.show();
    lower_strip.show();
  }
}

void vu_meter_sub(void * parameter) {
  while (true) {
    esp_task_wdt_init(30, false);
    if (vu_meter) {
      lower_strip.clear();
      lower_strip.show();
      while (vu_meter) {
        sub_prev = sub;
        sub_adc = analogRead(sub_sample);
        if (sub_adc > LOWER_LED_COUNT)
          sub_adc = LOWER_LED_COUNT-1;
        sub_filter.Filter(sub_adc);
        sub = sub_filter.Current();
        //        if (sub < 0)
        //          sub = 0;
        Serial.println(sub);
        if ((sub > sub_prev) && (sub <= LOWER_LED_COUNT)) {
          for (int x = sub_prev; x < sub; x++) {
            //            lower_strip.setPixelColor(x, color);
            lower_strip.setPixelColor(x, 0, lower_strip.gamma32(brightness), 0);
            lower_strip.show();
          }
        }
        else if (sub_prev > sub) {
          for (int x = sub_prev; x >= sub; x--) {
            lower_strip.setPixelColor(x, 0, 0, 0);
            lower_strip.show();
          }
        }
        Blynk.run();
      }
    }
  }
}

I am not sure this is related to thread-safety, but you should be aware
that strip.show() is a slow function that blocks while the data is
being sent. setPixelColor(), in contrast, is fast, as it only updates
the data in memory.
I suggest you modify musicVisualizer() in such a way that it only
show()s each strip once. The bulk of the function should be about
computing the colors you want and setting them with setPixelColor().
Then, at the very end of the function, show() the three strips.

I thank you for the suggestion. I implemented this into my code, but this did not fix the issue I'm experiencing with one of the cores freezing up. I feel like this might have to do with the fact that they are sharing the same library header?


text:
ov2640 with 18 pin and no arducam shield
I bought this ov2640 camera module with 18 pins and I don't have shield to insert it to. I am looking for a library or working code on this my camera sensor but all I kept getting was arducam examples or at most ov7670 example code. Can anybody help me out here?
The image of the module is at this link https://i.stack.imgur.com/tUVg0.jpg
PS: I am using an arduino due
(Edit: Added image of camera module)

not an Arduino specific question

@jsotola, sorry, why would this be not arduino specific? the questions asks how to wire a camera module to Arduino Due without the Arduino shield usually used for this type of camera

I am using arduino due

There is a datasheet for the module at https://www.mpja.com/download/35647mpdata.pdf
It references the Arducam library at https://github.com/ArduCAM/Arduino/tree/master/ArduCAM.
The library specifically supports this camera type. By studying the camera specific code you may get a better idea of what is required. To connect the module directly to a Due, the work that was designed to be done by the intended shield would need to be replicated. Which seems non-trivial.

Thank you. I had a headway. The library can help you connect to the ov2640 camera and communicate with it through sccb interface. There is a whole lot of spi interface configuration that doesn't apply in my own case, so I didn't use the spi pin. Getting the snapshot of what is in the D0 - D7 pins without an assistant of library is not as trivial for a learner as you think. I am using arduino due and would like to facilaitate this using DMA. I want to send the snapshot straight to sd card.

You’re welcome, I’m glad the suggestion helped you progress. As I thought, non-trivial (i.e., complicated).  A further suggestion might be to finalize the basics of interfacing directly to the camera before introducing DMA? It may be worth a separate question on the DMA idea? If you resolve the direct interface you might consider posting an answer to this question, I’m sure there will be other readers interested in how you did it.