text:
Arduino Object Oriented Programming
Can anyone send me a link tutorial about Arduino Object Oriented Programming? I want to learn Arduino, I am just a beginner.

A little information that is missing from the answers: OOP has a small overhead because of a some boiler plate and object instantiation. This overhead is so marginal on desktops, servers and even mobile devices that we usually don't even mention it. On the arduino however, with it's severe restrictions on memory and computing power and where every byte may count, this overhead can become noticeable. Depending on your use case, this might be something to consider.

Agreed with @Douwe - the Arduino is not the place to lean OOP because it is not an environment where OOP can really leverage its power.  OOP is a design strategy that came out of a need to simplify and abstract complex programs.  The arduino is so small and so simple that programs never really get that complex to begin with.  A desktop or mobile environment is a much better place to learn OOP because everything you're using in that environment are already objects - there's a whole framework to learn from.  On the arduino there's nothing except what you build.

"Arduino" is just plain old C++ with (in some cases) bits removed and some helper functions and classes.
For the smaller (lower powered AVR for example) there is no full STL in the C++ library, and some functions are of a reduced complexity (such as no floating point support in the printf family of functions by default).
For OOP you don't need to know anything "Arduino" - it's just C++. Any C++ OOP tutorial will teach you what you need to know for Arduino OOP.

Thank you, I will look into it

Have you programmed OOP before? For alot of projects you can get away with not knowing it.
I'll also point out that if you are just a beginner, I don't recommend starting off with OOP. Stick to simpler scripts (Trust me, OOP is a pain sometimes).
If you still INSIST on starting your arduino knowledge with OOP, look up "C++ classes" or "C++ OOP" as the default language that the arduino IDE uses is just a modified version of "C++"

Yes, I already done oop in different language like c#, I just want to familiarize the arduino c++ syntax.

http://paulmurraycbr.github.io/ArduinoTheOOWay.html really helped me understand what was happening. i had some previous oop expierence with java, but i still have a hard time using multiple files vs writing more methods in one file

I used OOP with C++ on an Arduino Due in an open source project.
Since I did not find any tutorila for the same the example might be helpful for You.
https://github.com/eschlot/Box-Joint-Jig-Control
W.r.t. the usability of OOP in embedded systems for scenarios like the above one there are plenty of good reasons to use OOP. A good example is the menu structure and the display control in the project.
Nevertheless from my experience it is important to understand the effects of automatic object creation and tentative memory reorganization to the behavior of real time systems. This is much less predictable with C++ then with plain C and can be a reason to not use OOP in any real time system.


text:
Is an Ultrasonic Sensor or Infrared Sensor better for measuring distance (to/from a human body)?
I'm trying to make a sensor to detect that a person is within 50cm to trigger a function. But when I use the HR-SR04 sensor, it works accurately on flat surfaces (e.g. walls, books) with a margin of error around 5cm, but not on uneven surfaces (e.g. humans) where the value randomly jumps between 0cm to 1000cm.
I was thinking whether using an IR distance sensor would be better.

That depends on your requirements. An IR distance sensor will work better with different materials, since IR light is mostly reflected in very broad angles (expect for very reflective materials, like mirrors), so that uneven surfaces are also detected. But you will get a significantly worse error margin in your 50cm range. Normal IR distance sensors are just an LED and an IR photo transistor, sometime with some extra components. So the LED is lighting up and the photo transistor is measuring, how much of the IR light is coming back. The IR sensor depends also on the reflectiveness of the materials and the level of surounding IR light.
But as you don't really need to measure the distance, but just want to know, if there is an object in the range, an IR sensor might be enough. You would need to change the threshold of your IR sensor according to your needs (by experimenting with it).
All in all I think, yes, an IR sensor can give you better results for your application, though not for really measuring the distance, but only for the presence in a range with rather big error margin.

I've upvoted your answer (even though I like mine better) because you provide good information and a good, alternative perspective.

I have found IR accuracy to be poor resolution (+/- a few centimeters), as it's highly dependent on the refectivity of the surface. It also frequently has very poor range (a few cm to tens of cm), depending on the emitting power of the illumination source.
I have found ultrasonics, however, even the cheap $0.99 ones you mention, to have much better resolution (+/- mm), and much better range (about 2m), depending on the code driving them. I have yet to see good non-blocking code in any library for one of these, but when I write my own non-blocking code with interrupts and basic digital signal processing, such as a median filter, I get excellent results.
So, I recommend you use ultrasonics, but it requires advanced knowledge to do it well and do it right, such as using interrupts and taking the median of every 3 to 5 samples to remove spurious results.
On very flat surfaces, such as walls, at angles 45 deg or larger, ultrasonics also do poorly, since they end up measuring the distance including the extra reflections off the walls, but contrary to what you experienced, on odd shaped or softer objects, such as humans, I find them to do much better. I have used ultrasonics as the means of detecting humans several times before with good results. The real secret/challenge is your code. And again, I have yet to find a library worth using, and good code on these cheap things makes a HUGE difference in results and reliability and accuracy!

would you have any link to recommend to showcase such code (interrupts, median measurements)?

source: Stack Exchange

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

sort: votes


text:
Wake up from a pin, Sleep when work is done
I have a project which needs to sleep most of the time, and when a button gets pressed, it does its thing which is producing a fading sound wave (using interrupts) until it's time to sleep again.
The goal is to reduce work load on the battery so the item can last as long as possible.
#include <avr/sleep.h>
void setup(){
  /*givePin! This is the pin that will spark the waking up!*/
  pinMode(givePin,INPUT);
  noInterrupts();
  set_sleep_mode(SLEEP_MODE_IDLE);
  /*changes to timers registers*/
  interrupts();
}
void loop(){
  ampCurrentlyOn = digitalRead(givePin);
  ampPulse =  (ampCurrentlyOn && !ampPreviouslyOn) * 255     //Reset
           + !(ampCurrentlyOn && !ampPreviouslyOn) * ampPulse//Same
           -   bool(ampPulse);  //Decay
  ampPreviouslyOn = ampCurrentlyOn;

  if(!ampPulse){//Once that value reaches 0 time to GOTO bed;
    /*This! Is this what I need to do?*/
    cli();
    sleep_mode();
    sei();
  }
}

Am I doing in the right direction? Could any pin work? How do I get the chip to understand a pin set to digital HIGH to wake up from nap time?
Thank you!

you search for something like attachInterrupt(digitalPinToInterrupt(givePin), [](){}, FALLING);? givePin must be pin capable of external interrupt.(pin 2 or 3 on Uno/Nano) ([](){} is empty anonymous function)

You shouldn't call cli before sleep, or it will never wake up. I also think you need to call sleep_enable();.

@Gerben: sleep_mode() takes care of calling sleep_enable().

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


text:
Frequency of Retrieving Data from Website
I have wrote a code that communicate with my website to retrieve data to power on or off a 5V relay. I'm running the code every second to make sure it is real time. Is there more efficient way to tell Arduino to get the data whenever it is changed rather than continuous GET request.
// Send HTTP GET request
  int httpResponseCode = http.GET();

  if (httpResponseCode>0) {
    Serial.print("HTTP Response code: ");        Serial.println(httpResponseCode);        String payload = http.getString();
        StaticJsonDocument<2000> doc;             DeserializationError error = deserializeJson(doc, payload);
        if (error) {              Serial.print(F("deserializeJson() failed: "));              Serial.println(error.c_str());              return;            }

        String status = doc["status"];
        Serial.println(status);
         if ( status == "ON" ) {
           digitalWrite(ledPin, LOW);
         } else {
           digitalWrite(ledPin, HIGH);
         }
  }

you could use the response code to indicate the state of the relay

Use websockets instead. Or MQTT if you can run your own server or use a free public server...

Your two best options would be MQTT and WebSockets.
Both would open a long lived TCP connection that the ESP8266 and browser could use to transmit and receive data. Both would avoid constant polling to see if there's a new command.
MQTT requires an external broker. There are MQTT services with free tiers you could use for this or you could run one locally - Eclipse Mosquitto is a popular MQTT broker that runs nicely on a Raspberry Pi. MQTT is particularly useful for networks with multiple publishers and subscribers (it's a "pubsub" protocol) and is probably overkill if you just have a single device and endpoint.
It's easy to use MQTT from a browser using Javascript. The Paho Javascript MQTT client works well. The ESP8266 would establish a connection to the MQTT broker, subscribe to a topic name and set a callback function that would be called when data was published to that topic. The browser would also establish a connection to the MQTT broker and would publish a message to the topic when responding to events from the user.
WebSockets would allow the ESP8266 and browser to establish a full duplex connection between them. The ESP8266 would create a websocket server which the browser would connect to. The ESP8266 would check for data on the websocket during while running code in loop() and would assemble messages from the browser.
Either works easily if both your devices are on the same network (for instance, at home). If your browser is outside the network, it won't be able to communicate directly with the ESP8266.
MQTT has the advantage that an MQTT server located outside of the network (not one running locally on a Raspberry Pi) would allow the browser and ESP8266 to communicate with one another through it. WebSockets would require the use of a proxy server (there are modules for popular web servers like NGINX and Apache, but this requires control of the web server to configure). If you only ever want to use the browser to control the ESP8266 while they're both on the same network you don't need to worry about this.


text:
I am very new to Arduino and the kit tutorial just told me to wire this, I do not know how to wire it. Can Someone plz help!

I can't figure out how to do this the only wires I have are Jumper Wire and M-F 20 Pin DuPont Wire.

Comments are not for extended discussion; this conversation has been moved to chat.

If you don't have a breadboard, get one. It's a board with lots of holes in it that you can use for experimenting.
Something like this:

https://www.adafruit.com/product/64?gclid=EAIaIQobChMIz9XDj9bF6wIVcuW1Ch2_kgD3EAQYAiABEgL4DvD_BwE
As Delta_G said in their comment, you could wire a circuit as simple as yours by just putting the wires from the components directly into the terminals on the Arduino, but that quickly becomes impractical. Get a breadboard and learn how to use it.


text:
SG 90 servos randomly spinning
I started one project where i need 4 servos to control 4 grabbers jaws. i use STM32F103C8T6 with arduino IDE for programming it. The motor TZT Micro Servo 9g SG 90. First, I was playing with stepper motors to make them rotate how I want, then I added one servo on the same protoboard where are steppers and drivers for each. I used servo sweep example, and it randomly started twitching and sometimes to spin until power is off. the STM is powered with usb cable from PC. Then i tried other 3 motors and got same result.
Then i put STM on separate protoboard and there connected servo and it was not perfect but it was much stable than on onther protoboard. Then i used old PC power supply which i modified long time ago to have jacks for 12V, 5V and 3,3V, and connected servo to it and it worked normally.
So I started connecting motors 1 by one back to protoboard with other elements and tested them while adding them, first the first one , then added second and tested both, then added 3rd and tested all 3...
First two worked fine, but when i added third, all of them started twitching again, but then it stopped. So i added fourth and now all of them are twitching even if I write in code to rotate only one or two of them, which I don't understand how they can move if I do not give them signal from code.
Here is code for controlling both servo and stepper motors:
#include<Servo.h>

const int stepPin1 = PA4;
const int dirPin1 = PA0;
const int stepPin2 = PA5;
const int dirPin2 = PA1;

const int stepPin3 = PA6;
const int dirPin3 = PA2;

const int stepPin4 = PA7;
const int dirPin4 = PA3;

Servo servo1;
Servo servo2;
Servo servo3;
Servo servo4;

void setup() {
  pinMode(stepPin1,OUTPUT);
  pinMode(stepPin2,OUTPUT);
  pinMode(stepPin3,OUTPUT);
  pinMode(stepPin4,OUTPUT);

  pinMode(dirPin1,OUTPUT);
  pinMode(dirPin2,OUTPUT);
  pinMode(dirPin3,OUTPUT);
  pinMode(dirPin4,OUTPUT);

  servo1.attach(PB12);
  servo2.attach(PB14);
  servo3.attach(PA8);
  servo4.attach(PA10);

  //servo1.write(0);
  //servo2.write(0);
  //servo3.write(0);
  //servo4.write(0);
}

void loop() {
  digitalWrite(dirPin1,HIGH);
  digitalWrite(dirPin2,HIGH);
  digitalWrite(dirPin3,HIGH);
  digitalWrite(dirPin4,HIGH);

   //servo1.write(100);
   servo2.write(100);
   //servo3.write(100);
   //servo4.write(100);

  for(int x = 0; x < 200; x++) {
    digitalWrite(stepPin1,HIGH);
    digitalWrite(stepPin2,HIGH);
    digitalWrite(stepPin3,HIGH);
    digitalWrite(stepPin4,HIGH);

    delayMicroseconds(750);

    digitalWrite(stepPin1,LOW);
    digitalWrite(stepPin2,LOW);
    digitalWrite(stepPin3,LOW);
    digitalWrite(stepPin4,LOW);

    delayMicroseconds(750);
  }

  delay(1000); // One second delay

  digitalWrite(dirPin1,LOW);
  digitalWrite(dirPin2,LOW);
  digitalWrite(dirPin3,LOW);
  digitalWrite(dirPin4,LOW);

  //servo1.write(-100);
  servo2.write(-100);
  //servo3.write(-100);
  //servo4.write(100);

  for(int x = 0; x < 200; x++) {
    digitalWrite(stepPin1,HIGH);
    digitalWrite(stepPin2,HIGH);
    digitalWrite(stepPin3,HIGH);
    digitalWrite(stepPin4,HIGH);

    delayMicroseconds(750);

    digitalWrite(stepPin1,LOW);
    digitalWrite(stepPin2,LOW);
    digitalWrite(stepPin3,LOW);
    digitalWrite(stepPin4,LOW);

    delayMicroseconds(750);
  }

  delay(1000);

}

Here is also link to a short video of how the servos are behaving:

Do the servos still twitch if the steppers are quiet ? If the stepper-drivers are disconnected?

Yes, they are twitching. Soon I should get another STM and Arduino uno to test board and motors to check if they are broken.

Try assigning pins to the servos that are physically distant on the Arduino board from those assigned to steppers. Does anything change? It's looks rather like crosstalk from one to the other.

They are already separated because pins for stepper motors are on one side of board and servo pins are on another. Btw i managed to get both arduino and another STM from friend. I tested only servo motors on arduino alone with separated power supply, and only once one motor started spinning continuously until power supply is off. Next I will try same with STM and if it works, I will put it back on protoboard with other elements. But first I need to sleep after being awake all night, so I will update situation after some time.

With second STM it doesn't work too. When I added first servo, it started twitching, then i tried other 3 and then I tried them on other pins but its same. Maybe they would work if I would use software for STM, but this was easier way for me. So because it works on arduino (I tested them now again), I will probably buy arduino nano and use it just to control servos with them, MEGA is expensive here where I live and i do not have much time left so I have to use 2 controllers for this...
Anyway, thanks :D

Not necessarily on topic, but I could swear I saw the front servo in the video turn 360°; did it? As far as I know, the SG90 servos only do about 180°.

Just got arduino nano and it worked perfectly fine. So only problem that I see now is probably that Arduino IDE and arduino libraries are not fully compatible with STM chips and that is why that happened to me.
Anyway, thanks for help

ocrdu, sorry for late answer. Yeah it did 360°, sometimes it was going more than 360°. But if you make mods on those servos, than they can be continuous servos, so it isnt impossible. But my problem was that they all did it without mods and i was totally confused how is that happening xD


text:
Confuse about PROGMEM and R"====()===="
I saw the following code from https://circuits4you.com/2018/03/10/esp8266-jquery-and-ajax-web-server/ but I could not understand it thoroughly...
I looked at the documentation of PROGMEM from this https://www.arduino.cc/reference/en/language/variables/utilities/progmem/ but could not understand the importance in the code on why you should put your variables in flash memory instead of SRAM (the usual memory?)?
const char MAIN_page[] PROGMEM = R"=====(
  <!DOCTYPE html>

If you click on me, I will disappear.

Click me away!

Click me too!

  circuits4you.com

)=====";

Also, I could not understand the definition of R"====()====", what is meant by this in arduino?

why you should put your variables in flash memory instead of SRAM

Because the Arduino has only a very small amount of memory. If you have data that will never change it's better to store it in flash (of which there is much more) so as to leave the SRAM free for data that does change.

Also, I could not understand the definition of R"====()====", what is meant by this in arduino?

The R means "Treat everything between these delimiters as a raw string".  That is, everything between "=====( and )=====". It's not an Arduino thing, but a general C++ thing (see here). The ===== can be anything you like (within certain bounds) as long as it's the same at both the start and end of the string.  So you could use R"-=(This is "text")=-" which would assign the string This is "text". It's a great way of working with long strings that may want to contain " as otherwise you would have to escape each and every " as \". So the string I showed just now would otherwise have to be written as: "This is \"text\"", which can get very messy if there are lots of " in there.  The important thing to remember is that )===== mustn't appear in your text anywhere, so make sure it's something really obscure.

Thank you very much for being patient in helping beginners!

This applies to older AVR architectures. Newer one (for example ATMega4809) are mapping flash and the other memories into data space and there is no need for using PROGMEM. The same applies to ARM architecture - there is no PROGMEM, as there is no need to copy const variables into RAM to be accessible directly.

In your example, wouldn't R"-=(This is "text")=-" actually need to be R"-=(This is "text")-="? Or am I not understanding it right? It's almost like the HEREDOC syntax right?


text:
APDS-9960 detected but not showing output on serial monitor
I just bought an APDS-9960 sensor yesterday and tried it out today using Sparkfun's example from its APDS-9960 lib, and the only thing it printed out was:
"SparkFun APDS-9960 - ProximitySensor" twice then it didn't show any output
Using an Arduino Uno, and wires are connected correctly:
APDS :  Arduino Uno
VCC  :  3.3V
GND  :  GND
SDA  :  A4
SCL  :  SCL
INT  :  D2
I've also tried I2C scanning, and the device address was shown, but SparkFun's example code just didn't work at all.

Using PCB terminals because another sensor will also be integrated into the Arduino Uno.

Code:
/****************************************************************
...
****************************************************************/

#include <Wire.h>
#include <SparkFun_APDS9960.h>

// Global Variables
SparkFun_APDS9960 apds = SparkFun_APDS9960();
uint8_t proximity_data = 0;

void setup() {

  // Initialize Serial port
  Serial.begin(9600);
  Serial.println();
  Serial.println(F("------------------------------------"));
  Serial.println(F("SparkFun APDS-9960 - ProximitySensor"));
  Serial.println(F("------------------------------------"));

  // Initialize APDS-9960 (configure I2C and initial values)
  if ( apds.init() ) {
    Serial.println(F("APDS-9960 initialization complete"));
  } else {
    Serial.println(F("Something went wrong during APDS-9960 init!"));
  }

  // Adjust the Proximity sensor gain
  if ( !apds.setProximityGain(PGAIN_2X) ) {
    Serial.println(F("Something went wrong trying to set PGAIN"));
  }

  // Start running the APDS-9960 proximity sensor (no interrupts)
  if ( apds.enableProximitySensor(false) ) {
    Serial.println(F("Proximity sensor is now running"));
  } else {
    Serial.println(F("Something went wrong during sensor init!"));
  }
}

void loop() {

  // Read the proximity value
  if ( !apds.readProximity(proximity_data) ) {
    Serial.println("Error reading proximity value");
  } else {
    Serial.print("Proximity: ");
    Serial.println(proximity_data);
  }

  // Wait 250 ms before next reading
  delay(250);
}

I've tried putting delay(100); below Serial.begin(9600); as suggested here: https://learn.sparkfun.com/tutorials/apds-9960-rgb-and-gesture-sensor-hookup-guide/discuss and it did not help.
Any help is appreciated!

I cannot see in your image, how exactly the jumper wires are attached to the proximity sensor board. Are you sure, that they have good and stable contact?

the picture shows that it printed more than what you said

Hey @chrisl! Thanks for the comment. The issue went away by itself, somehow, so I'm guessing it's the sensor or the board. Thanks anyways!


text:
Most Efficient & Cost Effective Home Automation Setup
I managed to build a system using Wemos D1 R1 connected to my website to retrieve data to power on or off a 5V relay. Now I would like to expand the project to control all my house outlet. Assuming I have, 5 rooms each of which has 5 electricity wires to control. My question is what is the best setup to achieve my goal in terms of efficiency and cost optimization. If I clone my current setup, I would be needing Wemos Module for every room that connecting separately to my Wifi and then to my server which seems too much for me. So what would you recommend?
Thoughts:

Can I use one single central Wemos and then communicate to each room through ESP2866 or 433MHZ RF modules.
I would be using at least 4 channel 5V relay Module. Could it be powered using 5V in Wemos or Arduino or should be powered with adapter
If I want to control a fridge or AC or water heater, should I need SS Relay or any relay would suffice
if SS Relay to be used, I have read that heat sink or fan should be included, is that a must?

Those are a lot of questions in one. You could start by using 3V relay modules that do not need an external transistor. In my home, I am using a separate ESP module, connected to my Wifi for each device that needs to be controlled. What would be the advantage of using a central module with separate 433MHz channels to other modules? It only adds complexity and unnecessary dependencies. As for your other questions, you should look into the specifications of the relays / Solid State relays.

Just get a bunch of SWA1 WiFi socket adapters. They are ESP8266 based and you can hack them with your own code.

@Majenko, exactly. Sonoff also makes hackable ESP8285 / ESP8266 based smart switches that can be modified to run your own code.

why would you want to unplug your fridge or water heater? Both of those would be better with relays than SSRs, unless you deal with the SSR's heat correctly. Assume 1.5 watt of heat for every amp of current. I would much rather have 1 ESP per outlet than illegally re-wiring 4 outlets to a 4 channel relay. Wifi can handle the "traffic", don't worry about that; i ran out of reserved IPs on mine, and have dozens of static IPs going as well, yet i still have about 10-20ms lag per command, which is typical and acceptable.

I like sonoffs, but I found "WiOn 50050" smart outlets can be controlled by node-red without cracking them open using UDP packets, so if all you need is on/off control, they are a decent low-effort option.

I advice you to buy some Sonoff devices, either the basic or S20. (they are pretty cheap on AliExpress/ebay etc.) They are perfect for the job. Flash them with Tasmota, which you find on github Tasmota. Then use a RaspberryPi (or similar) as a server. Run Node-RED on this server to communicate via MQTT to all your (Sonoff) devices. Use Mosquitto as the MQTT broker.
I know this sounds like a lot, but thank me later when your done.


text:
Error reading from PROGMEM
I was trying to run a code from this https://circuits4you.com/2018/03/10/esp8266-jquery-and-ajax-web-server/
I am pasting it here.
/*
 * ESP8266 NodeMCU jQuery CDN Demo
 *
 * https://circuits4you.com
 */
#include <ESP8266WiFi.h>
#include <WiFiClient.h>

//ESP Web Server Library to host a web page
#include <ESP8266WebServer.h>

//---------------------------------------------------------------
//Our HTML webpage contents in program memory
const char MAIN_page[] PROGMEM = R"=====(
  <!DOCTYPE html>

If you click on me, I will disappear.

Click me away!

Click me too!

  circuits4you.com

)=====";
//---------------------------------------------------------------

//On board LED Connected to GPIO2
#define LED 2

//SSID and Password of your WiFi router
const char* ssid = "circuits4you.com";
const char* password = "yourWiFipassword";

//Declare a global object variable from the ESP8266WebServer class.
ESP8266WebServer server(80); //Server on port 80

//===============================================================
// This routine is executed when you open its IP in browser
//===============================================================
void handleRoot() {
 Serial.println("You called root page");
 String s = MAIN_page; //Read HTML contents
 server.send(200, "text/html", s); //Send web page
}
//==============================================================
//                  SETUP
//==============================================================
void setup(void){
  Serial.begin(115200);

  WiFi.begin(ssid, password);     //Connect to your WiFi router
  Serial.println("");

  //Onboard LED port Direction output
  pinMode(LED,OUTPUT);

  //Power on LED state off
  digitalWrite(LED,HIGH);

  WiFi.mode(WIFI_STA); //WiFi mode station (connect to wifi router only

  WiFi.begin(ssid, password);

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

  //If connection successful show IP address in serial monitor
  Serial.println("");
  Serial.print("Connected to ");
  Serial.println(ssid);
  Serial.print("IP address: ");
  Serial.println(WiFi.localIP());  //IP address assigned to your ESP

  server.on("/", handleRoot);      //Which routine to handle at root location. This is display page

  server.begin();                  //Start server
  Serial.println("HTTP server started");
}
//==============================================================
//                     LOOP
//==============================================================
void loop(void){
  server.handleClient();          //Handle client requests
}

When I deploy this to my nodemcu esp-12e, I a m getting below error
I used the exception decoder
Exception 3: LoadStoreError: Processor internal physical address or data error during load or store
PC: 0x4000bf64
EXCVADDR: 0x4023d581

From the decoder it says the offending line is this one
void handleRoot() {
 Serial.println("You called root page");
 String s = MAIN_page; //<<<<<<<<<<<<<<<<<<<<<< Error on this line
 server.send(200, "text/html", s);
}

It looks like it cannot read from the variable in PROGMEM..
I replaced that line with this code and converting it into a string and the error was gone.
String MAIN_page = R"=====(
  <!DOCTYPE html>

If you click on me, I will disappear.

Click me away!

Click me too!

  circuits4you.com

)=====";

Is there something wrong in the code that I am following on how it reads the variable from the PROGMEM flash memory?

server.send_P(200, "text/html", MAIN_page);

In the ESP32, anything declared as const will end up in the rodata segment, which then will go into flash and is read directly from that.. Don't know about the ESP8266.

https://arduino-esp8266.readthedocs.io/en/latest/PROGMEM.html PS why the UNO tag?

You cannot assign a PROGMEM string directly to a String object. Besides, the whole concept makes no sense, since String objects store their data in RAM regardless.
If you want to use PROGMEM you need to use const char * not String.

String s = (const __FlashStringHelper*) MAIN_page; would work and does use RAM only temporary. it could be useful to replace some parts of the string. But the whole approach by OP to this is wrong.

Yes, I just followed everything from that link.. I am just not sure how they are able to make it work at their end though.

The whole point of using PROGMEM is to save the RAM for other uses.  If you have a huge string that would overflow your RAM then PROGMEM is essential.  However, if the string isn't too large and the program works fine, then just use String instead of PROGMEM.


text:
Leonardo keypresses not working with OBS
I am using an Arduino Leonardo to have hotkeys for OBS but they don't work when the OBS Studio window is not focused.
I have the Leonardo press Ctrl + Alt + Shift + F7 when I press a button connected to the Leonardo. On OBS I have Ctrl + Alt + Shift + F7 switch to a slide. When I have the OBS window focused and I press the button it works fine. But when I have another application focused it does not work. The strange thing is, is that when I press (on my keyboard) Ctrl + Alt + Shift + F7, it will switch to the slide, but when I press the button it does not work.
I am running OBS as an Administrator btw.
My code for the Leonardo is below
int pinA = 8;

void setup() {
    pinMode(pinA, INPUT);
}

void loop(){
digitalWrite(pinA, HIGH);
readPinA = digitalRead(pinA);
if (readPinA == 0){
    Serial.print("A\n");
    Keyboard.press(KEY_RIGHT_CTRL);
    Keyboard.press(KEY_RIGHT_ALT);
    Keyboard.press(KEY_RIGHT_SHIFT);
    Keyboard.press(KEY_F7);
    Keyboard.releaseAll();
    delay(250);
    }
}

you really need to examine the example sketch closely

@jsotola could you give me a bit more info?

Try adding a delay between pressing the keys and releasing them all.

@RyanVogel have you looked at the example sketch? ... what does it have that your sketch does not have?

Warning: the below is all supposition.
When the OBS window is focused the OS can send keyboard events to the window. That means that it gets "The button has been pressed" messages. These are generated when the "press" events are sent from the Leonardo.
When the OBS window isn't focused it can't be sent those messages - so it has to manually poll the state of the keyboard to see what buttons are pressed at any one time. It can't be doing this all the time, so it does it periodically (but still pretty fast).
The knock-on effect is, though, that when not focused it can only see buttons that have been pressed for at least enough time for it to poll the state.
If you add a delay into your routine between the last "press" and the "release all" commands that is longer than the period between polling (no idea what that is - you'll have to experiment, but starting at around 50ms to 100ms should be adequate) you should give OBS enough time to see that the buttons are pressed before you then release them.

This worked! Thanks!


text:
ESP8266-01 Upload Sketch Problem Arduino UNO
My problem is actually in two stages.
I am very new to arduino uno and 8266-01. I have read many documents and watched videos for nearly 2 weeks, but I cannot even run the simplest "blink" example.
First of all, I installed the compatible software with an esp download tool as follows according to 6014h. And it seems okay.

After triple check, my wires and connections where they have to .
Rx->Rx  Tx->Tx  CH-3.3v GPI0 grounded Ground->Ground  and also 8266-01 VCC connected to Arduino 5v with 3.3v regulator and connected with capacitor, to debug voltage i check with voltmeter.
Problem is:
When I try to upload simple Blink example below imag.  My IDE gives a very different output from the videos I watched. I could not understand the reason for this.
the IDE outputs on the all of videos that i watched, are while uploading

This kind of upload starts when it says upload and when it's finished, the program runs.
BUT!In my case my  IDE is acts like that and nothing happens end of the upload.

My 8266 generic settings are as follows.

Led out pin in the blink example is 2 and GPI1 is connected to led to blink after all this explanation, where i missed up ?
Why i am taking different uploading process and code is not working?

Set flash mode to DOUT instead of QIO? You get different output because the videos you have seen are out of date and use an old uploading tool (esptool.exe) rather than the current one (esptool.py) or maybe the OTA tool (espota.py).

I set the flah mode to DOUT. I uploaded sketch again and hard resetting via rst pin is occured again and not blinking or any other serial AT commands not working. I think i catch somethings but i dont know. Why my code is not running or how I run the code after uploaded ?

you deleted the AT firmware with sketch upload

@Juraj how I run sketch ? is there any other connection mode for running mode ?

buy a development board for Arduino sketches on esp8266. something like Wemos D1 mini. it has USB and controls the flashing mode and reset of the esp8266. with esp-01 you must manually handle io 0 and reset for every upload. I wire buttons to esp-01 for frequent flashing. Then for flashing I hold the button for io 0 and click the button for reset. then I release the io 0 button.

My general advice these days: forget ESP8266 - use the ESP32. It's so much more capable.

Do you know whether you have an ESP-01 or ESP-01S? Visually, ESP-01 has two LEDs near the PCB antenna, a Blue LED connects to Tx line (GPIO1) and a Red LED as a power indicator. ESP-01S however only has one Blue LED and it is connected to GPIO2 instead. Based on your Arduino Menu, you are selecting GPIO2 as LED pin which only works for ESP-01S. If you have an ESP-01, you need to change "Builtin Led" to "1". See my blog for more explanation.


text:
Sparkfun OBDII - Arduino Uno Stuck at 832RPM-13Kmh
I'm working on a hobby project with Sparkfun OBDII UART + Arduino Uno + 16x2 LCD Screen, i'm trying to read my car's RPM-Speed-Coolant Temprature-Oxy Sensor on runtime.
Product Page
Wired OBDII to Arduino as:
OBD TX -> ARDUINO RX
OBD RX-> ARDUINO TX
OBD GND -> ARDUINO GND
As far as i understand OBDII board does all the job and it's just communicating with arduino through serial, they provided an example here : Hookup Guide
I don't have sparkfun serial lcd, so i've changed codes according to my lcd as follow;
#include <SoftwareSerial.h>
#include "DFRobot_RGBLCD.h"
const int colorR = 255;
const int colorG = 0;
const int colorB = 0;
DFRobot_RGBLCD lcd(16,2);  //16 characters and 2 lines of show
char rxData[20];
char rxIndex=0;
int vehicleSpeed=0;
int vehicleRPM=0;
void setup()
{
lcd.init();
lcd.setRGB(colorR, colorG, colorB);
Serial.begin(9600);
lcd.clear();
lcd.setCursor(0,0);
lcd.print("Hiz: ");
lcd.setCursor(0,1);
lcd.print("Devir: ");
delay(1500);
Serial.println("ATZ");
delay(2000);
Serial.flush();
}

void loop()
{
Serial.println("010D");
getResponse();
getResponse();
vehicleSpeed = strtol(&rxData[6],0,16);
lcd.setCursor(4,0);
lcd.print(vehicleSpeed);
lcd.print(" km/h");
delay(100);
Serial.flush();
Serial.println("010C");
getResponse();
getResponse();
vehicleRPM = ((strtol(&rxData[6],0,16)*256)+strtol(&rxData[9],0,16))/4;
lcd.setCursor(6,1);
lcd.print(vehicleRPM);
delay(100);
}
void getResponse(void){
  char inChar=0;
  while(inChar != '\r'){
    if(Serial.available() > 0){
      if(Serial.peek() == '\r'){
        inChar=Serial.read();
        rxData[rxIndex]='\0';
        rxIndex=0;
      }
      else{
        inChar = Serial.read();
        rxData[rxIndex++]=inChar;
      }
    }
  }
}

with above code i believe arduino receives last rpm and speed record before i shut down the engine which is 832RPM - 13 Kmh (at this point i'm not sure if arduino receive speed value correctly because when i shut down the engine i was parked the car and speed was 0kmh), in normal case when i start the car rpm and speed value should have changed but even after started the car the value stands still,it's not changing.
I bought waveshare's USB FTDI(TTL) adapter to figure it out is this board communicate with car or pc properly, connected usb ttl as;
OBD TX -> TTL RX
OBD RX-> TTL TX
OBD GND -> TTL GND
connected to OBDII port of my car, opened tera term, connected to COM20 (ttl defined as com20 on the pc) and run below commands as suggested in their manual;
ATZ -- resetted card successfully
ATRV -- returned 12.4 V as it should be, which is my battery voltage
ATSP0 -- auto find and select car's protocol it returned OK
010C -- RPM of the car it returned 41 0C 00 00 (engine wasn't started)
010C -- RPM of the car it returned 41 0C 10 F4 (engine started--idle RPM arround 1.000 rpm)
010D -- speed of the car it returned 41 00 00
010D -- speed of the car it returned 41 00 00 both value is the same because the car is not moving :)

According to above outcome the board is fine and communicating with car or pc or arduino without any problem.
But when i try with arduino when i connect the board to my car and turn my ignition to battery mode it reads rpm as 832 and speed as 13 and don't update those values even i start the engine.
What am i doing wrong?

after 1 week of try i finally solved it :)
As you guys know UNO has 1 i/o serial port, and Sparkfun's OBDII board doesn't work on same i/o serial port (at least i couldn't be able to), with uno when you send a command through serial to obd board you need to wait minimum 3 seconds to send another command or car's can-bus thinks that you canceled the first command returns STOPPED error, but with MEGA it works perfectly because mega has 3 i/o serial ports. You simply define Serial(TX)-Serial1(RX) and it works perfectly with 75ms delay.
Here is the working code.
//Set up ring buffer
char rxData[20];
char rxIndex = 0;
int rpmstored = 0;

    void setup()
    {
      Serial.begin(9600); // prints to serial monitor
      Serial1.begin(9600); //Hardware serial connection to the obdii uart
      OBD_init(); //initiates obd link
      delay(3000);
    }

    void loop()
{
rpmstored = getRPM();
//int mph = (int)((getSPEED() * 10000L + 5) / 16090); //convert to mph
//  Serial.print (mph);
Serial.print("S:");
Serial.print (getSPEED());
Serial.print (",");
Serial.print("R:");
Serial.println (getRPM());
//Serial.print (",");
//Serial.print("W:");
//Serial.print (getWATERTEMP());
//Serial.print (",");
//Serial.print("O:");
//Serial.print (getOILTEMP());
//Serial.print (",");
//Serial.print("F:");
//Serial.print (getFUEL());
//Serial.print (",");
//Serial.print("V:");
//Serial.println (getVOLT());
delay(100);
Serial.flush();
    }

    void OBD_init(void)
    {
      //Wait for a little while before sending the reset command to the OBD-II-UART
      delay(2000);
      //Reset the OBD-II-UART
      Serial1.print("ATZ\r");
      //Wait for a bit before starting to send commands after the reset.
      delay(2);
      OBD_read();
      Serial1.print("ATE0\r");
      OBD_read();
      //Serial1.flush();
    }

    int getRPM(void)
    {
      //Query the OBD-II-UART for the Vehicle rpm
      Serial1.flush();
      Serial1.print("010C\r");
      OBD_read();

      return ((strtol(&rxData[6], 0, 16) * 256) + strtol(&rxData[9], 0, 16)) / 4;
    }

    int getSPEED(void)
    {
      //Query the OBD-II-UART for the vehicle speed
      Serial1.flush();
      Serial1.print("010D\r");
      OBD_read();

      return strtol(&rxData[6], 0, 16);
    }

    int getOILTEMP(void)
    {
      //Query the OBD-II-UART for the vehicle speed
      Serial1.flush();
      Serial1.print("015C\r");
      OBD_read();

      return strtol(&rxData[6], 0, 16);
    }

    int getFUEL(void)
    {
      //Query the OBD-II-UART for the vehicle speed
      Serial1.flush();
      Serial1.print("012F\r");
      OBD_read();

      return strtol(&rxData[6], 0, 16);
    }

    int getVOLT(void)
    {
      //Query the OBD-II-UART for the vehicle speed
      Serial1.flush();
      Serial1.print("0142\r");
      OBD_read();

      return strtol(&rxData[6], 0, 16);
    }

    int getWATERTEMP(void)
    {
      //Query the OBD-II-UART for the Engine Coolant Temp
      Serial1.flush();
      Serial1.print("0105\r");
      OBD_read();

      return strtol(&rxData[6], 0, 16) - 40;
    }

    void OBD_read(void)
    {
      char c;
      do {
        if (Serial1.available() > 0)
        {
          c = Serial1.read();
          if ((c != '>') && (c != '\r') && (c != '\n')) //Keep these out of our buffer
          {
            rxData[rxIndex++] = c; //Add whatever we receive to the buffer
          }
        }
      } while (c != '>'); //The ELM327 ends its response with this char so when we get it we exit out.
      rxData[rxIndex++] = '\0';//Converts the array into a string
      rxIndex = 0; //Set this to 0 so next time we call the read we get a "clean buffer"

    }

I only need RPM & Speed that's why i comnented out other parameters but tested all and works perfectly.


text:
How to set the data length for SPI communication in Arduino library?
How can I set the number of bits that need to be transferred in SPI communication from a Slave chip to Master MCU using Arduino SPI Library in a SPI transaction? Let us say I want to read 14-bits data from Slave into my Master Arduino MCU then how would set this 14-bits in the SPI Library?

You don't. You transfer multiples of 8 bits. In general you would transfer 16 and discard or ignore 2.


text:
Arduino-controlled Pet Door Lock
Have a problem: new house but it gets super-windy and the doggy doors' magnets are too weak and blow open. Can't use bigger magnets because the doggies are too small.
So I thought I'd reinforce the pet-doors with a latch.
Next problem: the dogs are too dumb to learn wait for the doors to open. So the release mechanism must be rapid.
My plan was:
Arduino - uno or beetle/leonardo
motion sensor or ultrasonic sensors x2 (one inside and one outside) -> arduino -> relay ->wall power supply -> electromagnet release (normally on)

only the electromagnet gets super hot, so may not be best. Do servos or solenoids open fast? as in < 1s

Anyone have any suggestions on a  better way?? THanks so much!

Solenoids are probably your best bet. Get a spring loaded one with a chamfered actuator designed for door locks. https://www.amazon.co.uk/Solenoid-Electromagnetic-Electric-Cabinet-Intelligent/dp/B07GSV92YJ


text:
7segment display on Multi Function shield - Arduino Uno
I’ve bought this shield .
I’m looking for a way to display decimal point, without using any a designated library.
Most examples as this one shows only 0-9.
EDIT1 update link
Link

this display requires frequent refresh else it looks like it shows only one number

Does this answer your question? delay() problem for 74HC595 and 7-segment

The link to the example is dead. The decimal point is just like any other segment on the display. Set the corresponding output pin of the 75HC595 shift register to high or low (depending on the way, that the display is wired).

So if you click your 2nd link, it includes sample code for various sections of the multi-function shield.
One of them is titled "segment display".
If you look at that code, line 7 defines the bit patterns for each of the digits from 0 to 9:
const byte SEGMENT_MAP[] = {0xC0,0xF9,0xA4,0xB0,0x99,0x92,0x82,0xF8,0X80,0X90};

If you map them out in binary, you get:
0xC0,   1100 0000   0
0xF9,   1111 1001   1
0xA4,   1010 0100   2
0xB0,   1011 0000   3
0x99,   1001 1001   4
0x92,   1001 0010   5
0x82,   1000 0010   6
0xF8,   1111 1000   7
0X80,   1000 0000   8
0X90    1001 0000   9

A 0 character has all the segments lit except the middle "cross-bar". An 8 character has ALL of the segments lit. But the bit pattern for 8 is 1000 0000. That suggests that a 0 bit means a segment is lit, and 1 means it is off. Since the highest order bit of all of those characters is 1 (off) it suggests that the high-order bit is the decimal place bit. (It's the only bit that never changes.)
So if you replace
const byte SEGMENT_MAP[] = {0xC0,0xF9,0xA4,0xB0,0x99,0x92,0x82,0xF8,0X80,0X90};

with
const byte SEGMENT_MAP[] = {0x40,0x79,0x24,0x30,0x19,0x12,0x02,0x78,0X00,0X10};

You should get all the digits drawn with their corresponding decimal place lit.
I'd try that first to verify that I'm correct.
I'd then suggest writing code that reads the segments value for each digit, decides if you want a decimal place at that position, and if so, doing a bitwise AND (& in C/C++) on the value with 0X7F to clear the decimal bit for that character. (Remember it looks like a 0 means a given LED segment should be lit.
You could modify the function WriteNumberToSegment() to take a "lightDot" parameter, and have it change the bit if you pass TRUE (1):
void WriteNumberToSegment(byte Segment, byte Value, bool lightDot)
{
    digitalWrite(LATCH_DIO,LOW);
    bool bits = SEGMENT_MAP[Value]);
    if (lightDot) {
       bits &= 0x7F; //To light the decimal for this digit, clear the 0x80 bit
    }
    shiftOut(DATA_DIO, CLK_DIO, MSBFIRST, bits);
    shiftOut(DATA_DIO, CLK_DIO, MSBFIRST, SEGMENT_SELECT[Segment] );
    digitalWrite(LATCH_DIO,HIGH);
}

(I don't remember for sure if bool is a valid type in Arduino C/C++. If not, just replace bool with uint8 in the above.)


text:
Communication between ESP01 Arduino NANO and using External Interrupt in Arduino NANO for other than communication program same time
I have done communication between ESP01 and Arduino NANO (ATMEGA328 based). ESP pins used are GPIO-0 and GPIO2. In NANO, used D2 and D3. This program working Ok. Now I want to add external interrupt in my Arduino NANO program while continuing communication with ESP01. But I cannot use D2 and D3 because it was used by communication program. Now Arduino NANO's limit is it has only two interrupt pins which are D2 and D3. So if I use this for external interrupt program, I lose communication with ESP01. Can anybody help me to use my both task at the same time: Task1- External interrupt in Arduino Nano, Task2- Communication with ESP01. Your reply will help me to solve this issue. Thanks in advance.

Don't use D2 and D3 for the communication? There's plenty of other pins on a Nano...

so move the SodtwareSerial to other pair of pins. 4 and 5 are good for PWM but 6 and 7 are not special.

D2 and D3 Pins on Arduino nano support external Interrupt. Hence, you have to use one of those for the interrupt.
Since you are using softwareSerial() you can easily remap it to other digital pins of the Nano.
Pins from D4-D12can be used for communication.
You just have to change the parameters in the softwareserial() as below:
SoftwareSerial mySerial(4, 5); // RX, TX;;for example

how do you know OP is using SoftwareSerial? it is not mentioned in the question. I made a wild guess in a comment


text:
Send only one packet from one ESP32 to another ESP32 without acknowledgment
I have a network consisting 10 slaves and one master. I am using ESP-NOW to send the messages between the nodes. All of the nodes are within close proximity. I do NOT need a mesh network to reach all the nodes.
ESP-NOW works amazing. It is simple to use and the library is easy to understand. But in this project esp-now is not working for me and here is why:

If the 10 slaves want to send data at the same time it does not work. With 10 nodes they can send data every 200ms. If I lower the time some nodes even crash and restart.

Because all nodes cannot send data at the same time I am having the master ping each node to synchronize who can send a message. The moment a slave receives a message it can reply back.

If one slave node sends data to the wrong peer for some reason the web server of the master node stops working. It freezes until that node is done sending data.

If I send a broadcast message all the nodes reply. How can I configure esp-now so that no acknowledgment is sent back?

With esp-now when you send a packet the destination node always replies with a confirmation. I want to send that confirmation once the job that the slave had to perform worked. Because I am planing to work with a lot of nodes with close proximity I want to reduce network traffic. Moreover, on esp-now if a packet is not delivered it attempts again increasing the network traffic. I only want to resend packets that are important in order to reduce network traffic.

esp-now limits the number of nodes you can have specially if you encrypt the messages.

So my question is: is there a way to instruct esp-now to NOT send an acknowledgment? Can I instruct esp-now to only send one packet regardless if it failed or not? On the NRF24L01 you can set this value with the method setRetries. I just want something like UDP where it is a fire and forget. I cannot use UDP because I do not want to be connected to a WiFi network.
It will be great if I could have 2 methods. One for sending a simple raw packet and another for reading those packets on another esp32. I know I will be having to do a lot of filtering on the receiving side.

Edit

Here is a solution that works but needs improvement
It is possible to send raw packets with the function esp_wifi_80211_tx. But still esp32 sends 5 packets when using that function! Moreover, in order to use that function you must send a wifi beacon with whatever data you want. The minimum size of a beacon packet I believe is 128 bytes. So this is a solution but not a good one.
Anyways I bellow is the code for the transmitter esp32 and the receiver esp32. The transmitter code has to be compiled with the ESP-IDF framework and NOT arduino. If I use arduino framework it compiles fine (replace main function with setup) but it does not work once I upload it to the esp32. The receiver code I compiled it using the arduino IDE.
transmitter code (tx)
#include <stdio.h>

#include "driver/gpio.h"
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"

#include "esp_event_loop.h"
#include "esp_system.h"
#include "esp_event.h"
#include "esp_wifi.h"

#include "nvs_flash.h"
#include "string.h"

// pin used to flash led
#define PIN GPIO_NUM_2

/*
 * This is the (currently unofficial) 802.11 raw frame TX API,
 * defined in esp32-wifi-lib's libnet80211.a/ieee80211_output.o
 *
 * This declaration is all you need for using esp_wifi_80211_tx in your own application.
 */
esp_err_t esp_wifi_80211_tx(wifi_interface_t ifx, const void *buffer, int len, bool en_sys_seq);

esp_err_t event_handler(void *ctx, system_event_t *event)
{
    return ESP_OK;
}

void send_raw_packet_task(void *pvParameter)
{

    for (;;)
    {
        uint8_t dataToSend[] = { 0 } ;

        esp_wifi_80211_tx(WIFI_IF_AP, dataToSend, sizeof(dataToSend) , false);

        // turn on and off led AND wait 10 seconds
        gpio_pad_select_gpio(PIN);
        gpio_set_direction(PIN, GPIO_MODE_OUTPUT);
        gpio_set_level(PIN, 1);
        vTaskDelay(9500 / portTICK_PERIOD_MS);
        gpio_set_level(PIN, 0);
        vTaskDelay(500 / portTICK_PERIOD_MS);
    }
}

extern "C" void app_main(void)
{
    nvs_flash_init();
    tcpip_adapter_init();

    wifi_init_config_t cfg = WIFI_INIT_CONFIG_DEFAULT();

    ESP_ERROR_CHECK(esp_event_loop_init(event_handler, NULL));
    ESP_ERROR_CHECK(esp_wifi_init(&cfg));
    ESP_ERROR_CHECK(esp_wifi_set_storage(WIFI_STORAGE_RAM));

    // Init dummy AP to specify a channel and get WiFi hardware into
    // a mode where we can send the actual fake beacon frames.
    ESP_ERROR_CHECK(esp_wifi_set_mode(WIFI_MODE_AP));
    wifi_config_t ap_config;

    // SSID = TTTT (4 times the letter t in uppercase)
    wifi_ap_config_t x;
    x.ssid[0] = 84; x.ssid[1] = 84; x.ssid[2] = 84; x.ssid[3] = 84;
    x.ssid[4] = 0;
    x.ssid_len = 4;

    //x.password = "dummypassword"; // for some reason this does not compile
    x.password[0] = 84; x.password[1] = 84; x.password[2] = 84; x.password[3] = 84; x.password[4] = 84; x.password[5] = 84; x.password[6] = 84; x.password[7] = 84;
    x.password[8] = 0;

    x.channel = 1;
    x.authmode = WIFI_AUTH_OPEN;
    x.ssid_hidden = 0;
    x.max_connection = 4;
    x.beacon_interval = 60000;
    ap_config.ap = x;

    //ESP_ERROR_CHECK(esp_wifi_set_config(WIFI_IF_AP, &ap_config));
    auto res = esp_wifi_set_config(WIFI_IF_AP, &ap_config);
    if (res == ESP_OK)
    {
        printf("set esp_wifi_set_config. It worked!\n");
    }
    else
    {
        printf("It did NOT worked :/\n");
        return;
    }

    // ESP_ERROR_CHECK(esp_wifi_start());
    res = esp_wifi_start();
    if (res == ESP_OK)
    {
        printf("wifi started! It worked!\n");
    }
    else
    {
        printf("It did NOT worked :/\n");
        return;
    }

    // ESP_ERROR_CHECK(esp_wifi_set_ps(WIFI_PS_NONE));
    wifi_ps_type_t t = WIFI_PS_NONE;
    res = esp_wifi_set_ps(t);
    if (res == ESP_OK)
    {
        printf("wifi set to WIFI_PS_NONE! It worked!\n");
    }
    else
    {
        printf("It did NOT worked :/\n");
        return;
    }

    res = esp_wifi_set_channel(1, WIFI_SECOND_CHAN_NONE);
    if (res == ESP_OK)
    {
        printf("wifi set channel to 1! It worked!\n");
    }
    else
    {
        printf("It did NOT worked :/\n");
        return;
    }

    // output size of bytes that we will be sending
    printf("*** Size of configuration is %i bytes. Starting task send_raw_packet_task...", (int)sizeof(ap_config));
    xTaskCreate(&send_raw_packet_task, "send_raw_packet_task", 2048, NULL, 5, NULL);
}

receiver code (rx)
#include "freertos/FreeRTOS.h"
#include "esp_wifi.h"
#include "esp_wifi_types.h"
#include "esp_system.h"
#include "esp_event.h"
#include "esp_event_loop.h"
#include "nvs_flash.h"

uint8_t channel = 1;

static void wifi_sniffer_packet_handler(void* buff, wifi_promiscuous_pkt_type_t type);
void wifi_sniffer_packet_handler(void* buff, wifi_promiscuous_pkt_type_t type) {

    // in here esp32 will capture all wifi traffic

    auto t = (unsigned char*)buff;

    // create flag to see if packet contains "TTT"
    bool containsX = false;

    // index where the first T is located on the buffer in case it is found
    int indexWhereNameOfSsidWasFound = 0;

    // look to see if its a packet of interest
    for (int i = 45; i < 100; i++)
    {
        if (t[i] == 84 && t[i + 1] == 84 && t[i + 2] == 84)
        {
            containsX = true;

            indexWhereNameOfSsidWasFound = i;
            Serial.println(i);

            break;
        }
    }

    if (containsX == false)
        return;

    // print SSID if found
    for (int i = indexWhereNameOfSsidWasFound; i < indexWhereNameOfSsidWasFound + 20; i++)
    {
        Serial.print((int)t[i]);
        Serial.print(" ");
    }
    Serial.println();

}

esp_err_t event_handler(void* ctx, system_event_t* event)
{
    return ESP_OK;
}

// the setup function runs once when you press reset or power the board
void setup() {

    Serial.begin(115200);

    // delay 2 seconds so that esp32 initializes
    Serial.println("Starting...");
    vTaskDelay(2000 / portTICK_PERIOD_MS);

    // init wifi sniffer
    {
        // order of initializations matter!

        wifi_country_t wifi_country = { .cc = "IT", .schan = 1, .nchan = 13 }; // Most recent esp32 library struct

        nvs_flash_init();
        tcpip_adapter_init();

        ESP_ERROR_CHECK(esp_event_loop_init(event_handler, NULL));

        wifi_init_config_t cfg = WIFI_INIT_CONFIG_DEFAULT();
        ESP_ERROR_CHECK(esp_wifi_init(&cfg));
        ESP_ERROR_CHECK(esp_wifi_set_country(&wifi_country)); /* set country for channel range [1, 13] */
        ESP_ERROR_CHECK(esp_wifi_set_storage(WIFI_STORAGE_RAM));
        ESP_ERROR_CHECK(esp_wifi_set_mode(WIFI_MODE_NULL));
        ESP_ERROR_CHECK(esp_wifi_start());

        // turn on promiscuous to capture everything
        esp_wifi_set_promiscuous(true);
        esp_wifi_set_promiscuous_rx_cb(&wifi_sniffer_packet_handler);

        // listen on channel 1
        esp_wifi_set_channel(channel, WIFI_SECOND_CHAN_NONE);
    }
}

void loop() {
    // empty
}

So basically the receiver code is listening for all network trafic in promiscuous mode. Kind of like wireshark. If it sees a packet that contains the string "TTTT" it will output it.
Because there is so much wifi traffic this is way slower than esp-now. I could not figure out how to send smaller packets. Lastly when sending a packet it takes about 2 second to capture the packet. I belive esp32 stores all those packets on a queue and then latter calls the call back function.
I guess I will go back on using esp-now. Can I modify the source code of esp-now? I just want want to remove the part where it send the packet multiple times and also the part where it replies with an acknowledgment.

I don't know ESP-NOW but for one way messages in TCP/IP network UDP protocol is used. That is WiFIUdp with the WiFi library

Can I send UDP messages without being connected to a network? I guess I will have to create a network between the nodes correct?

yes it would require a standard WiFi network. one of the esp32 can create it as SoftAP

I surmise that the esp32 'raw' tx isn't really that, based on the restrictions on what can be sent (data, but not QoS data, for example.)
I think that among the 5 packets you report seeing are 1.RTS, 2. CTS, 3. DATA, 4. ACK. These (at least 1,2) are necessary to avoid collision.
ESPNow sends a vendor-specific packet which doesn't (I surmise) require or follow the CTS/RTS or ACK 802.11 conventions.
Point to Point ESPNow, however, is written to expect a packet acknowledgement from the receiver, and will resend for a certain number of times until it receives one.
Broadcast ESPNow does not expect, and in fact cannot automatically receive, one of these ESPNow-specific acknowledgements.
If you need the fastest, least reliable 802.11 packet transmission, I would advise to use Broadcast ESPNow.
Having said that, you must be aware that you will not get the full collision-avoidance protections of more usual 802.11 protocol usage. You may need to provide your own ... such as listen-before-send, random exponential backoff, and who knows what else.
Seems to me that you are embarking on a wilderness adventure :)


text:
How to create a 1-hour timer with an ATtiny13A microcontroller?
I want to control an AC load such that it powers on for 1 minute, then turns off for 1 hour, then on again for 1 min, and so on, in a loop.
I just modified the blink sketch to do:

Turn A1 on
Then delay for 60,000 ms
Then turn A1 off
Then delay for 3,600,000 ms (3,600 sec, or 1 hour)

...but it doesn't seem to work.
It looks like the LED connected to A0 turns on but instead of turning off after 1 min, it turns off after 8 min 30 s.
Any suggestions?

I rectified the sketch. Now it takes 1 sec as actual 1 sec. I chose 1 MHz clock in IDE.
int ledPin =  A3; // the number of the LED pin
int ledState = HIGH; // ledState used to set the LED
unsigned long previousMillis = 0; // will store last time LED was updated
unsigned long OnTime = 60000; // milliseconds of on-time
unsigned long OffTime = 10000; // milliseconds of off-time

void setup()
{
  // set the digital pin as output:
  pinMode(ledPin, OUTPUT);
}

void loop()
{
  // check to see if it's time to change the state of the LED
  unsigned long currentMillis = millis();

  if((ledState == HIGH) && (currentMillis - previousMillis >= OnTime))
  {
    ledState = LOW;  // Turn it off
    previousMillis = currentMillis; // Remember the time
    digitalWrite(ledPin, ledState); // Update the actual LED
  }
  else if ((ledState == LOW) && (currentMillis - previousMillis >= OffTime))
  {
    ledState = HIGH;  // turn it on
    previousMillis = currentMillis; // Remember the time
    digitalWrite(ledPin, ledState); // Update the actual LED
  }
}

Then it turns on for 1 sec and then turns off for 1 sec, then randomly turns on at 30 sec or 1 min 30 sec. I want to turn it on for 1 min every hour.
I tried the Blink sketch modified as follows:
void setup() {
  pinMode(A3, OUTPUT);
}

void loop() {
  digitalWrite(A3, HIGH);
  delay(60000);
  digitalWrite(A3, LOW);
  delay(900000);
}

But it still turns on for 1 min and turns off for 1 min.
I also tried this:
void setup() {
  pinMode(A3, OUTPUT);
}

void loop() {
  digitalWrite(A3, HIGH);
  delay(60000);
  digitalWrite(A3, LOW);
  delay(3.6e+6);
}

No matter what I do on time and off time, it always remains the same.
I wanted to know one thing: can I set a 1-hour off and 1-min on timer using ATtiny13A or not?
I tried 1.2 MHz, 1 MHz, all clocks in the IDE, nothing seems to work.

What are you running this on?

Are you sure, that the Attiny is running at the frequency, that you think it runs? I once had my Attiny85 configured for 1MHz instead of the 8MHz, that I was expecting, so I wondered why my code was running 8 times slower.

How fast does the LED blink when you run the original and unchanged blink sketch?

Its about 8.4 seconds

Sounds like ChrisL nailed it. Your attiny13a is running at 1 MHz instead of 8.

How are you programming the ATtiny? Which programmer and board manager do you use?

I use arduino mega as isp attiny on breadboard

Please post your exact code. What are your variable types? int, for example, can only hold up to 32767 ms, NOT 3600000 ms! It is 2 bytes on AVR microcontrollers. That means unsigned int only holds up to 65535 ms.

Please move all your answers that are additions to your question to your question, then delete all your answers that aren't answers. It's okay to write an answer to your own question, but if you're just trying to improve your question, edit your question and add directly to your question instead.

As the unchanged blink sketch blinks with 8.4 seconds, I think my assumption is right. The clock of the Attiny is running 8 times slower, than the code thinks.
When you have installed the Attiny core, there should be a menu entry for the clock frequency. Most likely the standard is 8MHz. But having 8MHz set does not mean, that the Attiny is using 8MHz. To choose between different clock sources and frequencies, you must change the fuses of the microcontroller (which are just some bits of special non-volatile memory in the chip, that set special hardware configuration; more information in this question). This is done, when you burn the bootloader to the chip. That's the easy version. Alternatively you can use the avrdude command directly to set the fuses. That's the advanced way.
Currently the fuses of your Attiny seem to be set to the 1MHz internal clock. But the compiler uses the frequency, that you have chosen in the menu, hence 8MHz internal clock. So the compiler thinks, that the chip runs at 8MHz and thus generates the timing code for this execution speed. But your chip is currently 8 times slower, than the compiler thinks.
TL;DR: Burn the bootloader onto the chip to let the Arduino IDE set the right fuses for your clock frequency.

I doubt an ATtiny13a is large enough for a bootloader, having only 1K of Flash / program memory. My experience with ATtinyCore (which does not support the tiny13 AFAIK) is that it correctly sets the fuses when choosing the "burn bootloader" option even when, in the board settings, the "ATTiny XX (No Bootloader)" option is chosen.

The code you wrote should work as expected. If it doesn't, I suspect
there is something broken in the Arduino core you are using. However,
such a trivial task can very easily be programmed in plain C, at the
avr-libc level:
#define F_CPU 1000000  // 1 MHz
#include <avr/io.h>
#include <util/delay.h>

int main(void)
{
    DDRB |= _BV(PB3);  // PB3 as output
    for (;;) {
        PORTB |= _BV(PB3);   // PB3 high
        _delay_ms(60e3);     // 1 min
        PORTB &= ~_BV(PB3);  // PB3 low
        _delay_ms(3.6e6);    // 1 h
    }
}

I would compile it with:
avr-gcc -mmcu=attiny13a -Os -Wall -Wextra 1h-timer.c -o 1h-timer.elf

See the Port Registers Arduino tutorial for the meaning of the
macros used here. You can tweak F_CPU to fine-tune the delays, in case
your ATtiny clock is not quite 1 MHz.

Attiny13 has very as in very small memory. So if you want it to crunch stuff which seems to be easy for other mcu, it might not have enough memory for it. It cannot for example consistently carry out millis() like in:
long timeStart = millis();
.
.
.
if (timeIsUp=0 && millis()-timeStart=>60000)
.
.
.
The most that that code will loop is less than 50 seconds in my experience.
As a workaround I was able to make attiny13 keep track of time for more than 10 minutes by using only integers and using count. The count being incremented after 10seconds. So example:
for (int i=0; i>10; i++){
delay(10000);
count++;
Then you can use count to keep track of time that has elapsed.
Using millis() is very heavy for attiny13.


text:
What is this potentiometer for?
I am working on an anemometer project using Arduino. I don't know barely anything from Arduino and I am following this tutorial.
I have some doubts on the making part. This is what I have to make:
and this is the code:
//anemómetro con LCD
#include <LiquidCrystal.h>

LiquidCrystal lcd(7, 8, 9, 10, 11, 12);

float veloc1 = 0; // entrada A0
int tiempo = 0;
int cnt = 0;
float v1 = 0;
float v2 = 0;

void setup() {
  lcd.begin(16, 2); // Fijamos el numero de caracteres y filas
  lcd.begin(16, 2); // Fijamos el numero de caracteres y filas
  lcd.print("Anemometro EC"); // Aqui va el mensaje
  analogReference(INTERNAL);// pone como referencia interna 1.1V
}

void loop() {
  v1 = (analogRead(0)); // lectura de sensor a0
  veloc1 = (v1 * 0.190); // 0,190 corresponde a la pendiente de la curva aca deben poner el numero que calcularon
  lcd.setCursor(0, 1); // Ponte en la line 1, posicion 0
  lcd.print(veloc1); //muestra la velocidad del viento en el LCD
  lcd.setCursor(4, 1); // ponte en linea 1, posicion 5
  lcd.print("Km / h");
  lcd.setCursor(9, 1);
  lcd.print("Max");
  if (veloc1 > v2)v2 = veloc1, lcd.print (v2, 1); // muestra la velocidad maxima que alcanzo
  delay(1000);
}

What is the potentiometer doing here? Why is it necessary?
My lcd screen doesn't show anything. Does anyone knows why??

Thanks in advance.

What is the potentiometer doing here? Why is it necessary?

It's there to control the "offset voltage" of the LCD, which is what controls the contrast of the display.

My lcd screen doesn't show anything. Does anyone knows why??

Maybe you wired it wrong. Maybe you didn't put the potentiometer in the circuit because you didn't understand what it is for. Maybe you just need to adjust the contrast by turning said potentiometer. It's hard for us to tell. By showing us what you intended to build and then telling us that what you actually built doesn't work, there is nothing we can tell you. There must be some difference between what you intended to build and what you did build, but we can't see what you built, so we can't have any clue.


text:
RFID-RC522 not working properly?
So I'm working with an arduino uno and I want to read the UID from one card and write it to another with the code of Miguel Balboa but the RC522 doesn't appear to read anything on the serial monitor. However, if I the one below, it actually reads everything. I've also used the hardware checker and it says that everything is working fine. What am I doing wrong or what do I have to do to clone the UID with this code? Thank you very much in advance.
#include <SPI.h>

#define SAD 10
#define RST 5

MFRC522 nfc(SAD, RST);

void setup() {
  SPI.begin();
  // Read a fast as possible. There is a limit for how long we are
  // allowed to read from the tags.
  Serial.begin(115200);

  Serial.println("Looking for MFRC522.");
  nfc.begin();

  // Get the firmware version of the RFID chip
  byte version = nfc.getFirmwareVersion();
  if (! version) {
    Serial.print("Didn't find MFRC522 board.");
    while(1); //halt
  }

  Serial.print("Found chip MFRC522 ");
  Serial.print("Firmware ver. 0x");
  Serial.print(version, HEX);
  Serial.println(".");
}

byte keyA[6] = {0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, };
byte keyB[6] = {0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, };

void loop() {
  byte status;
  byte data[MAX_LEN];
  byte serial[5];
  int i, j, pos;

  // Send a general request out into the aether. If there is a tag in
  // the area it will respond and the status will be MI_OK.
  status = nfc.requestTag(MF1_REQIDL, data);

  if (status == MI_OK) {
    Serial.println("Tag detected.");
    Serial.print("Type: ");
    Serial.print(data[0], HEX);
    Serial.print(", ");
    Serial.println(data[1], HEX);

    // calculate the anti-collision value for the currently detected
    // tag and write the serial into the data array.
    status = nfc.antiCollision(data);
    memcpy(serial, data, 5);

    Serial.println("The serial nb of the tag is:");
    for (i = 0; i < 3; i++) {
      Serial.print(serial[i], HEX);
      Serial.print(", ");
    }
    Serial.println(serial[3], HEX);

    // Select the tag that we want to talk to. If we don't do this the
    // chip does not know which tag it should talk if there should be
    // any other tags in the area..
    nfc.selectTag(serial);

    // Assuming that there are only 64 blocks of memory in this chip.
    for (i = 0; i < 64; i++) {
      // Try to authenticate each block first with the A key.
      status = nfc.authenticate(MF1_AUTHENT1A, i, keyA, serial);
      if (status == MI_OK) {
        Serial.print("Authenticated block nb. 0x");
        Serial.print(i, HEX);
        Serial.println(" with key A.");
        // Reading block i from the tag into data.
        status = nfc.readFromTag(i, data);
        if (status == MI_OK) {
          // If there was no error when reading; print all the hex
          // values in the data.
          for (j = 0; j < 15; j++) {
            Serial.print(data[j], HEX);
            Serial.print(", ");
          }
          Serial.println(data[15], HEX);
        } else {
          Serial.println("Read failed.");
        }
      } else {
        // If we could not authenticate with the A key, we will try
        // the B key.
        status = nfc.authenticate(MF1_AUTHENT1B, i, keyB, serial);
        if (status == MI_OK) {
          Serial.print("Authenticated block nb. 0x");
          Serial.print(i, HEX);
          Serial.println(" with key B.");
          status = nfc.readFromTag(i, data);
          if (status == MI_OK) {
            for (j = 0; j < 15; j++) {
              Serial.print(data[j], HEX);
              Serial.print(", ");
            }
            Serial.println(data[15], HEX);
          } else {
            Serial.println("Read failed.");
          }
        } else {
          Serial.print("Access denied at block nb. 0x");
          Serial.println(i, HEX);
        }
      }
    }

    // Stop the tag and get ready for reading a new tag.
    nfc.haltTag();
  }
  delay(2000);
}```

you are not doing anything wrong ... it appears that there is no code for writing to a card

that's the code that i'm using instead of the one from Miguel Balboa, which doesn't work. I was asking for a code to actually write a card with the code i've given


text:
Static IP for ESP8266 based on gateway
I'm new to Arduino programming. I want to make my ESP8266 get a static IP address based on the gateway's IP address.
I mean if the gateway is at 192.168.0.1 then the ESP8266 should get 192.168.0.15 as a static IP address. And if the gateway is at 192.168.1.1 then it should get 192.168.1.15 as an IP address.

Isn't that the role of DHCP? Your Access Point / Router should be handing out that IP address. If you want it to be static then configure your router to allocate a static IP for the MAC address. If you're getting the gateway by DHCP then you will also be getting an IP through DHCP.

I'm wondering why you would want to do that. You run the risk of IP collissions and network problems that are hard to diagnose. I would not want such a device in my network ;-) A (Static) DHCP Address reservation is the mechanism you should be using.

You can either set the router to allocate a static IP address based on your ESP8266's MAC address, or go the DHCP-way first, read the gateway IP address you got, and then do a WiFi.config(), something roughly like this (untested):
WiFi.begin(ssid, password);
IPAddress ip = WiFi.gatewayIP();
IP[3] = 15;
IPAddress dns(8, 8, 8, 8);
WiFi.config(ip, WiFi.gatewayIP(), dns, WiFi.subnetMask());

It is a bit of a trick, and not pretty, and you don't get to set the DNS as provided by the DHCP, because there is no getDNS(), for some silly reason, hence the use of Google's DNS server.
Note that when doing this, you run the risk of setting the ESP8266's IP address to an address already taken by another device on the same router.

Here is the idea that I have not implemented yet.

Connect to the wifi and let the router assign the IP to it.
After getting the IP from the router save that IP to eeprom
Now next time you want to connect to the wifi use this code.

// Set your Static IP address
IPAddress local_IP(192, 168, 1, 184);
// Set your Gateway IP address
IPAddress gateway(192, 168, 1, 1);

IPAddress subnet(255, 255, 0, 0);
IPAddress primaryDNS(8, 8, 8, 8);   //optional
IPAddress secondaryDNS(8, 8, 4, 4); //optional

if (!WiFi.config(local_IP, gateway, subnet, primaryDNS, secondaryDNS)) {
    Serial.println("STA Failed to configure");
  }

  // Connect to Wi-Fi network with SSID and password
  Serial.print("Connecting to ");
  Serial.println(ssid);
  WiFi.begin(ssid, password);

load the saved ip, gateWay and other information saved in the eeprom before passing to wifi.config function.


text:
NRF24 receiving data while turned off
The code to set up the nrf24 is from Electronoobs. The further if-clauses are suposed the drive a motor. The problem I am facing is, that if ther is no data transmission (emitter turend off; or receiver antenna unplugged) the Arduino-Nano-Chip is receiving random values, but there should not be anything at all. I need something which sets the variables left/right to 512 as long as there is no data transmission, when the remote/controller is turned off for example.
//Emitter-Code
#include <SPI.h>
#include <nRF24L01.h>
#include <RF24.h>

//const uint64_t my_radio_pipe = 0xE8E8F0F0E1LL; //Remember that this code should be the same for the receiver
const uint64_t my_radio_pipe = 0xE8E80000E1LL; //Remember that this code should be the same for the receiver

RF24 radio(9, 10); //CSN and CE pins

// The sizeof this struct should not exceed 32 bytes
struct Data_to_be_sent {
  byte ch1;
  byte ch2;
};

Data_to_be_sent sent_data;

void setup()
{
  radio.begin();
  radio.setAutoAck(false);
  radio.setDataRate(RF24_250KBPS);
  radio.openWritingPipe(my_radio_pipe);
  sent_data.ch1 = 119;
  sent_data.ch2 = 58;
}

/**************************************************/

void loop()
{
  /*If your channel is reversed, just swap 0 to 255 by 255 to 0 below
  EXAMPLE:
  Normal:    data.ch1 = map( analogRead(A0), 0, 1024, 0, 255);
  Reversed:  data.ch1 = map( analogRead(A0), 0, 1024, 255, 0);  */

  sent_data.ch1 = map(analogRead(A1), 0, 1023, 0, 255);
  radio.write(&sent_data, sizeof(Data_to_be_sent));
  sent_data.ch2 = map(analogRead(A3), 0, 1023, 0, 255);
  radio.write(&sent_data, sizeof(Data_to_be_sent));
}

//Receiver-Code
#include <SPI.h>
#include <nRF24L01.h>
#include <RF24.h>

const uint64_t pipeIn = 0xE8E8F0F0E7LL;     //veränderter
//const uint64_t pipeIn = 0xE8E80000E1LL; //echter
RF24 radio(9, 10);  //CSN and CE pins

// The sizeof this struct should not exceed 32 bytes
struct Received_data {
  byte ch1;
  byte ch2;
};

int ch1_value = 0;
int ch2_value = 0;
Received_data received_data;

/**************************************************/
//PIN-Deklaration
short enB = 5;
short enA = 6;
short in1 = 1;
short in2 = 2;
short in3 = 3;
short in4 = 4;

//Variablendeklaration
short linker;
short rechter;
short vLinker;
short vRechter;
short ivLinker;
short ivRechter;
short gem;
short gemRest;
short rest;
short mitte = 512;
short ober = 561;
short unter = 462;
short orest;
short urest;

void lV(){
  digitalWrite(enA,LOW);
  digitalWrite(in1,HIGH);
  digitalWrite(in2,LOW);
  digitalWrite(enA,HIGH);
}

void lR(){
  digitalWrite(enA,LOW);
  digitalWrite(in1,LOW);
  digitalWrite(in2,HIGH);
  digitalWrite(enA,HIGH);
}

void lF(){ //links aus / Leergang
  digitalWrite(enA,LOW);
}

void rV(){ //rechter Motor vorwärts
  digitalWrite(enB,LOW);
  digitalWrite(in3,HIGH);
  digitalWrite(in4,LOW);
  digitalWrite(enB,HIGH);
}

void rR(){ //rechter Motor rückwärts
  digitalWrite(enB,LOW);
  digitalWrite(in3,LOW);
  digitalWrite(in4,HIGH);
  digitalWrite(enB,HIGH);
}

void rF(){ //rechts aus / Leergang
  digitalWrite(enB,LOW);
}

void lrF(){ //beide aus / Leergang
  digitalWrite(enA,LOW);
  digitalWrite(enB,LOW);
}

void setup(){

  Serial.begin(9600);

  //Pinfestlegung
  pinMode(enA,OUTPUT);
  pinMode(enB,OUTPUT);
  pinMode(in1,OUTPUT);
  pinMode(in2,OUTPUT);
  pinMode(in3,OUTPUT);
  pinMode(in4,OUTPUT);

  //We reset the received values
  received_data.ch1 = 119;
  received_data.ch2 = 58;

  //Once again, begin and radio configuration
  radio.begin();
  radio.setAutoAck(false);
  radio.setDataRate(RF24_250KBPS);
  radio.openReadingPipe(1,pipeIn);

  //We start the radio comunication
  radio.startListening();

}

/**************************************************/

unsigned long last_Time = 0;

//We create the function that will read the data each certain time
void receive_the_data()
{
  while ( radio.available() ) {
  radio.read(&received_data, sizeof(Received_data));
  last_Time = millis(); //Here we receive the data
}
}

/**************************************************/

void loop(){

  while(true){ //!!!receiving two analog values, and storing them in left and right
     lrF();
     ch1_value = map(received_data.ch1,0,255,0,1023);
     ch2_value = map(received_data.ch2,0,255,0,1023);
     linker = ch1_value;
     rechter = ch2_value;
     Serial.print("left: ");
     Serial.println(left);
     Serial.print("right: ");
     Serial.println(right);
  } //why is the Serial print showing ramdom values, even if there should not be a transmission

  //beide vorerst aus
  lrF();
  linker = 512;
  rechter = 512;

  //Receive the radio data
  receive_the_data();

  //Übernahme der Analogreferenzwerte für beide Knüppel
  //ch1_value = received_data.ch1;
  ch1_value = map(received_data.ch1,0,255,0,1023);
  ch2_value = map(received_data.ch2,0,255,0,1023);
  //Überschreibung der Werte in Variablen links/rechts
  linker = ch1_value;
  rechter = ch2_value;

  for(int i = 200; i > 0; i--){ //PWM-Signalanlegung

  if((linker <= ober && linker >= unter) && (rechter <= ober && rechter >= unter)){ //Leergang
    lrF();
    delayMicroseconds(463);
  }

  if((rechter == linker) && (linker > ober)){ //geradeaus
    vLinker = linker - ober;
    gem = vLinker;
    rest = 463 - gem;
    lV();
    rV();
    delayMicroseconds(gem);
    lrF();
    delayMicroseconds(rest);

  }

  if((linker > ober) && (rechter > ober) && (linker > rechter)){ //linksvorwärts
    vLinker = linker - ober;
    vRechter = rechter - ober;
    gem = vRechter;
    gemRest = vLinker - vRechter;
    rest = 463 - gem - gemRest;
    rV();
    lV();
    delayMicroseconds(gem);
    lV();
    rF();
    delayMicroseconds(gemRest);
    lrF();
    delayMicroseconds(rest);
  }

  if((rechter > ober) && (linker > ober) && (rechter > linker)){ //rechtsvorwärts
    vLinker = linker - ober;
    vRechter = rechter - ober;
    gem = vLinker;
    gemRest = vRechter - vLinker;
    rest = 463 - gem - gemRest;
    rV();
    lV();
    delayMicroseconds(gem);
    rV();
    lF();
    delayMicroseconds(gemRest);
    lrF();
    delayMicroseconds(rest);
  }

  if((rechter == linker) && (linker < unter)){ //rückwärts
    vLinker = linker;
    ivLinker = 463 - linker;
    gem = ivLinker;
    rest = 463 - gem;
    lR();
    rR();
    delayMicroseconds(gem);
    lrF();
    delayMicroseconds(rest);
  }

  if((linker < unter) && (rechter < unter) && (rechter > linker)){ //linksrückwärts
    vLinker = linker;
    vRechter = rechter;
    ivRechter = 463 - rechter;
    ivLinker = 463 - linker;
    gem = ivRechter;
    gemRest = ivLinker - ivRechter;
    rest = 463 - gem - gemRest;
    lR();
    rR();
    delayMicroseconds(gem);
    lR();
    rF();
    delayMicroseconds(gemRest);
    lrF();
    delayMicroseconds(rest);
  }

  if((linker < unter) && (rechter < unter) && (rechter < linker)){ //rechtsrückwärts
    vLinker = linker;
    vRechter = rechter;
    ivRechter = 463 - rechter;
    ivLinker = 463 - linker;
    gem = ivLinker;
    gemRest = ivRechter - ivLinker;
    rest = 463 - gem - gemRest;
    lR();
    rR();
    delayMicroseconds(gem);
    rR();
    lF();
    delayMicroseconds(gemRest);
    lrF();
    delayMicroseconds(rest);
  }

  if((linker < unter) && (rechter > ober) && (463 - linker >= rechter - ober)){ //linker rück rück, rechter vor
    ivLinker = 463 - linker;
    vRechter = rechter - ober;
    gem = vRechter;
    gemRest = ivLinker - vRechter;
    rest = 463 - gem - gemRest;
    lR();
    rV();
    delayMicroseconds(gem);
    lR();
    rF();
    delayMicroseconds(gemRest);
    lrF();
    delayMicroseconds(rest);
  }

  if((linker < unter) && (rechter > ober) && (463 - linker < rechter - ober)){ //linker rück, rechter vor vor
    ivLinker = 463 - linker;
    vRechter = rechter - ober;
    gem = ivLinker;
    gemRest = vRechter - ivLinker;
    rest = 463 - gem - gemRest;
    rV();
    lR();
    delayMicroseconds(gem);
    rV();
    lF();
    delayMicroseconds(gemRest);
    lrF();
    delayMicroseconds(rest);
  }

  if((linker > ober) && (rechter < unter) && (463 - rechter <= linker - ober)){ //linker vor vor, rechter rück
    ivRechter = 463 - rechter;
    vLinker = linker - ober;
    gem = ivRechter;
    gemRest = vLinker - ivRechter;
    rest = 463 - gem - gemRest;
    lV();
    rR();
    delayMicroseconds(gem);
    lV();
    rF();
    delayMicroseconds(gemRest);
    lrF();
    delayMicroseconds(rest);
  }

  if((linker > ober) && (rechter < unter) && (463 - rechter > linker - ober)){ //linker vor, rechter rück rück
    ivRechter = 463 - rechter;
    vLinker = linker - ober;
    gem = vLinker;
    gemRest = ivRechter - vLinker;
    rest = 463 - gem - gemRest;
    rR();
    lV();
    delayMicroseconds(gem);
    rR();
    lF();
    delayMicroseconds(gemRest);
    lrF();
    delayMicroseconds(rest);
  }

  if((linker > ober) && (rechter > unter) && (rechter < ober)){ //linker allein vor
    vLinker = linker - ober;
    gem = vLinker;
    rest = 463 - vLinker;
    lV();
    rF();
    delayMicroseconds(gem);
    lrF();
    delayMicroseconds(rest);
  }

  if((rechter > ober) && (linker > unter) && (linker < ober)){ //rechter alleine vor
    vRechter = rechter - ober;
    gem = vRechter;
    rest = 463 - vRechter;
    rV();
    lF();
    delayMicroseconds(gem);
    lrF();
    delayMicroseconds(rest);
  }

  if((linker < unter) && (rechter > unter) && (rechter < ober)){ //linker alleine rück
    ivLinker = 463 - linker;
    gem = ivLinker;
    rest = 463 - ivLinker;
    lR();
    rF();
    delayMicroseconds(gem);
    lrF();
    delayMicroseconds(rest);
  }

  if((rechter < unter) && (linker > unter) && (linker < ober)){ //rechter alleine rück
    ivRechter = 463 - rechter;
    gem = ivRechter;
    rest = 463 - ivRechter;
    rR();
    lF();
    delayMicroseconds(gem);
    lrF();
    delayMicroseconds(rest);
  }
  }

}

Transmit a checksum with your data. If the checksum doesn't check out then it's garbage and you throw it away, setting your "no signal" values in the process.

Add a 10K ohm resistor between each pin and the GND pin to avoid them floating.


text:
parallel communication simulation problem
Hi I am trying to send data(1 byte) from one arduino to another using parallel communication(a bus of 8 connections) and not using any library. However, the problem is the data gets corrupt all the time and what I am supposed to receive at receiver arduino is not what I send. The protocol that I made up is similar to uart protocol. There is ES pin and when it is low, transmission is started and when it is high, the transmission is ended. I think the problem could be related to wires that I use to connect two arduinos. There could be some noise induced that could flip bits in wires or the code is problematic. I am posting my code. Maybe you can help me get through this and help me to resolve my problem.
Sender code:
#define ES 8 //enable sampling
#define B0 0 //Bus 0
#define B1 1
#define B2 2
#define B3 3
#define B4 4
#define B5 5
#define B6 6
#define B7 7
const char dataToBeSent = 'C';
bool data_bit;

void setup() {
  pinMode(ES,OUTPUT);
  pinMode(B0,OUTPUT);
  pinMode(B1,OUTPUT);
  pinMode(B2,OUTPUT);
  pinMode(B3,OUTPUT);
  pinMode(B4,OUTPUT);
  pinMode(B5,OUTPUT);
  pinMode(B6,OUTPUT);
  pinMode(B7,OUTPUT);
  digitalWrite(ES,HIGH);
  delay(3000);
}
void loop() {

 digitalWrite(ES,LOW); //transmission is started
 delay(10);

 for(int i = 0 ; i<8 ; i++){
    data_bit = dataToBeSent & (0x80 >> i);
    digitalWrite(i,data_bit);
 }
  delay(10);
  digitalWrite(ES,HIGH); //end transmission
  while(true){}
}

Receiver code:
#define ES 8 //enable sampling
#define B0 0 //Bus 0
#define B1 1
#define B2 2
#define B3 3
#define B4 4
#define B5 5
#define B6 6
#define B7 7

char rx_data;
byte rx_byte= 0;
bool rx_pin;

void setup() {
  Serial.begin(9600);
  pinMode(ES,INPUT);
  pinMode(B0,INPUT);
  pinMode(B1,INPUT);
  pinMode(B2,INPUT);
  pinMode(B3,INPUT);
  pinMode(B4,INPUT);
  pinMode(B5,INPUT);
  pinMode(B6,INPUT);
  pinMode(B7,INPUT);
  delay(1000);

}

void loop() {

  byte rx_byte= 0;

  while(digitalRead(ES) == HIGH){}
  delay(15);

  for(int i = 0 ; i<8 ; i++){
    rx_pin = digitalRead(i);
    Serial.print(rx_pin);
    if(rx_pin == 1){
      rx_byte |= (0x80 >> i);
    }
  }

 rx_data = rx_byte ;

 Serial.print("Received data: ");
 Serial.println(rx_data);

 delay(15);

 while(digitalRead(ES)== HIGH){}

}

pins 0 and 1 are Serial on some Arduinos. if you would use pins of one port you could write the data at once

You problem is that you are only using one phase of your "ES" clock, when in fact you should be using two.
In the first phase, where ES is high, is where you set the IO pins to represent your transmitted byte. Only once that is done can you then progress to the second phase, where ES is low, to indicate to the receiver that "I have set up my outputs, it's now time for you to read them".
So your transmitted code would flow like:

Set ES HIGH
Set output pins to represent the byte
Set ES LOW
Delay
Set ES HIGH

If you look at any timing diagrams for any protocol there will be places where the data is being written to the bus, and places where the data is considered stable and able to be read by the receiver. It's the job of the clock signal to indicate where these points in the protocol - to synchronise the receiver.
For example, here is the Centronics (parallel port) protocol:

The data changes while nStrobe is HIGH, and only when that data is "settled" is nStrobe brought LOW to tell the receiver it can read the data. Once nStrobe is taken HIGH again the data is changed to the next byte to transmit.

thanks a lot I will give a try


text:
Arduino respond to input from HT12D data output
Is there a way to connect a data output pin from an HT12D to an Arduino or ESP8266-12e input pin, then sense when the data pin is activated so I can have the Arduino or ESP8266-12e do something like turn on an output pin?

What's a HT12D?

Sure, as long as the voltage levels are ok for the Arduino or ESP, just connect the data pins to digital input puts of the Arduino or ESP.

The ESP is 3.3v and I think the HT12D is 5v.  Could I use resisters as voltage divider.  What kink of code would I use to recognize the input?  HT12D is a unit that takes an RF signal and makes it a digital signal I think.

I am afraid I could not understand your question properly. But maybe, the answer is YES, if ...
First of all, OUTPUT pins, cannot be turned ON and turned OFF, however, you can start or stop READING that particular OUTPUT PIN based on another INPUT pin value.
If you want to connect HT12D decoder to any arduino or ESP, you must be aware to use same voltage level between IO PINS, a good approach is to use a I2C bi-directional level shifter.
if(INPUT_PIN_VALUE >= SOME_VALUE)
{
   digitalRead(PIN)
}

on the ESP I can make a pin D5 HIGH based on the reading of another input pin from the HT12D.  So if I used a l2C to make the 5v from the HT12D computable with the 3.3v ESP.  I could read the input level and then make another pin go HIGH in reaction.                                                                                digitalRead(D5);                                                                                if(D5>=SomeValue){                                                                          digitalWrite(D6,HIGH);

Disclaimer: In this answer I'm using ESP and Arduino interchangeably, as if they were the same. They are in context this question, but not in general.
First: According to the datasheet of the HT12D, the supply voltage can be between 2.4V and 12V, so you could just provide it with the 3.3V of your ESP. That way the output pins will also run on 3.3V. Then you can simply run a wire each from an output of the chip to a digital input pin of the Arduino.
Though you then should also provide your receiver chip with 3.3V. If that is not possible, you can provide the HT12D with 5V and use simple voltage dividers on each output to break the voltage down to 3.3V. That places restrictions on the transmission speed, but I don't think, that this is relevant here, as the outputs are more meant as momentary state outputs, not data transmission outputs. In that case you connect the output of the voltage dividers to one digital input pin on the Arduino each.
How to read the data:
The chip will read the data from the receiver on its Din pin. When it has found a valid transmission for the used address (which is configured through the address pins), then it will pull the VT pin to HIGH and output the new data on the pins. The datasheet says:

The HT12D, on the other hand, provides 4latch type data pins whose data remain unchanged until new data are received.

Let's imagine, that you have send the pattern HIGH, LOW, HIGH, LOW. The HT12D will see this as valid data and set it's outputs to this pattern. The VT pin is pulled high to show, that new valid data arrived. Now you can read this pattern into the Arduino via multiple digitalRead() calls, one for each output pin of the HT12D.
The surrounding code depends on your needs. For example you could just read the pins continuously again and again, every time just outputting corresponding on the data. For example like this:
void loop(){
    if(digitalRead(HT12D_pin1)) digitalWrite(LED_pin, HIGH);
}

Or even easier:
void loop(){
     digitalWrite(LED_pin, digitalRead(HT12D_pin1));
}

Or you could also read the VT pin of the HT12D and only do something, if it is HIGH. That way you only act, if there is valid data received.

For more info you really need to improve your question.