text:
Display issues with 4 Digit, 14 segment
I have this HT16K33 4 Digit 14-segment display I got brand new.
I connected it to my Arduino UNO, wired it up and uploaded some quick test code.
However, the display looks completely broken (see image below), only some segments turn on.

I soldered the connection pins to the HT16K33 board (see picture below). My solder isn't the best but it also shouldn't be too bad.

I did a quick resistance check on the connection pins to see if the pins were soldered correctly, and they seemed good. I'm not too sure how to test the ji2c pin though...

Here is the Wiring on my breadboard:

Finally here is the code i'm currently using:
#include "HT16K33.h"
#include <Wire.h>
HT16K33 seg(0x070);

void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
  Wire.begin();
  if(!seg.begin()){
    Serial.println("ERROR");
    while(1);
  }
  Wire.setClock(100000);

  Serial.println("displayTest()");
  seg.displayOff();
  delay(1000);

  seg.displayOn();
  seg.displayClear();
  seg.displayInt(5);
}

void loop() {
  // put your main code here, to run repeatedly:

}

I'm a bit troubled here and confused at what's going on... Help would be greatly appreciated

Can you provide a link to the used library? Have you tried the libraries example sketches? Do the shown LEDs light up right after powering or with the execution of displayInt()?

Are you sure that code example you've found matches the display module ?
That display has 14 segments plus a decimal point. The mappings between the pins of the HT16K33 and the display pins probably has no defined standard and could be completely arbitrary. Especially strange is the the '5' you intend to display appears spread over several digits. In the worst case, you are going to have to get the data sheet of the HT16K33 and the displays and work out the connections between the display pins and the HT16K33.

Do you see the "display off" state at the start of the sketch? And did you try different values for output? You might want to do investigate this systematically.

@chrisl I'm using https://github.com/RobTillaart/HT16K33 and its example demo1;

so @6v6gt's comment made me re-search for a library for a 14-segment HT16K33. It seems he/she was in the money since it started working after switching library. While I couldn't find any yesterday, I found this page today which covers 7-segment and 14-segment HT16K33:
https://learn.adafruit.com/adafruit-led-backpack/0-54-alphanumeric?view=all#library-reference-3052482
So I switched from the HT16K33 library to the "Adafruit_LEDBackpack" and "Adafruit_GFX" Libraries.

Code for those wondering:
#include <Wire.h>
#include <Adafruit_GFX.h>
#include "Adafruit_LEDBackpack.h"

Adafruit_AlphaNum4 alpha4 = Adafruit_AlphaNum4();

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

alpha4.begin(0x70);  // pass in the address

alpha4.writeDigitAscii(0, 'A');
alpha4.writeDigitAscii(1, 'B');
alpha4.writeDigitAscii(2, 'C');
alpha4.writeDigitAscii(3, 'D');
alpha4.writeDisplay();
}

void loop() {
}

One question I have is (which is an entirely different subject), how do I go from here to rotate the letters and alphabet 180 degrees?

To create custom characters, just to get you started, look here: https://github.com/adafruit/Adafruit_LED_Backpack/blob/master/Adafruit_LEDBackpack.cpp . You'll see an array static const PROGMEM uint16_t alphafonttable[]  . Make a local copy of the library and try changing the binary value marked say 'A' and see what happens.


text:
Touch Board from Bare Conductive not uploading arduino code example
I have an issue with this example https://github.com/BareConductive/mpr121/tree/public/MPR121/Examples/SimpleTouch when trying to upload it. Also, there was an issue when compiling it, however, the arduino suggested the change (wrong naming) that made the code compile. However, no upload. I have tried both boards available and both ports available *that are showing as options.
I get this verbose output:
processing.app.debug.RunnerException
    at cc.arduino.packages.uploaders.SerialUploader.uploadUsingPreferences(SerialUploader.java:152)
    at cc.arduino.UploaderUtils.upload(UploaderUtils.java:77)
    at processing.app.SketchController.upload(SketchController.java:732)
    at processing.app.SketchController.exportApplet(SketchController.java:703)
    at processing.app.Editor$UploadHandler.run(Editor.java:2061)
    at java.lang.Thread.run(Thread.java:748)
Caused by: processing.app.SerialException: Error touching serial port '/dev/cu.BLTH'.
    at processing.app.Serial.touchForCDCReset(Serial.java:107)
    at cc.arduino.packages.uploaders.SerialUploader.uploadUsingPreferences(SerialUploader.java:136)
    ... 5 more
Caused by: jssc.SerialPortException: Port name - /dev/cu.BLTH; Method name - openPort(); Exception type - Port busy.
    at jssc.SerialPort.openPort(SerialPort.java:164)
    at processing.app.Serial.touchForCDCReset(Serial.java:101)
    ... 6 more

Thank you in advance for any help.

try compiling and uploading an empty sketch ... one that has only void setup() {} and void loop() {} ... the github library is probably irrelevant to your question

This seems to be a problem with the Arduino IDE, not with your sketch. What OS are you using and what version of the Arduino IDE? How did you install it?

/dev/cu.BLTH This thing is (or was) supposedly an Arduino Leonardo so far the IDE is concerned and would that not present itself as cu.BLTH. If there's more to this than just choosing the wrong port, maybe make that clear.

@jsotola and others, thank you, I have just tried uploading an empty sketch over both available ports and I get the same results except that with the second port I also get the> avrdude: butterfly_recv(): programmer is not responding
// Arduino works fine with arduino uno.

@chrisl I am on Mac OS Monterey 12.4 and Arduino IDE 1.8.19

Verify that something relevant shows up in System Information if and only if the board is attached. If not, make sure your micro-usb cable is not the charging-only variety.

source: Stack Exchange

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

sort: votes


text:
Voltage drop when power from AA batteries
I am using a Arduino MKR 1010 Wifi board to control 4 servo (PS-1109MG). All the circuit is powered by 4 AA rechargeable batteries (1.2V * 4). Arduino is powered through the Vin port.
Below is a circuit just to show how they are connected (board type and other details is not correct).

When all the servos move, the arduino's LED oscillates in intensity. I deduced that the servos have a high instantaneous current consumption and the voltage of the batteries drops too much. I measured this with an oscilloscope.

The voltage drops to around 4V when the servos try to move. When the Arduino MKR is powered from the usb port and the servos from the batteries, everything works fine.
How can I reduce the voltage drop on the batteries, to use them as the only power source?
Could I use some electrolytic capacitors to reduce the voltage drop?

AA is too little for your current needs.  Use more in parallel or get bigger batteries.

Why does this question have a down vote?

You have a 1V drop from about 5V or a 25% load regulation error you know that you have excessive load and for active servos this is a result of the DC coil resistance of the motors that are active.

If you knew the motor coil resistance then for a transient servo seek, the surge voltage drop can be predicted from the ratio of the load to total resistance (Load+Rs of batteries)
the main Rule of Thumb to learn is the series resistance adds with batteries in series and reduces with batteries in parallel and thus larger capacity. So you expect the product or Rs and Ah to be constant within some family of same chemistry and brand name.

But there may be sources of deviations to test results so the method must be specified or the same to compare.

the Rs of batteries rises sharply as state of charge SoC drops below 10%  and gradually with repeated sweep tests but lowers gradually with rising temperature.

Let's compare different brands of NiMH (AA vs C) and see how close this is.  You can try your own plots to measure the slope of bulk resistance from the VI plots  ΔV / ΔI = Rs [Ω]

https://eneloop101.com/batteries/eneloop-test-results/
https://lygte-info.dk/review/batteries2012/Enesense%20C%204300mAh%20%28White%29%20UK.html
http://lygte-info.dk/review/batteries2012/Eneloop%20AA%20BK-3MCCE%201900mAh%20(White)%20UK.html

This means changing these products from AA to C results in 31% Rs which equates to a voltage drop and 226% of the AA's Ah capacity.
Eneloop is known to be a reliable high-performance NiMH brand.
Your batteries may have less performance.  You can measure your motor resistance and see if upgrading size or quality and/or cost of batteries to get the performance you need.
The LED fluctuation is a different problem from not using a constant current driver.

Thank you for suggestions. I will try to use a different battery for Arduino, so signal generated board is not affected by voltage drop. I will also consider to use a 2S LiPo with DC DC step down module.

Do not use a SMPS  unless it can handle the surge current of X Amps. It is always better to match the battery and motor voltage. Even 2 LiPo in parallel is better than using a buck regulator for burst current with undervoltage cut-out . OR Use better NiMH like Enerloop might be best if your ESR is much higher meaning lower Ah capacity like 800 mAh

Consider several options:

Larger batteries.  The type of battery was not specified.  For comparison a NiMH AA is on average about 800 mAh where a NiMH D is on average about 6600 mAh.
Use two sets of batteries.  Connect both battery grounds, all the servo grounds and the Arduino ground together.  Only connect the positive of one set of batteries to the Arduino.  Only connect the positive of the other set of batteries to the servos.  Do not connect the positive Arduino terminal with the positive servo terminals!
Using software, only operate one servo at a time.  Some (most) servos will stop moving if the position pulse is not seen by the servo.

Thank you for suggestions. I use GP ReCyko Pro Photoflash 2000mAh.

Two Amp Hours does sound good.  Still, your problems does sound like you are exceeding the capacity of your power source.  At such a point, I usually try to verify this by using a ridiculously large power source.  The advantage of going this route ... if the problem still exists ... then you are fairly sure the power source is not the problem.

Welcome! You picked a good place to connect the batteries when fully charged but it is the wrong place. You can use the Vin pin to Power your Arduino with an regulated or unregulated 7 to 12-volt power source. Like several AA batteries in series or a wall adapter that is in the range of 7 to 12 volts. Alternatively, you can power your Arduino through the 5V pin with an external regulated 5V power supply. Leave the 9V batteries for the smoke detectors they do not work very well.

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


text:
Arduino Mega, 6 push buttons for each analog input (A0-A9) - closing one results in reading by other
On day to day basis I'm more of a high level programmer, with little electronics knowledge, apologies in advance if I lack some nomenclature or basics. I communicate with my Arduino Mega via firmata, so won't really bother with code as I believe my issue is 100% hardware issue (if proven wrong I'll share details surely)
I'm creating a 'keyboard' with 60 arcade style push buttons (2pin), and I distinguish them by different resistance when circuit closes with A0-A9 (10 analog pins, 6 buttons each), and I need the rest of the pins for other functionalities.
I've created a circuit similar to this fritzting schema:

So my issue is: when press button A0/button 1, pins A1 & A2 also read the same value. If I press A0/button 2, I get a different value and can determine which button in A0 was pressed, but again - A1 & A2 also read this, even though I didn't press them.
I suspect I might've taken a different approach or even out of the box "keyboard" chips, but this is the route I've taken.

How do I make it so when I press A0/button 1, A1/A2 doesn't read the value? Do I need separate V5? Or I simply need to put the wires differently somehow?
Update: as per chrisl comment
I've updated the circuit by adding a resistor for each button group:

And that has solved my issue.

why are you using analog inputs?

To be able to use a single pin for multiple button press detection, and I do it so by reading analog value. Each button will show different value upon press because it has a different amount of resistors. Overall very similar to this: https://www.youtube.com/watch?v=Y23vMfynUJ0&ab_channel=MichaelKlements

your approach does not allow multiple buttons to be pressed simultaneously

yes, I'm aware of that caveat but this is not a concern for me, I don't really need this functionality

Of course all three analog inputs show the same value. You have literally connected them to each other. Each green wire is connected to a red wire, which leads to the resistor at the bottom. Thus all three inputs are tied together.
You can fix this by using one bottom resistor for each group of 2 buttons, each connected between 5V and the analog input/button system.
And when using analog inputs for multiple buttons the binary resistor latter is an interesting concept, which might give you more buttons per analog input (depending on the noise in your environment). Though the typical way to read so many buttons would be using an additional chip/microcontroller to scan the buttons in a matrix style arrangement. With your current circuit you still need 30 analog inputs.

I'll try to add a resistor between each analog input and 5v as suggested - thanks! This is where my lack of knowledge peaks. Will
come back later and update. The fritzting circuit is simplified - I have 6 buttons connected to each analog input, and I'm using 10 of those - so I would expect to cover 60 (10x6)? Or is that not the case? And thanks for sharing the usual go-to way of handling those kind of challenges.

I've updated my answer with the latest fritzting / source file as well. I pontetially missed the point or have some other issue, but even with resistor in between each of A0-A2 and 5V the result is still the same. Appreciate your time nonetheless.

@wopolow Your circuit looks correct, except for the rightmost two buttons. They aren't connected as the others. Are you sure, that your real life circuit is correct? And have you tested if measuring on analog input via firmata works as expected? You could use a multimeter to test the voltage on each analog input manually to check, if the circuit works as expected. Maybe it would be good to first build a test circuit on a breadboard instead of directly going to the real project setup.

Thanks, I did, I just failed at execution on a later stage. Having separate resistors was the answer to my question. Thank you sir.


text:
Lag in sensor reading when Arduino Powered with 12V adaptor
So I am trying to power an arduino to measure water flow. It works all fine and dandy when I am powering it with laptop, but when I directly power it with 12V 1.5A adaptor the readings take a second to come to the LCD even though the pump starts running. Also when they come, I can see that sometimes it hangs. Why is that?
Before taking the readings I am switching on a motor which is also directly powered by the adaptor just like the arduino.
Below is a block diagram.

Would adding a voltage regulator that steps down 12V to 9v between arduino and adaptor help?

Please show your code and your actual wiring, not only a course scheme.

@chrisl does code matter if it works fine on power from laptop? Its just a command to switch on the relay (which switches on the pump) switch and next command starts printing the sensor values on LCD...

Can you check the voltage of your power supply with a voltmeter? Does it drop when the motor is turned on?

@EdgarBonet yup, true, just checked, the voltage to vin drops by nearly one volt even though I am powering it through LM7812 regulator module. The main power source voltage falls by almost two volts.

@EdgarBonet I am using this regulator (https://www.electronicscomp.com/lm7812-12v-dc-ac-three-terminal-voltage-regulator-power-module?gclid=CjwKCAjwtKmaBhBMEiwAyINuwPN5G4qe8VA7Ph4SIXA2q-S0DIiZIf6m9JAuTOHBV2SMhl5Y-iIcbhoCQlQQAvD_BwE), even then voltage is not constant

Thanks for adding a schematic.  I gave you an up vote for that.  Because the relay is not actually in the schematic (just the relay socket) I can not tell if it is a only a bare relay (then it too likely needs a reversed bias diode) or if it a module which already contains a diode or a diode and a driver circuit.

Your power supply is actually advertised at 1.2 Amps.  It's assumed you are powering the Arduino, the Relay, the Water Valve Solenoid and the Water-Pump-Motor all w/the same 1.2A power supply.  It is within reason that the sum of all those loads exceeds your power supply's capabilities.

It works all fine and dandy when I am powering it with laptop ...

It is assumed you were only powering the Arduino with the laptop.  Providing the Arudino with an independent power source is a common solution to this type of problem.  Obtaining a larger power supply (more Amps) is another possible solution.
Why does it eventually work?
Motors require more Amps when under a physical load.  If the water is stationary, the motor will have to "get it moving" requiring more current. The term "locked motor current" is used here in this article.
Also, inductor loads require more Amps when ever the voltage potential is suddenly changed.  The motor and relay are likely both seen as inductive loads.  This is referred to as inrush current.
Both of these can be assumed transitory.  Once the motor is moving and after the potential across the inductive loads are closer to zero, the initial current demand will subside and the power supply may then be capable of sustaining the constant voltage needed by the Arduino's processor.
Alternate solution:
Obtaining a larger power supply is likely the better solution.  Another option involves filtering the power only for the Arduino.  This option is discussed in this thread on forum.arduino.cc where a diode and capacitor are used to somewhat isolate the power for the motor, relay and solenoid from the Arduino.

Ok, Ok. My adaptor is 1.5A, so I guess I should go for 2A? And also replace my LM7812 with a more amps module? Can you recommend something? I must use only a single power source, I can't use two power sources, so will have to look for a solution around this...

and your answer also explains the voltage drop which I mentioned in my comment on my question? I'm an amateur enthusiast, so might not understand too technical english...

Relay is powered by arduino, but yeah, there's a solenoid valve in there also on the power adaptor sucking a lot of current probably

If you're constrained to only one power supply then likely you need, as you said, a power supply rated for more amps.  I usually add up the maximum required currents and find a power supply with double the capacity.  There are ways around this.  But they require more knowledge and testing.  They are usually reserved for situations that are cost sensitive.  Like isolating the power path to the Arduino with a diode and a capacitor. Or somehow attenuating the inrush current to the motor.  Something along the lines of a soft start motor device.

Wait, you have a solenoid valve as well?  If the water is under pressure, why use a pump at all?  And if not under pressure, why use the solenoid valve?

Water is not under pressure. I thought maybe the pump could lead to leakage of flow, so to stop flow absolutely when I wanted I added a valve.

I would test it once without the valve, see if the valve is actually serving a purpose.

And about that solution, situations always like to be cost sensitive. So I can try putting a diode between the Vin pin and the +ve terminal? And what value capacitor can I use? Since LM7812 regulator module already has two capacitors, would adding another in the path help?

If this is a 1 time project, I would try a dependable solution by obtaining a higher capacity power supply and be done with it. Only if this is a product to be made many times over would I consider alternate solutions. Such as a forward biased diode between the positive 12 volt power supply line and the Arduino w/ a suitable capacitor (perhaps 100uF to 1000uF depending on the Arduino's current demand and the duration the capacitor needs to maintain a voltage (the duration of the high current demand event)).  It doesn't sound like you have an oscilloscope to help pick a suitable value.

Ok, its right I don't have a oscilloscope, would it do if I just try with a big 1000uF capacitor?

Is it possible I've fried up my arduino by now? Its giving even more lag even when connected to laptop now

One clarity needed, that voltage drop which comes, its because of Rush Current?

You need to make either your word descriptions more precise or you need to draw better diagrams for us to help.  Some people post pictures showing all connections clearly.  Did you remove the Arduino's positive connection to the 12 volt power supply when you connected only the Arduino to the laptop USB port?  And did you keep the Arduino ground connected to both the laptop and the 12 volt power supply?  I don't mean to put you off, but I think the safest option is to buy a bigger power supply and see if your situation improves.

BTW, many relays have build in diodes, but I'm not sure about solenoids.  Read this stack exchange question / answer to understand the purpose of this diode.

I have added my schematic, can you please take a look and let me know all is fine? I don't want to ruin another Arduino. The only difference to my current wiring is that the solenoid switch is on the -ve side while in the schematic its on the +ve side. Also there is only one tactile switch. The diodes are IN4007. I'm using a relay module so I have just added pinouts for it.

The diodes have been added now based on ur suggestions, they weren't there before

I added a link to a diode/capacitor option/discussion if the larger power supply does not work.

Ok thanks...had added the sockets for the relay as I am using a module https://www.electronicscomp.com/1-channel-5v-relay-module-without-optocoupler?gclid=Cj0KCQjwnbmaBhD-ARIsAGTPcfVcln-o_BiNm7Jp_9r5nsP2b0nzm48GdKvnlaBkGC-nYU4-5W0d5OcaAh6wEALw_wcB . Will test it out on the system once I get my replacements for the ruined stuff. If the problem still persists then will try the other way and let u know.

Welcome. Your pump is turning on as soon as the power is turned on because the relay is connected to 5V. Your processor needs to initialize itself and then the display, the pump is up and running. On your laptop the pump was powered from the power supply and the Arduino by the laptop. The arduino was on and up and running when the pump was started. Hope this helps. I will take a SWAG and say this is powered up when the pump is needed and powered down when it is not needed.

So how do I get it out of bed in time?


text:
Library files multiple users
I want to place all of my libraries on the server. Currently the sketches work fine and as far as I know the libraries are coming from the individual linux mint machines using cinnamon, releases vary depending on machine. I can move the libraries etc but what do I do to the IDE 1.8.18 and 1.8.19? to make it follow that path.

How about placing all libraries at a network share and then mount this share on each linux machine to the libraries folder?

The server is already mounted as far as I know. In the GUI I select the server then the appropriate folder. It shows as "network:///"  I then pick the server20 and get this "smb://server20.local/" then I pick my target folder "smb://server20.local/documents/" at this point any of the subfolders open and files are accessible such as opening a sketch etc and they will compile without a problem. I have used Linux for many years and appreciate its power but I definitely do not fully understand it.

If you type the command "mount" into a command line terminal it will list all mounted directories. But to mount a network share at a specific directory you most likely will have to learn how to mount them. There are many tutorials on the mount command and the fstab file for permanent mounts

How does that allow the IDE to access libraries on the server or other drives? From what I understand I have to change the default path in the IDE. If this is correct how?

It would allow to access the files, because with a mount the OS will make the files reachable inside the normal directory structure. With a mount you can choose the directory, where the network files should be visible. That is called a mount point. I currently cannot test, if using an smb:// URL in the preferences for the sketchbook location would work. So please test that first. When you have confirmed that this doesn't work (what I would guess so), then I will write an answer describing the mount solution

Arduino IDE can use libraries only from 3 locations.

libraries folder in sketchbook folder
libraries folder of selected board's platform
libraries folder in IDE installation folder (only IDE 1, not IDE 2)

There is no option to configure other paths and absolute or relative paths don't work in #include directive with the Arduino build process.
The only way to use libraries from a different location is to link with means of the operating system the folder with the library into one of the searched locations.

and question about how to link local or remote folders is off-topic on Arduino SE. you can ask it on other Stack Exchange sites. https://askubuntu.com/, https://unix.stackexchange.com/, https://superuser.com

Thanks, that is all I have been able to do. It does work with "libraries" in the sketch folder but I did not know I could add a libraries folder in the sketch folder, that is a great help. A real big thanks:-)

@Gil I am sure there is a libraries folder in your sketchbook folder. Arduino IDE installs libraries there too. libraries folder in the sketch folder will not work.

You are correct there is and many times I do not want to use them. There are no libraries in my other "sketchbook" folders (I have several with different names) other then the one the IDE created. I like to put the 'hardware' libraries in the actual sketch folder such as "LiquidCrystal_I2C.h" ,as many times older program files will not compile because of library changes that have occured. Many of the sketches are on the server and compile just fine from several different machines with the library in the same folder as the .ino file.

There are files such as home.h which has definitions for all the hardware, address etc in the home automation system. I only one one copy. I can include it from anywhere on a single machine but not the server.

@Gil home.h can be a library too

You are Correct now you know the problem, how to keep it in one place for several different computers where the only common thread is the server which they all use. Currently I keep it in one location and copy it to the others, very prone to errors. Thanks for the help.

@Gil why not just have the sketchbook folder on a shared network drive?

Let us continue this discussion in chat.


text:
Correct syntax for setCACert ESP8266
I am trying to use a cert with an ESP8266. The identical code works fine on ab ESP32, but in the ESP8266 I am getting errors.
I set the cert as follows:
const char *ROOT_CERT PROGMEM = R"EOF(= "-----BEGIN CERTIFICATE-----
MIIFYDCCBEigAwIBAgIQQAF3ITfU6UK47naqPGQKtzANBgkqhkiG9w0BAQsFADA/
MSQwIgYDVQQKExtEaWdpdGFsIFNpZ25hdHVyZSBUcnVzdCBDby4xFzAVBgNVBAMT
...
-----END CERTIFICATE--------)EOF";

For the ESP32 I use:
wifiClient.setCACert(ROOT_CERT)

This works fine, but on the 8266 I get:
no matching function for call to 'BearSSL::WiFiClientSecure::setCACert(const char*&)'

I have done some research and there are some suggestions the length is required, so I tried that also:
 wifiClient.setCACert(ROOT_CERT, sizeof(ROOT_CERT)-1);

But that produces the following error:
invalid conversion from 'const char*' to 'const uint8_t* {aka const unsigned char*}' [-fpermissive]

I am using the 2.7.4 8266 board library as I have heard the 3.X has similar issues.
I have tried V 3.X but I get the following:
class BearSSL::WiFiClientSecure' has no member named 'setCACert'

i could not use setCACert with 8266.  you need to do it differently and i had to do some web hunting.
But finally i did get my telegram test working from esp32 to 8266,
here is what i did and hope that you can adapt it
you need :
#include <ESP8266WiFi.h>

after your defines add:
X509List cert(TELEGRAM_CERTIFICATE_ROOT);
WiFiClientSecure client;
UniversalTelegramBot bot(BOTtokenValue,client);

in setup i had to add BOTH of these lines (i initially didnt think i needed the 1st line, but apparently you do) :
configTime(0, 0, "pool.ntp.org");   // get UTC time via NTP
client.setTrustAnchors(&cert);      // Add root certificate for api.telegram.org

this got my ESP32 code converted from ESP32 to 8266

PS- replace WiFi.h  with the ESP8266WiFi.h


text:
Blue pill acting as if it had 10bit ADC
I just got myself a STM32F103C8 Blue pill board. I am having funny behaviour with the analog readings. It behaves as if the unit was 10bits and not 12 bits.
I uploaded the very trivial Arduino code below. Just to read the analog input A0.
void setup() {
  Serial.begin(38400);
}
void loop() {
  Serial.println(analogRead(A0));
  delay(1000);
}

If I connect pin A0 to the 3.3v I get this output below.
1022
1022
1023
1022
1022
etc...

If I connect to a 1.5V source the above values becomes around 500.
It all behaves as if it was 10bits really which I fail to understand. Any ideas why?

If you run Arduino code on it, maybe it makes sense to have 10-bit ADC readings on this platform too like on all other Arduino platforms. Unless you configure the libraries to return full 12 bit, if even possible.
This is more an Arduino platform question though.

Adding the following line in the setup() section solves the problem.
analogReadResolution(12)

Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.


text:
Creating an AC pulse with arduino and perhaps components
I want to create an AC PWM pulse with arduino. The microcontoller, will be also responsible for specifying the frequency (which will be around 500 Hz).
External electronic components can also be used. Like an H-Bridge perhaps.
EDIT: This is the final waveform I want to produce:

I know the arduino is not capable of producing 36 V output. I plan to just create this waveform, with whatever the arduino can output  and then step up the voltage. But this is the final waveform that I want produced.

What exactly do you mean with "AC PWM pulse"?

@chrisl I edited the question.

Ah, ok. Using a H-bridge sounds good here. Have you tried it? What is your specific problem in doing so?

Yes a H-bridge is what you want. But be careful with controlling it as you may need to add a "dead zone" to prevent crowbaring (aka "overshoot").

@chrisl My problem is lack of experience.. So I do not know the best approach to this problem. Should I create a PWM pulse, double the frequency that I want with the arduino. Then half the frequency should be reversed with the H-Bridge? If yes, how exactly do I control the H-Bridge so that it reverses the pulse where I want? There is another option of a continuous output by the digital pin, then the H-Bridge will reverse half of the time .... So you get this AC square pulse.. But timing is critical so that you get the frequency you want...

Can you specify the load?

@TonyStewartEE75 The device that I am trying to emulate says OUTPUT: 31V, 193mA, 6W. I don't know if this fully describes the load. If it does not, please tell me so i can measure tomorrow with an Amp meter.

What is the supply? That does not load impedance or device or datasheet.  Do you mean +/-31V load from +/-36V supply drawing 6W max, non-inductive.  Do you need a power supply or want to make one from 12VDC or 5V?

@TonyStewartEE75 What i specified was from the supply output. Essentially, i want to recreate the power supply. Unfortunately, i do not know anything more. Can i measure the load with an current meter?

what can you say about the load?  what is it?  The arduino is not much help.

The load is a strip of LED lights.... If you want i can count them, if this will be of any help to figure out the load...

Yes, you want a H-bridge. That is the simplest way to make that "negative*" voltage.
But you can't just create a square wave and throw it blindly at a H-bridge, you have to be much more careful, otherwise you will cause short circuits and dissipate massive amounts of power.
You will need a "discrete" H-bridge where you have proper control over each transistor, and the best way of doing that is with discrete transistors (MOSFETs are best).
The important thing to remember though is than no transistor ever turns off or on instantaneously - so you have to add a "dead zone" into your waveform.  Turn one pair of MOSFETs off, then wait a moment, before turning the other pair on. Otherwise you get a brief overlap in the switching where massive currents can flow straight through everything as all the MOSFETs are turned on (or partially on) at the same time.
Some microcontrollers have programmable dead zones in their PWM outputs, but I am not sure if the AVR chips do - you'll have to check the datasheet - but it's not too hard to arrange a suitable waveform in software or using timers and interrupts (you could look at the tone() function and support code for some ideas for the latter).
The programming sequence, if you have 4 outputs H1/H2/L1/L2 for the HIGH and LOW sides of the H bridge pairs 1 and 2, would be:

Turn on H1 and L2
Pause
Turn off H1 and L2
Brief Pause
Turn on H2 and L1
Pause
Turn off H2 and L1
Brief Pause
Repeat

You haven't specified what your load is, but with an H-bridge it is important to remember that the output is not referenced directly to ground but ground alternates from side to side. If you want to properly isolate it from the Arduino ground a transformer can be used as the load to the H-bridge then use the output of the transformer to drive your real load. You can also use the transformer to change the output voltage (the ratio of windings is the same as the ratio of input to output voltage - so a 1:1 winding transformer will give the same voltage out as it gets in).

"Negative" only that the current flows the opposite way through the load, not an actual negative voltage WRT to Arduino GND.

Thank you so much for this comment! I have some quick questions and (i plan to really read about H-Bridges today). Unfortunately, at this moment the load is not clear to me... 1. Do you know if tone() supports dead zones in its PWM? 2. Should i stay away from ready solutions (like the L298) and rebuild the H-Bridge myself? If yes, i should make sure that the MOSFETS are within operating voltage right (36V)? 3. In the H-Bridge scenario, the initial pulse is PWM or constant voltage that the H-Bridge reverses polarity, and thus it creates an AC PWM? If it's PWM, should the frequency be double

of what i want? 4. How do i then step up the voltage to 36V (in both rails)? Does this come from the H-Bridge input? If yes, can i use a step down converter to use mains voltage to 36V that will feed the H-Bridge? Something like this perhaps? https://www.amazon.in/Electronicspices-LM2596-voltage-regulator-1-3-37V/dp/B08P7KT92B


text:
1Hz & 32Hz from 32.768 kHz on ATmega328P at 8MHz & DS3231 32K
I have a 32.768 kHz signal at the ATmega328P input.
I need to get 2 signals from this signal: 1Hz and 32Hz.
How well will it work?
How to do this with a ATmega328P Timer/Counter?
What gain will the Timer/Counter give compared to my solution?
void setup() {
   pinMode(S32768Hz_PIN, INPUT_PULLUP); // 32.768 kHz signal
   attachInterrupt(digitalPinToInterrupt(S32768Hz_PIN), s32768Isr, FALLING); // Pin 3
}

volatile bool s32768IsrWasCalled = false;  // ISR flag 32768Hz
void s32768Isr() {
   s32768IsrWasCalled = true;
}
uint16_t s32Counter = 0;
uint16_t s1Counter = 0;

void loop() {
  if (s32768IsrWasCalled) {
      s32768IsrWasCalled = false;
      s32Counter++;
      if (s32Counter == 1024) {
        s32Counter = 0;
        // 32Hz
      }

      s1Counter++;
      if (s1Counter == 32768) {
        s1Counter = 0;
        // 1Hz
      }
  }
}

Update 24.10.2022
I wrote my first timer 1 setup code. Will this run 32 times per second, indefinitely?
// ATmega328P 3.3V 8MHz, Timer 1 & DS3231 32768 Hz
void setupTimer1() {
    // Disables all interrupts
    cli();
    // Reset bits
    TCCR1A = 0;
    TCCR1B = 0;
    // Enable Timer 1 overflow interrupt (TOIE1)
    TIMSK1 = (1 << TOIE1);
    // PWM mode. Mode #7 (fast PWM, top is fixed at 10 bits = 1024)
    TCCR1A |= _BV(WGM10) | _BV(WGM11);
    TCCR1B |= _BV(WGM12);
    // External clock on T1 pin, on falling edge (DS3231 32768Hz pin)
    TCCR1B |= (1 << CS11) | (1 << CS12);
    // Enables interrupts
    sei();
    // pinMode(T1_pin, INPUT_PULLUP); ?
}

void loop() {
    // So get 1 Hz from 32 Hz?
    // There will be no data races here?
    if((pulse_counter % 32) == 0) {
        callback1Hz();
    }

    if((pulse_counter % 2) == 0) {
        callback16Hz();
    }
}

volatile uint8_t pulse_counter;
// Timer 1 Overflow (32 Hz)
ISR(TIMER1_OVF_vect) {
    pulse_counter++;
}

Thank you!

How well will it work? ... shouldn't you be the one who determines that? ... use a hardware divider, there are ICs suitable for that

Why don't you just measure? Do you have a scope available?

Oh, and hint: Don't use a flag in the ISR, increment the counter there instead.

You can edit your question to include the details and clarifications people are asking you about in the comments.

WHat accuracy do you need for 1Hz and 32Hz?  just logic level?

I can't use an external hardware divider. I can divide 1 signal into 2 signals only on ATmega328P. I use DS3231 32K output with accuracy ±2ppm.

@EdgarBonet I wrote my first Timer 1 setup code. Update from 24.10.2022. Will this run 32 times per second, indefinitely?

Yes, this looks like it should work. Time to test it.

@EdgarBonet So get 1 Hz from 32 Hz? There will be no data races here? if((pulse_counter % 32) == 0) { } I've updated my example in the header.

No data race, as you are reading a single-byte variable. But you are not doing edge detection.

I did not test your program but, just by looking at it, I would expect
it to work... provided you do not add more code! Obviously you will need
to add more code in order to do something useful with those signals, and
then thinks might break.
The problem with this approach is that the interrupt rate is pretty
high: the program gets interrupted every 30.5 µs. You may miss an
interrupt if either:

it fires while there is already an interrupt (or other critical
section) being processed, and that interrupt (maybe combined with
some other pending interrupt) takes more than 30.5 µs to
complete

you add more code to loop() and that function ends up taking more
than 30.5 µs.

The first condition should be obvious, but I would assume the risk is
quite low, as only a very poorly written ISR would take that long to
complete. Beware however of library code, as that might bring surprises.
The second condition is a bigger risk, although maybe less obvious. The
problem is that this loop() assumes the code within
if (s32768IsrWasCalled) is going to be called exactly once per
interrupt. This may not be the case: if the program gets bigger, you may
miss interrupts, and get the frequencies wrong.
A simple way to avoid the issue number 2 is to count the pulses within
the ISR, as PMF suggests in a comment. I would use a single counter for
this, and make it unsigned in order to guarantee that it wraps around
reliably:
volatile uint16_t pulse_counter;
void s32768Isr() {
    pulse_counter++;
}

void loop() {
    int signal_32Hz = (pulse_counter >> 9) & 1;
    int signal_1Hz = (pulse_counter >> 14) & 1;
}

Note that this is one of the few cases when you can access the volatile
multi-byte variable without disabling interrupts: since you only ever
care about one bit, there is no data race.
A better option, though, would be to use a hardware timer for this job.
I would suggest using Timer 1 in “counter” mode (external clock
source on pin T1). Using mode 7 (fast PWM, 10-bit) you get the
32 Hz signal entirely generated by the hardware. And then you can
use the timer overflow interrupt to generate 1 Hz. The interrupt
rate is now 1024 times lower. I let you check the datasheet for the
details.

Brilliant answer, as usual :)

Thank you, nice code and option!

@EdgarBonet What condition would be true for signal_1Hz? It if (signal_32Hz == 1) doesn't work once per second.

@Andre: signal_1Hz is a 1 Hz signal, with 50% duty cycle: it is 0 for half a second, then 1 for half a second. If you want a condition that is true only once per second (as opposed to being true during a whole half second) you will have to do edge detection on that signal. Alternatively, do change detection on pulse_counter&(1U<<15).


text:
Generate a sine wave with a predefined frequency and amplitude via DAC0 or DAC1 with Arduino Due
Good Morning to everyone,
I am a PhD Student in experimental fluid mechanics at the University of Naples "Federico II", Italy. I am working on Arduino Due card and i am novel in applications using it. First, I need to generate a sine wave with variable frequency and amplitude. I tried to download several codes which are able to generate sine waves with a pre-defined frequency, but I would like to change this value of frequency at the beginning of the execution of the code. How could i do this ?
Second, I would like to change, in real-time, the output voltage of Arduino DAC0 or DAC1 at high speed to generate an arbitrary waveshape.. Is it possible?
Thank you in advance for your answers.
Dr. Alessandro Scala

The formula commonly used to represent a sinusoidal signal is
V = A cos(ωt)
where A is the amplitude and ω is the angular frequency. This formula
should cope well with a variable amplitude. It is, however, not suitable
for a signal with variable frequency, because a discontinuity of the
frequency is not supposed to create a discontinuity in the signal.
The correct formula for a signal where both the amplitude and the
frequency can vary is
V = A(t) cos(φ(t))
where the phase is computed as
φ(t) = ∫ ω(t)dt
In terms of code, this means you need a static variable to keep track of
the current phase, and you have to update it periodically in order to
perform the numerical integration.
Here is a tentative implementation. I have qualified some variables as
extern only to hint that you are responsible for managing them. You
can remove the qualifier if you integrate this into your own code:
// Defined and updated elsewhere.
extern const uint8_t output_channel;
extern float angular_frequency;  // in rad/us
extern float amplitude, offset;  // in ADC steps

// Call this as often as practical.
void update_output()
{
    // Compute the time delta.
    static uint32_t time_of_last_update;
    uint32_t now = micros();
    uint32_t dt = now - time_of_last_update;
    time_of_last_update = now;

    // Update the phase.
    static float phase;
    phase += angular_frequency * dt;
    while (phase >= 2 * M_PI) phase -= 2 * M_PI;  // unwrap

    // Output the signal.
    float output = offset + amplitude * cos(phase);
    analogWrite(output_channel, round(output));
}

Regarding the second part of the question (about arbitrary waveshapes),
it is, of course, feasible. You just have to pass arbitrary values to
analogWrite().

thank you very much for your answer. Regarding the second part of the question, you are stating that i could be able to change the voltage in dependence of an input signal received by other pins ? Such as a measurement performed by a sensor read via Arduino and then change the voltage

@AlessandroScala: I am stating that you can change the output voltage however you like, and make it dependent on whatever you want.


text:
Temperature sensors are heating themselves
I have 2 IoT devices for measuring room temperature. Room does not have direct sunlight (it is north oriented and have tree in front of window). One is ESP8266 with DHT11 and next one is ESP8266 with DS18B20. DHT is on the table, away from PC. DS18B20 is on the top of bookshelf next to plant. Both of them shows temperature around 32-33 deg. celsius. It is not that hot in the room for sure. My home thermostat shows 23-24 deg. celsius. Outside temperature is about 15 deg. When I open the window and cool down the room, I can see temerature drop on both sensors, but still ony to around 26-28 celsius. I think, they are overheating themselves.
Code is almost same on both devices. Sampling every minute, so it should not be an issue of overloading sensors. Supply voltage is 3,3V. Not parasitic with 2k2 pull-up resistor.
What should I do to get correct temperature reading from these sensors?
EDIT: I have tired to get sensor out of PCB. First, I have just raised it for lengt of its legs (about 1cm) above board. It helped little, but it is visible, that sensor started cold, and slowly saturated heat from wires. So I took quite thick cables (0,25mm^2) and put sensor about 10cm away from board. And it helped! Temperature is about 23 degrees, what is somwhere in expected range. Most important is, that temperature curve was dropping before stabilizing. Spikes are just 85°C first reading.

Have you checked, if they are warm? If yes, then they are broken and you need to replace them. Though I suspect more of a calibration problem

DHT is cold. DS is little bit warmer than object around, but it is new original chip. I will try to get my hands on another one

I have bought brand new original DS18B20. Replaced other one. Temperature reading is still above 30⁰C. About 6⁰C above thermostat reading.

start by separating the sensor from the microcontroller by an insulating barrier

@jsotola it seems, that you hit the nail! I would not expect, that heat is transimiting that easily through wires to sensor.

Please write an own answer and mark it to help future visitors find a solution to their similar problem.

It seems, that problem is in heat transfer from ESP chip to thermometer via wires. Worst it was, when chip was on board itself, little bit better when it was raised about 1cm out of board. I have achieved correct readings only when I put sensor on longer and quite thick leads to avoid heat transfer as much as possible.

I can't just now find a source for this but I have read in several places that the DS18b20's leads (and the ground-lead in particular) conduct heat into the device rather well, and in the case of the plastic-packaged devices that most of us use, probably have the dominant influence on the sensor. This suggests that either the ground lead be in intimate contact with the surface to be measured, or the leads be well insulated, thermally, from influences not of interest.

It does not surprise me that a sensor needs a correction to calculate the correct value. I have had the same problems with a range of sensors.
Because linearity is not really important when you need to measure only a room temperature, it would be sufficient to measure room temperature with a reliable thermometer and see how much you need to subtract to correct the value from your sensor.
When still in doubt, you could cover the sensor with a plastic bag and measure the temperature dipped in a bowl of water with crushed ice cubes in it.

Unfortunately, that doesn't help if the error varies over time (e.g. when the sensor reading changes just because it's been on for hours)

I agree with you that this can happen with a very inaccurate sensor. In my case the fault was specified in the datasheet. A 12 bit digital sensor, LM76 with an accuracy of 1 degree C.


text:
Call functions of one class from another class - Callback
I am new to C++ & I need to call functions of one class from another class. And so that the classes do not know anything about each other. How to do it in Arduino environment?
class Encoder {
  using CallBack2 = void( * )(const int, const int);
  using CallBack0 = void( * )();
  private:
    CallBack2 callbackUpDown;
    CallBack0 callbackTab;
    CallBack0 callbackLongPress;
  public:
    Encoder() {}

  void Setup(CallBack2 updown, CallBack0 tab, CallBack0 cbLongPress) {
    callbackUpDown = updown;
    callbackTab = tab;
    callbackLongPress = cbLongPress;
  }

  void Loop() {
    if (true) {
      callbackUpDown(-1, 300);
      callbackTab();
      callbackLongPress();
    }
  }
};

class Menu {
  public:
    void UpDown(const int direction,
      const int count) {}
      void Tab() {}
};

class RTC {
  public:
    void Setup() {}
    void Toggle() {}
};

class Display {
  public:
    void Toggle() {}
};

Encoder encoder = Encoder();
RTC rtc = RTC();
Menu menu = Menu();
Display display = Display();

void setup() {
  rtc.Setup();
  encoder.Setup(menu.UpDown, menu.Tab, []{display.Toggle();rtc.Toggle();});
}

void loop() {
  encoder.Loop();
}

Output:
In file included from sun.ino:47:0:
callback.h: In function 'void setup()':
callback.h:52:75: error: invalid use of non-static member function 'void Menu::UpDown(int, int)'
   encoder.Setup(menu.UpDown, menu.Tab, []{display.Toggle(); rtc.Toggle();});
                                                                           ^
callback.h:28:7: note: declared here
  void UpDown(const int direction, const int count) {}
       ^~~~~~

Thank you!

Classes are designed to be self contained.  If you really need to use a function in a different class consider refactoring your code so as to avoid this.  Alternatively you could put the function in question into a new class which both existing classes inherit from.  Thereby giving access to that function from both existing classes.

pass an object of that class. https://arduino.stackexchange.com/questions/90329/invalid-use-of-non-static-member-function/90336#90336

Are there no interfaces in C++ to Inject Dependencies, Dependency Inversion?

What you are doing here
encoder.Setup(menu.UpDown, menu.Tab, []{display.Toggle();rtc.Toggle();});

is not only passing a function pointer. You are passing a member function pointer. This is 2 levels more difficult than function pointers on their own.

The syntax of declaring a member function pointer is different. You need to include the class name in the function pointer declaration. It would look like
using CallBack2 = void( Menu::* )(const int, const int);

When calling a member function pointer, you need an object to call the function on.

Unfortunately, this is so hard that I can't turn your code into a working example. If you want to be able to read your code in 3 months or if you want others to be able to read your code, stick to normal function pointers. They are hard enough.
Suggestion: implement free functions that do what you want:
void menuUpDown(const int dir, const int count)
{
  menu.UpDown(dir, count);
}
void menuTab()
{
  menu.Tab();
}

void setup() {
  rtc.Setup();
  encoder.Setup(menuUpDown, menuTab, []{display.Toggle();rtc.Toggle();});
}

Or, since you're already using lambdas (are you aware of that?), you can also
void setup() {
  rtc.Setup();
  encoder.Setup(
    [](const int dir, const int count){menu.UpDown(dir, count);},
    []{menu.Tab();},
    []{display.Toggle();rtc.Toggle();}
  );
}

Note that pupils and students might not have been introduced to the concept of lambdas. If you publish such code online, people might not be able to change it themselves because they don't understand it.

Nice answer! Thank you

@Andre: you're welcome. Once you have tried the suggestion and tested that it actually works for you, you may mark this question as solved by checking the checkmark beneath an answer so that others know they don't need to spend time on this any more. No need to hurry, take your time to check that it's really the answer you need.

@Andre: your design looks more like a C# or Java design. Be careful with that on Arduino. You may run out of memory if your designs are very sophisticated and your code is too PC-like.

What is wrong with my design and how can I improve it? I can make classes static singleton and/or use pointers. I don't need multiple instances of the same class. Actually I need one instance of each class. How to get rid of the out of memory?

@Andre: regarding OOM, I don't have much advise. Mainly avoid new (which I see you don't use, that's great). Next, avoid copies. Encoder encoder = Encoder(); could just be Encoder encoder;. (Yes, we have guaranteed copy elision in modern C++, but nobody really knows what C++ version Android actually supports)

@Andre: for the singletons, don't design singletons. Maybe someone really wants to create another object. I would try to do something similar as has been done for Serial. Instead of creating your own instance of Serial, there is just Serial, Serial1, Serial2 as predefined objects (don't exactly know how they did that)

Also, Using Static Methods Or Non-Member Functions (C-Style)
class MyClass {
  public:
    static void onMsg(int num1, int num2) {
      // NOTE: Can't call any non-static method functions here!
    }
};

class LibraryClass {
  using CallBack = void( * )(int, int);
  private:
    CallBack callBack;
  public:
    void Setup(CallBack callBackFunc) {
      callBack = callBackFunc;
    }
    void Loop() {
      callBack(1, 2);
    }
};

MyClass myClass;
LibraryClass libraryClass;

void setup() {
  libraryClass.Setup(&myClass.onMsg); // Provide the instance and function to call
}

void loop() {
  libraryClass.Loop();
}

Is there a difference between &myClass.onMsg and MyClass::onMsg? I don't think this provides an instance for the function to call. Otherwise you could call member functions and it needn't be static. (Side note: myClass with lower case m is not a class, it's an object; same for libraryClass)


text:
How real-time is an arduino (react to sensor)?
New to arduino here, sorry for asking what may be a trivial question.
I need to simulate an industrial machine at home. It operates in a cyclic motion, creating an event for every rotation / cycle. Imagine a turntable or wheel with a marker in one place.
What I would like is:

Have a physical wheel which I turn one rotation every 300 msec. This is the length in time of a cycle.
Read a marker on this wheel using a sensor, such as Sick or Omron. I have this already. Sensor can be PNP or NPN, providing a closed or open connection. I can go via an optocoupler if needed.
Once a signal is seen, the arduino should send a (sequential) string using RS232 to a PC. Approximately 90 characters.  It is not needed to wait for response.

My question is: would be time for arduino to do this be relatively constant - ie, send out the data at approximately same point in the cycle. Example: signal read at "12" on the clock, data sent around "5".
If possible, what sort of Arduino would I be looking at ?
Or do I need something more real-time for such project, like a PLC ?

You are asking for two different things: latency of your system and the jitter

You’re talking about responding to a an approximately 3.33Hz signal that you can monitor with a simple edge-triggered interrupt using a microcontroller running at almost six million times that frequency. You should be perfectly fine, even factoring in the few hundred instructions to send the serial data.

one rotation every 300 msec.

300 ms is a very long time for an Arduino, even for an AVR-based
one, like an Uno.
I did a little experiment. I generated (with an Arduino...) a periodic
signal consisting of a 96 µs-wide negative pulse repeating every
300 ms. I sent that signal to an Arduino Uno running the following
code:
const uint8_t sensor_pin = 3;

// 90-byte message.
const char message[] = "Korem ipsum dolor sit amet, consectetur "
        "adipiscing elit sed do eiusmod tempor incididunt\r\n";

void setup() {
    pinMode(sensor_pin, INPUT_PULLUP);
    Serial.begin(9600);
}

void loop() {
    if (digitalRead(sensor_pin) == LOW) {
        Serial.write(message);

        // Wait until the signal rises again.
        while (digitalRead(sensor_pin) == LOW)
            continue;
    }
}

This is not the nicest way to do edge detection, but for this simple
test it will do. You may notice that I am not using interrupts for
capturing the pulse: 96 µs is long enough to be captured with this
simple digitalRead(). I then captured the input and output signals
with a dual-channel pocket oscilloscope. Here is a screen capture:

The cyan trace at the top is the received pulse. The yellow trace below
is the output of the serial port. The negative pulse on this trace that
is almost coincident with the received pulse is the start bit. Then the
signal rises to transmit the first data bit, which is a 1 (that's
why I chose “K” rather than “L” as the first letter).
What you can see in this capture is that the latency of the Arduino is
tiny at this scale: a small fraction of the duration of the start bit.
What you cannot see is the jitter, which is quite large in relative
terms, but still small compared to the time scales relevant to you. In
short, the delay between the falling edge on the input and the falling
edge of the serial port start bit fluctuates roughly between 10 and
20 µs. Yes, those are microseconds. This delay is roughly
20,000 times shorter than the rotation period. If the signal is read at
“12” on the clock, the start bit fires at 12 hours with
0 minutes and 2 seconds.
Note that, on the other hand, the time needed to send the message at
9600 b/s is 93.6 ms, a significant fraction of the rotation
period. And I didn't look at the behavior of the USB-to-serial converter
chip, which is another can of worms...

There's no reason why the serial port speed can't be increased. I'm always using 115200 as baud rate, and never had any problems.

@PMF: The OP has a very good reason to not increase the serial port speed: he wants to simulate an industrial device that speaks at 9600 b/s.

Note that a 90 char message will probably exceed the output buffer size of the (chip being used on the) Arduino. There's obviously ways around this (send a few bytes, delay, send a few more...) but there's both a risk of determinate overrun here (the last message hasn't yet been written when the wheel comes round to its trigger point) and an indeterminate overrun (interrupts are still being serviced when the wheel comes round). The first case will be easy enough to recognise but the second less so... and might be enough to cause problems if this is being used for e.g. ignition timing.

@EdgarBonet I see nothing in the question that specifies the speed of the actual device he wants to simulate. But if the message was, in fact, to long to be transmitted within a time slot, that would be the same for the real system as well.

@MarkMorganLloyd: The output buffer of the chip in question is one byte deep. Two bytes if you count the shift register holding the remaining bits of the byte being transmitted. And yet, the code I posted has no issues reliably sending the whole message: Serial.write() is smarter than you think. There is no risk of overrun as long as the input pulses are spaced more than 93.6 ms apart, and they only come every 300 ms.

@EdgarBonet Thank you kindly, but HardwareSerial.h demonstrates precisely how smart it is: either 16 or 64 bytes depending on the type of chip/board. I assure you that it IS possible to overrun that.

@MarkMorganLloyd: My point is, even with this 64-byte internal buffer, Serial.write() reliably sends a 90-byte string if asked to.

@EdgarBonet Not in all cases in my experience. However /my/ point is that if the ISR is still clearing the buffer at the time that the next revolution pulse arrives it is likely to result in indeterminate jitter... unless of course it's attached to a higher-priority interrupt, which I suspect is unlikely (and which is definitely not the case in your posted example).

@MarkMorganLloyd: Re “Not in all cases in my experience”: If Serial.write() does not send reliably 90 bytes when asked to, you have a bug in your code. Probably one that is corrupting memory. Re “if the ISR is still clearing the buffer..”: In this case, a new message is due while the previous one has not been sent completely. Of course there will be extra jitter! There is no way around this. Fortunately for the OP, the messages take 93.6 ms to send and are sent every 300 ms.

@EdgarBonet I disagree. However I think I was using Serial.print() etc. when I discovered this rather than Serial.write() (and that I can't remember the precise symtoms), and I would caution that even in the Serial.write() case if it can't fit the data into the available buffer then it's likely to pause the main loop (with an effect on any hardcoded delay) rather than magically allocating more storage space. However your point about a 90-byte message occupying roughly 90 mSec at 9600 BPS is of course a good one.

@MarkMorganLloyd: You are right about the pause. In this instance, Serial.write() takes 26 ms to complete. I did not mention that in the answer because I believe the OP is not going to be concerned about that, as his main concern was whether there would be a latency in the hundreds of milliseconds.

TLDR: any Arduino is probably sufficient for your purpose when done properly.
I'll assume a proper HIGH/LOW binary signal from the sensor, HIGH when it "sees" the marker, LOW when it doesn't.
What could go wrong?

You use digitalRead() to get the state of the digital input. Depending on the pulse width, you might not catch the high state. Use interrupts instead.
Sending the data over Serial port takes longer than a turn of the machine. 90 bytes at 9600 bit/s needs (90 bytes * 10 bits/byte / (9600 kbit/s) = 93ms. In 300ms, there's enough time to send the 90 bytes. And 9600 bit/s is quite slow: you can probably use 115200 bit/s on short or shielded wires.
"Approximately 90 characters": calculate everything for the maximum data that will eventually be sent
Getting the data on Arduino side takes too long. You didn't give details on where those 90 bytes come from. Asking 90 devices to each give you a byte of data might not be possible in 300ms.
Receiving the data on the PC side (or whatever) might be delayed, because it is buffered. Especially USB to Serial adapters have no guaranteed timing. Doing the math for USB devices is hard.
Threading on the PC side: due to the OS Thread scheduling, the application that shall receive the data might not get CPU time for several milliseconds, 16ms (1/64s) is quite common. Doing the math is impossible (try running 8 real time threads that do something else and your PC is basically frozen)
Processing on the PC side: unknown
Displaying: after processing until a signal is displayed on the screen, that may take another 16 ms (at 60 Hz refresh rate).

would be time for Arduino to do this be relatively constant

Relatively: yes. It certainly depends on the implementation (the Arduino C++ code).
If the data to send is hard coded 90 characters, I would expect the complete signal has been sent at before the 4 o'clock mark (94ms /300ms * 12 hours ~ 3 hours) . I see the problem more on the receiving side (see points 5., 6., 7. and 8.).

what sort of Arduino would I be looking at ?

I don't know all of them, but an Uno will certainly work. If you only have that one digital input, even smaller ones are probably ok. Just start with an Uno or what you have available and see how it goes.

do I need something more real-time for such project, like a PLC?

I don't see a need for a PLC in your project.

Your answer is also useful, but I had to accept the other once for providing exact measurements.  As this would just be a simulation the 90 characters would be just fixed text and an increasing counter, so no delay getting input from anywhere. The receiving end is well capable of handling the input.  Unfortunately switching to 115k is not possible due to the actual machine being simulated.

@MyICQ: accepting the other answer is ok. I am not overly happy with the digitalRead() decision of that answer - probably because I had too many issues with digitalRead() not working reliably enough in my projects. Anyway, if the suggested code is roughly what you need, that's a fine answer.

What would be the alternative to digitalRead() ? I am new to Arduino, and somehow the event of sending serial string should be triggered ?

@MyICQ: note that I accidentally calculated with kbits/s instead of bit/s, so I was off by a factor of 1000. OMG! See the new calculation. The whole data is sent at around the 3 o'clock mark

@MyICQ: use digitalRead() as suggested by Edgar. Later you can try https://www.arduino.cc/reference/en/language/functions/external-interrupts/attachinterrupt/

I am not a huge fan of digitalRead() either, but it has the benefit of simplicity, and it is newbie-friendly. If the stuff was really time-critical, I would use interrupts. With care, because printing to Serial from interrupt context has its issues. 2. 90 bytes at 9600/8N1 should take 93.75 ms (do not forget the start and stop bits). At the Arduino-rounded “9600 bps” speed it takes 93.6 ms.


text:
Seeeduino XIAO read PWM duration (period) using timers change Pins freom D2 to D1
I designed a circuitboard and need to proof the function.Therefore i have to modify the code to read from Pins D1 instead of D2.
Unfourtunatly i am not that familar with the high level programming so im not sure if i got all changes.
Basically all PINS on the circuit are used.
Basecode foud here:
Seeeduino XIAO write and read PWM duration (period) using timers
Reading short square waves with Seeeduino XIAO pin D2
// Setup TC4 to capture pulse-width and period on digital pin D2 on Seeeduino Xiao
volatile boolean periodComplete;
volatile uint32_t isrPeriod;
volatile uint32_t isrPulsewidth;
uint32_t period;
uint32_t pulsewidth;

void setup()   {
  SerialUSB.begin(115200);                         // Initialise the native serial port
  while(!SerialUSB);                               // Wait for the console to open

  PM->APBCMASK.reg |= PM_APBCMASK_EVSYS;           // Switch on the event system peripheral

  GCLK->GENDIV.reg = GCLK_GENDIV_DIV(1) |          // Divide the 48MHz system clock by 1 = 48MHz
                     GCLK_GENDIV_ID(4);            // Set division on Generic Clock Generator (GCLK) 4

  GCLK->GENCTRL.reg = GCLK_GENCTRL_IDC |           // Set the duty cycle to 50/50 HIGH/LOW
                      GCLK_GENCTRL_GENEN |         // Enable GCLK 4
                      GCLK_GENCTRL_SRC_DFLL48M |   // Set the clock source to 48MHz
                      GCLK_GENCTRL_ID(4);          // Set clock source on GCLK 4
  while (GCLK->STATUS.bit.SYNCBUSY);               // Wait for synchronization

  GCLK->CLKCTRL.reg = GCLK_CLKCTRL_CLKEN |         // Route GCLK4 to TC4 and TC5
                      GCLK_CLKCTRL_GEN_GCLK4 |
                      GCLK_CLKCTRL_ID_TC4_TC5;

  // Enable the port multiplexer on port pin PA10
  PORT->Group[PORTA].PINCFG[10].bit.PMUXEN = 1;
  // Set-up the pin as an EIC (interrupt) on port pin PA10
  PORT->Group[PORTA].PMUX[10 >> 1].reg |= PORT_PMUX_PMUXE_A;

  EIC->EVCTRL.reg |= EIC_EVCTRL_EXTINTEO10;                                // Enable event output on external interrupt 10
  EIC->CONFIG[1].reg |= EIC_CONFIG_SENSE2_HIGH;                            // Set event detecting a HIGH level
  EIC->INTENCLR.reg = EIC_INTENCLR_EXTINT10;                               // Disable interrupts on external interrupt 10
  EIC->CTRL.reg |= EIC_CTRL_ENABLE;                                        // Enable EIC peripheral
  while (EIC->STATUS.bit.SYNCBUSY);                                        // Wait for synchronization

  EVSYS->USER.reg = EVSYS_USER_CHANNEL(1) |                                // Attach the event user (receiver) to channel 0 (n + 1)
                    EVSYS_USER_USER(EVSYS_ID_USER_TC4_EVU);                // Set the event user (receiver) as timer TC4

  EVSYS->CHANNEL.reg = EVSYS_CHANNEL_EDGSEL_NO_EVT_OUTPUT |                // No event edge detection
                       EVSYS_CHANNEL_PATH_ASYNCHRONOUS |                   // Set event path as asynchronous
                       EVSYS_CHANNEL_EVGEN(EVSYS_ID_GEN_EIC_EXTINT_10) |   // Set event generator (sender) as external interrupt 10
                       EVSYS_CHANNEL_CHANNEL(0);                           // Attach the generator (sender) to channel 0

  TC4->COUNT32.EVCTRL.reg = TC_EVCTRL_TCEI |               // Enable the TC event input
                            //TC_EVCTRL_TCINV |              // Invert the event input
                            TC_EVCTRL_EVACT_PPW;           // Set up the timer for capture: CC0 period, CC1 pulsewidth

  TC4->COUNT32.CTRLC.reg = TC_CTRLC_CPTEN1 |               // Enable capture on CC1
                           TC_CTRLC_CPTEN0;                // Enable capture on CC0
  while (TC4->COUNT32.STATUS.bit.SYNCBUSY);                // Wait for synchronization

  NVIC_SetPriority(TC4_IRQn, 0);      // Set the Nested Vector Interrupt Controller (NVIC) priority for TC4 to 0 (highest)
  NVIC_EnableIRQ(TC4_IRQn);           // Connect the TC4 timer to the Nested Vector Interrupt Controller (NVIC)

  TC4->COUNT32.INTENSET.reg = TC_INTENSET_MC1 |            // Enable compare channel 1 (CC1) interrupts
                              TC_INTENSET_MC0;             // Enable compare channel 0 (CC0) interrupts

  TC4->COUNT32.CTRLA.reg = //TC_CTRLA_PRESCSYNC_PRESC |      // Overflow on precaler clock, (rather than the GCLK)
                           TC_CTRLA_PRESCALER_DIV1  |      // Set prescaler to 1, 48MHz/1 = 48MHz
                           TC_CTRLA_MODE_COUNT32;          // Set TC4/TC5 to 32-bit timer mode

  TC4->COUNT32.CTRLA.bit.ENABLE = 1;                       // Enable TC4
  while (TC4->COUNT32.STATUS.bit.SYNCBUSY);                // Wait for synchronization
}

void loop() {
  if (periodComplete)                             // Check if the period is complete
  {
    noInterrupts();                               // Read the new period and pulse-width
    period = isrPeriod;
    pulsewidth = isrPulsewidth;
    interrupts();
    SerialUSB.print("PW: ");
    SerialUSB.print(pulsewidth);
    SerialUSB.print(F("   "));
    SerialUSB.print("P: ");
    SerialUSB.println(period);
    periodComplete = false;                       // Start a new period
  }
}

void TC4_Handler()                                // Interrupt Service Routine (ISR) for timer TC4
{
  // Check for match counter 0 (MC0) interrupt
  if (TC4->COUNT32.INTFLAG.bit.MC0)
  {
    TC4->COUNT32.READREQ.reg = TC_READREQ_RREQ |           // Enable a read request
                               TC_READREQ_ADDR(0x18);      // Offset address of the CC0 register
    while (TC4->COUNT32.STATUS.bit.SYNCBUSY);              // Wait for (read) synchronization
    isrPeriod = TC4->COUNT32.CC[0].reg;                    // Copy the period
    periodComplete = true;                                 // Indicate that the period is complete
  }

  // Check for match counter 1 (MC1) interrupt
  if (TC4->COUNT32.INTFLAG.bit.MC1)
  {
    TC4->COUNT32.READREQ.reg = TC_READREQ_RREQ |           // Enable a read request
                               TC_READREQ_ADDR(0x1A);      // Offset address of the CC1 register
    while (TC4->COUNT32.STATUS.bit.SYNCBUSY);              // Wait for (read) synchronization
    isrPulsewidth = TC4->COUNT32.CC[1].reg;                // Copy the pulse-width
  }
}

Do i only have to change the IOs:
from:
PORT->Group[PORTA].PINCFG[10].bit.PMUXEN = 1;
PORT->Group[PORTA].PMUX[10 >> 1].reg |= PORT_PMUX_PMUXE_A;
to:
PORT->Group[PORTA].PINCFG[4].bit.PMUXEN = 1;
PORT->Group[PORTA].PMUX[4 >> 1].reg |= PORT_PMUX_PMUXE_A;
or do i need to mod more code?
Thanks for helping.

In addition to the changes you mentioned, your EIC_EVCTRL_EXTINTEO10, EIC_INTENCLR_EXTINT10, and EVSYS_ID_GEN_EIC_EXTINT_10 usages will need to be changed to EIC_EVCTRL_EXTINTE4, EIC_INTENCLR_EXTINT4 and to EVSYS_ID_GEN_EIC_EXTINT_4, to re-target the event system source, because PORT_PMUX_PMUXE_A on both these pins routes the signal to the EIC, but not to the exact same interrupt number.  The EIC->CONFIG line needs to change to the first group of 8 ([0]) and fourth SENSE within that group (EIC_CONFIG_SENSE4_HIGH) to the change to D1 (PA04) uses EXTINT4.  This is something I'd left out of the first edit before I'd been able to test. I did eventually find a XIAO to test with and these modifications seem to make it work just fine on digital pin 1 now instead of digital pin 2.
EIC->EVCTRL.reg    |= EIC_EVCTRL_EXTINTE4;
EIC->CONFIG[0].reg |= EIC_CONFIG_SENSE4_HIGH;
EIC->INTENCLR.reg   = EIC_INTENCLR_EXTINT4;
EIC->CTRL.reg      |= EIC_CTRL_ENABLE;
while (EIC->STATUS.bit.SYNCBUSY);

...
EVSYS->CHANNEL.reg = EVSYS_CHANNEL_EDGSEL_NO_EVT_OUTPUT |
                     EVSYS_CHANNEL_PATH_ASYNCHRONOUS |
                     EVSYS_CHANNEL_EVGEN(EVSYS_ID_GEN_EIC_EXTINT_4) |
                     EVSYS_CHANNEL_CHANNEL(0);

The changes you'd mentioned and those I've said above as diff:
--- original.ino
+++ modified.ino
@@ -24,14 +24,14 @@
                       GCLK_CLKCTRL_GEN_GCLK4 |
                       GCLK_CLKCTRL_ID_TC4_TC5;

-  // Enable the port multiplexer on port pin PA10
-  PORT->Group[PORTA].PINCFG[10].bit.PMUXEN = 1;
-  // Set-up the pin as an EIC (interrupt) on port pin PA10
-  PORT->Group[PORTA].PMUX[10 >> 1].reg |= PORT_PMUX_PMUXE_A;
+  // Enable the port multiplexer on port pin PA04
+  PORT->Group[PORTA].PINCFG[4].bit.PMUXEN = 1;
+  // Set-up the pin as an EIC (interrupt) on port pin PA04
+  PORT->Group[PORTA].PMUX[4 >> 1].reg |= PORT_PMUX_PMUXE_A;

-  EIC->EVCTRL.reg |= EIC_EVCTRL_EXTINTEO10;                                // Enable event output on external interrupt 10
-  EIC->CONFIG[1].reg |= EIC_CONFIG_SENSE2_HIGH;                            // Set event detecting a HIGH level
-  EIC->INTENCLR.reg = EIC_INTENCLR_EXTINT10;                               // Disable interrupts on external interrupt 10
+  EIC->EVCTRL.reg |= EIC_EVCTRL_EXTINTEO4;                                 // Enable event output on external interrupt 4
+  EIC->CONFIG[0].reg |= EIC_CONFIG_SENSE4_HIGH;                            // Set event detecting a HIGH level
+  EIC->INTENCLR.reg = EIC_INTENCLR_EXTINT4;                                // Disable interrupts on external interrupt 4
   EIC->CTRL.reg |= EIC_CTRL_ENABLE;                                        // Enable EIC peripheral
   while (EIC->STATUS.bit.SYNCBUSY);                                        // Wait for synchronization

@@ -40,7 +40,7 @@

   EVSYS->CHANNEL.reg = EVSYS_CHANNEL_EDGSEL_NO_EVT_OUTPUT |                // No event edge detection
                        EVSYS_CHANNEL_PATH_ASYNCHRONOUS |                   // Set event path as asynchronous
-                       EVSYS_CHANNEL_EVGEN(EVSYS_ID_GEN_EIC_EXTINT_10) |   // Set event generator (sender) as external interrupt 10
+                       EVSYS_CHANNEL_EVGEN(EVSYS_ID_GEN_EIC_EXTINT_4) |    // Set event generator (sender) as external interrupt 4
                        EVSYS_CHANNEL_CHANNEL(0);                           // Attach the generator (sender) to channel 0

   TC4->COUNT32.EVCTRL.reg = TC_EVCTRL_TCEI |               // Enable the TC event input


text:
Best practice for wiring two sensors that have SCL and SDA connections
I have two different sensors which have SCL and SDA connections which I am trying to connect to an Arduino nano. From what I understand, connecting both of these sensor to the A5 and A4 pins doesn't make any sense, considering that I need to collect data continuously from both sensors. Moreover, there are no other pins with the same functionality as A5 and A4. I am a beginner learning about microcontrollers, but it seems to me like the best practice to follow here would be to use two Arduino nanos. Is this this the only way, or is there another method I am not aware of?

you can't even collect data continuously from one sensor ... the data is transmitted serially ... there is always a delay between readings

which sensors are you talking about? ... what data throughput are you expecting?

I2C is a bus, it allows multiple sensors to be connected (as long as they have different address) to the same bus using the two wires. Y

@jsotola I have two different temp sensors. By continuous I meant I need to be collecting data every 10 ms.

@hcheung , but wouldn't the data I collect be a jumbled up version of the data collected by the different sensors?

Read the I2C wikipedia to understand how I2C works first. At any giving point, the I2C Host(Master) talk to one I2C Client(Slave), that is, those I2C sensors who was not addressed will not interfere the communication on the bus. The best way is for your to try it out in addition to the reading.

@hcheung , wouldn't this would mean that I couldn't get simultaneous data from the two sensor, or would the time difference not be significant? Also, what do you mean by "using the two wires"?

Define "simultaneous", if you run an I2C clock at 400kHz, each bit take 1/400000=2.5uS(microsecond) to send. Reading a temperature sensor would probably take about 7.5uS, more than sufficient for reading it in every 10 millisecond.

Your question does not have enough detail for a good answer. Please edit the question (don't reply in a comment) and add the following information: (1) What are the part numbers of the two sensors? (2) How far apart are they from the Arduino, and each other. (3) How often do you want to collect the data?

The whole point of the I2C bus is to allow multiple sensors or devices to be connected, as long as they have different I2C addresses. The addresses are usually built into the part, and often they have some provision for selecting an address from a range.
Whilst you can't simultaneously collect data from two sensors at once, you can certainly query them in quick succession. You need to connect SDA, SCL, Ground and +5V to each sensor, and the Arduino.
Your code would do something like:

Query sensor at address 42
Query sensor at address 43
Do something with the data
Wait a bit before doing it again

You could look at Wikipedia for some general information about I2C, and I also have a page about I2c that might help you.
Note that you also need a pull-up resistor on both SDA and SCL (that is, two resistors), a typical value would be 4.7k (connect the 4.7k resistors between SDA/SCL and your +5V line).


text:
How to upload code to Arduino without a laptop
I would like to know is there a way of burning programs to microcontrollers like that on Arduino without using a computer? Like a pendrive or something? Suppose you want to update firmware on a utility end, must you carry the editable source code with you? How do the big companies do it?

SD card is possible. do you want a solution for Uno or is the tag random?

@Juraj Well I've been using Uno, nano and pro mini for now.

Are we talking strictly about solo Arduino boards? OTA (Over the Air) internet upload may be interesting feature for you

One good way to update Uno/Nano/Mini without connecting it to a computer is to use SD bootloader. SD bootloader reads at boot the bin file with the update from the attached SD card and copies it to flash memory.
There are not many SD bootloader for ATmega. I use avr_boot by zevero. It works well. The downside is that it doesn't support upload over USB.
zevero doesn't offer built binaries of the bootloader so you have to compile it with the avr toolchain.
avr_boot requires a bin file, not a hex file, but it is simple to set Arduino IDE to create a bin file along with the hex file. You create platform.local.txt file next to platform.txt in the avr boards package, and put this line into the file:
## Create output (bin file)
recipe.objcopy.bin.pattern="{compiler.path}{compiler.elf2hex.cmd}" -O binary {compiler.elf2hex.extra_flags} "{build.path}/{build.project_name}.elf" "{build.path}/{build.project_name}.bin"

Then you can use "Export compiled binary" from Sketch menu in Arduino IDE and you will find the binary file next to your ino file in the sketch folder.

There are different ways how to update an Arduino without connecting it to computer. For small ATmega328p on Uno/Nano/Mini there is not enough flash space to do a self update. The code required to do the update takes more than half of the flash so there is no space left to store the update binary before applying it. (The updated sketch of course must have to have the code for the self update too.)
For illustration what is possible, here is a sketch for Arduino Mega which does a self update from SD card reading a hex file. It requires a modified Optiboot available in MegaCore.


text:
No matching function for call to'DS3231 (const uint8_t &, const uint8_t &)
This was supposed to be the code for automatic pet feeder
Got it from here1
The problem is that I always got a "No matching function for call to'DS3231 (const uint8_t &, const uint8_t &)"
Here's the error code
Arduino: 1.8.19 (Windows 10), Board: "Arduino Uno"

ANA_FEEDER_PROJECT:53:18: error: no matching function for call to 'DS3231::DS3231(const uint8_t&, const uint8_t&)'

 DS3231 rtc(A4, A5);

                  ^

In file included from C:\Users\SERIES\Desktop\ANA_FEEDER_PROJECT\ANA_FEEDER_PROJECT.ino:1:0:

D:\Documents\Arduino\libraries\DS3231/DS3231.h:67:3: note: candidate: DS3231::DS3231(TwoWire&)

   DS3231(TwoWire & w);

   ^~~~~~

D:\Documents\Arduino\libraries\DS3231/DS3231.h:67:3: note:   candidate expects 1 argument, 2 provided

D:\Documents\Arduino\libraries\DS3231/DS3231.h:66:3: note: candidate: DS3231::DS3231()

   DS3231();

   ^~~~~~

D:\Documents\Arduino\libraries\DS3231/DS3231.h:66:3: note:   candidate expects 0 arguments, 2 provided

D:\Documents\Arduino\libraries\DS3231/DS3231.h:62:7: note: candidate: constexpr DS3231::DS3231(const DS3231&)

 class DS3231 {

       ^~~~~~

D:\Documents\Arduino\libraries\DS3231/DS3231.h:62:7: note:   candidate expects 1 argument, 2 provided

D:\Documents\Arduino\libraries\DS3231/DS3231.h:62:7: note: candidate: constexpr DS3231::DS3231(DS3231&&)

D:\Documents\Arduino\libraries\DS3231/DS3231.h:62:7: note:   candidate expects 1 argument, 2 provided

C:\Users\SERIES\Desktop\ANA_FEEDER_PROJECT\ANA_FEEDER_PROJECT.ino: In function 'void setup()':

ANA_FEEDER_PROJECT:84:7: error: 'class DS3231' has no member named 'begin'

   rtc.begin();

       ^~~~~

C:\Users\SERIES\Desktop\ANA_FEEDER_PROJECT\ANA_FEEDER_PROJECT.ino: In function 'void loop()':

ANA_FEEDER_PROJECT:130:10: error: 'class DS3231' has no member named 'getTimeStr'; did you mean 'getMinute'?

  t = rtc.getTimeStr();

          ^~~~~~~~~~

          getMinute

ANA_FEEDER_PROJECT:146:16: error: 'class DS3231' has no member named 'getTimeStr'; did you mean 'getMinute'?

  lcd.print(rtc.getTimeStr());

                ^~~~~~~~~~

                getMinute

ANA_FEEDER_PROJECT:152:16: error: 'class DS3231' has no member named 'getDateStr'; did you mean 'getDate'?

  lcd.print(rtc.getDateStr());

                ^~~~~~~~~~

                getDate

exit status 1

no matching function for call to 'DS3231::DS3231(const uint8_t&, const uint8_t&)'

This report would have more information with
"Show verbose output during compilation"
option enabled in File -> Preferences.

The problem is that I always got a "No matching function for call to'DS3231 (const uint8_t &, const uint8_t &)"
Here's the error code

please read what you wrote ... there is no reason to repeat sentences

You are using the wrong DS3231 library. Unfortunately, you can often find incompatible libraries that share the same name. The sketch you downloaded has been written for a specific version of the DS3231 library. Thus your choices are:

either you use that specific version (linked to in the page you gave as reference)
or you adapt the code to work with the version you have installed.


text:
How to turn off the display of line numbers on Mac Arduino IDE?
I'm trying to turn off line numbers on the Mac Arduino IDE but don't see the option for it after navigating to Arduino IDE > Preferences. Below is a screenshot of what I am seeing.

I saw this question asked previously, but there is no File > Preferences path on Mac. I am using Version 2.0.0 on macOS (10.14 or newer).

OT, just out of curiosity: Why do you want them to be off? For example, I cannot work without line numbers.

I don't see a proper place to do this in the 2.0.0 IDE preferences. However, modifying the .arduinoIDE/setting.json file to include "editor.lineNumbers": "off", seems to work.
{
 "editor.lineNumbers": "off",
 "editor.fontSize": 14,
 ...
}

Edgar Bonet pointed out in a comment that there's still a bunch of empty space in that region. The image above doesn't do a good of showing why though. In the below screenshots I've told the IDE to set a breakout and hovered over where folding region so it displays the fold indicators to make somewhat easier to see that and compare what effect on width results from disabling these things.
If you want to save a bit more space you can add turn off the code folding feature, which removes the spaced that would be used for fold indicators with an additional "editor.folding": "false", in the settings.json file.
For comparison, here's everything enabled, numbers but no folding, folding but no numbers, no folding and no numbers:

I haven't yet found out how to turn off the display of break-point indicators. I assume that it is possible though.

Looks like it didn't remove from the layout the column dedicated to the line numbers: it's now just wasted space.

Yeah, it doesn't get rid of the entire area they inhabit. That space is also used for the indicators for code folding and indicators for breakpoints. So the space is only narrowed so much by the removal of the line numbers themselves. Maybe, I'll look into seeing if there's a way to remove the entire area or what it looks like if told not to indicate breakpoints or folding.


text:
How to install FTDI Serial Drivers on Mac?
I'm following this tutorial on how to install FTDI drivers on macOS, but am facing some issues. After downloading the USB Serial Driver version 2.4.4 (for OS X 10.14) from FTDI Chip's virtual COM port (VCP) driver page (recommended by the tutorial), I still don't see any usbserial option listed under the Serial Port tab, shown below.

Because I'm running macOS Monterrey (12.0.1), I also tried downloading the Beta driver release (version 1.5.0) for OS X 10.15 and macOS 11/12. After running the installer from my Applications folder (as recommended), I get the following result, indicating success, but the options list remains the same as shown above.

Are there any workarounds? For reference, I am using Arduino IDE 2.0.0.

I have just managed to get the FTDI set up for my M1 mac using the Pro Mini. I think the issue is that newer macs automatically block the FTDI serial connection from being used as a com port. You need to install a program called D2XXHelper to prevent this behaviour.
I did the following, hopefully this will work for you too:

Install FTDI VCP Driver, found here: Scroll down to first table and find the latest Mac OS drivers. There are 2, the 2.4.4 version and the 1.5 version. I think you need to use the 1.5 version for the M1 but I’m not sure because I installed both before I did the next steps to get it working.
Install the D2XXHelper found here: Scroll down to first table and look in the comments column for the Mac OS row to find the download link.
After installing the D2XXHelper, you should get a security prompt saying system extension blocked. Follow this guide which shows how to provide permission for the system extension to be applied – this requires going into recovery mode and requires several computer restarts.
After following the steps in the guide, you should have enabled the D2XXHelper system extensions to be applied, in which case when you connect your Arduino to your computer via the FTDI connector, the Arduino IDE 2 should now recognise that a device has been connected via the FTDI virtual com port.
optional – to check that your FTDI is connected correctly to your Arduino, connect it up, Open a Terminal window and type “ls /dev/tty.*” and run this command. If the FTDI is connected properly then a usb serial device should show up in the results to this command.


text:
Improve SD logger - 0.02% of data isn't logged at desired rate
I'm working on a project to read data over CAN, display it on LCD and log data to SD card. LCD is on HSPI and SD card on VSPI. CAN and LCD code is working on core 1 and SD on core 0, there's no wifi. It's all working pretty well but now I'm looking for further improvements. I set the log to 20 Hz and took a sample of 117024 lines. Below is the "uniq -c" output of the seconds that weren't logged at 20 Hz (left column is the actual rate and right column is a specific second in the log). So only 21 out of 117024 lines. But why does this happen and how can I make sure that every line is logged at 20 Hz?
     18 3195
     17 5393
     16 5401
     16 1622
     14 5397
     14 1628
     14 1625
     14 1624
     13 5400
     13 5398
     13 5396
     13 5395
     13 5394
     13 1626
     12 1631
     12 1630
     12 1627
     12 1623
      8 5399
      8 1629

float timeStamp;
char filenameBuffer[23];
String filename;
bool logStarted = 0;
uint32_t lastSyncTime = 0, logStartTime = 0;

File file;

void initSD()
{
    if (SD.begin(5, SPI, 80000000))
    {
        Serial.println("Card Mount OK");
        updateFromFS(SD);
        generateFileName();
        sdInitialised = true;
    }
    else
    {
        Serial.println("Card Mount Failed");
        return;
    }
}

void logToSD()
{
    if (!sdInitialised) return;
    if (!EMUfresh) return;

    if (!logStarted)
    {
        file = SD.open(filenameBuffer, FILE_APPEND);
        if (file)
        {
            file.print("Time,RPM,MAP,TPS,IAT,CLT,Lambda,PulseWidth,EGT1,EGT2,Vbatt,Baro,IgnAngle,LambdaCorr,Gear,Pwm1,Vss,EmuTemp,CEL,FLAGS1,LambdaTarget,OilTemp,OilPress,CanState\r\n");
            logStartTime = millis();
            logStarted = true;
        }
    }

    uint32_t duration = millis() - logStartTime;
    uint32_t seconds = duration / 1000;
    uint32_t milliseconds = duration % 1000;
    String dataString = "";

    dataString += seconds;
    dataString += ".";
    if (milliseconds < 100) { dataString += "0"; }
    if (milliseconds < 10) { dataString += "0"; }
    dataString += milliseconds;
    dataString += ",";
    dataString += String(emu_data.RPM);
    dataString += ",";
    dataString += String(emu_data.MAP);
    dataString += ",";
    dataString += String(emu_data.TPS);
    dataString += ",";
    dataString += String(emu_data.IAT);
    dataString += ",";
    dataString += String(emu_data.CLT);
    dataString += ",";
    dataString += String(emu_data.lambda);
    dataString += ",";
    dataString += String(emu_data.pulseWidth);
    dataString += ",";
    dataString += String(emu_data.EGT1);
    dataString += ",";
    dataString += String(emu_data.EGT2);
    dataString += ",";
    dataString += String(emu_data.vBat);
    dataString += ",";
    dataString += String(emu_data.baro);
    dataString += ",";
    dataString += String(emu_data.ignAngle, 0);
    dataString += ",";
    dataString += String(emu_data.lambdaCorr, 0);
    dataString += ",";
    dataString += String(emu_data.gear);
    dataString += ",";
    dataString += String(emu_data.pwm1);
    dataString += ",";
    dataString += String(emu_data.vssSpeed);
    dataString += ",";
    dataString += String(emu_data.emuTemp);
    dataString += ",";
    dataString += String(emu_data.cel);
    dataString += ",";
    dataString += String(emu_data.flags1);
    dataString += ",";
    dataString += String(emu_data.lambdaTarget);
    dataString += ",";
    dataString += String(emu_data.oilTemperature);
    dataString += ",";
    dataString += String(emu_data.oilPressure);
    //dataString += ",";
    //dataString += String(can_error_data.state[1]); //Only first character
    dataString += "\r\n";

    file.print(dataString.c_str());

    if (millis() - lastSyncTime > 1000)
    {
        lastSyncTime = millis();
        file.flush();
    }
}

void generateFileName()
{
    char intBuffer[5];

    strcpy(filenameBuffer, "/");
    itoa(random(1000, 9999), intBuffer, 10);
    strcat(filenameBuffer, intBuffer);
    strcat(filenameBuffer, "-");
    itoa(random(10), intBuffer, 10);
    strcat(filenameBuffer, intBuffer);
    strcat(filenameBuffer, "-");
    itoa(random(10), intBuffer, 10);
    strcat(filenameBuffer, intBuffer);
    strcat(filenameBuffer, "_");
    itoa(random(10), intBuffer, 10);
    strcat(filenameBuffer, intBuffer);
    strcat(filenameBuffer, ".");
    itoa(random(10), intBuffer, 10);
    strcat(filenameBuffer, intBuffer);
    strcat(filenameBuffer, ".");
    itoa(random(10), intBuffer, 10);
    strcat(filenameBuffer, intBuffer);
    strcat(filenameBuffer, ".csv");

    Serial.println(filenameBuffer);
}

Excess usage of String class is bad. Use a fixed char buffer instead

Can you also show the code that calls the function logToSD() at 20Hz ?
In the meantime,  maybe read this to see if it applies: https://www.best-microcontroller-projects.com/arduino-millis.html heading "Arduino millis not accurate".
In principle,  constructs like this (which you've used elsewhere)
if (millis() - lastSyncTime > 1000) { lastSyncTime = millis(); //...; } should be written as
if (millis() - lastSyncTime > 1000) { lastSyncTime +=1000; //...; } due to the way millis() derives 1000 milliseconds from 1024 timer ticks.

See also this thread for a discussion about the behaviour of millis() when timing regular events: https://forum.arduino.cc/t/millis-not-in-sync-with-8mhz-system-clock/179267


text:
Bluetooth Arduino Data Type Error
In my code I want to send some float values from my phone to the Arduino's Bluetooth which I will then split using the substring function. it will then print that split value to the serial monitor.
I don't even know what is wrong but there is no error and it just spits out the ascii code of those numbers (not split). Please help if anyone has any idea.
Here is my code:
#include <Wire.h>
#include<SoftwareSerial.h>
#define TxD 3
#define RxD 2
SoftwareSerial bluetoothSerial(TxD,RxD);

String Sstring;
String arrayOne;

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

void loop()
{

 if(bluetoothSerial.available()>0)
 {

  arrayOne=bluetoothSerial.read();

  Sstring=arrayOne.substring(0);
  Serial.println(Sstring);
 }
}

First thing, you have to decide what data format the phone application
will use for sending the data to the Arduino: define a “language” of
sorts. Then you have to program both the phone and the Arduino to speak
that same language.
Unless the data throughput is critical, I strongly advise you to use a
text-based format, where each “message” is followed by a dedicated
character that signals the end of the message. Popular choices for the
message terminator are '\n' (ASCII line feed, numeric value 0x0a =
10), '\r' (carriage return = 0x0d = 13) and ';' (semicolon = 0x3b =
59). The semicolon is often used as a second-level separator, to split a
message into smaller fields.
Here is a simple example that reads one-line messages, using a line feed
as a delimiter:
void loop() {
    if (bluetoothSerial.available() > 0) {
        String message = bluetoothSerial.readStringUntil('\n');
        Serial.println(message);
    }
}

If you want to send the data as binary, then message framing becomes a
tricky problem. Since every possible byte value can legitimately appear
within the message (any byte can appear within a float), you cannot
simply reserve one byte to serve as a terminator. This is why, unless
you are an advanced programmer, I strongly encourage you to send
whatever data you want to send as text. Text also makes debugging much
easier.
Finally, I have to warn you that the String class is not friendly to
the memory of your Arduino, and can lead to instabilities if used
extensively. If you have time, I encourage you to study the robust way
to read text from the serial port: see the article Reading Serial on
the Arduino, by Majenko.

Hey , Thanks for your reply . I tried out your code and it seemed to show no errors (which is good) but when I tried to send a message from my phone and then used the \n terminator , the IDE didn't care , it just printed the whole message . I saw some logs regarding substring and readstringuntil but found no answer . I probably think its still the data type error .Thanks still !

@CodeStuff: What do you mean by “the IDE didn't care”? The IDE has nothing to do with this. If the Arduino did not find the line feed terminator, that's because you did not send it from the phone. Did you send the two characters '\' and 'n' instead? I do not know what programming environment you are using on the phone side, or whether you really know how to properly use it, but it is essential that you know what you are sending. If line feed is too complicated for that environment, try ';'.

I'm guessing the line arrayOne=bluetoothSerial.read();
is converting the received value to a string (character array of ASCII charachters terminated with the '\0' character).
Then, you copy that string to another string variable. If you want to split the string you should:

define a starting character > 0
and/or: define an ending character < the total string size.

See this link for more info.
You could try the following. I'm sure it's far from perfect but it might get you a bit further.
void setup()
{
    bluetoothSerial.begin(9600);
    Serial.begin(9600);
}

void loop()
{
    if (bluetoothSerial.available)
    {
        delay(100); // wait a little for the serial buffer to saturate. This value should be as short as possible

        // Save the buffer bytes as the float (Big Endian!)
        double received_float = (bluetoothSerial.read() << 24) | (bluetoothSerial.read() << 16) | (bluetoothSerial.read() << 8) | (bluetoothSerial.read());
        Serial.println(received_float);
    }
}

Some conciderations:

The nr of bytes a float occupies may differ on your phone and your Arduino. The example above uses a 32-bit float
If possible you'd want to start the transmission with a sequency of starting characters. That way, you can be sure to read the proper value.

There are multiple issues with this way of building the float from individual bytes: 1. The order of the bytes is not defined: it will be whatever order this version of the compiler decides this day to use. 2. Shifting by 16 or 24 bits will overflow on an Uno. 3. This cannot work for a float: you will get the bits of the original float interpreted as an integer, and that integer represented as a (very different) float.

Hey , I tried using the code , but  there was no message printed itself .