text:
why is my char array empty
following sketch will run totally fine and as expected :
#include <Wire.h>

#include "SparkFun_External_EEPROM.h"
ExternalEEPROM ExtEEPROM;
char username[33] = "";
char password[65] = "";

void setup()
{
  Serial.begin(115200);
  delay(1000);
  Wire.begin();
  #define EEPROM_ADDRESS 0b1011000 // 0x58
  ExtEEPROM.setMemorySize(256000/8); // 256kbit = 32kbyte
  ExtEEPROM.setPageSize(64); // 64 byte page size.
  ExtEEPROM.enablePollForWriteComplete();
  ExtEEPROM.setPageWriteTime(10); // max. ms for AT24C128
  if (ExtEEPROM.begin(EEPROM_ADDRESS, Wire) == false)
  {
    Serial.println("No memory detected. Freezing.");
    while (1);
  }
  Serial.println("Memory detected!");

  String uuu = "myusername";
  String ppp = "mypassword";

  uuu.toCharArray(username, sizeof(username) - 1);
  ppp.toCharArray(password, sizeof(password) - 1);
  Serial.print("password=");Serial.println(password);
  ExtEEPROM.put(0, username);
  //delay(100);
  ExtEEPROM.put(0 + sizeof(username), "greatnewpassword");
}

void loop() {
  char xxx[33] = "";
  ExtEEPROM.get(0, xxx);
  Serial.print("xxx=");Serial.println(xxx); // prints the username

  char yyy[33] = "";
  ExtEEPROM.get(0 + sizeof(username), yyy);
  Serial.print("yyy=");Serial.println(yyy); // prints the password
  delay(1000);
}

However, if I replace ExtEEPROM.put(0 + sizeof(username), "greatnewpassword"); to ExtEEPROM.put(0 + sizeof(username), password);, then yyy prints empty in the serial monitor. Why?

Try doing a serial print of password to see if the toCharArray call did what it was supposed to do.

OT: Don't write any_boolean == false, use !any_boolean. If you think think, you should make sure that anyone understands, then I'd recommend (any_boolean == false) == true. :-D

OT: sizeof is an operator, not a function, so use sizeof variable. However, its operand can be a type, and then it needs parentheses for syntactIcal reasons. This leads to this ubiquitous bad habit to write it as a function.

Are you sure you are putting the actual array password, rather than a pointer produced by its decay (like char *foo = password; ExtEEPROM.put(..., foo);)?

256kbit is not 256000 bits. It's 256 * 1024 bits, or 262144.

problem seems to be the lib I am using. I think it can not handle data overlapping page size.
if I replace from this
char username[33] = "";
char password[65] = "";

to this:
char username[16] = "";
char password[16] = "";

everything works fine as it saves and reads from the EEPROM via I2C.

the conversation has been moved to chat.

As Majenko already mentions:

.get() and .put() should only be used for atomic, self-contained,
types like int or float, not pointers like char *.

Not sure what atomic means here, but you may .put and .get any data type, especially a struct.
struct EPROMData {
  char username[33];
  char password[65];
};
EPROMData data {"myusername","mypassword"};

void setup() {
   ...
   ExtEEPROM.put(0,data);
}
void loop() {
   EPROMData d;
   ExtEEPROM.get(0,d);
   Serial.print("user="); Serial.println(d.username);
   ...
}

Sure, if the data type is a pointer or a String object (containing a pointer only), you won't be happy with .put / .get

By atomic I mean "it is a thing complete in itself". A struct is complete. An int is complete. A char * is not complete since it doesn't contain the data, it is only a pointer to it. So it's not "atomic". Same goes for a String object, since the object doesn't contain the string data, only a pointer to allocated memory that contains the string data.

.get and .put are being passed a char pointer, not the contents of a char array. Thus you're not writing the content of the string but the address in memory where it's being stored.
With a string literal that is fixed and never changes, so what you write and what you read are fine. With a variable though the address could be anything, and storing the address of some RAM where a string is stored is pointless.
.get() and .put() should only be used for atomic, self-contained, types like int or float, not pointers like char *.
Instead you need to be using the .read(address, buffer, size) and .write(address, buffer, size) functions to read and write the contents of your char arrays.

In the OP's code, get() and put() are being passed actual arrays, not pointers. As the arrays are being passed by reference, they do not decay to pointers.


text:
RFM69HCW connected to Arduino Nano 33 BLE
I tried to connect my RFM69HCW to Arduino Nano 33 BLE, so that I won't be needing a logic level shifter to downgrade the voltage, since Arduino Nano is already 3.3V. Upon checking its data sheet and pinout, I noticed there's no dedicated pin for CS (Chip Select).
Which pin should I use as CS in the Arduino Nano?
Which pin should I connect the DI0 pin of RFM69HCW in the Arduino Nano?

On any Arduino you can use any free digital pin as SPI CS.

Okay. Thank you! Even the DI0 pin of RFM69HCW can I connect it too to any pins of Arduino Nano?

@lostresearch, why not? it is free. the SPI pins on Nano are 11, 12 and 13

There is no dedicated CS pin, and you can use any available Dx pin – which enables you, among other things, to have several devices on the same bus. The CS pin allows you to select (hence the S) the right device.

source: Stack Exchange

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

sort: votes


text:
What GSM module I should use for HttpClient, ArduinoHttpClient, WebSockets etc.?
I need to use some API in my project. So I'm gonna use such libraries as listed in the title? What GSM/SIM module do I need for this purpose? I've checked 800L and similar - it only can use plain http, and only via AT command. At least based on this, that's not what I really need. Thanks in advance.

The TinyGSM library implements the Arduino Client class required by networking super libraries you mention in the question.
TinyGSM supports the SIM800 modems.

Ok, thanks, but what about http only, no https?

@picKit, see the "SSL/TLS (HTTPS)" paragraph in README

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


text:
Wind speed measuring using Hall effect Anemometer
I need your help regarding a problem I am facing while measuring wind speed. In my sketch I get a reading every 20 counts which the magnet goes past the sensor. I need to change it in order to get a reading every 20 seconds. How can I do it with minimum changes to the sketch?
volatile byte revolutions;

float rpmilli;
float speed;

unsigned long timeold=0;

void setup()
{
  Serial.begin(9600);
  attachInterrupt(digitalPinToInterrupt(2), rpm_fun, RISING);

  revolutions = 0;
  rpmilli = 0;
  timeold = 0;
}

void loop()
{
  if (revolutions >= 20) {
    //Update RPM every 20 counts, increase this for better RPM resolution,
    //decrease for faster update

    // calculate the revolutions per milli(second)
    rpmilli = ((float)revolutions)/(millis()-timeold);

    timeold = millis();
    revolutions = 0;

    // WHEELCIRC = 2 * PI * radius (in meters)
    // speed = rpmilli * WHEELCIRC * "milliseconds per hour" / "meters per kilometer"

    // simplify the equation to reduce the number of floating point operations
    // speed = rpmilli * WHEELCIRC * 3600000 / 1000
    // speed = rpmilli * WHEELCIRC * 3600

    speed = rpmilli * 0.6597 * 3600;

    Serial.print("RPM:");
    Serial.print(rpmilli * 60000);
    Serial.print(" Speed:");
    Serial.print(speed);
    Serial.println(" kph");
  }
}

void rpm_fun()
{
  revolutions++;
}

You can use the millis() function to measure time intervals and do things regularly in these intervals. Refer to the BlinkWithoutDelay example, that comes with the Arduino IDE, or to one of the many tutorials for the millis() function on the web.
Basically you will need to do the following:

Declare a timestamp variable to hold the time when the data was displayed last time (in global scope):
 unsigned long timestamp = 0;

Declare the interval, that you want the display to happen in:
 #define DISPLAY_INTERVAL  20000

In your if statement check if the time difference between now and the timestamp is bigger than the interval
 if(millis() - timestamp > DISPLAY_INTERVAL){

Note that you should do millis() comparisons always this way (by calculating the difference), so that the rollover of millis() will not affect the result.


text:
Cannot read values stored in bool* pointer
I'm trying to read values stored in a bool* pointer from a modbus coil call.
I'm using modbus-esp8266 library. it's all ok with Input Registers and Holding Registers but i cannot read the result of a coil read.
#include <ModbusRTU.h>
#include <SoftwareSerial.h>

SoftwareSerial S(D2, D1);
ModbusRTU mb;

bool cb(Modbus::ResultCode event, uint16_t transactionId, void* data) { // Callback to monitor errors
  if (event != Modbus::EX_SUCCESS) {
    Serial.print("Error result: 0x");
    Serial.print(event, HEX);
  }
  return true;
}

void setup() {
  Serial.begin(115200);
  S.begin(9600, SWSERIAL_8N1);
  mb.begin(&S);
  mb.master();
}

void loop() {
bool* coils;
  if (!mb.slave()) {    // Check if no transaction in progress
    mb.readCoil(1, 1, coils, 1, cb); // Send Read Hreg from Modbus Server
    while(mb.slave()) { // Check if transaction is active
      mb.task();
      delay(10);
    }
    Serial.println(*coils);

  }
  delay(1000);
}

I get this kind of error when trying to print *coils
Exception 28: LoadProhibited: A load referenced a page mapped with an attribute that does not permit loads

How to get the boolean result value from it?

please add the full error message text

The coils pointer points to some random place as you didn't bother to define any value for it (depends on what was in the memory where that pointer gets space).

bool coils; and mb.readCoil(1, 1, &coils, 1, cb);. this way the function can the value of the variable coil

When programming an Arduino you are actually writing in the language C.  As such you can search the internet for C programming answers of which there is likely 50 years of answers.
You have defined "coils" as a pointer.  This is done by preceding the name with an asterisk where it is defined.  In this line of code:
bool* coils;

This means you are using coils to store the memory location of where the actual value is to be stored.  However, in the case of the code in the posted question, the memory location of where the actual value is to be stored is never defined.
This is like going on a bad clue hut.  You receive instructions to obtain the next clue at a specific location.  But when you get there you find no further instructions.
Beginning programmers often find pointers confusing.  But later find pointers very useful tools that simplify many otherwise complex programs.
Consider dropping the asterisk in front of "coils" on the two lines of code where is exists and try running the program again.

Added later:
Guessing, it may be that the call to readCoil function assumed to be defined in ModbusRTU.h requires a pointer to be passed to in as the 3rd formal variable parameter.  This is more advanced C programming.  If true, then keep your original code but add a line of code setting the value of "coils" to the address of a new bool variable.  Perhaps something along these lines:
bool* coils;
bool coils_value;
coils = &coils_value;


text:
How would I link inline debugger with esp32 on Mac?
I am trying to connect JTAG debugger to my esp32 according to the following steps https://www.instructables.com/How-to-Use-a-Debugger-on-an-ESP32/
but still I am facing issue in debugging. I am working with MAC
below is the error I am facing while debugging
No dependencies
Building in debug mode
Checking size .pio/build/uno/firmware.elf
Advanced Memory Usage is available via "PlatformIO Home > Project Inspect"
RAM:   [          ]   0.4% (used 9 bytes from 2048 bytes)
Flash: [          ]   3.5% (used 1118 bytes from 32256 bytes)
Configuring upload protocol...
AVAILABLE: arduino
CURRENT: upload_protocol = arduino
Looking for upload port...
Auto-detected: /dev/cu.usbserial-1201
Uploading .pio/build/uno/firmware.hex
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x00
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 2 of 10: not in sync: resp=0x00
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 3 of 10: not in sync: resp=0x00
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 4 of 10: not in sync: resp=0x00
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 5 of 10: not in sync: resp=0x00
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 6 of 10: not in sync: resp=0x00
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 7 of 10: not in sync: resp=0x00
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 8 of 10: not in sync: resp=0x00
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 9 of 10: not in sync: resp=0x00
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 10 of 10: not in sync: resp=0x00

avrdude done.  Thank you.

*** [upload] Error 1

You have built for (and are attempting to upload to) an Arduino UNO not an ESP32.


text:
How do I use BLE module and RFM69 module together?
I am trying to use an Adafruit BLE module and an RFM69 module on the same Arduino.
The higher-level functions in each included library (Adafruit_BLE.h, RFM69.h) both use the SPI.h library to talk to each respective module.
I think all I need to do is make a copy of the SPI.h file, and edit it to make the SS pin for one of the modules different.
Is there a better way to do this?

The SS pin will be defined by the target device library, not SPI.h. Check the options for the constructor in each library for how to change the SS pin from your own code.

you mean like Arduino.h?

No, I mean like RFM69.h or Adafruit_BLE.h or whatever the libraries are called that you are using.


text:
Looking for help with an improved vibration sensing method for Arduino
I am trying to test how vibration waves move through different material...ie how sensitive certain components are.
I am needing a vibration sensor that will send me back some kind of measurement say in the form of an integer between 1 and (a number).
I have tried the 801S with an Arduino board and it was successful. The problem though is it just returns a 1 for vibration and 0 for none. To get the results I had to keep retesting and moving the material further and further away to get it to fail.
I also tried a HiLetgo piezoelectric analog sensor. It does return a number...but the results are all over the place...from 5 to 250. I have a device that supplies a consistent "tap" to be measured...so the HiLetgo had to be letgo.
I did research SE and found this question Vibration sensor for arduino but it does not answer my question.

not a question about Arduino ... your question is off topic here

The sensor is for an Arduino.

Did you try with a microphone module it might pick up back ground noise too, better to do a FFT hmm.  Microphone module has a prebuilt in op amp to give analog values dc biased because Arduino picks only dc voltage values.

The sensor is for an Arduino that does not make it an Arduino specific question ... the same sensor could be used on a Raspberry Pi or any other microcontroller .... it's similar to having a question about a camping trailer roof and asking at a Porsche site because you are using a Porsche to pull the trailer

It is unclear how exactly you measured with the piezoelectric sensor. A vibration is a wave, thus the piezoelectric sensor will give you that wave in a specific range. To get something like vibration amplitude you would need to do further processing of the data/wave. You can do this in your code by finding the min and max value in a time interval and calculating the difference

@jsotola Look its a sensor for my Arduino board. Plain and simple. Just like the tag that says "Sensor". Whats the point of a "sensor" tag in the Arduino forum? Is a question about an ESP32 also not valid?

@chrisl I was just doing an analogRead(onThePin).  Are you saying I need to say: Start a process of recording and then do the tetst. Stop. and the process the measurments?

A vibration is when the body moves rapidly back and forth. Thus the signal will also rapidly move back and forth. In fact - since you want to measure "how vibration waves move through different material" - the vibration wave is just a sound wave in that material. A sound wave is an oscillating signal (look at the wave from any song or speech that you have). The sensor just gives you this wave. If you want the amplitude of the wave you would need to measure the wave values for a specific amount of time (at least one period of the wanted frequency) and then calculate the diff between min and max

So basically the sensor was probably totally ok. You just need to interpret the data in the correct way.

@chrisl Makes total sense...will give it another go.

Whats the point of a "sensor" tag in the Arduino forum? ... it is for a questions like how to use sensor XYZ with an Arduino? or is sensor XYZ suitable for use with Arduino? ... it is not for which sensor should I use?

@jsotola Your not helping...as a matter of fact your rather rude and a hinderance. I never asked which sensor to use. I was asking for suggestions....not insults.

@ChrisCatignani I am not trying to insult you ... my apologies to you if it made you feel that way

I did some experiments a year or so ago to sense vibration through a (physical) office desk top using the inbuilt accelerometer and gyroscope of an Arduino Uno Wi-Fi Rev2. That chip is an LSM6DSM but I would think that any such module (e.g., MPU6050) connected to any Arduino could be useful.
There’s a good comparison article at Seeed Studios introducing vibration sensors for Arduino.
Update. Looking at the similar question linked by the OP I see several comments that the MPU6050 which I suggested  would have poor resolution. You may have to study data sheets (or experiment) to find the best  device for your purpose.
Second update. This white paper, “Measuring vibration with accelerometers” has some good engineering notes about selecting suitable accelerometers for different purposes.

Thanks for your answer...

The STMicro IMU chip can be set up in a number of ways.  It's complex enough to seek the benefits of using the STMicro IDE to simplify its configuration.  And that would put this project onto an STMicro development board (not an Arduino). The short of it is, we don't know what type of testing you are doing.  For example are you interested in detecting a hammer hit or are you interested in how long the vibration lasts and at what frequencies. The answers dictate how the IMU is setup or even if an IMU is a solution to your problem.

@st2000 Im wanting to measure the signal strength through various materials. For example...I would expect the signal to be higher through rock versus a sponge.

Briefly, IMUs are normally used for much slower changes in force.  A tilt compensating compass or in a quadcopter. I think you can speed up the sampling time in that STMicro IMU.  But I don't know if that will be enough.  I think STMicro also makes an "X" series of sensors w/smarts built in.  You might be able to program those STMicro sensor to detect vibrations specifically. If you are designing a product maybe this is worth looking into. If this is a one-off project, then maybe just adjusting the 801S's sensitivity and repeating the test.

@st2000 saying that “IMUs are normally used for much slower changes in force.” is maybe a generalization? The lsm6dsm I mentioned specifically has vibration monitoring listed as an application. There are also papers using  cheap sensors for vibration analysis (link to follow…)

e.g., https://www.researchgate.net/profile/Duc-Nguyen-113/publication/326032887_Low-Cost_Vibration_Measurement_for_Behavior_of_Small-Scale_Steel_Modeling_using_MEMS_Raspberry_Pi-3_and_Arduino_Mega_2560/links/5bad5b99299bf13e6051db9a/Low-Cost-Vibration-Measurement-for-Behavior-of-Small-Scale-Steel-Modeling-using-MEMS-Raspberry-Pi-3-and-Arduino-Mega-2560.pdf

Agreed. My thinking was vibrations in a bridge are slower than vibrations in a truck chassis are slower than vibrations in a jet engine.  And an IMU may not be the best choice if interested in the higher frequencies.  But I think I understand the end game a bit better now.  That's why I suggested repeating the test while adjusting the 801S's sensitivity.  Actually, I think I'd automate it having the Arduino controlling the 801S's pot using a controllable volume module.

@st2000 I follow you. That’s worth writing up as an answer.


text:
How can I SPI "Latch" (LE/CS/SS) for a specific number of SCLK cycles?
Context
I am working on a project which includes 13 cascaded STMicroelectronics LED1642GWs. These LED drivers are essentially 16bit shift registers, whereby the buffered serial data can be loaded to a number of different registers dependant on the required function.
The function is selected through the use of "digital keys", which is selected by number of CLK cycles for which the LE (CS/SS) pin is HIGH. For example, LE being HIGH for 1-2 CLK cycles will switch the 16 outputs as per the buffered bits, whereas LE being HIGH for 3-4 CLK cycles will load the 16 bits to a brightness register.

Question
How can I toggle my LE/CS/SS pin for a specific number of SCLK cycles? I had intended to use the SPI Libary, however I'm not sure this can be supported.
Many Thanks!

SPI works on bytes not individual clock cycles. You will have to bit-bang your own protocol.

Well it can still be write out as full bytes, "3-4 Clock Cycles" being written as 0x7 or 0xF for example (00000111 or 00001111). It's just writing out to LE which is the bit I can't figure.

Yeah, but you can only trigger your LE on multiples of 8 clock cycles. You will have to bit-bang your own protocol. It's not hard.

I've achieve this by "bit-banging" via a modified shiftOut() of ArduinoCore-avr/cores/arduino/wiring_shift.c, essentially allowing for two data lines on the same clocking:
void keyedShiftOut(
  uint8_t dataPin,
  uint8_t clockPin,
  uint8_t latchPin,
  uint8_t bitOrder,
  uint16_t val,
  uint16_t key)
{
    uint8_t i;

    for (i = 0; i < 16; i++)  {
        if (bitOrder == LSBFIRST) {
            digitalWrite(dataPin, val & 1);
            val >>= 1;
            digitalWrite(latchPin, key & 1);
            key >>= 1;
        } else {
            digitalWrite(dataPin, (val & 0x8000) != 0);
            val <<= 1;
            digitalWrite(latchPin, (key & 0x8000) != 0);
            key <<= 1;
        }

        digitalWrite(clockPin, HIGH);
        digitalWrite(clockPin, LOW);
    }
}

I used this to implement the sequence described within the data sheet (Figure 24. Brightness register setting) to set all of my 16 Brightness Registers to a half setting (0x7FFF) with a timed LE providing the digital key. This scoped out as:

Running on my Arduino Nano 33 IoT this clocked at 150kHz which is sufficient for my application.


text:
Pulsein() function blocks other tasks from running silmultaneously
I am using a zumo bot with a reflectance sensor used to follow a black line. I want to use an arduino to make the zumo bot stop once it gets a certain distance from an obstacle.
I have an ultrasonic sensor (HC-SR04) which ive connected to the bot.
Both of these tasks work independently but once i merge the code together(so it follows the line aswell as stoping when it detects an object using the ultrasonic sensor), it doesn't work properly.. (the zumo bot no longer follows the line)
I THINK it is to do with the pulsein() function blocking any other tasks but not sure.
My code is below. Can anyone help please?

#include <Wire.h>
#include <ZumoShield.h>

ZumoBuzzer buzzer;
ZumoReflectanceSensorArray reflectanceSensors;
ZumoMotors motors;
Pushbutton button(ZUMO_BUTTON);
int lastError = 0;

// This is the maximum speed the motors will be allowed to turn.
// (400 lets the motors go at top speed; decrease to impose a speed limit)
const int MAX_SPEED = 400;
#define echoPin A4
#define trigPin A5

// defines variables
long duration; // variable for the duration of sound wave travel
int distance; // variable for the distance measurement

void setup()
{
  reflectanceSensors.init();

  pinMode(trigPin, OUTPUT); // Sets the trigPin as an OUTPUT
  pinMode(echoPin, INPUT); // Sets the echoPin as an INPUT

  // Initialize the reflectance sensors module

  // Wait for the user button to be pressed and released
  button.waitForButton();

  // Turn on LED to indicate we are in calibration mode
  pinMode(13, OUTPUT);
  digitalWrite(13, HIGH);

  // Wait 1 second and then begin automatic sensor calibration
  // by rotating in place to sweep the sensors over the line
  delay(1000);
  int i;
  for(i = 0; i < 80; i++)
  {
    if ((i > 10 && i <= 30) || (i > 50 && i <= 70))
      motors.setSpeeds(-200, 200);
    else
      motors.setSpeeds(200, -200);
    reflectanceSensors.calibrate();

    // Since our counter runs to 80, the total delay will be
    // 80*20 = 1600 ms.
    delay(20);
  }
  motors.setSpeeds(0,0);

  // Turn off LED to indicate we are through with calibration
  digitalWrite(13, LOW);

  // Wait for the user button to be pressed and released
  button.waitForButton();

  Serial.begin(9600); // // Serial Communication is starting with 9600 of baudrate speed
  Serial.println("Ultrasonic Sensor HC-SR04 Test"); // print some text in Serial Monitor
  Serial.println("with Arduino UNO R3");

}

void loop()
{

  unsigned int sensors[6];

  // Get the position of the line.  Note that we *must* provide the "sensors"
  // argument to readLine() here, even though we are not interested in the
  // individual sensor readings
  int position = reflectanceSensors.readLine(sensors);

  digitalWrite(trigPin, LOW);
  delayMicroseconds(2);
  // Sets the trigPin HIGH (ACTIVE) for 10 microseconds
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);
  // Reads the echoPin, returns the sound wave travel time in microseconds
  duration = pulseIn(echoPin, HIGH);

  // Our "error" is how far we are away from the center of the line, which
  // corresponds to position 2500.
  int error = position - 2500;

  // Get motor speed difference using proportional and derivative PID terms
  // (the integral term is generally not very useful for line following).
  // Here we are using a proportional constant of 1/4 and a derivative
  // constant of 6, which should work decently for many Zumo motor choices.

  int speedDifference = error / 4 + 6 * (error - lastError);

  lastError = error;

  // Get individual motor speeds.  The sign of speedDifference
  // determines if the robot turns left or right.
  int m1Speed = MAX_SPEED + speedDifference;
  int m2Speed = MAX_SPEED - speedDifference;

  if (m1Speed < 0)
    m1Speed = 0;
  if (m2Speed < 0)
    m2Speed = 0;
  if (m1Speed > MAX_SPEED)
    m1Speed = MAX_SPEED;
  if (m2Speed > MAX_SPEED)
    m2Speed = MAX_SPEED;

  motors.setSpeeds(m1Speed, m2Speed);

  //if (distance <20){
  //  motors.setSpeeds(0,0);
 // }

////////////////////////////////////////////

  // Calculating the distance
  distance = duration * 0.034 / 2; // Speed of sound wave divided by 2 (go and back)
  // Displays the distance on the Serial Monitor
  Serial.print("Distance: ");
  Serial.print(distance);
  Serial.println(" cm");

}

It is quite likely due to blocking. The description of the pulseIn() function in the Arduino site's reference section says:

Reads a pulse (either HIGH or LOW) on a pin. For example, if value is
HIGH, pulseIn() waits for the pin to go from LOW to HIGH, starts
timing, then waits for the pin to go LOW and stops timing. Returns the
length of the pulse in microseconds or gives up and returns 0 if no
complete pulse was received within the timeout.

If you can limit the range within which you want to stop the vehicle, try setting a timeout on pulseIn() that will return control once the maximum sound travel time has passed. Maybe that will give you enough response to correct the vehicle's steering. Slowing the vehicle's velocity will help, too (it won't be able deviate as far from it's path as quickly).
Otherwise, you'll probably need a non-blocking equivalent to pulseIn().

There’s an article on this topic here https://roboticsbackend.com/arduino-pulsein-with-interrupts/

Thank you so much! this answer really helped and finally fixed the issue using your advice. Thanks again!


text:
Per-Arduino calibration files?
I am planning on having an array of embedded devices in my garden, and each of these is going to have its own analog moisture sensor. Each moisture sensor needs to be individually calibrated.
In an ideal world, I would have the same software on each embedded device, with a configuration file holding the calibration for the attached analog moisture sensor, so that I can minimize the development and CI/CD work.
Is this possible with Arduino, or would I be better off with an embedded device with addressable flash, like an ESP32?

You may try to use the embedded EEPROM.

If the embedded EEPROM is too small, there are many serial EEPROMs for the SPI and I²C bus, giving you lots of non-volatile memory.

there are some misconception in your question. esp32 can be used with Arduino too. there are many different Arduinos with different not-volatile memory capabilities. you have to be more specific,

i would put a pot on-device since the calibration changes as the sensors oxidize and wear out (which happens in several months, even when not actively powered). They are not very accurate anyway, swinging 10% on back to back readings is considered good for all but brand new sensors.

As Edgar Bonet already mentioned, the embedded EEPROM is good to try. I give some options below though:

In case the configuration file (data) is max. 1 KB, you can use the embedded/internal EEPROM of the Arduino UNO.
In case the configuration file is larger you have multiple options:

On the ESP32 you can use 4 KB EEPROM.
If it is higher, on the ESP32 you also can use the SPIFFS file system stored in EEPROM.
For other MCUs (ESP32 included), you can use external EEPROM with various sizes, based on SPI or I2C.

If you want to use a very large configuration file, you could use an SD card, which is much slower of course, which is normally SPI based and can be used on both Arduino and ESP32.

So for a comparison between Arduino Uno / ESP32
MCU         Solution            Speed Size   External    Wearout
                                             Hardware
----------- ------------------  ----- ------ -------- --------------
Arduino     Internal EEPROM     High  1 KB      No    EEPROM Wearout
ESP32       EEPROM Simulation   High  4 KB      No    Flash Wearout

ESP32       SPIFFS File System  High  <Flash    No    Flash Wearout
                                      Size

Both        External EEPROM     High  <1MB *   Yes    EEPROM Wearout
Both        SD Card             Slow  <256GB   Yes          -

*Typically 4 KB to 1 MB, using SPI or I2C


text:
sim800l ftp error after http request
I am using esp32 CAM by Arduino IDE and send an image file by ftp using SIM800l GSM/GPRS  module  to a server and every thing is ok .
I can perform http request also and read some data from a website and every thing is ok.
Problem is ftp for large file  and http request can not work at the same time .
if I send AT+HTTPINIT after AT+FTPEXTPUT=1 , it fails
or if I send AT+FTPEXTPUT=1  after  AT+HTTPINIT again it fails .
I close http connection by AT+SAPBR=0,1 but problem exist
How to solve this problem?
How is possible to clear the setting done in the  the sim800l without restarting the module by AT+CFUN=1,1 ?

I found the way to solve the problem .
Http request must be terminated with command AT+HTTPTERM . After this command large ftp works and command AT+FTPEXTPUT=1 is without error . After termination of ftp if we want to do http request again the command AT+FTPEXTPUT=0 must be executed


text:
VSCode vs. Arduino IDE - same program, different behavior
I've got this simple program for testing DS18B20 temperature sensors.
#include "OneWire.h"
#include "DallasTemperature.h"

#define ONE_WIRE_BUS D3

// Setup a oneWire instance to communicate with any OneWire devices (not just Maxim/Dallas temperature ICs)
OneWire oneWire(ONE_WIRE_BUS);

// Pass our oneWire reference to Dallas Temperature.
DallasTemperature sensors(&oneWire);

void setup()
{
  Serial.begin(19200);
  sensors.begin();
  delay(1000);  //time for serial to connect
  Serial.print(sensors.getDeviceCount());
  Serial.println(" sensors found");
  Serial.print(sensors.getDS18Count());
  Serial.println(" DS18 sensors found");
}

void loop()
{
  sensors.requestTemperatures(); // Send the command to get temperatures

  Serial.print("Temperature for Device 1 is: ");
  Serial.println(sensors.getTempFByIndex(0));

  Serial.print("Temperature for Device 2 is: ");
  Serial.println(sensors.getTempFByIndex(1));

  delay(5000);

}

I'm compiling for the Wemos D1 mini.
When I compile on the Arduino IDE, the code runs as expected. It reports two devices, then gives the temperature reading from each device.
When I compile using VSCode and the Arduino extension, the code compiles and uploads successfully, the program reports 2 devices, just like the Arduino IDE compilation does, but then it prints -196.60 for the temperature reading, which is the "no device" value.
Same breadboard, same host computer - the only difference is the IDE. I'd much prefer to stick with VSCode, but if the resulting executable is wrong, then it's a non-starter.
Why the different results? More importantly, how do I get the VSCode to produce the same (correct) output as the Arduino IDE?
UPDATE:
Apparently the issue has something to do with the serial monitor. The project I'm actually trying to build has an OLED display for the temperature. The temperature is correct if the VSCode serial monitor is closed. Open the monitor and the incorrect values appears. Close the monitor and the correct values appear again.
UPDATE 2:
The problem remains over a range of serial port speeds, from 19200 to 115200. I didn't try outside that range.
UPDATE 3:
Code compiled using VSCode but run observing through the Arduino IDE serial monitor has the correct behavior - ie, shows the correct temperatures.

what is your question?

What do you want to know? -- "Why is this?" can be quite difficult to answer, while "How to avoid?" is already answered by yourself. -- Since you have not shown the source with the display code, we cannot say anything on that case. Please [edit] your question.

Looks like an issue worth reporting to whoever maintains the Arduino extension for VSCode.

Originally developed by Microsoft, the Arduino extension for vscode reportedly went open source circa 2017. It looks like the repository on GitHub takes bug reports https://github.com/Microsoft/vscode-arduino/issues

There is discussion in some of the error reports at the GitHub repository regarding ongoing instability with the VSCode serial monitor and some ‘fairly significant’ code changes they’re working through.

@EdgarBonet - I've submitted an issue to the github repo for the project.

@RowanP - I've submitted an issue to the github repo for the project

Further testing by OP isolated a bug in the Arduino Extension for VSCode which was logged as an issue at https://github.com/microsoft/vscode-arduino/issues/1467


text:
LiquidCrystal issue with HD44780 display
Here my sample code for an Arduino Leonardo-based custom board:
#include <LiquidCrystal.h>

const int rs = 3, en = 0, d4 = 4, d5 = 30, d6 = 12, d7 = 6;
LiquidCrystal lcd(rs, en, d4, d5, d6, d7);

void setup()
{
  pinMode(2, OUTPUT);
  digitalWrite(2, LOW);

  Serial.begin(115200);

  lcd.begin(16, 2);
  lcd.print("Hello world");
}

void loop()
{
}

And here my schematic:

The MCU is an ATmega32U4.
Running the code above the display is completely empty, I also tried to change the values of R4 and R5 but nothing changes. I don't see anything, not even the background of each character.
The display is a common HD44780 compatible one.
I retrieved the pin numbers from here:

/opt/arduino-1.8.19/hardware/arduino/avr/variants/leonardo/pins_arduino.h

Am I missing anything?

R4/5 should be a potentiometer not fixed resistors.

is the backlight lit? .... please post pictures of front and back of the LCD module

The schematic pin assignments do not match the Arduino Pin definitions you used in your code. Please see Arduino PinMapping32u4 or read the correct pin mapping for Leonardo from the source code.

@hcheung gosh, I used exactly those two documents to retrieve the pin assignment! Would you please tell me what is wrong? PD0=3, PD2=0, PD4=4, PD5=30, PD6=12, PD7=6. This is what I read from the header file.

@hcheung I confirm the assignments are correct! There was only a hardware problem as "the busybee" pointed out

Sorry, my bad, I didn't realise that your d5 is means PD5 and 30 means D30.

The error is, that V0 has VDD level by the way you connected the resistors. The "lower end" of your ladder needs to be at GND, pin 1.
The pin 15 (A) is the anode of the backlight, and is not connected to the LCD driver circuit. BTW, to lit the backlight, you need to connect pin 16 (K), too. See the data sheet for details.
Use a potentiometer for V0, wiper to V0 and the ends to VDD and GND, respectively.
Just a side note: From the back of my memory, V0 can be commonly connected by a single resistor or directly to GND, since the wiper of the potentiometer was mostly at the GND end. It will give some contrast, depending on the temperature.

I'm trying right now and I'll write back soon. I assumed Vee was the negative rail, my fault. I don't want to put a pot otherwise I need to tune each board. I'm going to experiment and find the correct resistors ratio at room temperature.

It works. With Vo = GND the contrast is perfect.


text:
How do I modify the value of a variable when I press a switch
I am new to arduino and I want to make a project where I have a motor spinning clockwise then when a button is pressed it spins anti-clockwise and if it is pressed again it goes back to clockwise etc... Unfortunately I am having trouble getting this to work. How I was aiming to make it work was to have a variable and whenever a button is pressed the value of that variable changes from HIGH to LOW to HIGH and so on and based on that variable the motor spins in either direction. I have got this code so far:
const int buttonPin = 8;     // the number of the pushbutton pin

// variables will change:
int buttonState = 0;         //variable to change status

void setup() {

 Serial.begin(9600);
 pinMode(buttonPin, INPUT);
}

void loop() {
 // read the state of the pushbutton value:
 buttonState = digitalRead(buttonPin);
 Serial.print("Digital value: ");
 Serial.println(buttonState);
 delay(150);
}

so, what is your question? ... you are doing good so far

use the Bounce2 library to read the button

You've made a good start by first working with the button by itself (no motor) to keep your experiments simple. You've probably noticed that buttonState changes when you press or release the button, where your description says you want it to change each time you press the button. That means you have to ignore the releases, and invert the buttonState only on the presses.
Make that change next.
When you test that, you may discover that the buttonState changes several times when you press it once. Mechanical switches may make/break... several times at each change. (It's called bouncing even though it isn't "bouncing" but the two contacts grating across one another. The result is the same.) There are several ways to deal with that, but the simplest is to wait 20-30 milli-seconds after you first see a change; read it again, and if it is still in the new state, accept that, otherwise ignore it. That time delay is approximate; you might need to adjust it for a particular button.
Once you've decided that the button really has been pressed, then change the direction of the motor.

Thank you that is a good explanation

I would recommend that you "debounce" the button input first. Instead of re-inventing the wheel, you could use an existing library: Bounce2.
Using the conditioned input, you could simply manipulate a counter to determine state.
// Connect one end of a N.O. push button switch to
// GND and the other end to pin 2 of the Arduino.
#include <Bounce2.h>
byte buttonState = 0;
const byte modeButtonPin = 2;
const unsigned long debouncerInterval = 50;  // Time in ms.

Bounce modeButton = Bounce();

void setup(){
  Serial.begin(9600);
  pinMode(modeButtonPin, INPUT_PULLUP);
  modeButton.attach(modeButtonPin);
  modeButton.interval(debouncerInterval);
}

void loop(){
  if(modeButton.update()){
    if(modeButton.read() == 0){
      buttonState++;
      if(buttonState > 1){buttonState = 0;}
      Serial.println(buttonState);
    }
  }
}

First I would make create an enumeration type and motor direction variable (instead of the button state):
enum EMotorDirection
{
    CLOCK_WISE,
    COUNTER_CLOCK_WISE
}

EMotorDirection _motorDirection = CLOCK_WISE;

Then read the button and when it has changed (make a variable `_previousButtonState), adjust the motor direction.
int _previousButtonState = LOW;

In the loop function:
int buttonState = digitalRead(buttonPin);
// Debounce buttonState;
if (buttonState != _previousButtonState)
{
   if (_motorDirection == CLOCK_WISE)
   {
       _motorDirection = COUNTER_CLOCK_WISE;
   }
   else
   {
       _motorDirection = CLOCK_WISE;
   }
   SwitchMotorDirection();

   _previousButtonState = buttonState;
}

And create the function SwitchMotorDirection
void SwitchMotorDirection()
{
   if (_motorDirection == CLOCK_WISE)
   {
       // Control motor clock wise
   }
   else
   {
       // Control motor counter clock wise
   }
}

The above example is not compiled, and also it could be smaller, but serves as a explanatory example, with the advantage to separate the UI (button), state machine (state variable), and hardware (motor).
Below is the complete code, which compiles. The bouncing has to be implemented (check the link for that above), and the actual motor driving.
// Types

enum EMotorDirection
{
    CLOCK_WISE,
    COUNTER_CLOCK_WISE
};

// Constants
const int _buttonPin = 8;     // the number of the pushbutton pin

// Global variables
int             _previousButtonState = LOW;
EMotorDirection _motorDirection      = CLOCK_WISE;

// Function prototypes
void SwitchMotorDirection();

// Functions

void setup()
{
  Serial.begin(9600);
  pinMode(_buttonPin, INPUT);
}

void loop()
{
  int buttonState = digitalRead(_buttonPin);
  // Debounce buttonState;
  if (buttonState != _previousButtonState)
  {
     if (_motorDirection == CLOCK_WISE)
     {
         _motorDirection = COUNTER_CLOCK_WISE;
     }
     else
     {
         _motorDirection = CLOCK_WISE;
     }
     SwitchMotorDirection();

     _previousButtonState = buttonState;
  }
}

void SwitchMotorDirection()
{
   if (_motorDirection == CLOCK_WISE)
   {
       // Control motor clock wise
   }
   else
   {
       // Control motor counter clock wise
   }
}

I am very new and I have no idea how to compile this could you maybe tell me?

I added the code which compiles.


text:
Wired Teensy 3.5 AudioShield and RFID RC-522
I received a set of wired Teensy 3.5 AudioShield and RFID RC-522.
The audio shield is mounted on the Teensy but I cannot connect the MFRC522
Using MFR222 library. Pins are set to 0 and 31:
#define RST_PIN         0          // Configurable, see typical pin layout above
#define SS_PIN          31         // Configurable, see typical pin layout above

MFRC522 mfrc522(SS_PIN, RST_PIN);  // Create MFRC522 instance

Getting:
Firmware Version: 0x0 = (unknown)
WARNING: Communication failure, is the MFRC522 properly connected?
Scan PICC to see UID, SAK, type, and data blocks..

Tried any other combination I can think of.
Checked all soldered points.
I did not find any guide on how to connect teensy 3.5 with RC522. only older versions.
Do I need to tell the library where to find the other pins (MISO, MOSI...)
Any help will be appreciated.
Thanks
Yehuda

the wiring diagram does not show a ground connection to the teensy

The teensy is mounted to audio, wired to RFID, and connected via USB to PC. Do I need to add another wire?

The answer is (as far as I understand) that when both audio shield and rfid are mounted, they have protocol collision  (same protocol for both). So if you want them to work. You need to wire rfid to different pins.


text:
Poor man's serial sniffer: reading Serial.print logs of an Arduino esp32 dev kit from another
(I use ESP32 dev kits with Arduino api.)
My dev kit 1 is running my firmware; and I want to measure the current it draws, therefore I don't like to plug the USB in.
As I need to read the logs from the dev kit 1, I want to plug another dev kit that collects the log from the first through the UART.
The dev kit 1 firmware is as it is, but on the dev kit 2, I wrote such a thing:
#include <Arduino.h>
#include <Hardware.h>

HardwareSerial Reader();

void setup() {
    Serial.begin(115200);
    Reader.begin(115200, SERIAL_8N1, 16, 17);

}

void loop() {
    while(Reader.available()) {
        Serial.print(Reader.read());
    }
}

The wiring is as follows:

Dev kit 1
Wiring
Dev kit 2 (sniffer)

TXD
<=>
RXD (16)

RXD
<=>
TXD (17)

GND
<=>
GND

But this doesn't work, that is I can't see anything on the dev kit 2 serial on my computer.
Any idea?
[UPDATE] As suggested by @juraj, I simply wire TX to TX, RX to RX and GND to GND and removed the Serial.begin(115200) from the firmware running on dev kit 1.
Dev kit 2 firmware is as simple as:

void setup() {
  Serial.begin(115200);
  //Serial.printf("Serial2 logger RX (%d)<=>TX & TX(%d)<=>RX @ 115200 bauds", RX, TX); Serial.println();
}

void loop() {
  static unsigned lastHeartbeat = 0;

  const unsigned now =millis();
  if (now-lastHeartbeat > 4000) {
    lastHeartbeat = now;
    Serial.println("Heartbeat");
  }
}

Note that on dev kit 1, I commented out the line Serial.begin(115200).
No kit 1 logs appears on my computer.
The wiring of this setup:

But this doesn't work is not a useful description of any problem ... what were you expecting to happen? ... what actually happens?

As you just want to forward the serial data, don't use print() but write() in your sketch. Otherwise print() will interpret the data before sending and you just want to forward the raw data. With TXD and RXD I guess you mean (depending on the notation) TX0 and RX0 (or U0_TXD and U0_RXD), so GPIO1 and GPIO3 on the firmware board?

yep, TXD is TX0 is GPIO1 and RXD is RX0 is GPIO3. I could craft a macro to transform the prints in write, but then it should be easier to hook an ISR and write to the pins myself. What do you think?

Serial.write(Reader.read());

if you just wire RX to RX and TX to TX the CH340 on the dev board will read it directly and send to USB. upload Blink or any other sketch without Serial.begin into the esp32

HardwareSerial Reader(); should be HardwareSerial Reader;

@juraj I tried this but nothing is received. The USB logger do not show any logs. I update the question with a simple board wiring photo, just in case I did something wrong.

I finally managed to make it work.
The final wiring:

Kit 1
kit 2

The firmware to spy
The firmare that spys

RXD
17

TXD
16

GND
GND

The spying firmware uses Serial2

#define USE_READER true

#if USE_READER
#define USE_SERIAL2 true

#if USE_SERIAL2
    #define TX 17
    #define RX 16
    #define Reader Serial2
#else
    #include "SoftwareSerial.h"
    #define TX 12
    #define RX 13
    SoftwareSerial Reader;
#endif
#endif

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

#if USE_READER
  Serial.printf("Serial logger RX (%d)<=>TX & TX(%d)<=>RX @ 115200 bauds", RX, TX); Serial.println();

  #if USE_SERIAL2
  Reader.begin(115200);
  #else
  Reader.begin(115200, SWSERIAL_8N1, RX, TX, false);
  #endif
  #endif
}

void loop() {
  static unsigned lastHeartbeat = 0;

  const unsigned now =millis();
  if (now-lastHeartbeat > 4000) {
    lastHeartbeat = now;
    Serial.println("Heartbeat");
  }

  #if USE_READER
  if (Reader.available()) {

    Serial.write(Reader.read());
  }
  else {
    #endif

    //Serial.print(".");
    delay(500);

    #if USE_READER
  }
  #endif
}

The spied firmware
You leave it as it is. Don't remove Serial.begin(115200);.
The breadboard photo:


text:
Servo keeps resetting position when there is no difference in received value?
So I'm working on a code that basically receives x and y coordinates and stores them in a variable. Whenever a coordinate is received, it goes through a conditional statement to store them in a variable, x and y, then passes it to a servo mover function. This servo motor function then moves according to what's given. It works well, but, as the values get updated over time, the servo' position always resets then goes back to where it was, again and again. Even when the coordinates are kept the same, it just resets then returns to its position over and over again.
How do I make it so that not only does it not reset then return to where it was but instead make it move to where it is supposed to go, but also to stop it from resetting anyway when the position is kept the same?
The below code is what I tried to do to basically alleviate the "position reset when coordinate is the same" issue. Unfortunately, it did not work.
bool constant = false;
// Rest of code inbetween, irrelevant to issue

// Relevant codes below
void statusCodes() {
  if (received_str == "1") {
    Serial.println("Raspberry Pi - Connection Established");
  } else if (received_str == "2") {
    Serial.println("Raspberry Pi - Data Received");
  } else if (received_str == "100") {
    Serial.println("Raspberry Pi - Status OK");
  } else if (received_str[0] == '(' ) {
    Serial.println("Coordinates Received, Ready to Delete Target!");
    if (constant == true) { // checks if this constant boolean is true
      movement = false;
    } else {
      movement == true;
    }
    int r = sscanf(received_str.c_str(), "(%d, %d)", &x, &y);
    Serial.print("X: ");
    Serial.println(x);
    Serial.print("Y: ");
    Serial.println(y);
  }
}

void onDetectTarget() {
  x = map(x, 0, 1023, 0, 180);
  y = map(y, 0, 1023, 0, 180);
  if (movement == true) {
    for (pos = 0; pos <= x; pos += 1) {
      myservo.write(pos);
      delay(15);
    }
    movement = false; // corrected
    pos = 0; // corrected

  }
}

void compareOldNew() {
  x_old = x;
  y_old = y;
  delay(900);
  if (x == x_old && y == y_old) {
    constant = true;
  } else {
    constant = false;
  }
}

In onDetectTarget() you use this for loop
for (pos = 0; pos <= x; pos += 1) {
  myservo.write(pos);
  delay(15);
}

So every time movement is true, the servo will run again from zero to the target position. So it won't "reset", but it will approach the new target value always from the zero position. You have two options to correct that:

If you just want to reach the target position, just replace the for loop with a single myservo.write(x).

If you want the servo to move slower to its new target position, you need to save the last set position of the servo in a variable and then run the for loop from that value up to the new target value. So declare a corresponding variable (for example on global scope):
  int current_pos = 0;

Then run the for loop from that position to the new target position:
  for(pos = current_pos; pos <= x; pos += 1)

And after the for loop you can set current_pos to the new servo position:
  current_pos = x;

And I guess this happens also, when the values don't change, because you never change the constant variable. You haven't implemented any check if the values are constant. (At least you haven't shown such a code and you claim the rest of the code is irrelevant)

Thanks for your response man, that was really helpful. I thought I had to use a for loop to constantly write the value but with your explanation, everything made more sense to me. As for detecting the same position, i later researched and found that you could basically use static variables to store older values, compare them and have a flag to see if they were equal or not.


text:
Using Arduino to allow continuous servo to go in the opposite direction
For my project I am using 6 continuous servos connected to an Adafruit Servo Shield. To run them I use
pwm.setPWM(0, 0, 1000)
and then set a delay to run them for how long i’d like to, then run
pwm.setPWM(0, 0, 0)
to stop it.
I would like to run the servo in the opposite direction. How would I do this?

You probably already know that continuous servos are different to other hobbyist servos in that they rotate freely, and the PWM signal is used to control speed and direction of rotation.
The specific model of servo you're using is important and you'll need to refer to the datasheet to find out its details. Particulalry the servo's minimum (typically clockwise rotation); mid-point (neutral / no rotation); maximim (usually counter clockwise rotation) PWM pulsewidths. The mid-point is often set by a PWM pulsewidth of 1500 microseconds, but this can vary and it pays to check.
The library you referenced does implement a setPWM() function as you mentioned, however you'll note that it works in a range of ticks from 0 to 4095. The two parameter values set when to turn the PWM pulse on and off expressed as values from 0 to 4095. To use this function you'll need to map these parameters to produce the PWM signal the servo is expecting.
I recommend an alternative, using the writeMicroseconds() function of the same library, which accepts a value in microseconds for which the PWM signal will be high. You'll be able to obtain these directly from the datasheet.
In your question you mention using a PWM of approximately 25% duty cycle (1000/4095) for ON. This is likely much longer than the desired maximum for your servo which if it is 2000 microseconds, might need a value something like 430 (/4095). Similarly you mentioned a zero pulse to achieve a stop. I think this library uses zero as a special case for no PWM pulse. You said this generates a stop condition for your servos, but finding the neutral value may be better.
Rather than figuring out the maths for setPWM() to turn on and off the PWM pulse, the writeMicroseconds() function may be easier.
You'll need to check datasheets for your servos but a value of 1500 microseconds should be near neutral / no rotation. Decreasing values less than this should generate increasing speed clockwise. Increasing values greater than neutral should generate increasing speed counter clockwise.


text:
Trying to understand the bottleneck of sensor sampling rate
Lets say I have a sensor connected to Arduino Uno Rev3's I2C Bus. I am reading the sensor output and using Serial.print() to send the sensor reading back to a my laptop.
I am trying to understand the bottlenecks that limits the sensor sampling rate received at the laptop.
The sampling rate of the sensor depends on many factors. Lets assume sensors sampling rate is not limited. That would mean I am limited by how much data each intermedia bus can carry before it reaches the laptop. For example, I am limited by I2C bus atmega328p is using to read the sensor data. I am also limited by the UART bus atmega16u2 is using to send the data to my laptop. Am I correct so far? Also, on what bus atmega328p and atmega16u2 are connected over?

refer to the sensor datasheet

Are you using I2C Fast Mode (400kHz) (if the sensor is even capable of that)? If not, then the I2C interface is probably the bottleneck (assuming that the sensor samples fast enough)

@chrisl I am using MPU6050 on I2C 400KHz. On Spec, the sensor can sample from 4 to 1kHz, but I am applying a digital low pass filter that adds 19ms delay. So the sensor sampling rate is too slow already. But still I am trying to understand the intermediate steps so better understand the hardware.

If there had been a specific scenario you were considering, it might help to share. There's quite a lot to think about with just theoretical assumptions.

That would mean I am limited by how much data each intermedia bus can carry before it reaches the laptop

Yes, mostly yes. The bandwidth of the entire transmission interface which includes the I2C interface, ATMEGA328P, connection to ATMEGA16U2, and the USB interface would account for the theoretical max sampling rate of the sensor.
For some cases, you may need to consider the latency as well as the bandwidth of the transmission media, which would include the I2C interface, ATMEGA328P, ATMEGA16U2, and the USB interface. The sensor may require some calculations which may result in some delay. The I2C interface or the UART interface could introduce some delay too, especially if it's driven by bit-banging(although probably not with 328P).
Also from 328P's perspective here, it has to receive data from the sensor, make calculations from the incoming raw data if needed, and send over the UART interface to the 16U2. Most of these processes will happen step by step and if the combined processing time takes longer than the delay between each sample coming from the sensor, the 328P itself could theoretically be a bottleneck too.

Thanks for the detailed answer. That cleared things up.

Also, on what bus atmega328p and atmega16u2 are connected over?

See:
https://www.arduino.cc/en/uploads/Main/Arduino_Uno_Rev3-schematic.pdf
They are connected by TxD and RxD.
Without seeing your code (hint) it is extremely difficult to say. Perhaps a faster baud rate would help.

Thanks, I just wanted to know that atmega16u2 and atmega328p are connected via UART.  Do Serial.begin also set the baud rate of this connection as well?

@QuaziIrfan, only there

@Juraj Sorry, I don't get what you mean.

@QuaziIrfan, USB line doesn't use that baud rate

So, is there a fixed baud rate that's set during the manufacturing process?

USB doesn't have a baud rate. It's all quite complex, but the protocol involves NRZI (search for stuff about that). However when you do a Serial.begin you set the baud rate of the USB interface chip. That is, the rate at which it expects data from the Atmega328p. The USB interface will be able to handle virtually any baud rate you choose to set.


text:
ESP8266: ESPASyncserver + client
I have project with an ESPAsyncWebServer with websockets working already. What I need to add is Client functionality to poll a site for a response. I looked at the ASyncTCP library and it has two different implementations that aren't well documented in how to use.
There's the SyncClient option that looks like this:
  SyncClient client;
  if(!client.connect("www.google.com", 80)){
    Serial.println("Connect Failed");
    return;
  }
  client.setTimeout(2);
  if(client.printf("GET / HTTP/1.1\r\nHost: www.google.com\r\nConnection: close\r\n\r\n") > 0){
    while(client.connected() && client.available() == 0){
      delay(1);
    }
    while(client.available()){
      Serial.write(client.read());
    }
    if(client.connected()){
      client.stop();
    }
  } else {
    client.stop();
    Serial.println("Send Failed");
    while(client.connected()) delay(0);
  }

I don't know if i'm supposed to put code after a client.connected() or client.available()? Of if I need the full structure as shown or just one of the commands. It also doesn't show all the commands and syntax available (such as an equivalent for client.write(), client.print or the like).
Then there is the simply named ClientServer > Client which only has the following:
static void replyToServer(void* arg) {
    AsyncClient* client = reinterpret_cast<AsyncClient*>(arg);

    // send reply
    if (client->space() > 32 && client->canSend()) {
        char message[32];
        sprintf(message, "this is from %s", WiFi.localIP().toString().c_str());
        client->add(message, strlen(message));
        client->send();
    }
}

/* event callbacks */
static void handleData(void* arg, AsyncClient* client, void *data, size_t len) {
    Serial.printf("\n data received from %s \n", client->remoteIP().toString().c_str());
    Serial.write((uint8_t*)data, len);

    os_timer_arm(&intervalTimer, 2000, true); // schedule for reply to server at next 2s
}

void onConnect(void* arg, AsyncClient* client) {
    Serial.printf("\n client has been connected to %s on port %d \n", SERVER_HOST_NAME, TCP_PORT);
    replyToServer(client);
}

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

    // connects to access point
    WiFi.mode(WIFI_STA);
    WiFi.begin(SSID, PASSWORD);
    while (WiFi.status() != WL_CONNECTED) {
        Serial.print('.');
        delay(500);
    }

    AsyncClient* client = new AsyncClient;
    client->onData(&handleData, client);
    client->onConnect(&onConnect, client);
    client->connect(SERVER_HOST_NAME, TCP_PORT);

    os_timer_disarm(&intervalTimer);
    os_timer_setfn(&intervalTimer, &replyToServer, client);
}

This doesn't tell me a whole lot about how to use this library.
I need some guidance on how to deploy the client alongside my server. I don't need much, just listen for server directive, parse it and then send a response (client.println) or upload a file (client.write). I'd like to implement the asynchronous version of this.

It is actually well-documented and plenty of examples online on how to use it. client.connect() establish a TCP connection, it is up to you implement your own http request with client.print or client.printf in according to http protocol, you can add http headers, POST or GET as per your need. The http response can be read with client.read(), it is up to you on how you want to capture it (e.g. reading into a buffer and parse it) or simple print it on Serial Monitor(as show in the example code).

If you don't want to handle the http creation and parsing, you can use ESP8266HTTP client which provide simpler API.


text:
how accurate is the calculation in stm32?
I have a project plan in which there are calculations that require high precision, which later will have calculations with numbers after commas such as 245.5431657288. from some of the information that I read to make the project a success it must use 32 bytes, initially I wanted to use arduino due, but for some reasons I was more interested in using STM32 but my knowledge of STM32 is not much, especially in terms of the level of precision calculation, therefore I ask is STM32 suitable for my project? I hope my question can be understood, thank you.

not an arduino question

numbers after commas ...  do you mean numbers after the decimal point? ... a comma is , ... those are called decimal places ... 245.5431657288 has 10 decimal places in the fractional part

you could convert to integer by multiplying ... 245.5431657288 becomes 2455431657288, which is hexadecimal 23B B321 B748 ... that fits into 43 bits

There are multiple arduino compatible devices based on STM32 architecture. Understanding the precision of the various CPU offerings is key to making proper design choices. I believe this question is on topic.

There is an intro to floating point units(fpu) for STM32 MCUs at https://www.st.com/resource/en/application_note/dm00047230-floating-point-unit-demonstration-on-stm32-microcontrollers-stmicroelectronics.pdf

You have to look for a platform that supports double-precision floating point, i.e. 64-bit floats. According to RowanP's link, some STM32 do. Or you could do 64-bit fixed point on any Arduino, but that may not be easy.

The hardware does not affect the precision. The software affects the precision. The hardware affects the efficiency of processing at different precisions.

The hardware makes no difference to the accuracy of calculations. That is purely down to the software - whether you use single or double precision floats, whether the compiler flags disable double precision to save space (as some 8 bit configurations do), etc.
The choice of hardware only affects the efficiency of the processing at different precisions, such as if there is an FPU, or what precision the FPU can operate at (using precisions outside the range of the FPU will only affect speed not precision).
Both the stm32 and due are ARM based MCUs, so any differences will be down to what additions there are in any specific chip (such as FPU).

As far as I know, only the AVR compiler by default disables double precision. For other architectures, I would assume that if the hardware has no (or limited) FPU support, the compiler would emit emulation code (as was common for x86 as well, before they included FPUs)

I just checked the gcc for AVR: That compiler has software support for double. I'm not sure if the Arduino tool suite uses the gcc compiler; however it would be possible to use the gcc compiler with Arduino Uno and similar devices instead of the "official" one.

@MartinRosenau Depending on what version of the core it may have a command line option enabled that forces singe-precision when double is used.


text:
How do I debounce multiple external interrupt buttons?
I have an Arduino sleeping most of the time to save power and there are two buttons attached to different interrupt pins that run different functions.  These functions are different from each other, but both have to run long blocking code.  I don't want the button bouncing (or even deliberately being pressed multiple times during the blocking code) to queue up multiple runnings of the interrupt function.  I also don't want the sleep period to be short because I'm trying to keep if off as much as possible to save power.  I don't want to have to wait 8 seconds after a button press before the button's action happens.  As such, I would think flags or polling the pins from the main loop are not the way to handle this because of power inefficiency and long latency between button press and action.  Should I have each ISR detached its own interrupt pin until its action is complete and then reattach?
const int buttonA = 6;
const int buttonB =  10;

void setup() {
  pinMode(buttonA, INPUT_PULLUP);
  pinMode(buttonA, INPUT_PULLUP);
  attachInterrupt(digitalPinToInterrupt(buttonA), actionA, FALLING);
  attachInterrupt(digitalPinToInterrupt(buttonB), actionB, FALLING);
}

void loop() {
  sleep_function();  //takes 8 seconds
}

void actionA(){
  //some blocking code that takes 2 seconds, but that I want to run immediately upon button press
}

void actionB(){
  //some blocking code that takes 10 seconds, but that I want to run immediately upon button press
}

the blocking code is like having one driver with one vehicle, and without a cell phone, picking up packages

When using interrupt, I personally prefer to use hardware debouncing with a RC circuit and a Schmitt Trigger. See "RC Debouncer" section of Jack Ganssle's A Guide to Debouncing.

do not do action on button press ... insert a layer of separation between a button press and the desired action ... a button press should set a flag, nothing more ... the desired action should only occur when flag is set ... that way, multiple button presses are ignored if the flag is already set

Just set a flag in the interrupt, and run your code in the loop
const int buttonA = 6;
const int buttonB =  10;
volatile byte flagA = 0;
volatile byte flagB = 0;

void setup() {
  pinMode(buttonA, INPUT_PULLUP);
  pinMode(buttonA, INPUT_PULLUP);
  attachInterrupt(digitalPinToInterrupt(buttonA), actionA, FALLING);
  attachInterrupt(digitalPinToInterrupt(buttonB), actionB, FALLING);
}

void loop() {
  if(flagA){
    //some blocking code that takes 2 seconds, but that I want to run immediately upon button press
    flagA = 0;
  }
  if(flagB){
    //some blocking code that takes 10 seconds, but that I want to run immediately upon button press
    flagB = 0;
  }
  sleep_function();  //takes 8 seconds
}

void actionA(){
   flagA = 1;
}

void actionB(){
   flagB = 1;
}

will the interrupt always end the sleep or will it just resume the sleep?

The interrupt ends the sleep, and if you want to sleep, you have to put it to sleep again.  https://www.gammon.com.au/power


text:
Send batch info to com port?
I'm trying yo get a .bat file to send my cpu data to the com port my arduino is on. I've tried multiple google results (including one from this site) and everything I found will just... erase all the variable tied to the com port. The arduino is hooked up to an lcd (not really because arduino microview, but basically that) which displays the variables I want and works as expected when I put the data into the serial monitor manually, but when I run anything that's supposed to send the info they all go blank when I have nothing in my sketch that clears them.
The file is getting the data how it should. If I run this
wmic /namespace:\\root\wmi PATH MSAcpi_ThermalZoneTemperature get CurrentTemperature
then I get the temperature as normal. But If I try to send that to the com port...
wmic /namespace:\\root\wmi PATH MSAcpi_ThermalZoneTemperature get CurrentTemperature > COM3
The arduino reads whatever it's getting as literally nothing and blanks the variables.

download and install com0com from https://sourceforge.net/projects/com0com/ ... that will create two linked virtual serial ports ... connect a serial monitor, such as PuTTy, or arduino IDE console to one port ... send the WMIC output to the other port ... see what is being sent from WMIC

what is your specific question? ... you have not provided any information that could be used to debug the problem

The problem is that the batch file sends literally nothing (to the point where the arduino sets its variables to nothing, not even "0", just nothing) the moment I run the .bat file, even though when I just request the info normally it gives me the correct value.

(@jsotola see above, forgot to reply)

The Arduino may be resetting itself each time you open the serial port.

The variables cannot be blanked. They always have a value. Do you know what exactly the wmic command sends in what format? This sounds like your Arduino code expects one format (like ASCII formatted text in a specific form) but the command sends in a different format. You need to make sure that the wmic command is sending exactly what you expect from it.

As Edgar has noted in the comments the Arduino resets every time you open the serial port.
Every time you perform a redirect the serial port is opened afresh, which resets the Arduino into the bootloader. There is then a brief delay while the bootloader looks for suitable communication for uploading new code, and then your existing program gets started afresh.
Coupled with that is the problem of baud rate: you need to ensure that the serial port is configured for the same baud rate as your program is expecting.
All together that means that a simple redirect like you are using is really not the best way of communicating with an Arduino. Instead you will need to write a proper program that opens the serial port, waits for the Arduino to reset, then starts periodically probing for and sending the information that you need it to.
Python and PySerial is a common choice for beginners as is easy to get started with and has plenty of examples.


text:
ESP32-C3 SPI Class documentation/features?
ESP32-C3 has a nice feature called GPIO Matrix which allows to map most of it's peripherals to any GPIO pin. And it has feature called IO_MUX which allows direct & faster operations for some of the high speed peripherals, including SPI. The API from ESP-IDF (HAL SDK) provides some library documentation on SPI functions.
But Arduino-ESP32 core documentation seems to completely miss SPI library & it's functions. It refers to basic Arduino SPI class, but it lacks description of features ESP32 family has.
I've found this example for ESP32 (note that I'm looking for ESP32-C3 info) which sets SPI pins through SPI.begin method actually.
I've also found this source which seems to feature a lot of SPI internal HAL functions. And a C++ SPI class sources are here. But it's actually doesn't have any useful comments on how to use IO_MUX or allowed values for ::setFrequency() method.
So basically I'm asking for a documentation on ESP32-C3 Arduino specific SPI class features. But to narrow things down I'm actually looking now how to initialize SPI2 (which is the only generally available SPI master on C3) as IO_MUX at the fastest SPI clock speed possible from the Arduino core/SPI class. Any suggestions are also welcomed!

Hi NStorm, I know your post is from a while ago, but for everyone's and anyone's sake: I'm still figuring out how to use the GPIO Matrix with ESP32-C3 and Arduino, but if you are using Arduino with it, then the default pins for SPI2 are defined here. Depending on whether you're initializing the peripheral yourself or a device is doing it for you, there are ways to pass in a different SPI clock speed.


text:
Failure to recognize the Arduino Mega2560 R2 board by the computer
I am using an Arduino mega2560 R3 My Arduino port is not recognized by the computer.led on is green,leds Tx and Rx are yellow and led L is blinking constantly(According to the figure).I used an Arduino Uno to upgrade the Arduino Mega bootloader(According to the figure)  but the problem with the Arduino Mega board was not resolved.What do you think is the solution? Is the mega board burnt?m
I tested the communication cable, there was no problem.I also tested a UNO board that had no problems and was programmed by computer.

If the PC isn't recognising it then the problem is anywhere between the PC and the ATMega16U2 USB interface chip (the small square one by the LEDs).

I tested the communication cable, there was no problem.I also tested a UNO board that had no problems and was programmed by computer.

Did you test a different PC?

Then you should consider re-burning the firmware on the USB chip.

The "L" LED is controlled by the main MCU. This is blinking because the bootloader is running fine. There is nothing (superficially) wrong with the main MCU.
The TX ad RX LEDs are controlled by the ATMega16U2 (or 8U2 or 32U2 depending on the board version) chip which forms the USB interface bridge. These being solidly on are a bad sign. Normally they would be off until some form of communication between the PC and the main MCU (via the 16U2) takes place. This is not happening. If it were a faulty cable then the LEDs would be off. If the PC were not configuring the port the LEDs would be off. But they're on. Therefore the fault is most likely with the 16U2 itself.
Either the chip has been physically damaged (maybe through overvoltage or other misuse) or it has "forgotten" its firmware, either again through misuse or having the firmware overwritten with something else (which can only happen if you specifically perform such an action through the programming header for that chip).
The first step of diagnosis is to try and communicate with that chip through the 6 pin header adjacent to it. You can do this in the same way as you do for programming the bootloader on the main MCU, but instead of programming a bootloader you program the 16U2's firmware (IIRC it's included with the IDE or the AVR core somewhere).
If that is successful and the LEDs start working correctly and the board starts to function again then it's cured. If not, then chances are the chip is dead.
If the chip is dead does that mean the board is dead? Not necessarily, no. It depends on how the board died. If only the 16U2 is dead and the main MCU is fine you can still use it, just not through the USB connection.  You could either use the TX/RX pins and your own external USB to UART interface to replace the 16U2 or program it through the ICSP (SPI) header using another Arduino or a dedicated USB programming dongle. It's less convenient, but means you can still use the board.

Insightful answer, great example of problem solving bit by bit. Thank you for taking the time.

Thanks for your full explanation


text:
I can't get my Micro Pro to bootloader mode anymore
It's important to start by saying that this micro was working perfectly, and the keyboard I built with it was great. Then this happened:
While using the QMK Toolbox I tried to upload an oversized .hex file, and since it was taking too long, I hit the reset button. Clearly uploading an oversized hex file was the problem here.
Now the pro micro won't respond to anything. The green LDE lights up, but windows won't recognize it. I tried clicking the reset button and grounding the reset pin, and nothing works. I even tried the double tap on the reset key, or the tap and hold, nothing.
Have I totally broken the micro somehow? Can't I hard-reset it?

Reinstall the bootloader...

how @Majenko? I can't connect to it....

did you try a double reset? it activates the bootloader

@Juraj, " even tried the double tap on the reset key,"

@Deleteman With another Arduino or hardware programmer (USBASP for example).

Can I use another pro micro for this?  @Majenko

Yes, you sure can.

Alright, just answering my own question in case someone comes along in the future:
The problem in my case, as @Majenko mentions in the comments, was the bootloader. In my case, there was no way around it, I had to re upload it with a ISP.
I got another Arduino Pro Micro and using the wiring from this answer: Trying to verify that Arduino Pro Micro ISP is working and following this tutorial: https://docs.arduino.cc/built-in-examples/arduino-isp/ArduinoISP
I managed to get it working.
Notes:

I did not have to change anything on the code for the ISP sketch.
Careful with the picture from the first answer, the comments show an issue with the wiring you need to take into account.

After that, the "Burn bootloader" action worked like a charm.


text:
Why is the Adafruit splashscreen logo not displayed properly?
I'm working with a 128x64 Oled display. I have just installed the Adafruit library and I'm running some sample codes. I have not modified the sample code in anyway yet just testing if the oled display is working but I've noticed that the splashscreen logo only shows the top half of the image.
How can I fix this?

What sample code are you running? That looks like the sample code supposes a different display height

I'm running the ssd1306_128x64_i2c

Can you provide a link to it?

https://codebender.cc/example/Adafruit_SSD1306/ssd1306_128x64_i2c#ssd1306_128x64_i2c.ino

I added #define SSD1306_LCDHEIGHT 64 before line #53 to remove the compilation error

It looks like you're displaying only 50% of the lines with a blank between each one...

I'm unable to test this now, but here goes:
Turns out I did have the ability to test it (found an extra display module) and this does indeed explain the problem. The only other change I needed to make to your code in order to replicate the problem was change the display's I2C address to 0x3C. Adafruit GFX Library v1.10.13 and Adafruit SSD1306 version v2.5.1.

From comments on the question:

I added #define SSD1306_LCDHEIGHT 64 before line #53 to remove the
compilation error

Yeah, you can't do that. Under the old method of defining the screen dimensions, you are intended to modify the header itself:
// ONE of the following three lines must be #defined:
//#define SSD1306_128_64 ///< DEPRECTAED: old way to specify 128x64 screen
#define SSD1306_128_32 ///< DEPRECATED: old way to specify 128x32 screen
//#define SSD1306_96_16  ///< DEPRECATED: old way to specify 96x16 screen
// This establishes the screen dimensions in old Adafruit_SSD1306 sketches
// (NEW CODE SHOULD IGNORE THIS, USE THE CONSTRUCTORS THAT ACCEPT WIDTH
// AND HEIGHT ARGUMENTS).

You can see by default it is using a screen with dimensions 128x32. Later in the header this is used to set SSD1306_LCDHEIGHT to 32 in the header.
#if defined SSD1306_128_32
#define SSD1306_LCDWIDTH 128 ///< DEPRECATED: width w/SSD1306_128_32 defined
#define SSD1306_LCDHEIGHT 32 ///< DEPRECATED: height w/SSD1306_128_32 defined
#endif

What you have done in your code is redefine SSD1306_LCDHEIGHT to 64 from the point where you issued the #define downward, which only affects the code compiled in your sketch.
Meanwhile, over in Adafruit_SSD1306.cpp, SSD1306_LCDHEIGHT is still 32, because this file is compiled independently of your .ino and is unaware of your own re#define.  In other words, part of the code you've put into your Arduino thinks it has 32 lines and part of it thinks it has 64 lines.

So, the solution would be get rid of the #define that you inserted into the sketch and to modify header to read:
#define SSD1306_128_64 ///< DEPRECTAED: old way to specify 128x64 screen
//#define SSD1306_128_32 ///< DEPRECATED: old way to specify 128x32 screen
//#define SSD1306_96_16  ///< DEPRECATED: old way to specify 96x16 screen

Or to use the new method of supplying the dimensions by way of the constructor as is done in newer examples:
#define SCREEN_WIDTH 128 // OLED display width, in pixels
#define SCREEN_HEIGHT 64 // OLED display height, in pixels
/// ...
Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, OLED_RESET);

The Adafruit SSD1306 version v2.5.1's ssd1306_128x64_i2c.ino example that uses this newer method of passing screen dimensions into the Adafruit_SSD1306 constructor and compiled and ran without modification in testing here.

I have edited the header file and it fixes the problem, thank you. One question though, do I need to use 0x3D as the address for the oled? I used 0x3C because it does not turn on when I use 0x3D. I just want to know why that happened

In short, if it's working you have chosen the correct address. The SSD1306 controller chip has a pile of different pins and transfer modes. In I2C mode one of those pins can be used to configure to chip to respond to either 0x3C or 0x3D, such that two of those displays could coexist on the same I2C bus with no other changes. For your display, the choice of I2C interface and 0x3C address has been made for you by the PCB design.  I believe the 0x3C/0x3D hard configuration tends to follow the x32/x64 display type, but that nothing guarantees that.


text:
Uploading to an external Atmega328P with a clone UNO R3 with soldered chip
As a complete newbie, after much looking for the best bargain, I ended up buying one of these UNO R3 clones, without realizing it had the chip soldered on the board. It looks like this:

It works OK for development, but after that I want to get rid of the Arduino board and just use the Atmega with the minimum set of components on the final project.
As far as I understand, two tasks need to be acomplished here:

Program the bootloader on the spare Atmega328P
Upload code to the spare Atmega328P

Acording to this tutorial, I should be able to accomplish 1) with my "Arduino" board and a breadboard, but after that I couldn't upload any programs to that same Atme328P as the original microcontroller from the "UNO R3" should be removed and that can't be done on rip off.
Does anybody know of a method to accomplish 2) with my current setup? I also have one of those USB-to-serial converter (FTDI) boards. According to this other tutorial that can be done using it and some components, but I'd like to avoid that if, let's say, there's some trick like disabling the RX and TX line from the soldered chip by software so the external chip ones could be used instead...

it is unclear what the problem is

You don't need to remove the microcontroller from the board. Just keep it in the reset state by connecting the reset pin to ground. That prevents the microcontroller to disturb the communication with the external atmega

OT, you don't upload source code. You upload the executable that is compiled and linked from your source code.

You don't need to put a bootloader on the spare Atmega328P. The bootloader is a nice convenience for development, as it allows you to upload the program through the serial port. For the final product, if you are OK with using an ISP programmer (e.g. “Arduino as ISP”), the bootloader is not needed. Ditching it will make your sketch start way faster. 2. You don't need to remove the microcontroller from the Uno.

The idea of removing the existing MCU is either so you can replace it with yours, or to use the Arduino purely as a USB to UART adapter. For the latter just connect RESET to GND and it will disable the onboard MCU - it will be just like you have removed it.

Thanks a lot for the comments; they are really helpul. I edited the question acording to the busybee notes and added the missing link to the 2nd tutorial I mentioned. @EdgarBonet, is my link to the 1st tutorial an example of Arduino as ISP?

Yes, the first tutorial uses “Arduino as ISP” for burning a bootloader, then the USB-to-serial converter of the Arduino to burn the actual sketch through the bootloader. What I am saying is that you can forgo the bootloader and use “Arduino as ISP” (or any other ISP programmer, for that matter) to burn the actual sketch.

Thanks anyone for the comments. Very clarifying! So, all in all, the replies to my question and other doubts are:

There's no need to remove the existing MCU; it's enough to connect it's RESET pin to ground (GND), so it prevents from messing with the external Atmega, and
There's no need to have a bootloader on the "final" product, as it's only a convenience when developing which allows to upload the program easily.


text:
Could not find AHT? Check wiring! How do i connect an AM2315C - Encased I2C Temperature/Humidity Sensor to a STM32F103C8T6?
am a little new at this so i sincirely need your help.
So I have a temperature & humidity sensor i got from http://www.aosong.com/en/products-70.html which is probably based on the AM2315C - Encased I2C Temperature/Humidity Sensor https://learn.adafruit.com/am2315-encased-i2c-temperature-humidity-sensor?view=all
I am trying to get it to read the temperature and humidity values, via an STM32F103C8T6 that am using as my microcontroller.
So whats going on is when i try this code:
#include <Adafruit_AHTX0.h>

Adafruit_AHTX0 aht;

sensors_event_t humidity, temp;
void setup() {
  Serial.begin(115200);
  if (! aht.begin()) {
    Serial.println("Could not find AHT? Check wiring");
    while (1) delay(10);
  }
  Serial.println();
  Serial.println("Temperature C || Humidity %rH");
}
void loop() {
  aht.getEvent(&humidity, &temp);// วัดค่าอุณหภูมิและความชื้น
  Serial.print(temp.temperature);
  Serial.print("                ");
  Serial.println(humidity.relative_humidity);
  delay(1000);
}

I got from this guy on YouTube and uploaded it in my Arduino Uno; it works perfectly, tried it with my ESP 32, works flawlessly and reads accurate values, BUT when i try to use the same code with my STM32 (STM32F103C8T6) Blue Pill it says "Could not find AHT? Check wiring" probably because of this line of course
  if (! aht.begin()) {
    Serial.println("Could not find AHT? Check wiring");
  }

I'm not sure if it's something to do with the I2C pins and how  they are defined for each board, or maybe the STM32F103C8T6 requres a different library, am not sure. By the  way i also tried adding 2 10k pull-up resistors between the SDA & SCL (AM2315C) and the SDA & SCL (STM32F103C8T6), still no change.
My pinout is as follows:
STM32F103C8T6 >> AM2315C
5v >> VDD
GND >> GND
PB6 (SCL) >> I2C SCL (White Line)
PB7 (SDA) >> I2C SDA (Yellow Line)
I need this to work for a project am doing and i would apppreciate if someone pointed me in the right direction, please let me know if i need to share more info so aid in the solving process.


text:
Erratic behaviour using a DUE with the Microchip 24FC64 EEPROM chip?
I am attempting to read and write from/to an EEPROM chip, and have got access to this 64 kbit device.
It appears I can write to the device and read from it, but there appears to be some strangeness around addressing the written data for later writing.
I am using this page as a reference for my code, and getting some strange results. For starters, the 64 kbit is in fact 8k, and I was able to write to the 10000 the byte and read from it (though I suspect it rolled over on the memory address).
The strangeness was when I attempted to write two adjacent bytes to two adjacent addresses. The subsequent read of the two addresses read the second byte both times. It was as if the location pointer was stuck on the last read.
when I reset my code, I can read the previously written addresses, confirming they are not just stuck in memory.
Similarly when I write an array of bytes to an address, I can read back the bytes, but if I change the read pointer to read again, the bytes are returned all the same, until the pointer goes a significant distance away from the read address (over say 50 bytes). At this point the return data is all 255.
Finally if I read many bytes, requesting say 50, the most I get back is 32 bytes.
Say I write:
[60, 61, 62, 63, 64, 65] to position 8000 in memory

if I attempt to read from the address or addresses near it or anywhere else, I either get the exact bytes I wrote at whatever position I request, or I get nothing (all 255).
I have managed to read old data from other locations from previous compiles, so the data is for sure in the chip, just accessing it seems uncertain.
Some read results:
7000: [255, 255, ..., 255]
7500: [255, 255, ..., 255]
7980: [60, 61, 62, 63, 64, 65, 255, 255, ..., 255]
8040: [60, 61, 62, 63, 64, 65, 255, 255, ..., 255]
7960: [60, 61, 62, 63, 64, 65, 255, 255, ..., 255]
8060: [60, 61, 62, 63, 64, 65, 255, 255, ..., 255]
7940: [60, 61, 62, 63, 64, 65, 255, 255, ..., 255]
8500: [255, 255, ..., 255]
8150: [60, 61, 62, 63, 64, 65, 255, 255, ..., 255]

Code:
  const int memoryI2CAddress = 0x50;

  void Initialise() {
    Wire.begin();
    Test();
  }

  void Test() {
    unsigned int baseAddress = 8000;
    byte data[6] = {64, 65, 66, 66, 65, 61};
    Wire.beginTransmission(memoryI2CAddress);
    Wire.write((byte)(baseAddress >> 8));
    Wire.write((byte)(baseAddress && 0xFF));
    Wire.write(data, 6);
    Wire.endTransmission();
    delay(10);

    ReadTest(7000);
    ReadTest(7500);
    ReadTest(7980);
    ReadTest(8040);
    ReadTest(7960);
    ReadTest(8060);
    ReadTest(7940);
    ReadTest(8000);
    ReadTest(8500);
    ReadTest(8150);
  }

  void ReadTest(unsigned int baseAddress) {
    Serial.println(baseAddress);
    Wire.beginTransmission(memoryI2CAddress);
    Wire.write((byte)(baseAddress >> 8));
    Wire.write((byte)(baseAddress && 0xFF));
    Wire.endTransmission();

    int count = Wire.requestFrom(memoryI2CAddress, 50);
    Serial.print(count);
    while (Wire.available()) { Serial.println(Wire.read()); }
  }

Update:
The data addressing seems to be sensitive to the first address byte and not the second. When inverting the order of the most and least significant bytes and comparing to the MSB change with the address, I can reliably return the byte at the correct address. This appears to explain why I either get the same data for some addresses and not others, where the MSByte is or is not changing.
So why is the system insensitive to the least significant byte in the address?

Good catch, was a typo in my description.

8000 in my description is in decimal, under the 8192 limit

I'm not sure I understand what your question is. But, what I'm wondering when reading it is whether or not you read section 6 of your linked datasheet.

I have read 6 and 8, but admit I'm not totally au fait with it and am wondering what the Wire library will be doing on my behalf. What have you spotted explicitly? Primarily I'm not getting an expected behaviour in reading and writing to specific addresses of one or several bytes, either the write is not writing to the correct address, and/or the read is not reading from the correct address.

Sadly the simple answer is in how the least significant byte was being calculated, and the boolean operator generating it.
Wire.write((byte)(baseAddress && 0xFF));

should have been
Wire.write((byte)(baseAddress & 0xFF));

Tough lesson to check my assumptions!


text:
Arduino Uno R3 not recognized by Arduino IDE on Ubuntu 21.04
Now I've been pulling my hair for two days over this one. I've tried everything. I've turned every stone, looked at every search result, and every Arduino Forums thread.
The problem is that Arduino IDE does not recognize the Arduino when connected to the PC, thus I can't upload compiled sketches. As usual, the serial port dropdown menu is greyed-out.
Things I have tried so far:

Tried a different USB cable. Same results.
Tried it on a Mac. It works flawlessly with different sketches.
Looked at dmesg logs for Arduino when connecting. It connects to the PC successfully.
Created a custom udev rule for it to be symlinked from /dev/bus/usb/001/00X to /dev/ttyACMX.
Modified the custom udev rule for it to be symlinked from /dev/bus/usb/001/00X to /dev/ttyUSBX (since for some reason IDE was looking for ttyUSB0 first).
Tried Arduino IDE from snap, apt, and from arduino.cc. All of them work the same.
Tried different versions of AVR board packages from the Boards Manager, none of them work at all.
Tried a NodeMCU (ESP8266), it works flawlessly.
Tried Arduino Due, it works flawlessly.
Added myself to dialout, uucp, and tty groups. Nothing changed.
Changed permissions to a+rwx for all possible Arduino device file nodes.
Changed group ownership to dialout, uucp, and tty for all possible Arduino device file nodes.
Tried running Arduino IDEs as root. Nothing changed.
Installed different firmware and libraries for linux (ex. libserialport0)
Patched the apt version of Aruino IDE with patchelf.
Updated.
Rebooted.

"But hey man, why don't you just use the Mac to compile and upload the sketch, or any other MCU for that matter?" - Because I need to get output from my main PC and delegate it via serial to the Arduino. And Arduino Due is too clunky. And NodeMCU has disputable support for FastLED.
If any of you crazy mfs has an idea on how to solve this, I owe you a beer.

it may be a baud rate mismatch ... load a sketch that sends a known character at a known baud rate every 1/2 second, or so ... use a serial console, other than arduino IDE, to monitor the serial port

When the Arduino is connected, are there any ttyACMX or ttyUSBX device files in /dev? If yes, please connect to them with a serial program (like cu -l /dev/ttyUSB0 -s 115200 on the commandline) and try to sends something. Is the RX LED lighting up a bit (will only be very shortly, but visible)?

@jsotola The sketch can't send anything since I can't upload anything to the Arduino sadly :(

@chrisl There can be ttyACX/ttyUSBX since I created an udev rule to symlink the device once it connects. It is normally "mounted" at /dev/bus/usb/001/00X for some reason.
I'll try the cu trick. Thank you very much!

@Tozzart you said that it works on a Mac ... use the Mac to load a test sketch

Until you sort out your basic problem of getting connected to it, I would remove whatever udev rules you've added, because these are only going to complicate troubleshooting.

After upgrading to Ubuntu 22.04 from 20.10, I could no longer upload anything to Arduino UNO boards. Issue was, the correct port was not listed in the Arduino IDE. All I had available as a port was ttyS0. It won't work with USB boards. I am using Arduino IDE 1.8.19, but I believe this is irrelevant to the issue.
After checking the logs :
sudo dmesg

I got this output:
usb 4-2: Product: USB2.0-Serial
ch341 4-2:1.0: ch341-uart converter detected
usb 4-2: ch341-uart converter now attached to ttyUSB0
input: BRLTTY 6.4 Linux Screen Driver Keyboard as /devices/virtual/input/input27
usb 4-2: usbfs: interface 0 claimed by ch341 while 'brltty' sets config #1
ch341-uart ttyUSB0: ch341-uart converter now disconnected from ttyUSB0
ch341 4-2:1.0: device disconnected

So, my Arduino UNO boards all seem to be recognized as some braille tty device (!). Then braille support tries to establish dialog with the UNO board. This of course fails, resulting in a disconnection of the UNO board, causing removal of device /dev/ttyUSB0. This is the reason why it does not show up in the IDE.
The quick fix is to simply remove braille tty display devices support if you don't need it.
sudo apt remove -y brltty

This worked for me. Hopefully it works for you too.
The issue might be related to some udev rule installed with the package brltty. If I am not mistaken, udev rules are processed in alphabetical order. So it could be that some braille udev rule matches in first, causing the above mentioned scenario.

Thanks for specific details of dmesg.  That helped out, because I had gone all through this and uninstalled brltty many months ago after upgrading to 22.04.  However, today I tried connecting a Arduino Nano and I couldn't get it to be recognized.  I discovered that brltty had been installed again. I ran the apt remove and arduino nano came up on ttyUSB0 just as it should.   Because you showed dmesg I was able to compare to mine and see that it was the problem.

I have experienced that with several new installs of the Linux OS.  Try this:
Linux does not see board Run:
Type 'groups', is 'dialout' there ?
sudo usermod -a -G tty yourUserName
sudo usermod -a -G dialout yourUserName
Log off and log on again for the changes to take effect.
https://playground.arduino.cc/Linux/All/#Permission
sudo ln -s /usr/bin/python3 /usr/bin/python