text:
Problem with using PubSubClient, the "callback" function doesn't seem to work correctly
I have a program that communicate between a esp8266 and a atmega328 using Serial, the esp8266 will connect to a MQTT server running on local network, and publish/subscribe to some topics. In the callback function for the subscribing, it will send an instruction to atmega chip to toggle the LED (pin 13). I am using XC4411 board which is an integrated 2-in-1 board with both esp and atmega.
The code looks like this:
On esp side:
#include <ESP8266WiFi.h>
#include <PubSubClient.h>
#include "credentials.h" // this is where I define the wifi ssid, psw, mqtt username/psw etc.
#include <Arduino.h>

#define SERIAL_BAUD 115200 //make sure this is the same in atmega code, serial communication with atmega chip
#define ESP8266_LED 1

WiFiClient espWifiClient;
PubSubClient espMQTTClient(espWifiClient);
const char* test_topic = "/test/msg01";
void reconnect();
void callback(char *topic, uint8_t *payload, unsigned int length);

void setup_wifi() {
    delay(10);
    WiFi.begin(MY_SSID, MY_WIFIPSW);
    while (WiFi.status() != WL_CONNECTED) delay(500);
}

void setup_mqtt() {
    espMQTTClient.setServer(MY_MQTT_SERVER_ADDRESS, MY_MQTT_SERVER_PORT);
    reconnect();
    espMQTTClient.subscribe(test_topic);
    espMQTTClient.setCallback(callback);

}

void reconnect() {
    while(! espMQTTClient.connected()) {
        if (espMQTTClient.connect(MY_MQTT_CLIENT_ID, MY_MQTT_USER, MY_MQTT_PSW)) {
            espMQTTClient.subscribe(test_topic);
        }
        else delay(500);
    }
}

void callback(char *topic, uint8_t *payload, unsigned int length) {

    digitalWrite(ESP8266_LED, !digitalRead(ESP8266_LED));
    Serial.println("[toggle]");

    // espMQTTClient.publish("/test/esp8266", topic, length);
    espMQTTClient.publish("/test/esp8266", payload, length);

    if (strcmp(topic, test_topic) == 0) {
        if (length >= 0 && (char) payload[0] == '1') {
            espMQTTClient.publish("/test/esp8266", "get payload 1");
        } else if (length >= 0 && (char) payload[0] == '0') {
            espMQTTClient.publish("/test/esp8266", "get payload 0");
        } else {
            espMQTTClient.publish("/test/esp8266", "unknown payload for topic /test/msg01");
        }

    }
}

void setup() {
    Serial.begin(SERIAL_BAUD);
    setup_wifi();
    setup_mqtt();
    pinMode(ESP8266_LED, OUTPUT);
}

String data_from_arduino = "";

void loop() {
    if (! espMQTTClient.connected()) reconnect();
    espMQTTClient.loop();
    while (Serial.available()) {
        char x = Serial.read();
        if (x == '\r')
            continue;
        data_from_arduino += x;
    }
    if (data_from_arduino != "") {
        espMQTTClient.publish("/test/arduino", data_from_arduino.c_str());
        data_from_arduino = "";
    }
    // espMQTTClient.publish("/test/esp8266", "hello from esp"); // this line works fine, so there is no connection problem
}

On atmega side:
#include <Arduino.h>

#define SERIAL_BAUD 115200

#define LED_PIN 13

String receivedCommand = "";
bool dataIn = false;

void setup()
{

    Serial.begin(SERIAL_BAUD); //same as ESP baud
    pinMode(LED_PIN, OUTPUT);
}

String msg_from_esp8266 = "";
bool start_receiving_msg = false;

void loop()
{
    while (Serial.available())
    {
        char c = Serial.read();

        if (c == '[')
        {
            start_receiving_msg = true;
            msg_from_esp8266 = "";
        } else if (start_receiving_msg && c != ']') {
            msg_from_esp8266 += c;
        } else if (start_receiving_msg && c == ']') {
            start_receiving_msg = false;
            if (msg_from_esp8266 == "toggle") {
                digitalWrite(LED_PIN, !digitalRead(LED_PIN));
                Serial.println("arduino toggle led");
            }
        }

    }
    delay(10);
}

Basically when you publish anything to topic /test/msg01 manually, it will try to toggle the esp8266's built in led. then esp8266 will publish a message to /test/esp8266 with the exact payload you publish to /test/msg01. Also, esp8266 will also send a serial message "[toggle]" to atmega. On the atmega side, it will check if it receives the "[toggle]" and toggle its built in LED, then it will send a message through serial. on the esp side, in the loop, it will receive that message from atmega and publish it to topic /test/arduino. This program is to test the communication between other mqtt client devices and the esp8266, as well as (communication between other mqtt client devices) and the atmega through esp8266 via serial.
The code in if (strcmp(topic, test_topic) == 0) is just some other additional test code.
Generally, you should expect the behaviour like this: once you publish any message to topic /test/msg01, you will see the same message being relayed to topic /test/esp8266. both esp8266 and atmega will toggle their LED on and off. And the message "arduino toggle led" will be published to topic /test/arduino.
However, neither LED toggles. And there is no message from /test/arduino. in topic /test/esp8266 I saw some garbage text instead of my original message.
I have already troubleshooted the connection, the board configuration and checked if the lED is broken. They are all good, and I am pretty sure that the problem is to do within the "callback" function.
Here are some screenshot with the mqtt message:
What I have published to /test/msg01:

What I get from /test/esp8266

And, there is no problem with the message in /test/msg01 as I was also subscribing to the topic and get the same message as I published.

I didn't receive any message from topic "/test/arduino", so seems like the Serial message didn't get to atmega.
And again no problem with XC4411 board configuration as I turn the button 1, 2 on after I done flashing the two chips, and the code compiled and was uploaded to both chip successfully.
Looks like the callback function just corrupted my message, and also just somehow skipped and ignored the line that sends the toggle message to arduino and the line that toggle esp8266's LED.
I am very new to these topic discussed in the question in general, so maybe there are some mechanism that I am not aware of. Thank you the answers in advance.

From the PubSubClient library documentation:

Internally, the client uses the same buffer for both inbound and outbound messages. After the callback function returns, or if a call to either publish or subscribe is made from within the callback function, the topic and payload values passed to the function will be overwritten

Hi, that make sense. Thanks. Any ideas on why the LED isn't turn on and off?

I'm not familiar with the XC4411 board but suspect the ESP8266 LED isn't on GPIO 1 and anyway it may not be possible to use serial and the built in LED at the same time


text:
Arduino Mega Loopback Test with Several TX/RX Ports
I am trying to do a loopback test using an Arduino Mega. What I am looking to do is send a byte over TX and receive said byte back at RX and verify that the byte is unchanged. More or less I just have a jumper wire connecting the TX and RX ports (In reality I have a circuit hooked up to the TX RX ports that effectively acts like a wire, I'm just trying to verify that the circuit traces are sound).
I am also doing the exact same thing over TX2/RX2 and TX3/RX3.
The issue I have run into is that I can't seem to get the data to send out the TX ports. In my attempt I used Serial objects where I would do the following:
void setup() {
Serial.begin(9600); //0 and 1
Serial2.begin(9600); //16 and 17
Serial3.begin(9600); //14 and 15
}

void loop() {

//RX TX
int bytesSent = Serial.write(1);
delay(500);
if(Serial.read()!=bytesSent){

  //Do Something

}

delay(500);

//RX2 TX2
bytesSent = Serial2.write(2);
delay(500);
if(Serial2.read()!=bytesSent){

   //Do Something

}

delay(500);

//RX3 TX3
bytesSent = Serial3.write(3);
delay(500);
if(Serial3.read()!=bytesSent){

   //Do Something

}

delay(500);

}

I'm aware that the use of "delay(500)" is not optimal nor good coding practice but is left here for now while I'm still trying to understand what's wrong with my transmit and receive.
I believe my misunderstanding comes in with the Serial objects; Am I not using them correctly in this case? I've referenced the Arduino Serial reference guide, so this seems like it would work, but does not.
Further details: I am currently powering my Arduino via USB (which I'm aware can be an issue, but I currently do not have the battery power source). Would switching to the other power source resolve my issue? Just to reiterate I'm not trying to communicate with the PC, I'm just trying to verify that this external circuit (which acts like a wire) is able to carry the signal.

you have a logic error ... your code assumes that  bytesSent contains the data that was sent

How exactly do you know, that it doesn't work? In the code above you aren't doing anything. You only have the comments in there.

There seems to be a slight misunderstanding here:
bytesSent = Serial2.write(2);
// [...]
if (Serial2.read() != bytesSent) // [...]

On the serial ports:

the method write() returns the number of bytes that were written,
not the value of a written byte

the method read() returns the byte that was read (or −1 if nothing
was available), not the number of bytes read.

I suggest you modify your test like this:
uint8_t byte_sent = random(256);
Serial2.write(byte_sent);
delay(100);
if (Serial2.read() != byte_sent) // there was an error

source: Stack Exchange

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

sort: votes


text:
override pinMode, digitalWrite and digitalRead
I am using the ESP32 Arduino Framework and I have some GPIO expanders attached via I²C. They work fine and I now want to map some unused pin numbers to them so I can used my custom pin numbers in pinMode, digitalRead and digitalWrite.
Luckily, the Arduino core links these functions weakly.
extern void pinMode(uint8_t pin, uint8_t mode) __attribute__ ((weak, alias("__pinMode")));

I defined my own functions like so:
void pinMode(uint8_t pin, uint8_t mode) {
    if(pin<0x80)
        // call conventional handler
    else
        // communicate with GPIO expander via I²C
}

Unfortunately, calling any of the functions will not result in the linker picking my implementation but the linker picks the default implementation.
Any ideas how to override the weakly linked pinMode, digitalWrite and digitalRead?

use a different parameter type. some struct MyPin {int pin;} create constants like MP0, MP1,..

It used overloading before and it works for my custom code. However, I want all 3rd party libraries and the Arduino core to call my functions. E.g. when a display library call digitalWrite on some pins, I want that to work even if that GPIO is on my GPIO expander. Overloading would require me to rewrite the Arduino core and 3rd party libraries to use my function instead. I want to avoid that.

there are very few uses of these functions in core (analogWrite, tone, shift). with which libraries you want to use the io expander?

E.g. in MD_AD9833. My project will a tons of peripherals attached so I would have to fork many different libraries. That would not be viable...

that library uses SPI. do you need to run the CS pin over io expander? most libraries use SPI, I2C, PWM or direct register manipulation

You are exactly right. I need to run the CS pin over an SPI expander. In fact, my project has five different CS signals attached to IO expanders in addition to the native GPIOs of the ESP32. The other GPIOs on the expanders are used for relays and MOSFETs so I could address them with an overloaded function as you proposed. But the five CS pins are addressed by some thrid party libraries using the builtin digitalWrite.

I found the issue: I ran platformio run --target clean instead of platformio run --target cleanall. It seems that only the latter command cleans all build artifacts. The next time I compiled and uploaded, it worked as expected.
Another issue occurs only with Adafruit libraries: Some libraries do not use uint8_t for ports but int8_t and they do checks like
if(pin_number >=0)  {
    // code that only works with pin numbers between 0x01 and 0x80
}

Take the Adafruit GFX library as an example. As a workaround, I will map my GPIO expander ports to 0x40, 0x41, ...

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


text:
What are the Vs and Vss pins on an L293D chip for?
I made a simple test circuit to help me understand the L293D H-bridge that comes with the Arduino starter kit.

Digital output pins of the Arduino are wired to the input pins on the H-bridge. Arduino code alternately sends 1/0 and 0/1 down those two output pins, basically (as I understand it) creating an extremely low frequency alternating current in the two output pins on the H bridge. Two LEDs are wired in parallel to the output pins, in opposite directions, so they flash, demonstrating the alternating nature of the current.
The project I'm working on from the starter kit right now is the Zoetrope (page 102), and in that project the L293D is used to control a motor. The Arduino's 5V is connected to Vss and a 9V battery is connected to Vs.
So I'm a little surprised that I got it to work without using the Vs and Vss pins at all. What are they for? I did try swapping the LEDs out for the motor and it doesn't work (not enough power, I guess). But if I hook the 5V on the Arduino up to the Vs pin, it does! Hooking the 5V up to only the Vss pin, however, is not enough to power the motor.
So I sort of get the idea that without Vs and Vss current, the current from the input pins is enough to light the LEDs, but what I don't understand is:

If the voltage on the input pins isn't enough to drive the motor, how come connecting the 5V to the Vs pin is? It's the same voltage as is on the input pins.

What is the Vss pin for?

As you can see in the linked L293D PDF
VS is Supply Voltage (here connect the power source for motor)
VSS is Logic Supply Voltage (here connect the power source for the L293D chip logic - usually the same source as for +5V for Arduino)

The VSS suplies energy for the L293D to work correctly (like the Enable pin, inputs and such)

Also as you can see on the BLOCK DIAGRAM there are some mysterious diodes connected in little unusual way - at least on first look. When everything is well powered and normal, there are closed and do not conduct any current.
But if the voltage on (say) OUT1 became negative, then the lower diode connected to ground would start lead current and pull the OUT1 to the ground.
Similary if the voltage on OUT1 became higher, then the VS power source, then the top diode would open and drag the OUT1 down to the VS voltage.
It is for secure the internal circuits to work in sane environment. And if there is a motor (if any other inductance as relay or so), then there will be such peaks.
Similar security diodes are probably also on all input pins. (It is usual in logical circuits to limit input voltage in such way.) As you did not connect the VS to any power, when you send +5V (logical one) to any input pin, it was "pulled down" to VS via some such diode. This effectively "pulled up" the VS near the voltage on the pin and with VS powered the internal logic of L293D begin work, so magic happened.

There may be even some similary secured connection between VS and VSS, so some power from your Arduino output pin leaked by long and non-planed way to your LEDs and made them shine. LEDs do not need much current.

When you connected the motor instead, the long way proved to be too long and to have too much rezistence along it, that (nearly) all the voltage was distributed along it and on the motor was nearly nothing - and nearly no current was able go thru. Which is luck, as Arduino output pins have limit of 20 mA of current (or so).
When you conected +5V on the VS pin, there is much shorter way from it to motor and also with a lot less resistance along it, so there was enought voltage and enought current for the motor, so it was able to run.
Try it and measure the resistence of your motor - you will see, it will be nearly nothing, compared to the R=220 you used with the LEDs.
While it may not be visible in such simple example like this, you really should power the VSS so the logic there would work reliable.


text:
How can I observe the "voltage dips" the starter kit talks about in Project 5?
Project 5 of the Arduino Starter Kit book (page 63) involves wiring up a potentiometer to control a servomotor (see diagram). The book also recommends wiring up decoupling capacitors as shown in the diagram:

When a servo motor starts to move, it draws more current than if it were already in motion. This will cause a dip in the voltage on your board. By placing a 100uf capacitor across power and ground right next to the male headers as shown in Fig. 1, you can smooth out any voltage changes that may occur. You can also place a capacitor across the power and ground going into your potentiometer.

Since the book doesn't explicitly warn against it, I decided to do this whole project without the capacitors just to see what would happen. It seemed to work fine, I didn't notice any erratic behavior. Is there some experiment I could do to actually measure these voltage "dips"?
I thought maybe I could try to measure the voltage drop across the servo, so I wired it in series with a resistor and connected the A0 ADC pin between the servo and the resistor. I did measure a drop, but the servo didn't work... I'm guessing it wasn't getting enough power because of the resistor?

I'm guessing it wasn't getting enough power because of the resistor?

Yes, that is probably what happened (you didn't specify what value your resistor had). When the servo tries to draw more current, more current has to flow through the resistor. This means more voltage over the resistor and less for the servo, which then doesn't have enough to to powerful or even run at all (depending on the resistors value).

Is there some experiment I could do to actually measure these voltage "dips"?

You tried to measure the dips with the Arduino. Since the servo is connected directly to the 5V line of the Arduino, so its own Vcc, you cannot measure it the same way as the potentiometer. By default analogRead() uses Vcc as reference, meaning the max value. Instead you can configure it to use the internal 1.1V fixed reference (which doesn't depend on Vcc)(refer to analogReference()) and divide down Vcc with a fixed voltage divider (so that the voltage on the analog input pin would not exceed 1.1V).
Though to see the dips you still would need to measure the data points fast enough to catch them. Without knowing how long the dips might be it is difficult to say, if you can easily catch them. There are ways to do analog measurements relatively fast, but for a beginner (and specifically for a beginner book) that is a bit much.
The easier, but also more expensive solution (in terms of tools) is to measure Vcc with an oscilloscope. As entry a USB oscilloscope might be fitting (in the range of maybe 50$). If you don't wanna buy, you might be able to get access to one at the next makerspace or university. Some schools also might have some oscilloscopes.

Since the book doesn't explicitly warn against it, I decided to do this whole project without the capacitors just to see what would happen. It seemed to work fine

Dips in your supplied voltage might cause the Arduino to reset. But that only happens, when the dip is too big. And that depends on multiple factors:

How much current can be drawn from your power supply. USB ports on a PC won't give you more than 500mA for example. And some battery types have a big series resistance, meaning that the voltage will drop significantly, when you draw too much current from them.
Sometimes, when working on a breadboard, the contacts might also have a significant resistance to them. This can lead to a voltage loss there.
How strong the motor is. In starter kits you typically have these cheap and small SG90 micro servos. These don't draw a lot of power generally and are not really strong.
How much load is on the motor. A motor draws different amounts of current depending on its load. When it runs feely the currently is the smallest. When its starting, then it needs to fight against its own inertia, thus needing more current. The most current is used, when the motor stalls, because it is not powerful enough to push against the load.

The last two points affect the motor current, which might cause a voltage dip, if the power supply cannot provide that much current with the specified voltage.
The capacitors are a precaution in this case. I think the author wanted to explain this to make sure that it would work for everyone and that students would already know about this, when moving to bigger, more power hungry projects.

I tried a 10k resistor and a 220 ohm - with the former the servo didn't budge, with the latter it kind of twitched slowly.


text:
Mobile hotspot with wemos d1 mini
I recently got a wemos d1 mini and now am trying to connect it to my IPhone 13's hotspot, however it doesn't connect, I tried to run the wifiscan example - and it doesn't even detect it there.
I tried connecting it to my home router - and this worked hence I have no ideas on fixing it, so any help would be appreciated!

By default the iPhone hotspot is 5GHz only, which is why your ESP8266 can't see it. The ESP8266's WiFi radio is 2.4GHz only.
To enable 2.4GHz on the iPhone hotspot, turn on the "Maximize Compatibility" button under "Settings | Personal Hotspot". Then 2.4GHz devices should be able to connect to the phone.

Thank you!! This completely fixed the issue.


text:
how to avoid an Arduino pro micro waking up a pc
I have an Arduino Pro Micro only sending data via com port, connected to a PC.
I don't use the USB protocol and I think the Arduino send request with USB and it's the reason why my computer wakes up
I checked the device manager and there is no power management tab for the arduino, so I can't refuse the Arduino to wake the system up.
Also my BIOS don't have any option to wake up on a particular key combination

This "I don't use the USB protoco" is confusing. The Arduino is connected by USB, correct?  So it uses one of over a dozen USB protocols.  Probably USB/CDC.  Or are you trying to emulate a keyboard with the Arduino.  In that case USB/HID. Clearing this up may make it easier for people to answer your question.

No I use it as a standard Arduino only using the com port

The Aduino Pro Micro uses an Atmel,now Microchip, ATMEGA15U4 processor with built in USB. As it is built into the processor (other Arduinos have the USB outside the processor) your program can alter it. In normal operation I suspect the port is configured for USB/CDC and presents its self as a COM device to a Win computer. Did you check the COM device associated w/the Arduino for a power management tab? If there is no Arduino COM device, could your program have changed the USB protocol?

My Arduino appears in the com device as an Arduino Leonardo. And the program I have in is the deej project which I found on GitHub

Well, I'm confused. I just spent a lot of time looking at a github project that hasn't been touched in 2 years trying to figure out if the host Win computer needs to run a GO program or not. Then chasing down what looks like an obsolete discord account (which would likely be a better place to have this discussion). In the end, I'm no more enlightened as to what to suggest. I think the Arduino looks like a USB/CDC and I think your computer is unusual in that it turns on when seeing USB/CDC activity.  Or maybe any USB activity. IDK.

Arduinos with USB modules built in the MCU can announce themselves as compound devices consisting of a COM device, a keyboard and a mouse. At least the Leonardo does this, and I suspect yours, too. You might want to look for such devices with the same VID/PID, and then check your power preferences.

Assuming the computer is turning on due to the data received over the USB cable from the DEEJ box and not from simply plugging in the USB cable from the DEEJ box.
Consider, if this project otherwise works, re-writing the Arduino Sketch to not send out any data until after a specific digital GPIO pin goes from 1 to 0. Place a N.O. push button switch to ground on that digital GPIO pin. Remember to program that pin as a GPIO input with a pull up. If this works, not only will the DEEJ box control volumes, but might also be able to turn on the computer.

Before going to the trouble of re-writing the Sketch and adding a switch you might try to erase the Arduino and confirm that simply plugging on an Arduino does not power up your computer.

I just figured out window wakes up when the deej program is running with the Arduino connected,but when the Arduino is connected without the program running there is no problem.
So trouble is deej

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.

yes, but the questions sounded like how to not wake-up the PC with such a firmware in the Micro

No problem in answering your own question @Hadrox1.  But, it sounds like you are finding the cause and not a solution.  It is encouraged here (as in all stackexchange web sites) to make the question better by editing it instead. So: 1) Are you running a Windows program for DEEJ  on your Windows computer? 2) "without the program running" Is this the program on the Arduino or on the Windows computer? 3) What is returned whey you type "powercfg -requests" into a command prompt on your Windows computer after it has been powered up by DEEJ?


text:
Can I use regular pins (Example: D2, A3, etc...) as serial (RX, TX)?
Python/Arduino Beginner here...
I have a DFplayer I am trying to hook to my Arduino and I want to hook it up through the regular pins instead of the RX and TX pins, but I've not been able to find detailed information on if I can do that and how to set it up... Is this possible to do?

https://docs.arduino.cc/learn/built-in-libraries/software-serial


text:
Errors when trying to connect esp8266 to firebase
hello guys i was trying to connect my project to firebase but got this erorrs:
d:\Kuliah\Mata Kuliah\Internet of Things\Arduino\libraries\FirebaseArduino\src\Firebase.cpp: In member function 'int FirebaseRequest::sendRequest(const string&, const string&, char*, const string&, const string&)':
d:\Kuliah\Mata Kuliah\Internet of Things\Arduino\libraries\FirebaseArduino\src\Firebase.cpp:78:1: error: no return statement in function returning non-void [-Werror=return-type]
   78 | }
      | ^
d:\Kuliah\Mata Kuliah\Internet of Things\Arduino\libraries\FirebaseArduino\src\Firebase.cpp: In member function 'void FirebaseStream::startStreaming(const string&, const string&, const string&)':
d:\Kuliah\Mata Kuliah\Internet of Things\Arduino\libraries\FirebaseArduino\src\Firebase.cpp:91:16: warning: ISO C++ forbids converting a string constant to 'char*' [-Wwrite-strings]
   91 |   analyzeError("STREAM", status, path_with_auth);
      |                ^~~~~~~~
d:\Kuliah\Mata Kuliah\Internet of Things\Arduino\libraries\FirebaseArduino\src\FirebaseHttpClient_Esp8266.cpp: In member function 'virtual void FirebaseHttpClientEsp8266::begin(const string&)':
d:\Kuliah\Mata Kuliah\Internet of Things\Arduino\libraries\FirebaseArduino\src\FirebaseHttpClient_Esp8266.cpp:47:50: error: no matching function for call to 'begin(const char*, const char [60])'
   47 |     http_.begin(url.c_str(), kFirebaseFingerprint);
      |                                                  ^
In file included from d:\Kuliah\Mata Kuliah\Internet of Things\Arduino\libraries\FirebaseArduino\src\FirebaseHttpClient_Esp8266.cpp:9:
C:\Users\NyK\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\3.1.2\libraries\ESP8266HTTPClient\src/ESP8266HTTPClient.h:166:10: note: candidate: 'bool HTTPClient::begin(String, uint16_t, String)' (near match)
  166 |     bool begin(String host, uint16_t port, String uri = "/")  __attribute__ ((error("obsolete API, use ::begin(WiFiClient, host, port, uri)")));
      |          ^~~~~
C:\Users\NyK\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\3.1.2\libraries\ESP8266HTTPClient\src/ESP8266HTTPClient.h:166:10: note:   conversion of argument 2 would be ill-formed:
d:\Kuliah\Mata Kuliah\Internet of Things\Arduino\libraries\FirebaseArduino\src\FirebaseHttpClient_Esp8266.cpp:47:30: error: invalid conversion from 'const char*' to 'uint16_t' {aka 'short unsigned int'} [-fpermissive]
   47 |     http_.begin(url.c_str(), kFirebaseFingerprint);
      |                              ^~~~~~~~~~~~~~~~~~~~
      |                              |
      |                              const char*
In file included from d:\Kuliah\Mata Kuliah\Internet of Things\Arduino\libraries\FirebaseArduino\src\FirebaseHttpClient_Esp8266.cpp:9:
C:\Users\NyK\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\3.1.2\libraries\ESP8266HTTPClient\src/ESP8266HTTPClient.h:167:10: note: candidate: 'bool HTTPClient::begin(String, const uint8_t*)' (near match)
  167 |     bool begin(String url, const uint8_t httpsFingerprint[20])  __attribute__ ((error("obsolete API, use ::begin(WiFiClientSecure, ...)")));
      |          ^~~~~
C:\Users\NyK\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\3.1.2\libraries\ESP8266HTTPClient\src/ESP8266HTTPClient.h:167:10: note:   conversion of argument 2 would be ill-formed:
d:\Kuliah\Mata Kuliah\Internet of Things\Arduino\libraries\FirebaseArduino\src\FirebaseHttpClient_Esp8266.cpp:47:30: error: invalid conversion from 'const char*' to 'const uint8_t*' {aka 'const unsigned char*'} [-fpermissive]
   47 |     http_.begin(url.c_str(), kFirebaseFingerprint);
      |                              ^~~~~~~~~~~~~~~~~~~~
      |                              |
      |                              const char*
d:\Kuliah\Mata Kuliah\Internet of Things\Arduino\libraries\FirebaseArduino\src\FirebaseHttpClient_Esp8266.cpp: In member function 'virtual void FirebaseHttpClientEsp8266::begin(const string&, const string&)':
d:\Kuliah\Mata Kuliah\Internet of Things\Arduino\libraries\FirebaseArduino\src\FirebaseHttpClient_Esp8266.cpp:51:60: error: invalid conversion from 'const char*' to 'const uint8_t*' {aka 'const unsigned char*'} [-fpermissive]
   51 |     http_.begin(host.c_str(), kFirebasePort, path.c_str(), kFirebaseFingerprint);
      |                                                            ^~~~~~~~~~~~~~~~~~~~
      |                                                            |
      |                                                            const char*
In file included from d:\Kuliah\Mata Kuliah\Internet of Things\Arduino\libraries\FirebaseArduino\src\FirebaseHttpClient_Esp8266.cpp:9:
C:\Users\NyK\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\3.1.2\libraries\ESP8266HTTPClient\src/ESP8266HTTPClient.h:168:70: note:   initializing argument 4 of 'bool HTTPClient::begin(String, uint16_t, String, const uint8_t*)'
  168 |     bool begin(String host, uint16_t port, String uri, const uint8_t httpsFingerprint[20])  __attribute__ ((error("obsolete API, use ::begin(WiFiClientSecure, ...)")));
      |                                                        ~~~~~~~~~~~~~~^~~~~~~~~~~~~~~~~~~~
cc1plus.exe: some warnings being treated as errors

exit status 1

Compilation error: exit status 1

i've installed the latest version of esp8266 and "Firebase Arduino Client Library for ESP8266 By Mobitz" but the error still occured. please help
here's my full code:

#include <ESP8266WiFi.h>
#include <SoftwareSerial.h>
#include <FirebaseArduino.h>
#include <ArduinoJson.h>
#include <ESP8266HTTPClient.h>
#include<DHT.h>

#define FIREBASE_HOST "*****firebaseio.com"
#define FIREBASE_AUTH "*****UKBpSMo07nUT8ZWYS9"

#define WIFI_SSID "******"
#define WIFI_PASSWORD "******"

#define DHTPIN D5
#define DHTTYPE DHT11

DHT dht(DHTPIN, DHTTYPE);

bool light;
bool fan;

unsigned long previousMillis = 0;
const long interval = 10000;

void setup() {
  pinMode(D1, OUTPUT);
  Serial.begin(115200);
  delay(500);
  WiFi.begin(WIFI_SSID,WIFI_PASSWORD);
  Serial.println("Connecting..");

  while (WiFi.status() != WL_CONNECTED){
    Serial.print(".");
    delay(500);
  }
  Serial.println();
  Serial.print("Connected");
  Serial.println(WiFi.localIP());

  Firebase.begin(FIREBASE_HOST,FIREBASE_AUTH);
  dht.begin();

  delay(2000);
  // put your setup code here, to run once:
}

void readDatas(){
  float h=dht.readHumidity();
  float t=dht.readTemperature();

  Firebase.setFloat("Data/Temperature:",t);
  Firebase.setFloat("Data/Humidity:",h);
}

void loop() {
  light = Firebase.getBool("LightStates/switch");
  Serial.println(light);
  if(light==true){
    digitalWrite(D6, HIGH);
  }
  if(light==false){
    digitalWrite(D6, LOW);
  }

  fan = Firebase.getBool("FanStates/switch");
  Serial.println(fan);
  if(fan==true){
    digitalWrite(D7, HIGH);
  }
  if(fan==false){
    digitalWrite(D7, LOW);
  }

  unsigned long currentMillis = millis();
  if(currentMillis-previousMillis>=interval){
    readDatas();
    previousMillis=currentMillis;
  }

}

The library "Firebase Arduino Client Library for ESP8266 By Mobitz"  doesn't have FirebaseArduino.h. You perhaps installed the wrong library?

I also installed the firebase master but still didn't work

I don't know which library is "firebase master". But I think you should select one library and stick to it. I believe "Firebase Arduino Client Library for ESP8266 By Mobitz" is pretty well documented. If you decide to use that, first check their examples and make them work. And then start injecting your code into their examples. Wherever you copied your code from I believe it is using an old library that is not maintained anymore and not available in the Arduino Library Manager.

fixed by downgrading my esp8266 version to 2.7


text:
ESP32-CAM OV2640 AS A SUN SENSOR
I want to use the ESP32-CAM as a sun sensor, the problem is that I would need to remove the lenses in order to put a membrane with a pinhole (like it's illustrated in the image) upon the CMOS, but I want to know first, will this make unoperable the OV2640? I want it to be working fine without the lenses, the second image is an illustrative of what I want to do.

what is preventing you from determining the results experimentally?

It is a bit expensive here in Mexico, 227.00 pesos (13.14 USD), so I only have one shot to buy it, I know It may not be that expensive in other currencies, but here is like a week worth of food haha, so that's why... I dont want anyone to make the experiment and possibly hurt their ESP32-cam, I just would like to know If someone has tried it.

that is a very good reason for not determining the results experimentally

what exactly are you trying to do? ... what does the sun sensor measure?

I want to measure the azimuth and elevation angle, thanks to the incident angle of the sun!

if you know your geographic location and the correct time, then those values can be calculated without the need for a camera

As an alternative to disassembling the camera, you may consider keeping the lens, and pointing the whole camera to the sun through a high-density neutral density filter. A B&W negative fully fogged and developed may serve as a cheap filter.

Yes, they can be calculated, but I want to make a sun sensor to use it to simulate an ADCS for a cubesat, this will be a second sun vector, I already have the sun position vector, thru the Vallado algotihm

Consider using the ESP32-CAM as is. Instead use a pin hole camera box. Put the ESP32-CAM inside the box pointing it at the image of the sun at the back of the box. This approach mitigates problems associated with exposing the sensor to the elements and direct exposure to sun light.
In order to measure azimuth and elevation, consider mounting the device such that it points directly up from the surface of the earth.  And such that it is aligned to true North. Consider using an accelerometer to detect the device is normal to the surface of the earth. And a magnetometer to detect magnetic north.  And a GPS receiver to detect the position on earth.  Combine the GPS data with  World Magnetic Model (WMM) data to correct for magnetic declination.

Yeah!! I thought of that, but I think that the aperture diameter of the camera already kinda serves as a pinhole, what I want to do is to have oportunity to make it myself so I will have the possibility of control the values that I want, like the FoV for example.

Unless you find someone who has done this, you are asking for opinions which stack exchange is not equipped to handle.  You added that you need azimuth and elevation. You will need to add a tilt compass in order to get azimuth and elevation. I'll add that to the answer.

That is a good idea, Im going to consider it, thanks!!

I am not sure how you would do this, but I believe that a SHARP distance measurement sensor has a linear optical sensor.  So it may be possible to modify 2 of these to measure the angle of the sun along the north south axis and along the east west axis.  Again, not sure how you would do this.  But these sensors my be less expensive to experiment with.


text:
NRF24L01 PA+LNA With Arduino
I am using the NRF module for remote communucation.I have been many research about nrf but my nrf module is not working This is my tranmistter code:
#include <SPI.h>
#include <nRF24L01.h>
#include <RF24.h>

RF24 radio(7, 8,4000000); // CE, CSN

const byte address[6] = "00001";

void setup() {
  Serial.begin(115200);
  radio.begin();
  radio.openWritingPipe(address);
  radio.setRetries(15,15);
  radio.setPALevel(RF24_PA_HIGH);

}

void loop() {
  radio.stopListening();
  const char text[32]="Hello world";
  if(radio.write(&text,sizeof(text))){
    Serial.println("Mesaj gönderildi");
  }
  delay(1000);

This is my receiver code:
#include <SPI.h>
#include <nRF24L01.h>
#include <RF24.h>

RF24 radio(7, 8,4000000); // CE, CSN

const byte address[6] = "00001";

void setup() {
  Serial.begin(9600);
  radio.begin();
  delay(400);
  radio.openReadingPipe(1, address);
  radio.setPALevel(RF24_PA_MAX);
//  radio.startListening();
   pinMode(10,OUTPUT);

}

void loop() {
 const char text[32]="";
  radio.startListening();
  if(radio.available())
  {
    while(radio.available()){
    radio.read(&text[0],sizeof(text[0]));
    Serial.println(text);
    delay(1000);
    }
  }
  delay(5);

}

ı tried the setPAlevel min but there is no change.In the transmitter side the write function returns true, but I can't get anything on the receiver side. Also, if I replace the cable connected to miso with the cable connected to mosi on the transmistter side, the write function still returns true. I also used adaptor ams1117

From your Receiver code: radio.read(&text[0],sizeof(text[0])); This looks odd. sizeof(text[0]) is only one byte.

I tried this buy now ı am trying gettinstarted examples in arduino.Mosi and miso pins does not connect to microcontroller but output which ı take is this:Tranmission successful.

Also.I get a radio hardware not responding error when mosi is connected to the arduino mosi pin on the adapter and miso on the adapter is connected to the miso pin on the arduino.When I reverse the cables and connect them, the transmission and reception occur.

const char text[32]=""; from the receiver also looks odd because this buffer is supposed to be writable. Anyway, use the code from the thread here: https://forum.arduino.cc/t/simple-nrf24l01-2-4ghz-transceiver-demo/405123 to test your nrf24L01 devices. Most problems with these nrf24L01 devices are related to inadequate power supplies.

"When I reverse the cables and connect them, the transmission and reception occur." Does this mean that if you cross over MISO and MOSI on the nrf24L01 adapter board,  it all works as expected? I'd be surprised considering the other errors but I suppose it could be a labeling error somewhere.

Yes.But this only happens at the very beginning. I uploaded the program to Arduino, then I get a radio hardware not responding error. Then I plug the mosi cable on the nrf board into the miso on the arduino. The radio hardware not responding error goes away. Transmissin timed out error comes.Then, after plugging the mosi in the nrf module into the mosi on the arduino, and the miso on the miso on the arduino, the transmission becomes successful.

In the receiver code, you are just reading one byte, as 6v6gt pointed out. Check the library to see how read() works.
If you follow the getting started example, this is how you should read bytes in the receiver:
char text[32];

if (radio.available())
{
  uint8_t bytes = radio.getPayloadSize();  // get the size of the payload
  radio.read(&text, bytes);                // fetch payload from FIFO
}

Don't use const for text in the receiver.
Also, you don't need to use stopListening and startListening in the loop(). They should just go to setup().

Tranmission failed or timed out erros is occured.I tried many things but this error is still continues

Update the code in the question that you tried last.


text:
How to communicate pt2262 and pt2272 modul

There is a library called Virtual wire. I used it, but without success. I couldn't quite understand its pins. Can you explain? How can I use it?First picture receiver(pc2272) second picture tranmitter(pc2262 module ı used)

please add the information that you are looking at ... explain what part you do not understand

For example, there are 4 channels. How will I use each of these channels? In some places, the receiver assumes that the data is received when the pin to which the receiver is connected is HIGH. Is this true? I couldn't understand how it works in general

Also .What is the difference nrf24l01?

wbere are you seeing this information? ... add all info to the question ... please use the edit button to add it


text:
Using interrupts as flags/latches without any ISR
I've got an Arduino Mega periodically running an (~400ms) operation that is sensitive to repeatable timing, so I don't ever want it to be interrupted.  But, I'd like to be able to use an interrupt flag from one of the built-in peripherals (PCINT, comparator, etc.) to check afterward if an external event (say, a pin going high momentarily) ever happened during the operation.
That is, it'd be nice if I could just treat one of the interrupt flags as a kind of async hardware latch that I can check (and reset) at my next earliest convenience instead of having my code interrupted.
It wouldn't be hard to add a discrete latch IC, but I was hoping I could get away with just using what was already built into the AVR without adding more hardware (and using an extra pin to reset the latch).
Looking at the documentation for each of the peripherals, it was unclear whether the flags will still be set when the interrupts themselves are disabled.  I saw a mention someplace of an "EMPTY_INTERRUPT" macro, but I'm guessing that still generates an interrupt vector with a single "return" instruction, so I'd still be losing cycles to the interrupt preamble, etc.
Can this be done without any ISR being called at all?  Or do I need to add more hardware?  I'm not sure wrapping the long-running task in noInterrupts()/interrupts() is a choice unless that also doesn't interfere with UART receiving.  Thanks!

According to my page about interrupts the minimum time to execute an ISR is  2.625 µs plus whatever the code does (like set a flag). Is that not acceptable? Once? In your 400ms routine? That's a tiny fraction of how long your code takes.

I'm not sure wrapping the long-running task in noInterrupts()/interrupts() is a choice unless that also doesn't interfere with UART receiving. - so some interrupts are actually OK?

If you are receiving from a UART then time isn't really of the essence, is it? What is the baud rate?

What are the specific requirements of that periodic operation, jitter, frequency, tolerances, and so on?

I'm strobing LEDs to provide uniform illumination for a dozen or so successive industrial camera exposures (using a busy-wait).  It's less about exact timing and more about repeatable timing.  Each exposure is only a couple hundred microseconds, so even 2.625µs of periodic jitter would increase the exposure time by at least 1%.  I could use one of the timers, but I preferred the simplicity of the straight-line code.  I didn't know the UART interrupts the CPU; I'll have to check out the datasheet and maybe ask a separate question about that.

For your requirements, I would consider adding external hardware to detect and buffer the condition, giving you a GPIO that you can poll, where high means "the event happened since the last time you reset it". My guess is you could do it easily and cheaply. You might ask over on the electronics stack exchange for the best way to approach it. Then you wouldn't need to deal with interrupts at all.

... Sorry, on reread I see that you considered that option and were looking for alternatives.

The answer to your question is: yes, you can use an interrupt flag even
if the interrupt itself is disabled. The flag is raised whenever the
peripheral detects the relevant event. You can check it at your
convenience.
As for resetting the flag, the way to do it varies from flag to flag.
Most are reset by writing a 1 bit to it (yes, it is kind of backwards,
but that's how it works). Others are reset by removing the condition
that raised them in the first place (e.g. the USART Data Register Empty interrupt). You will have to check the datasheet for the specific
interrupt flag you are interested in.
That being said, I would question your idea that you don't want your
code to be interrupted at all. As Nick Gammon writes in a comment, the
minimum time to execute an ISR is 2.625 µs. This is about 0.0007%
of the process period. If your operation is so time-sensitive that it
cannot tolerate this kind of variation, then it cannot run on a Mega at
all. The ceramic resonator that clocks a Mega has a typical accuracy of
about 0.1%, which is 150 time worse than the effect of a minimal
interrupt. Even if you calibrate this oscillator against an atomic
clock, in only a few hours its frequency will drift past 0.0007%.
In addition, if you want the code to work with no interrupts, you will
have to disable them explicitly with noInterrupts(). You will then
loose the Arduino timing function millis(), delay(), etc. And you
will not be able to receive data from the UART unless you write your own
code that polls the “receive complete” UART interrupt flag and then
grabs the data from the UART data register.

Are you certain about that? In the datasheet it says The External Interrupts 7 - 4 are activated by the external pins INT7:4 if the SREG I-flag and the corresponding
interrupt mask in the EIMSK is set. My reading of that was that the flag is set if the interrupt is enabled. Otherwise, how would it know if it is rising or falling?

I might be wrong about that, I admit.

@NickGammon: In edge-detection mode, the flag is set even if the interrupt is disabled (I just checked). However, this is a bad example, as the interrupt flag does not work in level-detection mode: “These flags are always cleared when INT7:0 are configured as level interrupt.” I changed the example in my answer.

I left a comment above, too, but the actual process period is ~200µs (repeated many times) while exposing an image to a camera sensor.  And it's less sensitive to any particular clock rate.  I just want each identical busy-wait to take the same wall-clock time so there isn't any brightness difference between each exposure.  Even that 2.6µs gives around 1.3% additional illumination.  On a 12-bit sensor, that starts to add up quickly.  The UART intentionally isn't sending or receiving during that period, so hopefully it's alright to just leave it enabled...

It seems to me that the question of whether the flag is set or not might be somewhat implementation-specific. Even if it is 100% guaranteed for AVR chips it might not be for others, hence relying on that behaviour is not very good practice.

@MarkMorganLloyd the entire code is specific to one particular chip, so that doesn't really make sense.

@hobbs: Not my Mega, nor the one shown on the Arduino store. Unless you are talking about the quartz clocking the 16U2 that does the USB-to-serial conversion, which is irrelevant to the question being asked.

@hobbs actually, OP specifies "Arduino Mega" rather than a specific chip- even if that is tightened up somewhat in subsequent discussion. However using the interrupt flags in this way appears (to me at least) to be a fundamental design decision, and even if this is expected to be a one-off hobby project that sort of thing is risks cause enormous problems in the future if somebody else tries to use the code, or if a more appropriate chip comes onto the market.

I'm not sure wrapping the long-running task in noInterrupts()/interrupts() is a choice ...

That's right. Turning off interrupts would stop the timing/delay working so you wouldn't be able to time your 200 µs (unless you use delayMicroseconds).

Each exposure is only a couple hundred microseconds, so even 2.625µs of periodic jitter would increase the exposure time by at least 1%.

I think you might be better off using a hardware timer to time the exposure, rather than a loop. I generated VGA signals in a post here where I wanted the horizontal and vertical sync to have no jitter whatsoever. The timers can be set to turn on, or off, an output pin, so that could be used to control your shutter. Then it would be completely precise.

I didn't know the UART interrupts the CPU ...

Incoming (or indeed outgoing) serial communications causes interrupts. The timers cause interrupts. In particular, if you haven't disabled it, Timer 0 generates interrupts which are counted so that millis() and micros() can function. You can disable interrupts but then timing exact intervals becomes problematic. My suggestion of using the timer hardware will give the most reliable and repeatable performance, in the same way that my VGA signal generation was completely without jitter.
Because of the timer interrupts, if you haven't disabled interrupts, some of your exposures may have the timer interrupt in the middle (making them longer) and some not, or at least, a different number of interrupts. This will make the exposure time non-precise.

Another approach would be to turn off interrupts for the exposure only (ie. your 200 µs, not the 400 ms you mention), and then use delayMicroseconds() to time the exposure. Then when interrupts are back on the closure of a switch (an external interrupt) could be processed by a normal ISR. This might add slight differences to the time between exposures, but the exposure time itself would be constant.
Even with interrupts off, an external interrupt is "remembered" and would be processed when interrupts are enabled again.

This is turning into an XY problem somewhat. It would have been better to mention your exact requirements (the photography part) rather than launching into questions about using interrupts as latches.

Example code
To demonstrate how you can do this with timers, I have written some sample code:
// Example of strobing a flash FRAMES_TO_TAKE times to take pictures
// The time between each flash is in TIME_BETWEEN_SEQUENCES
// The flash "on" time is in STROBE_ON_TIME
//
// For Atmega328P (Arduino Uno and similar)
// and Atmega2560 (Arduino Mega)

// Author: Nick Gammon
// Date: 4 July 2023

const byte FRAMES_TO_TAKE = 12;
const byte CPU_CLOCK_SPEED = 16;  // MHz

const unsigned long TIME_BETWEEN_SEQUENCES = 20000;  // µs
const unsigned long STROBE_ON_TIME = 200;  // µs
const byte PRESCALER = 64;

// set correct output pin
#if defined(__AVR_ATmega168__) || defined(__AVR_ATmega328P__)
  const byte FLASH_PIN = 10;  // OC1B (Output Compare Timer 1: B side) - Atmega328P
#elif defined(__AVR_ATmega1280__) || defined(__AVR_ATmega2560__)
  const byte FLASH_PIN = 12;  // OC1B (Output Compare Timer 1: B side) - Atmeg12560
#else
  #error Processor not supported
#endif

volatile byte count;  // how many times it fired

// Timer 1 Compare "B" ISR vector
// count up to the required number of exposures, then stop
ISR (TIMER1_COMPB_vect)
  {
  if (++count > FRAMES_TO_TAKE)
    {
    // stop timer 1
    TCCR1A = 0;
    TCCR1B = 0;
    } // end if number of frames reached

  }  // end of TIMER1_COMPB_vect

// does one sequence of FRAMES_TO_TAKE shots and then stops
void startSequence ()
{
  // stop timer 1
  TCCR1A = 0;
  TCCR1B = 0;

  TCCR1A = bit (WGM10) | bit (WGM11);  // fast PWM - top at OCR1A
  TCCR1B = bit (WGM12) | bit (WGM13);  //  (mode 15)

  TCCR1A |= bit (COM1B1);   // Set OC1B during duty cycle

  OCR1A = ((TIME_BETWEEN_SEQUENCES * CPU_CLOCK_SPEED) / PRESCALER) - 1;  // total cycle time
  OCR1B = ((STROBE_ON_TIME * CPU_CLOCK_SPEED) / PRESCALER) - 1;          // duty cycle time
  count = 0;

  TCNT1 = 0;    // reset timer count

  TIFR1   = bit (OCF1B);    // clear "compare B" flag
  TIMSK1  = bit (OCIE1B);   // interrupt on compare B match
  TCCR1B |= bit (CS10) | bit (CS11);     // start timer with prescaler of 64
} // end of startSequence

void setup ()
  {
  // stop timer 1
  TCCR1A = 0;
  TCCR1B = 0;

  // set up pin so we can toggle it
  pinMode (FLASH_PIN, OUTPUT);
  digitalWrite (FLASH_PIN, LOW);

  // for debugging etc.
  Serial.begin (115200);
  }  // end of setup

void loop ()
  {
  startSequence ();
  delay (20);
  Serial.print ("But does it get goat's blood out?\n");
  delay (1000);
   }  // end of loop;

Code explanation
What this code does is use Timer 1 to time the intervals you require. Based on what you posted earlier, I have assumed:

12 exposures in a "session" (FRAMES_TO_TAKE) - you said "a dozen or so"
Exposures are to be 20 ms apart (TIME_BETWEEN_SEQUENCES) - so a session is 240 ms
Exposure time is to be 200 µs (STROBE_ON_TIME) - you said "a couple of hundred microseconds"
You want to do other stuff like serial comms, checking switches etc.

The function startSequence initiates the timer which has a period of 20 ms and a duty cycle of 200 µs. At the completion of a duty cycle the ISR is called which counts duty cycles. At the end of the nominated number (12) the timer is turned off.
The output pin (pin 12 on the Mega, pin 10 on the Uno) is turned on during the duty cycle (ie. for 200 µs and off the rest of the time). Because this is done in hardware there is no jitter at all. In my demo I am doing serial comms to show that the intervals are exactly correct, despite the interrupts caused by the comms.

Logic analyser output
The logic analyser screenshot shows that the intervals are exactly correct (to within a fraction of a percent). In any case the intervals are consistent with each other.

This second screenshot shows that there are 12 pulses in that interval.

I have used a prescaler of 64 to get a nice long interval that can be timed (without overflowing the 16-bit counter size). This gives a granularity of 64 clock cycles (4 µs).

Timer 1 cheat sheet

These are all good suggestions.  Disabling interrupts for the individual exposures sounds like it might be the way to go.  I was only avoiding timers out of the convenience of not having to reason about the usual ISR problems: atomic (16-bit) read/writes, etc., but my scheme is simple enough that I could probably just set the timer, busy wait until it fires, and then continue on my way.  Regarding the XY problem, this is still an interesting question to me and I'm happy I know the answer for future projects, even if I don't end up using the interruptless-flags approach here.

@Nicholas If you let the timer itself change the pin state then you eliminate the (small) jitter based on where in your tight loop checking the timer to finish, it actually finishes. The read of the timer state, the compare, and the branch would probably amount to 6 to 8 clock cycles.

You are right that checking a timer flag in software introduces some jitter, but it's not as bad. A tight loop testing a flag on timer 1, 3, 4 or 5 is just sbis + rjmp. It takes 3 cycles, thus you have a 2-cycle jitter. Timers 0 and 2 require an lds, making it a 5-cycle loop.

@Nicholas See amended answer with example code of using a timer.


text:
Can I program ATTINY using Arduino as ISP whilst having other I2C devices connected?
I have an SMD ATTINY that I'm using for a project. Attached to it are 3 I2C devices. When programming it using an Arduino as an ISP, can I have those devices attached? Ie, do I have to program the ATTINY and then solder it on my board or can I solder it and the program (and re-program if necessary).

why don't you just try it? ..  you said that the I2C devices are already connected

@jsotola - Maybe because he'd rather not risk damaging something in case someone else already knows?

Welcome to SE/Arduino! Please [edit] your question and add the schematic, so we can see how you connect the I²C devices, together with the ISP connector.

Yes, the slave devices shouldn't respond unless addressed. When programming, data will obviously be on the lines however the probability of this data accidentally containing the right sequence to correctly query a slave is minimal.

Did you consider that devices are allowed to stretch any low clock pulse?


text:
Why does the ADC report 0 in this sketch?
This sketch always reports 0 for the ADC reading.
I think this is going to turn out to be something silly, but I cannot find the source. I've reviewed the sketch ADC lines carefully and they seem right, so maybe the problem with the physical connections or how I'm trying to report the ADC output or the order in which tasks are executed.  The capture_FID() etc functions are based on the example in Section 9.2.4 of Norman Dunbar's book, Arduino Software Internals.  The only difference is the position of ADCSRA |= (1 << ADEN); which I moved to right after the power up based on this answer.  That did not make a difference.

void init();
void setup() {
  Serial.begin(115200);
  capture_FID();
}
void loop() {
}

void capture_FID() {

  volatile uint16_t ADC_output = 0;  // max value 65536

  config_ADC();
  start_ADC();
  for (int i = 1; i <= 5; i++) {
    Serial.print("\ti = ");
    Serial.print(i);
    Serial.print(" value = ");
    Serial.println(ADC_output);
  }
  stop_ADC();
}

// ADC Configuration
void config_ADC() {
  Serial.println("Configuring the ADC...");
  PRR &= ~(1 << PRADC);                                            // power up the ADC
  ADCSRA |= (1 << ADEN);                                           // enable ADC
  ADCSRA = (1 << ADPS2) | (1 << ADPS1) | (1 << ADPS0);             // slow the clock
  ADMUX = (0 << REFS1) | (1 << REFS0);                             // use 5 V internal reference
  ADMUX &= ~(1 << ADLAR);                                          // right-align the 10 bit output in 2 byte/16 bit space
  ADMUX |= (0 << MUX3) | (0 << MUX2) | (0 << MUX1) | (0 << MUX0);  // multiplexer input; use A0
  DIDR0 |= (1 << ADC0D);                                           // disable digital input to pin A0
  ADCSRA |= (1 << ADIE);                                           // set interupt to notify data is available for further use
  ADCSRA |= (1 << ADATE);                                          // auto-trigger on
  ADCSRB = 0;                                                      // free-running mode
  delay(20);                                                       // wait for voltage to settle
}

// Start the ADC = start acquiring data
void start_ADC() {
  Serial.println("Starting the ADC...");
  ADCSRA |= (1 << ADSC);
}

// Stop the ADC = stop acquiring data
void stop_ADC() {
  Serial.println("Stopping the ADC...");
  ADCSRA |= (0 << ADSC);
}

ISR(ADC_vect) {
  volatile uint16_t ADC_output;  // max value 32767
  ADC_output = ADCW;
}

Hardware:

Arduino R3
0.1 uF cap across GND and AREF
PicoScope function generator is supplying a 500 Hz, 500 mV, 1 V offset signal; the negative output is wired to GND on the Arduino, the positive output is wired to A0.
A sketch that doesn't involve free-running and auto-triggering that I found on Nick Gammon's site works fine, so the board appears to be fine.  This also implies the hardware connections and scope settings are fine.

You have two different variables named ADC_output:

one which is local to capture_FID(), and is always zero (it is never
assigned another value)
one local to ISR(ADC_vect), which is set but never used.

You should use only one such variable.
There are also a handful more problems in this code:

capture_FID() prints multiple times the same result, without
checking that new data has arrived
access to ADC_output outside the ISR is not protected in a critical
section
the ADC register is called ADC, not ADCW.
ADCSRA |= (0 << ADSC) is a no-op
there is no point in declaring init()
probably more, I did not read it thoroughly…

Ah, so my limited experience with C is the problem. Let me poke around a bit.  Thank you.


text:
Getting a strange symbol when pressing buttons in a USB keyboard connected to the Arduino GIGA R1
I am using the following code:
#include "USBHostGiga.h"

//REDIRECT_STDOUT_TO(Serial)
Keyboard keyb;
HostSerial ser;

void setup() {
  // put your setup code here, to run once:
  Serial.begin(115200);
  while (!Serial);
  pinMode(PA_15, OUTPUT);
  keyb.begin();
  ser.begin();
}

void loop() {
  if (keyb.available()) {
    auto _key = keyb.read();
    Serial.println(keyb.getAscii(_key));
  }
  while (ser.available()) {
    auto _char = ser.read();
    Serial.write(_char);
  }
  //delay(1);
}

from here: https://docs.arduino.cc/tutorials/giga-r1-wifi/giga-usb
I am using Arduino GIGA R1 on which I have connected a USB keyboard and I press buttons. I see the results on the Serial. However, I face the following problem: When I press a button, apart of the letter I get also a square next to it. For instance, let's say I press the 'A' letter. In the serial I get 'A' letter + a square symbol. When I press 'B', I get 'B' + a square symbol, etc. I am trying for 2 days to fix it, I tried to read the button as a char array with two positions and delete the [1] where the square should be, but nothing worked. The auto type is very strange in order to make a type casting, because the Arduino IDE continuously shows me error. I cannot find a way to remove the strange 'square' ASCII character which I take with each letter pressed...The only things I noticed is that the square ASCII character is displayed the time I release the keyboard button, and also it delays to appear when I increase the delay ms in the delay(...); command. Has anyone any idea how to solve this?

does [SHIFT]+[A] look the same as [A]? what does Serial.println(_key, HEX) look like?

I don't have GIGA R1, so no practical way to test this.
I also cannot explain why it's showing up as square for you. It is common behaviour for character codes that don't have a font glyph to render in that way, but the one in question (null character) does not do that for me under the 1.x 2.x IDEs.
However, the rest of what follows may help.
According to github,
the type that is returned by .read() is HID_KEYBD_Info_TypeDef, so if you want you should be able to:
const HID_KEYBD_Info_TypeDef _key = keyb.read();

However, there's not much wrong with using auto here.  So far as I can tell, what you're really receiving
is the content of Boot mode HID reports.
Not individual key information really, but rather the state which may include up to 6 pressed keys.
If you're only pressing one key (one non-shift state key; as in not "shift", "control", "alt". etc,
it shows up in array index 0, which is what getAscii
is ultimately interpreting.
So when you release the key (all of them) you are getting a report with nothing (no key code; represented with a zero value) in keys[0], and so there's nothing there from which to get an ASCII code.
What it seems to be doing is translating the 0 value that's there into another zero.
So, it would seem all you need to do is check to see if it's a zero after the call to getAscii, e.g.:
if (keyb.available()) {
  const auto keyboard_input_report /*not really a key*/ = keyb.read();
  const auto first_as_ascii = keyb.getAscii(keyboard_input_report);
  //  where getAscii really means getAsciiCodeOfFirstkeyIfThereIsOneInTheReport
  if (first_as_ascii != 0) {
    Serial.println(first_as_ascii);
  }
}

You could to check before translation with if (keyboard_input_report.keys[0] != 0) {. However, the former may make more sense. Because not every key on the keyboard will map unto may onto an ASCII code value anyway.  E.g. ASCII does not represent the arrow keys, function keys, or page-up/page-down.
In any case, this code may have issues if multiple keys are pressed. It looks like doing so correctly would involve using the internals of getAscii to consult the translation tables for all six of the entries in the report's keys array.


text:
3 pin ethernet module?
So basically I'm working on a project that uses an Atmega328 like on the Arduino Uno. I need to receive both DMX (with max485) and E131 (Not both at the same time, I'll decide which with a boolean in the sketch) and then use that to control 16 channels. I need the TX and RX pins (UART) for the max485 (DMX), 16 outputs for the triacs, and 1 pin for zero-cross detection. If I use the Analog pins as digital outputs, that lets 3 pins to connect the ethernet module. Most of them use 4 pins, I believe it's SPI. I only have 3 available. Is this possible? Also, I may need a second zero-cross detector, so is it possible with 2 pins then?
Thanks!

Sounds like you need either an MCU with more pins or a second MCU for the ethernet.

Are there ethernet modules that use, say, i2c?

did you try to add Ethernet library to your sketch? don't you run out of flash?

you could use some UART module. esp8266 WiFi module uses Serial.

No, I havent actually made a sketch yet. Just trying to figure out the hardware side first.

And what do you mean by uart module and esp8266? I specifically need it to be ethernet, not wifi.

https://www.waveshare.com/uart-to-eth.htm it uses an MCU

I haven't heard of any I2C Ethernet modules, no, but that doesn't mean there aren't any. But then it wouldn't be too hard to write a sketch for an Arduino that has an Ethernet card on it and communicates over I2C with your existing setup.

Yes, your right I could use a uart ethernet module and then put a physical switch or jumper to connect one or the other. Those are kinda expensive tho, not sure why.

Also I don't need cs because I only have 1 chip connected to SPI bus right? That would get me down to 3 pins. And then do I need a tx for E131? Does the arduino need to send something to say that the packet was received, or to help connect it to a pc? Or can I just use RX only? If so, that would get me down to the 2 pins I need.

the W5x00 don't work without switching CS input

Could it just be constantly pulled high or low?

no. the logic in chip reads the CS signal edges


text:
How to connect multiple NodeMCUs and 1 PC over wifi and have PC control NodeMCUs?
I am trying to design a laser tag system using multiple NodeMCUs in the guns. I am trying to figure out how to connect and control them over WiFi. I also need a computer connected that will control the game. I was origionally just thinking I could use the PC as a server that tells all the guns what to do. Im sure this is possible, but it looks very complicated and I dont know a whole lot about theese types of things. So then I was thinking it might be better to have another NodeMCU connected to the computer with USB. That NodeMCU would then act as a WiFi server for the clients(Guns). That way, the PC would only have a GUI for that MCU, and once started the MCU would actually control the game. Is that the best option or is there some easier and simpler way? That seems like the best solution to me. I am just making sure this will work. Are there any other solutions or tips? Here is a basic idea of what would happen when someone shoots someone else.
Gun 1 will send IR signal (Shoot) gun 2.
Gun 1 will tell the server that it tried to shoot gun 2.
Gun 2 tells server it got IR signal from gun 1.
Server will first make sure no other guns were shot accidentally at the same time. If they were, it will determine which gun received the IR signal stronger. That gun will be the one actually shot.
Server will add points to gun 1 score and remove points from gun 2 score on both PC monitor and small screens on guns themselves.
Thanks!

there is no reason why the server would have to decide who shot a target (gun 2 in your example)  ... the decision should be made by the target ... determining an IR signal strength can be a problem ... it would be easiest to award the kill to the first shot and award a kill to each of the shots if received simultaneously .... also, it is pointless to count that gun1 tried to shoot gun2 ... how would you determine that if gun1 misses the target?

@jstola At this point I have tried so many things and researched so many ways of making this work that I cant think right. What I said is more complicated than it would really be. I am just looking to connect 5 or 6 MCUs together in a network, along with a PC. The MCUs will control almost everything by themselves.

All the PC will do is change settings, keep track of score and tell MCUs when to start and stop the game. My main questions are 1, How to connect 5-6 MCUs and a PC together over WiFi and send information between them, and 2, how to make a simple PC program that keeps track of score, tells MCUs when to start and stop, and changes settings. Also, all of the ways Ive seen people communicate over WiFi use a server that broadcasts out WiFi. How can I just use my existing router now that I arent using a server?

Plz tell me how I can do this.

I would not consider it easier to connect a NodeMCU to the PC just to act as a Wifi interface. Most computers already have means of connecting to a network. Wether it is via Wifi or LAN is not important. Every PC has a LAN port on it's mainboard. You could connect it directly to your Wifi router.
Using a NodeMCU as you proposed would mean, that you have to program for 2 platforms: The main logic on the PC and the Wifi communication on the NodeMCU. That does not really make it easier.
The communication depends on your wanted topology. I would build the PC as Server and the NodeMCUs as clients. You can easily create a webserver programmatically with python, for example with Flask, as I have done it once. Though there even might be better webserver modules for python. It is really not that difficult and you already need to write a program for the game logic on the PC,so why not using python. Though of course you could choose any language, that you like. Python is just an easy choice, that I already did.

So i guess my question then is more how to make that game logic on the PC. How exactly do I do this? Could you maybe point me towards a totorial? Thanks!

There is no tutorial, that explains how to write the game logic for your specific project, because it is specific to your project. Choose a fitting programming language and learn the basics of it. Variables, arrays, conditions, loops,... Them write down the game logic as text, convert that into pseudo code and then into real code. We cannot explain more, since the question is so broad

Ok thx, I will check out some languages.

web server? what for? sorry @chrisl, but this answers shows that you shouldn't write an answer to this question

@Juraj Please be a bit more specific about what is wrong with the answer. That would help both the OP and me

the question is too broad and a major part is outside Arduino. simple TCP/IP communication on sockets level or UDP can be used. here a write about Arduino to Arduino https://arduino.stackexchange.com/questions/60819/esp8266-tcp-ip-communication/60821#60821


text:
DHT11 analog or digital?
I saw some projects with DHT11, some connect it with analog pin, others connect with digital pin.
Is there any difference / advantage connecting to the analog?

The DHT11 is a digital component with its own digital communication protocol.
Analog pins can be used for either analog input or digital input and output.
You can use a digital device like the DHT11 on any pin, whether it is labelled analog or digital (except on a couple of boards which have a few analog-only pins).


text:
Why this program works on an old Nano and doesn't work on Nano Every
Can someone tell me why "XTronical graphical Pulse and Oxygen monitor Displays"
https://www.xtronical.com/colour-ecg-monitor/
works perfectly on an old Nano or an Uno and doesn't work on the new Nano Every
even with Registers emulation: "ATMEGA328" ?
Is the Nano Every a "BAD BUY" ?
I very much welcome an explanation.
JFT

you need to explain in detail what you are talking about ... problem descriptions like doesn't work are meaningless

why would it be "bad buy"? because of some incompatible library you try to use?


text:
Hooking Up 8 ohm Speaker to Arduino
Is this a correct way to connect an 8 ohm beaker to an Arduino?
https://www.c-sharpcorner.com/article/audio-play-using-sd-card-module-and-arduino/

You probably need a small op-amp like an LM741 to drive an 8ohm speaker from an Arduino https://www.electronics-tutorials.ws/opamp/opamp_1.html

To effectively drive a speaker from an Arduino you need an amplifier. The good ol' LM386 is a common choice for this (readily available and cheap, though not recommended for battery based projects).
While it is possible to drive a speaker directly it's not recommended. Not only is it very quiet, but also it can damage the IO pin. Not only from excess current draw (peak current at 5V through 8Ω [nominal] is 626mA,  more than 15x the maximum the pin can supply, which not only stresses the pin but also distorts the output waveform) but a speaker is also an inductive load which has all the associated issues of back-EMF and such.

I have also seen 1 transistor designs which isolate the speaker from the processor's I/O pin.  Should we include these in the answer - or is there a reason to avoid this solution?

No, no reason why not. A transistor is just acting as an amplifier. I just mentioned the lm386 as an example.

You had to put a resistor in serial with the speaker, Max current from the pin is 40 mA if put 8 ohm speaker on the pin it can't drive the speaker. Try a speaker with higher impedans.

it can drive the speaker and it works, but it stresses the pin that is why there should be a resistor. to limit the current. (downvote is not my).


text:
How to change wifi credentials of multiple ESP8266 together
I need to change WiFi credentials of multiple ESP8266 in one go, without needing to change passwords for each of them individually. I know there is a WiFiManager library, which makes your ESP8266 access point when not connected to any network, but that will require me configure each of them individually.
How can I save the fatigue of changing their wifi credentials individually? All of them needs to connect to the same network, whose password is recently changed.

You could implement a "provisioning service". Kind of like WiFiManager but in reverse. If you can't connect to the real access point then connect to the provisioning access point, from which you can then obtain the credentials to connect to the real access point. Of course you just move your security weakness to the provisioning access point which can never have the details changed...

you can reconfigure your router, or whatever network mode you are using, with auto-login to the MAC addresses of your ESPs.
And then if you provide the MACs of the corresponding ESPs, and change your WiFi credentials, then you don't need to configure the ESPs individually. It will auto-connect itself.

Have your devices always try to download a config file from a webserver you control.  If the config file exists and has new wifi credentials then it can update itself and reset.  When you actually change the password for the AP all the devices will already have the new password.


text:
Digital to Analog converter with DAC5311, Any suggestion?
I made my DAC code with DAC5311 and Arduino Uno.
I think it has no problem, but it doesn't work well. Just print 0.(I use an oscilloscope.)
I don't know where has the problem. Please give me any suggestion.
#include <SPI.h>
#include <math.h>
#define pin_CS 10
#define pin_MOSI 11
#define pin_SCLK 13
#define max_VOLT 5

void setVoltage(float voltage){
  if (voltage < 0) voltage = 0;
  if (voltage > max_VOLT) voltage = max_VOLT;
  uint16_t temp = int(voltage * pow(2, 8) / max_VOLT);
  temp = temp << 6;
  uint8_t upper = temp >> 8;
  uint8_t lower = (temp & 0xff);
  digitalWrite(pin_CS, LOW);
  SPI.transfer(upper);
  SPI.transfer(lower);
  digitalWrite(pin_CS, HIGH);
}

void setup() {
  Serial.begin(9600);
  pinMode(pin_CS, OUTPUT);
  pinMode(pin_MOSI, OUTPUT);
  pinMode(pin_SCLK, OUTPUT);
  SPI.begin();
  SPI.setBitOrder(MSBFIRST);
  SPI.setDataMode(SPI_MODE0);
  digitalWrite(pin_CS, HIGH);
}

void loop() {
  setVoltage(5);
  delay(10);
}

a statement, it doesn't work well, has no meaning  ... I use an oscilloscope is also meaningless ... please explain what you expected to happen, what actually happened and what you did with the oscilloscope

Sorry, I'm not good at English. So it might be not clear. The point is that I want to set  voltage 5, but the output of DAC5311 is zero. And I check the output with oscilloscope.

now, that is clear ... please edit your question ... your english is just fine ... is your oscilloscope functioning correctly and are the controls set correctly? ... double check the output using a voltmeter

Classical +/- 1 problem
If you do this calculation by hand uint16_t temp = int(voltage * pow(2, 8) / max_VOLT);
you will get temp=256 and this is a value you can not convert with a 8 bit DAC.
Try uint16_t temp = int(voltage * (pow(2, 8)-1) / max_VOLT); instead.
(or event better for a µC uint16_t temp = (uint16_t) (voltage * (255 / max_VOLT));)

I revised it, but it was not still working. ㅜㅜ

So please try SPI_MODE1 or SPI_MODE3
(the device expects the valid bit on the falling clock phase)


text:
L298N motor driver not working with Arduino UNO R3
I was trying to use the motor driver, but the motors aren't spinning for some reason.
I am sure the motors are working; I tried and tested them. I can't understand if there is a problem with the code, motor driver or the Arduino board.
Arduino board used: Arduino UNO R3
Here is the code:
char data;  //Serial

void setup() {
  // put your setup code here, to run once:
  pinMode(4, OUTPUT);
  pinMode(5, OUTPUT);
  pinMode(6, OUTPUT);
  pinMode(7, OUTPUT);

  Serial.begin(9600);
}

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

  if (data == '1') {
    digitalWrite(4,HIGH);
    digitalWrite(5,LOW);
    digitalWrite(6,HIGH);
    digitalWrite(7,LOW);
  }
}

I do not see any problem with your code. However, the code must be compatible with the circuit connections. Please check your whole setup part by part. Check the motor driver with a direct power supply. See if you get the expected output. The motor may not spin due to insufficient voltage and/or current too. So, check your power supply with a multimeter. Since you are sending commands through the serial monitor, check if there has been any baud rate mismatch. You can also check this tutorial for some help: https://www.theengineeringprojects.com/2017/04/dc-motor-direction-control-arduino.html

Thanks!! I found the problem though. Somehow the motors got damaged during soldering.

@KnightRiderDutt you said that you tested the motors

They were working then. No idea what happened


text:
How to connect arduino mega 2650 and motor driver shield with seperate powers source?
I am building a robot that runs only when a matching rfid tag is identified..for that i need motor driver shield for running the motors and rfid module. The problem is if i attach the motor driver shield directly to arduino (MEGA) there won't be any 3.3v left which is necessary to power rfid so what i am thinking is connecting all the pins of arduino and shield seperately using jumper wires and leaving the 6 power sockets unconnected. If i connect 9v battery to arduino mega to power the rfid and micro-controller itself, what battery should be connected to the shield? Is it necessary to connect the GND of arduino awa shield even if power sources are seperate? Is it necessary to attach 2 switches for each source?

You should check the schematics for your motor shield to see what pins are actually used. Just because a pin exists doesn't mean it is connected to anything. You may well find the 3.3V pin isn't actually used by the shield.


text:
Timer with Webserver ESP8285
this is my first Project on an ESP.
I found a Code for a coffee-grinder-timer, which is programmed for a ESP8266, but unfortunately meanwhile the Sonoff changed to the ESP8285 with internal Flash.
I presume this is the reason for a memory problem. By default the times are according to the code 1000ms and 2000ms, but on the WebPage are the following times are displayed:

Singleshot: 16711680ms
Doubleshot: 807611680ms

Beside this problem I can't change these values by pressing the save-button.
what is my mistake?
// Libraries
#include <ESP8266WiFi.h>
#include <ESP8266WebServer.h>
#include <TTBOUNCE.h>
#include <EEPROM.h>
extern "C" {
#include "user_interface.h"
}

//======SERVER PART======================================================
const char* ssid     = "SSID";
const char* password = "password";
ESP8266WebServer server ( 80 );
char htmlResponse[3000];
//======LOKALER PART======================================================
os_timer_t myTimer;
bool tickOccured;
bool timerrunning;
int RelaisPin = 13;                 // GPIO13 Blaue LED auf dem Sonoff
TTBOUNCE b = TTBOUNCE(0);

int time_ss = 1000;
int time_ds = 2000;

void handleRoot() {

  snprintf ( htmlResponse, 3000,
"<!DOCTYPE html>\
\
  \
    <meta charset=\"utf-8\">\
    <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\
  \
  \

Zeiten für Singleshot und Doubleshot
\

Singleshot: %d% ms
\
          <input type='text' name='date_ss' id='date_ss' size=2 autofocus> ms \

Doubleshot: %d% ms
\
          <input type='text' name='date_ds' id='date_ds' size=2 autofocus> ms \

\

<button id=\"save_button\">Save</button>\

\
    \
    \
  \
",

time_ss,
time_ds
);

   server.send ( 200, "text/html", htmlResponse );

}

void handleSave() {
  if (server.arg("ss")!= ""){
    Serial.println("Singleshot: " + server.arg("ss"));
    time_ss = server.arg("ss").toInt();
    eeWriteInt(0, server.arg("ss").toInt());
  }
    if (server.arg("ds")!= ""){
    Serial.println("Doubleshot: " + server.arg("ds"));
    time_ds = server.arg("ds").toInt();
    eeWriteInt(4, server.arg("ds").toInt());
  }

}

// start of timerCallback
void timerCallback(void *pArg) {
Serial.println("Tick OccurredCB");
      tickOccured = true;
}

void setup() {
//======SERVER PART======================================================
  // Start serial
  Serial.begin(115200);
  delay(100);
WiFi.mode(WIFI_STA);
  // Connecting to a WiFi network
  Serial.println();
  Serial.println();
  Serial.print("Connecting to ");
  Serial.println(ssid);

  WiFi.begin(ssid, password);

  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }

  Serial.println("");
  Serial.println("WiFi connected");
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());

  server.on ( "/", handleRoot );
  server.on ("/save", handleSave);

  server.begin();
  Serial.println ( "HTTP server started" );
//======LOKALER PART======================================================
  os_timer_setfn(&myTimer, timerCallback, NULL);
  pinMode(RelaisPin, OUTPUT);       // GPIO13 als Ausgang definieren
  b.attachClick(click);         //attach the click method to the click event
  b.attachDoubleClick(doubleClick);//attach the double click method to the double click event
  b.attachPress(press);        //attach the press method to the press event
  delay(50);
  digitalWrite(RelaisPin, HIGH);  // turn LED ON
  tickOccured = false;
  timerrunning = false;
   EEPROM.begin(8);  //Initialize EEPROM
   time_ss = eeGetInt(0);
   time_ds = eeGetInt(4);
}

void loop() {
//======SERVER PART======================================================
  server.handleClient();
//======LOKALER PART======================================================
  b.update();
  delay(10);

   if (tickOccured == true)
 {
    Serial.println("Timer ausgelaufen");
    tickOccured = false;
    digitalWrite(RelaisPin, HIGH);
    os_timer_disarm(&myTimer);
    timerrunning = false;
 }

 yield();  // or delay(0);
}

void click(){
  if (!timerrunning)
  {
    Serial.println("Clicked");
    digitalWrite(RelaisPin, LOW);  // turn LED ON
    os_timer_arm(&myTimer, time_ss, false);
    timerrunning = true;
  }
  else
    {
    Serial.println("ABORT!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
    tickOccured = false;
    digitalWrite(RelaisPin, HIGH);
    os_timer_disarm(&myTimer);
    timerrunning = false;
    }
}

void doubleClick(){
    if (!timerrunning)
  {
    Serial.println("DoubleClicked");
    digitalWrite(RelaisPin, LOW);  // turn LED ON
    os_timer_arm(&myTimer, time_ds, false);
    timerrunning = true;
  }
    else
    {
    Serial.println("ABORT!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
    tickOccured = false;
    digitalWrite(RelaisPin, HIGH);
    os_timer_disarm(&myTimer);
    timerrunning = false;
    }
}

void press(){
  if (!timerrunning)
  {
    Serial.println("long_Clicked");
    digitalWrite(RelaisPin, LOW);  // turn LED ON
    os_timer_arm(&myTimer, time_ds-time_ss, false);
    timerrunning = true;
  }
 else
    {
    Serial.println("ABORT!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
    tickOccured = false;
    digitalWrite(RelaisPin, HIGH);
    os_timer_disarm(&myTimer);
    timerrunning = false;
    }
}

 void eeWriteInt(int pos, int val) {
    byte* p = (byte*) &val;
    EEPROM.write(pos, *p);
    EEPROM.write(pos + 1, *(p + 1));
    EEPROM.write(pos + 2, *(p + 2));
    EEPROM.write(pos + 3, *(p + 3));
    EEPROM.commit();
}

int eeGetInt(int pos) {
  int val;
  byte* p = (byte*) &val;
  *p        = EEPROM.read(pos);
  *(p + 1)  = EEPROM.read(pos + 1);
  *(p + 2)  = EEPROM.read(pos + 2);
  *(p + 3)  = EEPROM.read(pos + 3);
  return val;
}

what problem are you facing? ... what are you trying to do?

I would start by changing %d% to %d

You “found code” where? Are you certain the code was working? You mention a “memory problem”. What do you mean by that? In my experience, programatically there is almost no difference between an ESP8285 and an ESP8266 besides the difference in available flash memory, which I don’t think is the problem here. Why are you mentioning Sonoff?

@jsotola: I want to program a timer for my coffee-grinder, on which I can adjust the grinding duration via WLAN.

My timer is at the moment not changeable and set to weird values
@StarCat: I found the code on Kaffee-Netz:
https://www.kaffee-netz.de/threads/demoka-m203-timerumbau-und-totraum-minimierung.117220/
and it is meant to be working on a ESP8266.
My Memory problem is, that the durations of the single-and the  doubleshot are not changeable and the default values are extremely high and not according to the code 1000 and 2000ms.
Thanks in advance

@ Juraj: thanks, since I changed this, I am able to change the values at the first boot after flashing. But afterwards I cant change the values anymore. Pressing the save butten doesnt show any effect.

Try removing the location.reload(); call - your browser may be reloading the page before the AJAX GET can complete. Also you should wrap your Javascript in a jQuery $(document).ready() handler - you can Google it for more details.

At least one problem is this:

Singleshot: %d% ms
\

If you want a literal percent sign, you would need to double it, a form of escaping:

Singleshot: %d%% ms
\

It's not entirely clear how this implementation of snprintf handles %<space>, but experiments here show that it isn't being forgiving and merely interpreting it as %%.
In C and C++ and by proxy "arduino", adjacent string literals are concatenated at compile time into one logical string literal, so you can do that rather than \, which you may find cleaner.
It should also be possible to just .print the chunks of your payload to the stream rather than to cobble together one large string as a payload.


text:
How can I interface, received HC-12 data and transmit the received data using sx-1278 RF-module in arduino-UNO?
I am currently working on a project, where I need to send data from first unit to the second unit which is a few km apart, so I decided to go with hc-12 RF module as it covers upto 5km. Then the data received in the second unit is again to be transmitted to the last unit which is several km apart from each other, so I decided to go with sx-1278 RF module which can easily transmit data up to 30kms. I am trying to get the received data to print on the serial monitor. So, how do I transmit the received HC-12 data in the second unit using the sx-1278 RF module to the third unit? Is this operation even possible? Are these two boards compatible with each other?
If the answer is yes, please do help me out with the coding part on how to interface these two RF-modules.
Thanks in advance

what kind of I/O do the two RF modules use?

For the input parts, I am using a temp sensor (LM-35), a pulse senor (RC-A-4015), and a GPS sensor (neo-6m) and for the output part, as of now, I'm just trying to print it on the serial monitor.

i asked about the RF modules ... let me rephrase that ... how do the RF modules communicate with an arduino?

The RF module consists of a 433 MHz RF transmitter and receiver modules. These are ASK or FSK type RF modules....The transmitter and receiver are needed to be interfaced with arduino for data transfer...The data is sent serially from the transmitter and is received by the receiver on the other end... the RF transmitter receives serial data from arduino and transmits it to the receiver through an antenna connected to the transmitter. The receiver receives the data through an antenna and gives the data to the microcontroller connected to it.

i did not ask how the RF modules communicate with other RF modules

I have used the digital pins of the Arduino...i.e.(4,5) ..as the transmitter and the receiver part of the RF module.

is it I2C? ....

No....its UART.

the one in the middle will have to use at least one hardware serial ... an arduino cannot use two software serial ports

oh..ohk. But is there any other way to send the data? or should I simply use an other arduino to perform this operation...by this I mean...collect the data received from hc-12 and store it in some storage device, and then send the data that is there on the storage device using sx-1278? is this method efficient? Or is there any other method to do this work? Please suggest.

it is unclear how data collection relates to the transmission of data ... the two functions are not really related ... you have three arduinos ... connect the RF module to software serial at the endpoint arduinos ... at the middle arduino, connect one RF module to software serial and the second one to the hardware serial

Ohk..I get it now. Thank you so much for the help.

it may be possible to run without an arduino in the middle ... just connect the RF module data pins together

is that so?...I'll try that out then....One more thing, instead of using the hardware serial..could I just stick with two two software serial? Please check out this link where it demonstrates..on how to use to software serial .. https://www.arduino.cc/en/Tutorial/LibraryExamples/TwoPortReceive

if you can make it work, then go for it

Ohk...Thank you so much for the help.


text:
Average of 10 readings, wrong
I am reading from loadcell and calculating the average of last 10 readings. But when the load cell reads something more than 3800 g the average gets negative, how? The mass I read are not negative numbers. I have been trying to find my mistake but I am not able to. Any help?
#include "HX711.h"

const int numReadings = 10;
const int LOADCELL_DOUT_PIN = 8;
const int LOADCELL_SCK_PIN = 10;
int readings[numReadings];      // the readings from the analog input
int readIndex = 0;              // the index of the current reading
int total = 0;                  // the running total
int average = 0;                // the average
int mass  =0;
long reading = 0;

HX711 scale;

float a = 0.0088;
float b = 2009.7;

void setup() {
  // initialize serial communication with computer:
  Serial.begin(9600);
  // initialize all the readings to 0:
  for (int thisReading = 0; thisReading < numReadings; thisReading++) {
    readings[thisReading] = 0;
  }
  scale.begin(LOADCELL_DOUT_PIN, LOADCELL_SCK_PIN);
}

void loop() {
  if (scale.is_ready()) {
    // read from the sensor:
    reading = scale.read();
    // convert to mass
    mass = int((a*reading)-b);
    // subtract the last reading:
    total = total - readings[readIndex];

    Serial.print(int((a*reading)-b));
    readings[readIndex] = mass;
    // add the reading to the total:
    total = total + readings[readIndex];
    // advance to the next position in the array:
    readIndex = readIndex + 1;

    // if we're at the end of the array...
    if (readIndex >= numReadings) {
      // ...wrap around to the beginning:
      readIndex = 0;
    }

    // calculate the average:
    average = total / numReadings;
    // send it to the computer as ASCII digits

    Serial.print("   ");
    Serial.print(average);
    Serial.println("");
    delay(1000);        // delay in between reads for stability
  }
  else{
    Serial.print("loadcell not found!");
  }
}

It's called "integer wraparound" - int can only hold between -32768 and +32767 on an 8-bit Arduino.

Omg, thank you very much for the help. I was struggling with it

tip, if you know that it only should contain positive numbers, declare as an unsigned integer.

Another option would be use 'long' as a variable type for total.   Depending on your application, you also might look into an exponentially weighted moving average (EWMA); it can de-emphasize older data points, if that is an issue.

As already commented by Majenko, the problem in integer wraparound. One solution would be to get rid of that total variable and calculate every new average based on the previous average and the mass you are replacing in the array, using this formula:
new_average = old_average + (mass - readings[readIndex]) / numReadings

So your code would look like:
  if (scale.is_ready()) {
    // read from the sensor:
    reading = scale.read();
    // convert to mass
    mass = int((a*reading)-b);

    // calculate the new average:
    new_average = average + (mass - readings[readIndex]) / numReadings;

    Serial.print(int((a*reading)-b));
    readings[readIndex] = mass;

    // advance to the next position in the array:
    readIndex = readIndex + 1;

    // if we're at the end of the array...
    if (readIndex >= numReadings) {
      // ...wrap around to the beginning:
      readIndex = 0;
    }

    // set the average:
    average = new_average;

    // send it to the computer as ASCII digits
    Serial.print("   ");
    Serial.print(average);
    Serial.println("");
    delay(1000);        // delay in between reads for stability
  }

Just don't forget to add a declaration for new_average to the beginning of your code.


text:
Change character sequence
I turn on the transmission of one key that works to open the door, but after a certain time I need to close the door, and for this I need to use the second key. I want to do without additional buttons, so it is required to emit key 1 when power is applied, and after 20 seconds, for example, switch and emit key 2. What is the most simple and correct way to do this?
Apply a timer or emit key 1, for example 1000 times, and after overflow 1000, start emitting key 2.
This sketch only constantly sends the first key to the digital pin, without switching to the second.
You need to figure out how you can switch to the second key.
const int KEY_LEN = 54; //Number of characters in the key
const char key1[KEY_LEN] = {"SSSSSS001101001001110001000000000000000000000011001010"}; // Open
const char key2[KEY_LEN] = {"SSSSSS001010111010000000000001000000000000010000000000"}; // Close

int Preamble = 1000; // Preamble duration in microseconds
int zero= 200; // Duration of zero in microseconds
int One= 440; // Duration of a unit in microseconds

const int LED_PIN = 13; // Used digital pin 13 of the arduino to connect the transmitter
void setup()
{
  pinMode(13, OUTPUT);
}

void loop()
{

    for (int n = 0; n < KEY_LEN; n++)
    {
      if (key1[n] == '1') //execute if bit value == 1
      {
        sendSignal(One);
      }

      else if (key1[n] == '0')//execute if bit value == 0
      {
        sendSignal(zero);
      }
      else
      {
        sendSignal(Preamble); // Стартовый импульс
      }

    }
  }

void sendSignal(int duration)
{
  digitalWrite(LED_PIN, HIGH);
  delayMicroseconds(duration);
  digitalWrite(LED_PIN, LOW);
  delayMicroseconds(duration);
}

I usually recommend against using delay()s, but if this system will only ever have to do what you've described, using delay()s is the simplest way to implement it.
I would suggest sending key-1, possibly several times, maybe a half second apart, delay for the 20 seconds you suggested, then send key-2, definitely several times for security.