text:
TIMEOUT error when connecting ESP8266 to Arduino Uno
I am trying to set up my Arduino Uno to receive information from the internet, but I am having a very hard time finding proper guides online. I am using an Arduino Uno and ESP8266-01. I am trying to use the "WebClientRepeating" example from this library:
https://github.com/bportaluri/WiFiEsp
Here is the code I am running (updated the SSID and password):
/*
 WiFiEsp example: WebClientRepeating

 This sketch connects to a web server and makes an HTTP request
 using an Arduino ESP8266 module.
 It repeats the HTTP call each 10 seconds.

 For more details see: http://yaab-arduino.blogspot.com/p/wifiesp.html
*/

#include "WiFiEsp.h"

// Emulate Serial1 on pins 6/7 if not present
#ifndef HAVE_HWSERIAL1
#include "SoftwareSerial.h"
SoftwareSerial Serial1(6,7); // RX, TX
#endif

char ssid[] = "MY-SSID";            // your network SSID (name)
char pass[] = "MY-PASSWORD";        // your network password
int status = WL_IDLE_STATUS;     // the Wifi radio's status

char server[] = "arduino.cc";

unsigned long lastConnectionTime = 0;         // last time you connected to the server, in milliseconds
const unsigned long postingInterval = 10000L; // delay between updates, in milliseconds

// Initialize the Ethernet client object
WiFiEspClient client;

void setup()
{
  // initialize serial for debugging
  Serial.begin(115200);
  // initialize serial for ESP module
  Serial1.begin(9600);
  // initialize ESP module
  WiFi.init(&Serial1);

  // check for the presence of the shield
  if (WiFi.status() == WL_NO_SHIELD) {
    Serial.println("WiFi shield not present");
    // don't continue
    while (true);
  }

  // attempt to connect to WiFi network
  while ( status != WL_CONNECTED) {
    Serial.print("Attempting to connect to WPA SSID: ");
    Serial.println(ssid);
    // Connect to WPA/WPA2 network
    status = WiFi.begin(ssid, pass);
  }

  Serial.println("You're connected to the network");

  printWifiStatus();
}

void loop()
{
  // if there's incoming data from the net connection send it out the serial port
  // this is for debugging purposes only
  while (client.available()) {
    char c = client.read();
    Serial.write(c);
  }

  // if 10 seconds have passed since your last connection,
  // then connect again and send data
  if (millis() - lastConnectionTime > postingInterval) {
    httpRequest();
  }
}

// this method makes a HTTP connection to the server
void httpRequest()
{
  Serial.println();

  // close any connection before send a new request
  // this will free the socket on the WiFi shield
  client.stop();

  // if there's a successful connection
  if (client.connect(server, 80)) {
    Serial.println("Connecting...");

    // send the HTTP PUT request
    client.println(F("GET /asciilogo.txt HTTP/1.1"));
    client.println(F("Host: arduino.cc"));
    client.println("Connection: close");
    client.println();

    // note the time that the connection was made
    lastConnectionTime = millis();
  }
  else {
    // if you couldn't make a connection
    Serial.println("Connection failed");
  }
}

void printWifiStatus()
{
  // print the SSID of the network you're attached to
  Serial.print("SSID: ");
  Serial.println(WiFi.SSID());

  // print your WiFi shield's IP address
  IPAddress ip = WiFi.localIP();
  Serial.print("IP Address: ");
  Serial.println(ip);

  // print the received signal strength
  long rssi = WiFi.RSSI();
  Serial.print("Signal strength (RSSI):");
  Serial.print(rssi);
  Serial.println(" dBm");
}

My wiring is as follows:

ESP8266 RX - Uno Pin 7
ESP8266 TX - Uno Pin 6
ESP8266 VCC - 3.3V power source (not from Uno)
ESP8266 GND - Uno GND
ESP8266 CH_PD - 3.3V power source (not from Uno)

I also connected the GND of the 3.3V power source to the other GNDs.
When I go to run the WebClientRepeating example, my Serial output says:
11:05:04.764 -> [WiFiEsp] Initializing ESP module
11:05:05.760 -> [WiFiEsp] >>> TIMEOUT >>>
11:05:07.785 -> [WiFiEsp] >>> TIMEOUT >>>
11:05:09.758 -> [WiFiEsp] >>> TIMEOUT >>>
11:05:11.780 -> [WiFiEsp] >>> TIMEOUT >>>
11:05:13.803 -> [WiFiEsp] >>> TIMEOUT >>>
11:05:14.794 -> [WiFiEsp] Cannot initialize ESP module
11:05:20.794 -> [WiFiEsp] >>> TIMEOUT >>>
11:05:20.794 -> [WiFiEsp] No tag found
11:05:20.830 -> WiFi shield not present

The tutorial specifies that it uses a "ESP WiFi shield" but I am using a ESP8266 card only - could that be part of the problem? If that is a problem, are there any simple guides out there for how to connect the Arduino Uno to the internet to read information? I am frustrated with the lack of good documentation, and would really appreciate some help.

That's not a tutorial. That's a library. What code are you actually running? And how exactly have you wired your ESP-01?

Thank you, I updated the posting to include this information

So... you wired the ESP-01 to pins 0 and 1, not to pins 6 and 7 as specified in your sketch?

Oh sorry no that was wrong, I did wire to 6 and 7

There are a number of different AT firmware versions for the ESP-01. And they all use different baud rates. It may well be that you have one with 115200 baud, not 9600 baud. 115200 baud doesn't work well with SoftwareSerial, so you will have to change the baud rate on the ESP-01 to 9600 - however, how you do that depends on the firmware version, and some versions are known to commit suicide when you try changing the baud rate. You should confirm the baud rate by connecting the ESP-01 direct to the computer with a USB to UART adaptor.

OK, yes I think my ESP is 115200. I was able to get through this tutorial completely fine and it uses 115200: http://www.teomaragakis.com/hardware/electronics/how-to-connect-an-esp8266-to-an-arduino-uno/. This is so frustrating lol.

It means that your ESP8266 is not detected
Because of you connect RX and TX (6 and 7) to secondary pin.
Use your standart RX TX pin to solve the problem


text:
Arduino with ESP8266 via serial pass through
I bought an Arduino Mega 2650 alongside a couple of ESP8266 chips hoping to make a wireless project take off.
Using the basic serial passthrough code
void setup() {
    Serial.begin(9600);
    Serial1.begin(115200);
    Serial.write("Starting");
}

void loop() {
    if (Serial.available()) {      // If anything comes in Serial (USB),
       Serial1.write(Serial.read());   // read it and send it out Serial1 (pins 0 & 1)
    }

    if (Serial1.available()) {     // If anything comes in Serial1 (pins 0 & 1)
       Serial.write(Serial1.read());   // read it and send it out Serial (USB)
    }
}

updated to use a 115200 baud rate which it seems my version of the 8266 is programmed to use, I encounter this problem when trying to issue it commands:
Starting
AT

ERROR

Looking around I found that this could be caused by the chip not getting enough power. So I hooked it up to a small power breakout board
 with a small 12 power supply I used to have connected to something else. After doing that all it does is spit out question marks even when I dont send anything. Weird part is the TX pin on the arduino thats going crazy? As if I am sending it to myself without a prompt from the ESP board. This only happens when I'm connected to that breakout supply.

Other oddity:
If I have all my wires except for VCC/CH_PD connected everything is fine, but the second I connect them to that power supply everything goes crazy and my TX pin starts flashing up a storm (can it be a voltage issue that also transfers to my Arduino board as well?)

set Both NL & CR line ending in one of the Serial Monitor comboboxes

Many questions are open here: Are you sure the baud rate of the ESP8266 is 115200? Show us the code or firmware running on it please? Where are the voltage divider resistors to protect the ESP8266 receiving 5V from the Arduino Mega's UART TX line? What does is show when you read the ESP8266 serial to 74880, which is the baud rate of the first-stage bootloader?

You are also making the mistake of reading from serial at 115200 baud and sending it to the other at a much lower 9600 baud. When the ESP8266 will send a stream of data and you write it byte-wise to the 9600 serial, it takes too much time for writing it, and you will loose incoming data. You must set the serial you're outputting to at least as high or higher than its input.

@MaximilianGerhardt From power supply to VCC and from Arduino TX to ESP RX I have a 1/2kohm voltage divider to turn 5v -> ~3.3v. I've tried every baud rate now, and the only one that gave me anything other than question marks was 115200. I havent touched the code or firmware, I cant even establish a serial connection to start looking into that.

@Juraj Yeah the blue light isn't even active on the ESP module anymore so its like is not getting a signal

it replays with ERROR, so it is alive. do you have the line ending characters set?

@Juraj It will now print ok in response to the AT command but any other command from this list returns an error https://nurdspace.nl/ESP8266#AT_Commands

Was using the wrong commands, please write an answer and I will mark it as correct :)

But you didnt get marked as the answer for that one either, it would be good to have one marked as solved (and without -2 votes)

@Juraj - The OP did not use the @ symbol before your username, so you may not have seen their comment. They said "Was using the wrong commands, please write an answer and I will mark it as correct :)".

@VE7JRO, OP meant line endings not commands so I linked it to duplicate

source: Stack Exchange

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

sort: votes


text:
power consumption of esp32
I'm currently working on an IOT project with my esp32, ill need it to run on batteries, I will only be needing "active mode" with wifi once per hour to upload some data to a database and then go back to deep sleep (need to save data cant use hibernation).
THIS website explain pretty well how much energy the esp needs, but it says e.g. 30mA - 60mA, but on batteries it says mAh, so is the mA just mAh or how do I calculate the power usage?
.
ps.
currently, I'm thinking of using 2 cr2032 batteries, good recommendations on batteries are welcome

Please read https://learn.adafruit.com/low-power-wifi-datalogging/battery-life-and-current-consumption and https://learn.adafruit.com/all-about-batteries/overview. mAh is milli-ampere hours, i.e. a coin cell with a capacity of 210mAh can theoretically provide 210 mA for 1 hour before it's empty (or 105mA for 2 hours). You need to calculate the total spent battery capacity over 1 hour (based on the current consumption in activate / inactive mode times the time they are in that mode). Also be aware that CR2032 are 3.0V batteries whose voltage drops as its energy depletes (also current dependent)

Also be aware that due to internal resistances in batteries and other stuff, batteries have a maximum output current capability, so a coin cell might not contiously provide that much current. You might need a big capacitor from which energy is sourced then.

@MaximilianGerhardt thanks, any recommendations on batteries?

Many come to mind, Li-Po, Li-Ion (like a 18650 cell),.. You should these videos for a better understanding and tests: https://www.youtube.com/watch?v=heD1zw3bMhw https://www.youtube.com/watch?v=-769_YIeGmI https://www.youtube.com/watch?v=gG82_fG4VM8 https://www.youtube.com/watch?v=3O_vrKAmshA

@MaximilianGerhardt esp32 can only handle up to 3.5 so the lipo 18650 would fry it, and i would loose to much power to a step down

also i need something flat, maximum hight of 4 milimeters, therefor aa and aaa is not an option

Of course directly applying a 18650 would be bad, that's why there should be a DC/DC converter (preferably switch-mode) there. You might want to look into battery managment ICs and voltage regulators. @"something flat": Maybe experiment with the coin cells and a big capacitors or DC/DC converts and see if the ESP32 can still connect to WiFi despite the high inrush current at WiFi transmissions.

There's a number of things to consider when choosing batteries.
First is the capacity. In broad terms, the capacity is, mAh, means "This battery can supply X mA for one hour". So a battery of 1000mAh could supply around 1A (1000mA) for one hour before it goes flat.  Simply divide the mAh by your device's mA and you get the time it will run for before it goes flat. So a 50mA device would run for about (1000 / 50) 20 hours before running flat.  That is only a "ball park" figure though, since the capacity is somewhat dependent on the amount of current you draw.
Then there is the question of the internal resistance of the battery. This determines the maximum current that you can draw from the battery before the voltage drops below a usable level.  Different battery chemistries have different internal resistances.
Small button cells like the CR2032 have a high internal resistance and a low capacity.  A typical cheap CR2032 has around 200mAh capacity. At 50mA that would last 4 hours. But drawing 50mA from a CR2032 is not really on.  Looking at the graphs in the datasheet linked to above you can infer that, with a nominal voltage of 3V, with a 1kΩ load the output drops to 2.6V. That means that 1kΩ is drawing (2.6/1000) 0.0026A (2.6mA).  The internal resistance is dropping (3 - 2.6) 0.4V, therefore the internal resistance must be (0.4 / 0.0026) 154Ω.
Drawing 50mA from the battery would mean the internal resistance would drop (154 * 0.05) 7V. Since you can't get below 3V, that means the battery simply can't support that kind of current drain.  Indeed, in the datasheet I link to the "Standard Current Drain" (the current it's rated for as "normal" usage) is a mere 0.1mA.
So to work out what battery you need, you want:

The average current draw over the period of an hour
The peak current draw the device will draw
The length of time you need the device to run for between battery changes / recharges

For the ESP32 the current can peak at hundreds of mA depending on what you are doing (WiFi uses a lot of power in short bursts). The average will be based on the ratio of the "running" time to the "sleeping" time, and the current draw for both those states.

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


text:
Arduino IDE: sketch window has become unresponsive
I am very new to all this, but have programmed in other languages using several IDEs. Last night when returning to a coding session, I noticed that the background of the sketch window had gone from white to gray. Then when I tried to continue editing the sketch, I found that I could not make any changes. At all. Clicking anywhere on the screen is futile; the cursor never appears. Text can be highlighted but not copied or pasted. In short, I can’t go on from here at all.
What have I done?

You haven't done anything. It's Java. Notoriously bad at staying alive overnight. Kill it.

As one well-known IT guy would say, "Have you tried turning it on and off again"? :)

@duck dodgers: yes I have—multiple times. I’ve also tried using a bigger hammer and waving a dead chicken at it. I’ve not yet gotten to the point that I would kill a goat and examine its entrails, but I am getting close.

Interesting :). Then could you please possibly post a screenshot of the Arduino IDE here. I have never experienced something like this myself (barring minor glitches which one can get fixed by updating to a newer version).  Could you please state then the version number of your IDE, what operating system you are using, etc. It would be helpful.

(see my penultimate comment first please) p.s. you can also try something other than the Arduino IDE, just for the time, that you try to debug the problem with the "Arduino IDE".


text:
Soil moisture sensor not working in "pcb"
I have a little and common application in which a sc-28 moisture sensor reads humidity levels and turns a servo (which drives a little faucet) if the soil needs water. Arduino nano is the brain.
All of them is tested and working fine on the proto board. Soil sensor is powered by 5v rail of arduino and everything seems fine even with the servo pulling from 5v rail too.
With all working, I try to translate that to a perfboard. The only difference in circuits are how they are powered.
While the prototype is powered via usb, the definitive one is powered through a 24v psu, leveling the voltage with a lm2596 module down to 5v.
Then this 5v feeds the nano (vin pin) and servo, while the soil sensor still pulls from 5v rail of the arduino to avoid vref problems.
And then, the sensor does not work. No led indicating power or data. This were my steps trying to debug it:

Triple check every connection on the board. While I am a decent programmer, my solder skills are kind of lacking. But everything looks fine, nothing shorted or loose.
measure voltage. On the perfboard, voltage between vcc and gnd connector pins spits 4.78v, which is supposed to be in range for the sensor to work.
Power the board through usb I tried this too, and is not working. Lm module and arduino lights up, code can be executed. I can't explain why the lm2596 module lights up too, and I'm thinking is part of the problem but I do not know. Voltage at soil sensor is still 4.78

And then I'm done. I dont know what could be happening and I only can make wild guesses. It's obviously a board problem, and i am aware I am doing something wrong but I can't see it.
Below, my horror soldering skills and the board. Soil sensor is the 4pin females at the bottom left and servo the 3pin males at the bottom right.

Picture doesn't work. Attach the image directly in the post.

Are you sure, that you are feeding 5V to Vin? 5V is not enough there, since Vin is connected to the regulator, which needs 6 to 12 V. Have you tried to connect your regulated 5V directly to the Nanos 5V pin?

you missed an intermediate step ... power the protoboard from 24V power supply ... your question is pointless until you do that

@jsotola that is not possible. I guess I could make a point to point wiring in site, but I am unable to get 24v on the protoboard at this time.

do the opposite then ... power the prototype from USB

The answer was, in fact, my poor experience with these boards and how they work.
As you can see in the pictures, wire and connectors are on opposite sides of the board. I was assuming that pads were connected on both sides, which is not true. Therefore, connectors were simply dead.
Soldered again at the wire side and it works like a charm. Thank you all for every suggestion, and the learning experience.

Then this 5v feeds the nano (vin pin)

Can't feed 5V into Vin and get 5V out. Connect 5V to the 5V pin.


text:
Two Arduino Control a LCD Display
I´m building a system that has two arduinos (like the image on the botton) linked via ICSP. The "Programer"  programs the second one, called "Worker"( with a .hex file in the SD card of the Programer).
The Worker controls a LCD 16x4 and displays messages to the user.
What I´m tring to do is when the Programmer is programming the Worker it also displays a message like "Programming, wait" in the Worker LCD. But in code, just telling to the Worker displays a message is not going to happen because when it has been programmed it displays garbage in the LCD.
Q So is it possible the the Programmer takes control of the LCD before it begin to program the worker and displays its message?
The LCD works with normal 4-bit mode comunication and I would rather not converte it to I2C if it´s possible.

4-bit mode @jsotola

master / slave?

On the ICSP - Controler master, worker slave. On the LCD the conection is made exclusively by worker (Via Hardware). @tony gil

Have you thought of using I2C for the arduinos as well?  It works pretty well for me and, apparently, would work for you in this application as well.  If you want, I can post an answer expanding on that.  Please advise, otherwise the CONTENT POLICE will shout me down.

"The Worker controls a LCD 16x4 and displays messages to the user. What i´m tring to do is when the Programer is programing the Worker it also displays a message like "Programing, wait" in the Worker LCD, but in code, just telling to the Worker displays a messege is not gonna happen because when its been programmed displays garbage in the LCD" -> this sentence is a bit difficult to parse. Could you please break it down into smaller sentences that are more easy to understand?

@tony gil, yes i did, but for programing is way batter to use ISCP

Thanks for the help @DuckDodgers

Honestly, why put your self through designing a multiplexing solution when LCDs are inexpensive.  I suggest to Keep It Simple and simply use 2 LCDs.  The pain of trying to debug a situation where the "worker" may or may not be talking to the single LCD just sounds terrible.  If you insist on using one LCD I recommend manually switching the LCD between Arduino boards.  This, so you can be certain which Arduino is controlling the LCD.

There may be another solution.  There are some LCDs larger than the standard Hitachi paradigm allows.  Such LCDs appear, in some ways, as 2 independent displays.  But share the same interface.  So there's that.  Let me know if you need more details (that is if you want me to post an answer).  Otherwise it's a bit "off topic" and could be voted down.  So I'll abstain unless there is interest.

There are two solutions that come to my mind, one more HW based and another more SW based.
Solution 1
The HW way is to let the programmer control the LCD through 2:1 multiplexer(s). You will need to connect the LCD pins to the common pin of the multiplexer, the Programmer's ones to one of the two inputs and the Worker's to the other. Then the programmer can choose who controls the LCD through the additional pin. An example of the multiplexer you can choose is the 74LS157, but there are virtually infinite part numbers. The disadvantage of this approach is that you need to write the whole LCD control stack in the Programmer.
Solution 2
An alternative, more relying on the SW, is implementing a way to let the slave know that you want to program it. For instance, when a programming is needed the Programmer raises a pin; the Worker writes the string on the LCD, then stops working, raises another pin and waits to be cleared. The programmer then proceeds to flash the Worker, and the message will remain on the LCD. It may happen that garbage exits from the Worker's pins when being programmed. If so, change the enable pin or find a way to temporarily detach it from the Worker to avoid signals reaching the LCD. This schematic illustrates this concept:

simulate this circuit – Schematic created using CircuitLab
When the Programmer wants to program the unit, it sets the DL_Req pin to high. The Worker sees this, and performs accordingly. I think pins are not moved then, but if for instance some noise appears on the signals during programming (and the LCD displays this noise as weird chars), try changing the pin associated to the enable pins (LCD2 in the example above) or put something to prevent noise on that wire only, so that LCD content is not modified.
Personally I'd go with the second solution, but this depends on how much you can change the behavior of the worker and programmer

I rlly liked the second aproach, but will not generate conflict between the boards?, because the worker needs acess to the enable pin as well, or the enable pin is set to high all the time that the worker is sending information? what i understant is to leave the enable pin to the controler and data bus and RS pin in common to both boards, right?

@Dalequeiroz no, in the second approach the Programmer does not have access to the enable or any other pin of the LCD. I'm not sure if in the programming phase the arduino pins are moved (I think only pin 13 - connected to the onboard led - is changed during programming). I will add a sort of block diagram to the answer for the second solution to explain better

i liked that aproach, in this way i can control when to display the message that i what and when to activate the controller, i will try and give it a feedback, but i think it will work firne.

If you let the worker pull up the enable pin only with it's internal pullup resistor (not actively driven high), the programmer can pull it down without doing any harm, disabling the LCD. If the logic is inverse (LOW for enabled), you could do this with an external pulldown resistor

@chrisl this is a good solution if all the Worker's pins are moving randomly during programming. Or even using a series resistor to let the Programmer decide whether to control the EN pin or not. In any case I think it will not be necessary, since usually pins remain to a stable state when programming


text:
Control two stepper motors simulatenously?
I'm using Arduino Mega 2560, A4988 motor driver for 5 stepper motors. There are X1, X2, Y, Z, A axis, and if I control Y and Z at once, it works. But when I just change axis from Y&Z to X1&X2, only X1 stepper motor spins. X1&X2 need to move at once(simultaneously) due to they are connected in single bar.
My Arduino IDE code is,
==============================
const int X2step = 5;

const int X2dir = 4;

const int X1step = 3;

const int X1dir = 2;

void setup() {

    pinMode(X1step,OUTPUT);

    pinMode(X1dir,OUTPUT);

    pinMode(X2step,OUTPUT);

    pinMode(X2dir,OUTPUT);

}

void loop() {

    digitalWrite(X1dir,HIGH);

    digitalWrite(X2dir,HIGH);

    for(int x = 0; x < 4000; x++) {

        digitalWrite(X1step,HIGH);

        delayMicroseconds(2000);

        digitalWrite(X1step,LOW);

        delayMicroseconds(2000);

        digitalWrite(X2step,HIGH);

        delayMicroseconds(2000);

        digitalWrite(X2step,LOW);

        delayMicroseconds(2000);
    }

    delay(1000);

    digitalWrite(X1dir,LOW);

    digitalWrite(X2dir,LOW);

    for(int x = 0; x < 4000; x++) {

        digitalWrite(X1step,HIGH);

        delayMicroseconds(2000);

        digitalWrite(X1step,LOW);

        delayMicroseconds(2000);

        digitalWrite(X2step,HIGH);

        delayMicroseconds(2000);

        digitalWrite(X2step,LOW);

        delayMicroseconds(2000);
    }

    exit(0);

=================================================
Any suggestion would be helpful for me. Thanks.

Could you please, remove the empty lines, maybe. They just make the code appear longer than it has to be. (Just my opinion)

And align the code (make sure { and } blocks are indented correctly, and indent entire code (use ctrl-k after selecting all code).

Does it work, when you provide both steppers with the same signal line (connecting to the same output pin)?

@Duck Dodgers, Michel Keijzers In Arduino IDE, I correctly wrote my codes. I intentionally put the empty lines to read easily and also indented correctly in Arduino IDE.

@chrisl Do you mean like for example, in pin 2, connect X1, X2 dir and in pin 3, connect X1, X2 step? And thanks for your comments Duck Dodgers, Michel Keijzers, chrisl

@YangKeeWon, I can imagine that you did it correctly in the Arduino IDE. But the Arduino IDE, only you can see. We cannot. We see the code only in this post. And if the code isn't indented/formatted, then it becomes difficult to parse, especially for someone not familiar with the code. In any case, there is at least one closing bracket missing } for the loop() function in your code (which would've been nearly impossible to detect without the code being indented&so on). Sorry to be pedantic about this. Just saying that people can only help you, if you help them see your problem clearly.:)

@YangKeeWon Yes, just connect the pins of both motors to the same set of pins. If that still not works, there is something wrong with your wiring or mechanics

To all, Thanks for your help. And it was simple problem. First, I didn't set opposite direction but it wasn't the real problem because X2 motor still didn't move. I think the breadboard was problem so I changed and it worked. Best regards, YK.

You likely have other issues to boot based on what you said about only X1 moving, but first I suggest resolving the bug in your code.  It appears to be that you have delays between your digital writes to x1, x2. And set their directions to the same.
At the very least you should be writing to X2 step every time you write to X1 step.  If your wiring is identical and the motors are essentially attached mirrored on opposite sides of a shaft, don't forget to set the directions opposite before you start sending steps. (If they are on opposite sides of the shaft, one spinning counterclockwise means the other spins clockwise.  You can also play wiring tricks with what coil goes where and how, but identical is simpler.)
digitalWrite(X1dir,HIGH);
digitalWrite(X2dir,LOW);

Or
digitalWrite(X1dir,LOW);
digitalWrite(X2dir,HIGH);

Then step it like
digitalWrite(X1step,HIGH);
digitalWrite(X2step,HIGH);

delayMicroseconds(2000);

digitalWrite(X1step,LOW);
digitalWrite(X2step,LOW);

delayMicroseconds(2000);
...

Thank you. I didn't realized the motors had to spin opposite direction. The problem was just simple wiring, but after that your comment helped me a lot. Thanks for your kind answer. Best regards, YK.


text:
What Arduino boards would be compatible?
I am considering using an arduino over the raspberry pi for a new project. However, I am not sure what arduino I should buy so that it is compatible with the below add-on.

Are all Arduinos compatible?
TIA.
Edit:
Link to product- https://www.adafruit.com/product/3387
My goal is to use an arduino with the above product to move a 3D model in Unity 3D.

Potentially all are compatible, but it is hard to tell as you did not include any of the technical details. Can you update your question with the technical details and or a link to the product? Compatible is a big word, there are many aspects to it including voltage, signaling and software support on your Arduino of choice.

Of course, my bad. Editing now!

As one can see from the pinout description page (https://learn.adafruit.com/adafruit-lsm9ds1-accelerometer-plus-gyro-plus-magnetometer-9-dof-breakout/pinouts):

So this board is literally designed to be powered by 3.3V and 5V and have compatible logic levels for both these voltage ranges, which is what every Arduino known to me and the Raspberry Pi use.
Furthermore, there is also Arduino Code (https://github.com/adafruit/Adafruit_LSM9DS1)  which is compatible with pretty much every Arduino Core and Raspberry Pi Python code (https://learn.adafruit.com/adafruit-lsm9ds1-accelerometer-plus-gyro-plus-magnetometer-9-dof-breakout/python-circuitpython).
So by means of voltage levels and platforms, this board is highly compatible with everything out there that is either 3.3V or 5V powered and has a SPI or I2C peripheral.

Right. Which is to say pretty much every Arduino out there. If it has hardware I2C lines, it will work with that board, whether the Arduino is 3.3V or 5V. Note that most commonly used Arduinos and their accessories are 5V, so I'd recommend going with a 5V module for compatibility with other "shields" and accessories.


text:
Buffer overflow error in ESP8266_SoftwareSerial library
I am running into buffer issues when running the Firmware.ino example here.
The output from my Arduino serial log on baudrate 115200 (I put the ESP on baudrate 9600):
Begin
01:17:15.538 -> Baudrate set success
01:17:15.585 -> Station + softAP - OK
01:17:18.631 -> Joining AP successful, IP: 192.168 r⸮+@⸮
01:17:18.991 -> Single Mode OK
01:17:18.991 -> Sending Request to www.google.com
01:17:19.084 -> create tcp - OK
01:17:19.710 -> not sentbuffer is full!
01:17:20.022 -> HZiw93GUFmVJYFz-yRmahGURP_UBbRb4EF0Ahwzx8MJ1GOyC5Z0dns8UD41G8kUqnL0oxNPxa6xF9nAqNF3X3B_hKW11zoyaBPn8trvUNt-69qbFCNOZwNjgoaloKbOQs7NN-B3tpmwFKpHfKsfKyZfiMdhulN3SgZMhewYBg9c; expires=Wed, 05-Feb-2020 05:17:18 GMT; path=/; domain=.google.com; HttpOnly
01:17:20.162 -> Accept-Ranges: none
01:17:20.162 -> Vary: Accept-Encoding
01:17:20.209 -> ConnecS,
01:17:24.179 -> Sending Request to www.google.com
01:17:24.774 -> create tcp - ERROR
01:17:28.759 -> Sending Request to www.google.com
01:17:29.432 -> create tcp - ERROR
01:17:33.402 -> Sending Request to www.google.com
01:17:34.021 -> create tcp - ERROR
01:17:38.028 -> Sending Request to www.google.com
01:17:38.669 -> create tcp - ERROR
01:17:42.681 -> Sending Request to www.google.com
01:17:43.294 -> create tcp - ERROR
01:17:47.298 -> Sending Request to www.google.com
01:17:47.954 -> create tcp - ERROR
01:17:51.925 -> Sending Request to www.google.com
01:17:52.595 -> create tcp - ERROR
01:17:56.563 -> Sending Request to www.google.com
01:17:57.204 -> create tcp - ERROR
01:18:01.222 -> Sending Request to www.google.com
01:18:01.871 -> create tcp - ERROR
01:18:05.839 -> Sending Request to www.google.com
01:18:06.460 -> create tcp - ERROR
01:18:10.456 -> Sending Request to www.google.com
01:18:10.596 -> create tcp - OK
01:18:11.049 -> buffer is full!
01:18:11.049 ->
01:18:11.049 ->
01:18:11.049 -> +IPD,1430:HTTP/1.1 200 OK
01:18:11.096 -> Date: Tue, 06 Aug 2019 05:18:09 GMT
01:18:11.096 -> Expires: -1
01:18:11.096 -> Cache-Control: private, max-age=0
01:18:11.143 -> Content-Type: text/ht
l; charset=ISO-8859-1
01:18:11.143 -> P3P: CP="This is not a P3P policy! See g.co/p3phelp for more info."
01:18:11.190 -> Server: gws
01:18:11.190 -> X-XSS-Protection: 0
01:18:11.190 -> X-Frame-Options: SAMEORIGIN
01:18:11.224 -> Set-CooS,
01:18:15.192 -> Sending Request to www.google.com
01:18:15.822 -> create tcp - ERROR
01:18:19.849 -> Sending Request to www.google.com
01:18:20.473 -> create tcp - ERROR

As you can see, at first it starts ok, gives a buffer error, runs in error for a while, then runs OK again. This happens a couple times, then it runs only in error. I imagine this is some issue with the buffer of the ESP or the Arduino, but I'm not sure how to diagnose it further.
Things I have tried to fix the error:
 - As mentioned in the Firmware.ino example comments, I uncommented #define ESP8266_USE_SOFTWARE_SERIAL
 - Also as mentioned in the comment, I changed line 42 from 64 to 256. It didn't work either time.
 - There is a MAX_BUFFER_SIZE in the included ESP8266.h library that I also changed, from 300 to 256, because I thought that might help, but the error persisted.

You are sending/receiving too much data and you're out of memory is what the error is saying.

There's some heavy String usage in that library, would not recommend it for anything you want to be stable, especially with an Uno.
The library seems to create a connection by first clearing the SoftwareSerial buffer and then issuing the right AT command. It waits for 500ms for a response before giving up. I suspect the wait interval is sometimes not long enough for the module to receive, parse and handle the command before responding. So you should try increasing it to 2000 ms at line 773.
The buffer is full message just refers to the library's own buffer for holding received data, which is 300 bytes by default. The buffer's getting filled so quickly (and the SoftwareSerial internal buffer likely overrun too) because you're loading a webpage like Google's which has more than 300 bytes in the response header alone. It's even possible that by the time the next request commences with another AT command, the ESP8266 is still dumping the response from the previous request, and so the command's response is still way down the queue and so doesn't get read before the timeout.
Instead, try loading a simple webpage like httpbin.org/ip. That is, at lines 952, 954:
char* request =  "GET /ip HTTP/1.1\r\nHost: www.httpbin.org\r\nConnection: close\r\n\r\n";

if (createTCP("www.httpbin.org", 80))

Thank you! Can you recommend any better libraries for making simple http requests (maybe simpler than google.com) on the Arduino Uno using ESP8266?

@garson This looks popular with a decent interface: https://github.com/bportaluri/WiFiEsp. If this solved your problem, don't forget to upvote and accept the answer.

It's a step in the right direction, though I still have timeout errors with that library :(

Oh my god, it works! Thank you!


text:
ESP8266 spend 10mA, even though It is in the deep sleep mode
I am using Nodemcu ESP8266. I want to know how much my ESP board consume the battery during sleep mode.
as the Mannual said it spend about micro-ampere, but my multi meter said it spend 10 mili-ampere, I cannot believe the result.
so please see My arrangement is right and give some advice
arrangement image

red line is for vin, black line is for GND.
black pin is COM, red pin is mA.
I set multimeter on 20mA, 200mA, it said it is 10mA.
when I change multimeter to 10mA, 1mA, microAmpere, number was overflowed.
I already connected to RST - D0, so It is properly sleep & wake up automatically. and here is my running code in the board
#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266WebServer.h>
#include <EEPROM.h>

void setup() {

}

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

ESP.deepSleep(60e6);

}

You seem to be measuring the consumption of the whole board, not just the ESP8266.

O really? then I should optimize board also? but is it possible?

Usually, those breakout boards use CH340 Serial-USB converter. If USB is not connected, it automatically goes in deepsleep mode, It shouldn't consume more that 50uA. It can't be the problem, however, if you are skilled enough, you can desolder it to test its the power consumption.

There are other ESP8266 dev boards that consume less power while in deep sleep. Looks like you have a NodeMCU. Try a few other dev boards (e.g. I found that the LOLIN D1 mini consumes about 100 uA or 0.1 mA while in deep sleep). I also found that over time, components on the dev boards can become damaged (e.g. the voltage regulator) due to abuse, so that's also something to watch for.

ESP.deepSleep(60e6, WAKE_RF_DEFAULT); Try this code, it should decrease it a bit.

The Board you are using contains an ESP-12F Module, along with other chips that make it easy/possible to connect to UART over USB and thus flash the chip. This USB-to-UART converter chip isn't related to the ESP-12F Module, so is unaffected when the ESP goes to sleep, so the converter continues to draw about 10mA. You can't do anything about this unless you desolder it, or use a pure ESP-12F Module.


text:
Stepper motor based clock movement with DS3231
I am working on a clock movement that is powered using a stepper motor and the GSM2 driver board. The delay between steps needed to achieve 1 rpm on the second hand works out to 25 ms. In my current setup, I am sending pulses to the driver board using the delay() function. This works reasonably well, although it is not accurate enough for me. To remedy this problem, I ordered a DS3231 RTC module, thinking I could use that to replace delay()/millis(). However, I can't figure out how to achieve millisecond resolution using the RTC. It seems like it should be strait forward given the oscillator on board the RTC is 32kHz. I am new to arduino programming and am out of my comfort zone with this one.
Does anyone know of a way to achieve the 25 ms pulses we need while still retaining the accuracy of the RTC? Is it possible to use the RTC to correct the output produced by the built in delay()/millis() function? How would you then translate that output to pulses sent to the stepper motor driver board?
Internet research produces some mixed results on whether or not this is possible. I have yet to see an example of a clock with millisecond resolution. The theory behind it makes sense, but I don't know where to start.

It is unclear, why you need the high accuracy, and you didn't include your code. So my explanations will be as broad as your question.
"millisecond resolution" is a broad term. Generally you have to consider 2 different errors.

The jitter for every millis() value
clock drifting over time

You can eliminate the second point quite easily using the RTC with the Time library. It uses the RTC as a reference, so that you don't have the clock drifting this much. Though, you would have to use the libraries functions for all time related things, since it does not change the value of millis() or it's siblings.
Also, for low differences in the range of a few milliseconds, you should better use micros() instead of millis() (if you are not using the RTCs functions).

How would you then translate that output to pulses sent to the stepper motor driver board?

It is unclear, why exactly you need "millisecond resolution", and you didn't show us your code. But there are multiple Stepper libraries on the web, for example the standard Stepper library or the AccelStepper library (Accelstepper is more capable, don't know, if you need it). With the AccelStepper libraries you can set a certain speed and target position and then you simply call then run() method (haven't looked up the name, but there is definitely a function like that) until the desired position is reached. The method itself will only pulse the stepper, if it is time to do so. So you are freed from doing all the stuff with millis(), since the library is doing that for you.
Though the libraries are using the Arduinos internal time: millis() and siblings. To change that, you would have to change the library.

Consider a Phase Locked Loop (PLL) to synchronize your 40x 25ms pulses with your 1pps RTC.
If you need 25ms/pulse to get 1rpm, that's 2400ppm or 1pulse/0.025ms=40pps.  If you get a 1pps pulse out of the RTC, you can use it to discipline your timing.  https://www.romanblack.com/one_sec.htm is a good reference.
The basic trick is to keep track of the mismatch and run faster when it is slow, and run slower when it is too fast.
Try something like the below, but replace the LED pulse stuff with your stepper code.
// pps_pll.ino for https://arduino.stackexchange.com/questions/67699/stepper-motor-based-clock-movement-with-ds3231
//
// Adapting code from https://www.arduino.cc/reference/en/language/functions/external-interrupts/attachinterrupt/
// to do a PPS PLL per https://www.romanblack.com/one_sec.htm

const int pps = 40;
const int pulse_us = 1;
const int pulse_interval = (1000L / pps);
int count = 0; //
int count_at_sync = 0; //
unsigned long next_pulse = 0; //
unsigned long pulse_off = 0;

const byte led_pin = LED_BUILTIN;
const byte interrupt_pin = 2; // Choose pin per https://www.arduino.cc/reference/en/language/functions/external-interrupts/attachinterrupt/
volatile byte state = LOW;

void setup() {
  pinMode(led_pin, OUTPUT);
  pinMode(interrupt_pin, INPUT_PULLUP);
  attachInterrupt(digitalPinToInterrupt(interrupt_pin), sync_ISR, RISING);
}

void loop() {
  unsigned long loop_micros = micros();  // capture start of loop time
  if (loop_micros >= next_pulse) {
    // Schedule pulse
    digitalWrite(led_pin, HIGH);
    next_pulse += pulse_interval ;
    pulse_off = loop_micros + pulse_us; // schedule off time
    // PLL accounting
    count++;
    if (count_at_sync > 0) next_pulse++; // too fast: slow down
    else if (count_at_sync < 0) next_pulse--; // too slow: speed up
  }
  if (state == HIGH && loop_micros >= pulse_off) {
    state = LOW;
  }
  digitalWrite(led_pin, state);
}

void sync_ISR() { // called by 1pps interrupt
  count_at_sync = (count -= pps); // PLL accounting and record synchronization state
}


text:
Using Arduino to Record analog signals with SPI ADC + Sampling Rate Issue
I am using Arduino UNO to Read 8-channel, 24-bits resolution Analog signals using ADS1299 Analog-fornt-end. ADS1299 use SPI interface to talk with Arduino. Currently, I can record the analog signal with arduino based on the SPI protocol and send the data via serial port to the PC.
The ADS1299 has 8 channels with 24-bits resolutions. The sampling rate can be defined from 250s/s to 16Ks/s. As you can see in the below code, when the data is ready I put the device in reading data mode and store 8-bits (1-byte) in each run and concatenate 3 bytes to make a full sample. I repeat these procedures to obtain the whole samples of all channels. At the end I have sent a sample of one channel to the serial port using serial.print command.
Here is my problem: If I want to increase the sampling rate of device to e.g 10 Ks/s the arduino fails to provide this sampling rate due to  delay produced by Serial.println command. Is is possible to store the data into a big array and then send the whole array via serial port?  Is it possible that other types of microcontroller such as ARM types handle this issue? Generally how it is possible to avoid the delay of serial print?
    #include <SPI.h>
    #define WAKEUP 0x02
    #define STANDBY 0x04
    #define RESET 0x06
    #define START 0x08
    #define STOP 0x0a
    #define RDATAC 0x10
    #define SDATAC 0x11
    #define RDATA 0x12
    #define TESTaa 0xaa
    #define TEST55 0x55

    #define CONFIG1 0x01
    #define CONFIG2 0x02
    #define CONFIG3 0x03
    #define CH1SET 0x05
    #define CH2SET 0x06
    #define CH3SET 0x07
    #define CH4SET 0x08
    #define CH5SET 0x09
    #define CH6SET 0x0A
    #define CH7SET 0x0B
    #define CH8SET 0x0C

      const int PIN_START = 7;
      const int IPIN_DRDY = 9;
      const int PIN_CS = 10;

      const int DOUT = 12;
      const int DIN = 11;
      const int PIN_SCLK = 13;
      const int PIN_RESET = 8;

      byte chSet;
      byte chSet2;
      boolean flag = false;
      long t0, t;

    void setup(){

      // You can use serial communication for debugging
      Serial.begin(2000000);
      Serial.flush();
      delayMicroseconds(100);
      // You have to set SPI communication according to datasheet
      SPI.setDataMode(SPI_MODE1);
      //SPI.setClockDivider(SPI_CLOCK_DIV16);
      SPI.setBitOrder(MSBFIRST);
      SPI.begin();

      pinMode(DOUT, OUTPUT);
      pinMode(PIN_SCLK, OUTPUT);
      pinMode(PIN_CS, OUTPUT);
      pinMode(PIN_START, OUTPUT);
      pinMode(IPIN_DRDY, INPUT);
      pinMode(PIN_RESET, OUTPUT);

      //reset communication, see datasheet
        digitalWrite(PIN_SCLK, LOW);
        digitalWrite(DIN, LOW);
        digitalWrite(PIN_CS, HIGH);

      digitalWrite(PIN_CS, LOW); //Low to communicated
      SPI.transfer(RESET);
      digitalWrite(PIN_CS, HIGH); //Low to communicated

      // Wait longer for TI chip to start
      delay(500);
      send_command(SDATAC);
      delay(10);
      chSet = read_byte(0x00);
      Serial.println("-- ID CHIP is:" + hex_to_char(chSet) );

      // Write Config 1 and 2: see datasheet page 47
      // Config 1: Bits 7 6 5 4 3 2 1 0 --- 1 DAISY_EN=1 CLK_EN=0 1 0 DR[2:0] (110-- 250 Sample/S)  --->   0b11010110
      // Config 2: Bits 7 6 5 4 3 2 1 0 ----  1 1 0 INT_CAL=1(Int/Ext test sig) 0 CAL_AMP=(calibration signal amplitude)
      // CAL_FREQ[1:0] (calibration signal frequency)  ----->  0b11010100

      // for normal operation write to config1 0x02, config2 0xA0. For test signal write 0xA3 to config2
      write_byte(CONFIG1, 0x96);   // Daisy chain Enabled: D6 , Daisy chain Disabled: 96
      delay(10);

      write_byte(CONFIG2, 0xD1);   // Test signal Enabled: D0   Test signal  Disabpled: C0
      delay(10);

      write_byte(CONFIG3, 0xE0);   // INT Reference Enabled: E0    else  INT Reference Disabled: 60

      delay(1000);
      //this part is just to check if you send and read correct data
      Serial.println("Check Configs");
      chSet = read_byte(CONFIG1);
      Serial.println("CONFIG1: Received " + hex_to_char(chSet) );
      chSet = read_byte(CONFIG2);
      Serial.println("CONFIG2: Received "  + hex_to_char(chSet) );
      chSet = read_byte(CONFIG3);
      Serial.println("CONFIG3: Received "  + hex_to_char(chSet) );

      //remember that ch1 is used for respiration! use channel 2 for ECG measurements

       // Ch1 Setting: Bits 7 6 5 4 3 2 1 0 ---  PDn(channel power mode) GAINn[2:0] (PGA gain-- 101:  12 110 : 24)
       //SRB2 (SRB2 connection) MUXn[2:0] (channel input selection: 000 : Normal electrode input , 101 : Test signal )

       /// Input Channel Shorted  ---> 0b00000001 0X01;   Test signal Activated ---> 0b00000101 0X05;
      delay(1000);

      write_byte(CH1SET, 0x05); //
      write_byte(CH2SET, 0x05); //
      write_byte(CH3SET, 0x05); //
      write_byte(CH4SET, 0x05); //
      write_byte(CH5SET, 0x05); //
      write_byte(CH6SET, 0x05); //
      write_byte(CH7SET, 0x05); //
      write_byte(CH8SET, 0x05); //

      Serial.println("Check Channel Settings");
      chSet = read_byte(CH1SET);
      Serial.println("Ch1: Received " + hex_to_char(chSet) );
      chSet = read_byte(CH2SET);
      Serial.println("Ch2: Received  " +   hex_to_char(chSet) );
      chSet = read_byte(CH7SET);
      Serial.println("Ch7: Received  " +   hex_to_char(chSet) );
      chSet = read_byte(CH8SET);
      Serial.println("Ch8: Received  " +   hex_to_char(chSet) );

      // Start communication, you can use RDATAC or RDATA according to datasheet
      send_command(RDATAC);
      digitalWrite(PIN_START, LOW);
      delay(150);
      send_command(START);
    //  digitalWrite(PIN_CS, LOW); //Low to communicated
    //  SPI.transfer(START);
    //  digitalWrite(PIN_CS, HIGH); //Low to communicated

    }

    boolean gActiveChan [2];
    int nChannels = 1;
    int gMaxChan=1;

    void loop(){

    // Based on the Page. 36 For the 8-channel ADS1299, the number of data outputs is
    //[(24 status bits + 24 bits × 8 channels) = 216 bits].

      delayMicroseconds(10);

         if(digitalRead(IPIN_DRDY) == LOW){
          t0 = micros();

            digitalWrite(PIN_CS, LOW);

            long output[9];
            long dataPacket;
            for(int i = 0; i<9; i++){
                for(int j = 0; j<3; j++){
                    byte dataByte = SPI.transfer(0x00);
                    dataPacket = (dataPacket<<8) | dataByte;
                }

                output[i] = dataPacket;
                dataPacket = 0;
            }

            digitalWrite(PIN_CS, HIGH);
            Serial.println(output[1]);

    // t = micros()-t0;  // calculate elapsed time
   // Serial.print(1000000/float(t));
    //Serial.println(" samples per second");
    //delay(200);

     }

            }

        String hex_to_char(int hex_in) {
      int precision = 2;
      char tmp[16];
      char format[128];
      sprintf(format, "0x%%.%dX", precision);
      sprintf(tmp, format, hex_in);
      //Serial.print(tmp);
      return(String(tmp));
    }

    // see datasheet 38
    int read_byte(int reg_addr){
      int out = 0;
      digitalWrite(PIN_CS, LOW);
      SPI.transfer(0x20 | reg_addr);
      delayMicroseconds(5);
      SPI.transfer(0x00);
      delayMicroseconds(5);
      out = SPI.transfer(0x00);
      delayMicroseconds(1);
      digitalWrite(PIN_CS, HIGH);

      return(out);
    }

    void send_command(uint8_t cmd) {
      digitalWrite(PIN_CS, LOW);
      delayMicroseconds(5);
      SPI.transfer(cmd);
      delayMicroseconds(10);
      digitalWrite(PIN_CS, HIGH);
    }

    //see page 38
    void write_byte(int reg_addr, int val_hex) {
      digitalWrite(PIN_CS, LOW);
      delayMicroseconds(5);
      SPI.transfer(0x40 | reg_addr);
      delayMicroseconds(5);
      SPI.transfer(0x00);
      delayMicroseconds(5);
      SPI.transfer(val_hex);
      delayMicroseconds(10);
      digitalWrite(PIN_CS, HIGH);

    }

Yes (though limited by the small SRAM), yes (the ones faster than the Uno) and have you tried using higher baudrates? What baudrate are you actually using? And maybe dont print, but write them to Serial

Please provide the full code. And why are you printing only the second element of output?

@chris: could you help me how can I store the output[1] in the loop and serial print the big array after a specified time. in this code I am just printing one channel, but I can print the whole channel separated by a comma and then retrieve them in the host PC.

@chris  I tried to send the whole code but the text does not seem great. Is it possible to upload the code separately?

@chrisl I figure out and add the whole code. I checked with different baudrate but I could not see any obvious effect on the sampling rate

Try changing the order of these:
  SPI.setDataMode(SPI_MODE1);
  //SPI.setClockDivider(SPI_CLOCK_DIV16);
  SPI.setBitOrder(MSBFIRST);
  SPI.begin();

I think SPI.begin() needs to be started before the other two calls.
Instead of digitalWrite to control the chip select, use Direct Port Manipulation, much faster.
Does the ADC support 8 MHz SPI clock? From 7.6 & 7.7 of the datasheet, I would say yes.
You can get rid of all the delayMicroseconds(5), (1), (10), as well, they are not doing anything for you.
"Unpack" this and just do 3 SPI.transfers in a row to read the data, doing it in a loop slows it down:
        for(int i = 0; i<9; i++){
            for(int j = 0; j<3; j++){
                byte dataByte = SPI.transfer(0x00);
                dataPacket = (dataPacket<<8) | dataByte;
            }

I would go so far as to do all 27 in a row even, then do the array manipulation/data combining when all 27 bytes are captured.

Thank you, How can I put the the whole 27 bytes in an array?

dataByte[0] = SPI.transfer(0x00);  dataByte[1] = SPI.transfer(0x00);  dataByte[2] = SPI.transfer(0x00);   ... dataByte[25] = SPI.transfer(0x00);  dataByte[26] = SPI.transfer(0x00);

Thank you for your assistance. I managed to store bunch of bytes (e.g 270 bytes) at the reading part and send the big size array in the next part. But, the problem is that during sending the big array, I lose new incoming data. Is there any way to define an interrupt and do multi-task (Sending and receiving)?

The delayMicroseconds is to allow the ADC chip time to load its registers. 5uS may be a bit long, but some delay will be necessary.  You should consult the datasheet for the ADC.

@Abed.  The Serial data is already interrupt driven.  When you call Serial.print all you are doing is loading a buffer.  It only becomes blocking if the buffer is already full.  If that is what is happening then the problem is that you have more data than you have time to send.  Adding more interrupts won't solve that problem.


text:
ESP8266 and Arduino, using i2s and the built in adc?
I've done some extensive googling but haven't found any kind of proper documentation. Is it possible to use i2s with the built-in ADC on an esp8266 to sample audio?
And if so: any sample code on how to do so?

What do you mean by using i2s with the ADC? Do you mean you want to turn the ESP8266 into an I2S audio ADC to sample audio and send it out to some other I2S device? Why waste an ESP8266 on this (especially as the ADC is utter rubbish)?

I want to use the built in adc and use i2s to get a constant sampling rate, as I'm going to just need it for beat detection. (if you have any other suggestion how to get a constant sampling rate, i'm really up for it. determining how many microseconds have passed (which was suggested to me before) is not really one of them :/

Just use a timer. I'm not that up on the internals of the ESP8266's peripherals, but most MCUs allow you to use a timer as the sample trigger to the ADC, then a "conversion complete" interrupt to get the data.

As far as I can tell, the ESP8266 Timer only uses Microseconds, that's not fast enough :/

No, the ESP8266 timers use the clock frequency. 80MHz by default, which is a resolution of 12ns

every code I have so far seen uses void os_timer_arm(ETSTimer  *ptimer,  uint32_t  milliseconds, bool repeat_flag); which means it uses an integer amount of milliseconds making the maximum timer speed = 1ms...

os_timer_arm is for a software timer. You want the hardware timer. But it's all a bit of a moot point because the ESP8266's ADC is utter crap.

how would i then use the hardware timer in software? and what makes the ADC crap? i only want to do some beat detection kind of frequency analysis so i don't entirely care if the stuff is 100% accurate.

The results from the ADC are pretty meaningless if you have WiFi turned on. The noise is horrendous. You can use system_adc_read_fast to read a block of samples quite quickly. The SDK doesn't seem to allow you any real control over the hardware though. TBH the ESP8266 would be the absolute last choice for anything like this. Fine for WiFI, pretty naff at everything else.

SDK manual: https://www.espressif.com/sites/default/files/documentation/2c-esp8266_non_os_sdk_api_reference_en.pdf


text:
Powering two stepper motors with A4988 drivers
New to this site and wanted advice and sanity checking on my project design. I know there are similar questions to this but I couldn’t find one that was closely similar to mine.
I’m creating a device the uses two NEMA 17 stepper motors (https://www.omc-stepperonline.com/nema-17-stepper-motor-bipolar-l48mm-w-gear-raio-1001-planetary-gearbox-17hs19-1684s-pg100.html) with chunky 100:1 gearboxes in addition to using 1/16 microstepping. The end result of this is to achieve a stepper motor that turns very slowly (minutes per revolution).
Each motor is rated at 2.8V and 1.68A per phase (3.36A total since two phase) and I’m using an A4988 driver for each of them (https://www.amazon.co.uk/gp/product/B07FKXXJ41/ref=ppx_yo_dt_b_asin_title_o00_s00?ie=UTF8&psc=1) (note that these are Chinese versions where RCS = 0.1Ω). Since the A4988 drivers are limited to 1A without additional cooling, I’ve used the onboard potentiometer to reduce Vref to just below 0.9V to prevent overheating (using the equation Vref = 8 x Imax x RCS from Pololu).
This should mean that consequentially the torque output from each motor is reduced by a factor of 1/(3.36) = 0.3 (as torque α current) since each motor is only being supplied with 1A (which is not an issue due to the large gearing ratio giving a suitable output torque). I think 1/16th microstepping might also reduce the torque slightly, but I couldn’t find any conclusive sources that didn’t contradict each other on this.
This gives a power requirement of 2.8 x 1 = 2.8W per motor, hence 5.6W in total. So, I plan to use a power source that provides at least 3A (surplus on the 2A required by the drivers) and rated at a voltage of 12V-24V to run the stepper motors. I’m also aware that I need to make sure I power the drivers in parallel from this source, and not in series to reduce strain / overheating.
I’ve included two power sources I was thinking of using:
1: 24V, 4A, 96W Desktop Switching Power Supply (https://www.amazon.co.uk/DTK-Charger-90-240V-Switching-Transformers/dp/B07K85GJ54/ref=sr_1_1_sspa?crid=362Z7XFFLAYLL&keywords=24v+3a+dc+power+supply&qid=1565084176&s=electronics&sprefix=24V+3A+dC%2Celectronics%2C124&sr=1-1-spons&psc=1&spLa=ZW5jcnlwdGVkUXVhbGlmaWVyPUFHM1hUTjRTOUhYVDcmZW5jcnlwdGVkSWQ9QTA5NzA5MzQzM09IT05IR1JITEpQJmVuY3J5cHRlZEFkSWQ9QTA0NjgyMTUyQjY0UEYzRFI5OVBFJndpZGdldE5hbWU9c3BfYXRmJmFjdGlvbj1jbGlja1JlZGlyZWN0JmRvTm90TG9nQ2xpY2s9dHJ1ZQ==)
2: 24V, 15A, 360W PSU Transformer Adaptor (https://www.amazon.co.uk/NEWSTYLE-Universal-Regulated-Switching-Transformer/dp/B0758BNMLH/ref=sr_1_3?keywords=PSU+24V&qid=1565084433&s=electronics&sr=1-3)
Overall question is: would either of these power supplies be suitable, I think the second might be a bit overkill but i'm not sure.
Here’s the circuit diagram for reference:

Apologies for the long post, just needed to get all the information out of my head. I’m curious to see if I’ve made any errors in my calculations / assumptions, so any help is greatly appreciated.

Both power supplies are suitable.
The actual 12V/24V current required is not comparable to what the driver current is set at, since the stepper motor coils do not have those 12V/24V across them.
My first 3D printer came with a 12V 5A power supply, which proved suitable for simultaneous use of four stepper drivers, the control board, a display, and the heater cartridge (40W).

The 5A PSU might be a little under powered, since there might be a significant torque on the motors due to the gearboxes being so lowly geared, causing the windings to need more amps to move the shaft. However, since there's not likely to be any major/sudden speed changes with this setup, it should be minimal. Over driving a PSU can lead to premature failure, so getting a higher rated one is recommended. The price difference in negligible either way. I'd suggest testing to see what amps are actually pulled before buying anything.


text:
Using Arduino as contact to the world for linux box if app crashes
I am new to this micro controller thingie world so bare with me :)
Let me describe a scenario first.
Say I have a linux box for house automation embedded in a wall.
For security reasons is the only active access to the box the display mounted to the wall.
Another access would be via network and ssh but ssh is disabled.
Unfortunately does the web app sometimes crash and nothing goes. In the wake of that do I have to disassemble quite some stuff to get to the box and to revive it.
My Idea:
I can use a nfc or rfid sensor and hook it up to Arduino.
Would it be possible to make Arduino log on to the linux box and fire up and shutdown ssh?
I don't want to use Arduino Yun.
Is it achievable with an Arduino nano/Mega?
If not, which system would be your first choice to accomplish this task?
Thanks for your patience :)

What hardware is the Linux box? Something similar to a Raspberry Pi? Does it have a serial console? RS-232 or logic level? What logic voltage?

It has no rs232 but usb so attaching a rs232 to usb converter would be possible

Oh, a full scale micro PC in use.

Why should RFID be more secure, than SSH? If you use key-based authentication and only allow access from the local network or even only from specific devices, that should be plenty security. Or - if it is only the app, thats crashing - maybe you can write a small program, that checks if the app is still alive. I don't see the need for extra hardware, as long as not the whole linux crashes, in which case that might be the real security issue.

There's no reason why you couldn't start agetty on the /dev/ttyUSB0 or /dev/ttyACM0 of an Arduino board's USB interface - then get the Arduino to send the text required to log in and use sudo or su to run the commands to start or stop ssh. Seems very convoluted though. Simpler just to, as @chrisl says, to just run SSH but secure it to the local network.

I know that my approach is somewhat ..quirky.
But that is the way it has to go.
So Arduino can run linux commands? ...oh. let me guess. There is a library for this?

Yes, it's called HardwareSerial, you use it like this: Serial.println("sudo reboot").

Thanks for your help folks. :) You pushed me into the right direction.
It is now "just" a matter of reading documentation and make a decision in which direction to proceed.

If the web app crashes it should ideally restart. systemd has a mechanism for that. If the web app hangs, that's another thing. You could have a separate process monitor this. Then there is the case where the Pi crashes/hangs. The Pi actually has a hardware watchdog. This is a software problem, that can be solved in software. PS as a last resort you can power cycle the Pi to make it restart.

I will put our comments together in an answer.
You are overthinking the security issue. In my opinion, using RFID to reset the system is a bigger security thread, than using ssh the correct way. Normal RFID chips are susceptible to spoofing (copying an existing chip). Also the intruder could remove the RFID module to directly access the communication lines (depending on how much you will have accessible of the extra hardware). Also you can of course use the Serial interface of an Arduino to execute shell commands on your machine. You need a program on the machine to read the input and execute the commands (Majenko mentioned agetty for this). But is that really the best way? Using an Arduino here is a very hardware-ry way of solving a software issue. It is overly complex to do things this way and there are better options.
Instead you should really just use ssh with key-based authentication (disable password authentication). You can limit the ssh daemon to the local network (though, if you don't have configured corresponding port forwarding in your router, it isn't reachable from the internet either way), or - if you really want the additional security - to one specific device in your network. With a normal ssh key (I think 2048 bit is the standard), brute forcing is not a viable option for intruders. If you keep your private key save, there is very very little chance, that an intruder can get past that. You can also save the private key only on an USB stick, which you only use for resetting the machine. Also you can limit the commands, that the ssh user can execute, to only the resetting (like only allowing rebooting).
Depending on your actual security needs, you can choose, how far you want to go. I personally would just use key-based ssh limited to the local network. That should be plenty enough security and would also give you the possibility to access the machine, that is running in your home easier.

Or, if you really don't want to open ssh for the machine, you can write a simple watchdog program, that can run on the machine. Since the webapp is failing, you can write a simple python program (or any other language you like), which is regularly loading the webapp (how exactly depends largely on the webapp and the exact type of failure - may be a simple HTTP GET request) to check, if it is still alive. If the liveliness test fails for a defined number of times (let's say 3), it will reboot the machine.
This method does not require any access to the machine, but you will have to develop the liveliness test. Writing the program is then really simple.

All that said, it is not a good sign, that the app fails that often. You didn't write, what app that is, and what exactly fails. Maybe you are able to fix that issue directly. Or the developer of the app can, so maybe raise an issue on his platform (where the project is hosted).

You recap is nailing it pretty well.
I am aware of that this approach is not the best approach for a home network.
But it was just a scenario to help me to make  the point clear how and what to achieve.
I can tell you it is WAN based and the app is not failing that often.
It hangs max 1-2 times a year and the ssh approach with certificate works fine.
My scenario describes just the worst-case which until now not has happened.
This is just a pre-emptive action I am taking for convenience and saving time/money.


text:
I2C freeze on master
On my first big Arduino-project I made a game using the following Arduino's and the I2C-protocol:

1x Mega as master
4x Mega as slave
2x Uno as slave

The Arduino's controll a physical game where the players have to push 96 different buttons, according to how certain lights are controlled by relays. The two uno's are used for a MP3-shield and a timer.
My code might not be perfect at all, but I'm happy with how it works. The only problem is that sometimes my master freezes. This is on different moments, but always when the master processes multiple I2C-communications. Sometimes it completes the whole game without problem, but other times it freezes at different moments.
I used a 1ms delay at the end of the loop on all arduino's, because it looked like this might make the connection most stable. The I2C-cables are up to about 1m long, I can't make them shorter. I added 5K1-resesistors from the 5v-line of the master-Mega on the SDA and SCL line. Alle buttons and relays in the game are connected to seperate power sources and don't use the internal pullups.
The code is quite long, so I uploaded the code of the master and the code of 1 mega slave to Github: https://github.com/mrcbrgrs/Arduino-mega-buttons-game. Some comments might be in Dutch, sorry for that.
Who has an idea how I can stop the Mega from freezing?

Can you show us your code?

Things to try: 1) reduce the pullup resistors, see http://www.ti.com/lit/an/slva689/slva689.pdf, 2) reduce the i2c clock frequency, default is 100 khz, see Wire.setclock(), https://www.arduino.cc/en/Reference/WireSetClock

@MikaelPatel 1) I'll try. I already used without external pullup resistors, but was not a difference compared to the the 5K1 setup. 2) I tryed it on the master, but made it freeze very fast every time. Do i have to setclock on all slaves too?

@chrisl Link to code is in post now, was too long to add in post directly.

Use 1kΩ pullup resistors. 5k1 is too high even when using short PCB traces.

I2C is not designed to run over cables without proper "long distance" I2C drivers.

You askes the same question here: https://forum.arduino.cc/index.php?topic=628322.0 Is that 6 times 1 meter for a total of 6 meters? That is not possible, the i2c bus can be 50cm long, but that depends on the type of wires or cable. If you can not make them shorter, you might have to drop the i2c bus and think of something else.

@Majenko Thanks, I will use lower pullup resistors.

@Jot It's a bit less, think up to 4m in total. But even when I make all the cables shorter, the problems are about the same. So I'm not sure if the length is the problem.

Try a test with 50cm total length or shorter. If lowering the clock speed does not help, then there might be a ground problem. You need a GND signal that matches SDA and SCL and does not carry high currents of a motor. Only the Master sets the speed of the SCL clock, the Slaves just follow.

@Jot Thanks again for your help. A short total length had same problem, but also is not an option for the end product. The GND is directly from master-arduino (9v adapter). The master arduino does not power any elements. The clock speed change on the master only resulted on a crash almost every time the master needed to communicate, while without changes it only happens once in a while.

That is a serious problem. I have had multiple arduino slaves with a mega as a master without any problems. The pullup is 5 * 10k and 7 * 30k and 5k1, that is almost as low as 1k, that is too low. Without your 5k1 there is still too much pullup. At least remove the 5k1 resistors. On the arduino.cc forum they wrote about removing the Serial.println from the interrupt functions. Did you do that?

@Jot The setup is in a different workplace, so I'm collecting all info before driving there. Will try the tips soon and let know. Will also get some PCA9615 as I2C bus extenders to use as alternative.


text:
Convert Arduino MEGA Code to Arduino DUE Code?
I've been working with MEGA before. This code works completely with MEGA. I'm still at beginner level in Arduino.
Q: How do I adapt this code to DUE?
Note: I'm asking this question because I think the only problem in adaptation seems to be SoftwareSerial.

#include <SoftwareSerial.h>
SoftwareSerial bluetooth(52,53);    // TX,RX
int bar_analog=0;
int head_analog=0;
int bar_anim=0;
int strip_anim=0;
int motor_speed=1;
int direct=0;
int level=0;
boolean debug = true;
int IN1a=49;
int IN2a=48;
int PWM1=3;
int IN1b=22;
int IN2b=23;
int PWM2=4;
int hiz=100;
int PWM_kare=2;
int INA_kare = 51;
int INB_kare = 50; //LED '+'sı OUTPUT B'de olduğu için INB'yi  HIGH yapıyoruz.
void m1_cw() {
    digitalWrite(IN1a,HIGH);
    digitalWrite(IN2a,LOW);
    analogWrite(PWM1,hiz);
}
void m1_ccw() {
    digitalWrite(IN1a,LOW);
    digitalWrite(IN2a,HIGH);
    analogWrite(PWM1,hiz);
}
void m2_cw() {
    digitalWrite(IN1b,HIGH);
    digitalWrite(IN2b,LOW);
    analogWrite(PWM2,hiz);
}
void m2_ccw() {
    digitalWrite(IN1b,LOW);
    digitalWrite(IN2b,HIGH);
    analogWrite(PWM2,hiz);
}
void m1_stop() {
    digitalWrite(IN1a,LOW);
    digitalWrite(IN2a,LOW);
    analogWrite(PWM1,0);
}
void m2_stop() {
    digitalWrite(IN1b,LOW);
    digitalWrite(IN2b,LOW);
    analogWrite(PWM2,0);
}
void mast_up() {
    digitalWrite(24,HIGH);
    digitalWrite(25,LOW);
}
void mast_down() {
    digitalWrite(24,LOW);
    digitalWrite(25,HIGH);
}
void mast_stop() {
    digitalWrite(24,LOW);
    digitalWrite(25,LOW);
}
void kare() {
    analogWrite(PWM_kare,head_analog);
    digitalWrite(INB_kare, HIGH);
    digitalWrite(INA_kare, LOW);
}
void setup() {
    Serial.begin(9600);
    bluetooth.begin(9600);
    Serial.println("Program is starting...");
    Serial.println("by Berke Ogulcan Parlak");
    pinMode(IN1a,OUTPUT);
    pinMode(IN2a,OUTPUT);
    pinMode(IN1b,OUTPUT);
    pinMode(IN2b,OUTPUT);
    pinMode(PWM1,OUTPUT);
    pinMode(PWM2,OUTPUT);
    pinMode(24,OUTPUT);
    pinMode(25,OUTPUT);
    pinMode(INA_kare, OUTPUT);
    pinMode(INB_kare, OUTPUT);
    pinMode(PWM_kare, OUTPUT);
    digitalWrite(IN1a,LOW);
    digitalWrite(IN2a,LOW);
    digitalWrite(IN1b,LOW);
    digitalWrite(IN2b,LOW);
    digitalWrite(PWM1,LOW);
    digitalWrite(PWM2,LOW);
    digitalWrite(24,LOW);
    digitalWrite(25,LOW);
    digitalWrite(INA_kare, LOW);
    digitalWrite(INB_kare, LOW);
    digitalWrite(PWM_kare, LOW);
}

void loop() {
    if (bluetooth.available()) {
        while (bluetooth.available())
        {                                                //AppInventor'dan çektiğimiz verileri,değişkenlere atıyoruz.
            bar_analog = bluetooth.parseInt();
            head_analog = bluetooth.parseInt();
            bar_anim = bluetooth.parseInt();
            strip_anim = bluetooth.parseInt();
            motor_speed = bluetooth.parseInt();
            direct = bluetooth.parseInt();
            level = bluetooth.parseInt();
            if (debug) {                                   // Arduin seri ekranından değerleri okumak için gereklidir.
                Serial.print("Bar Brightness: ");
                Serial.println(bar_analog);
                Serial.print("Bar Animation Type: ");
                Serial.println(bar_anim);
                Serial.print("Headlight Brightness: ");
                Serial.println(head_analog);
                Serial.print("Strip Animation Type: ");
                Serial.println(strip_anim);
                Serial.print("Motor Speed Level: ");
                Serial.println(motor_speed);
                Serial.print("Direction: ");
                Serial.println(direct);
                Serial.print("Mast Goes: ");
                Serial.println(level);
                Serial.println("--------------------------------");
            }
            if (bluetooth.read() == '\n') {               //Yazdırma işlemleri bu satırda yapılacak..

            }
        }}
    if(direct==1) { //ileri
        m1_ccw();
        m2_ccw();
    }
    else if(direct==2) { //geri
        m1_cw();
        m2_cw();
    }
    else if(direct==3) { //sol
        m1_ccw();
        m2_cw();
    }
    else if(direct==4) { //sağ
        m1_cw();
        m2_ccw();
    }
    else if(direct==0) { //durur
        m1_stop();
        m2_stop();
    }
    if(level==1) { //mast yukarı
        mast_up();
    }
    else if(level==2) { //mast aşağı
        mast_down();
    }
    else if(level==0) { //mast durur
        mast_stop();
    }
    kare();            //kare LED aktif.
}

Why would you have been using SoftwareSerial on the Mega in the first place?!

You posted almost 300 lines of code with no explanation of what it does, and asked a very broad, open-ended question "how to convert." The code also only has a couple of comments, and those are not in English. You need to provide a detailed description of what your program does, what hardware it interfaces with, what I/O lines it uses, and what MEGA-specific features it uses.

You should also add detailed comments to your code, in English, so your readers can understand what it's doing. Further, you need to make an attempt to rewrite your sketch yourself, test it, and then post back asking for help with the problem you find.

SoftwareSerial is a workaround for Arduino versions without enough Hardware Serial ports, which is not the case of Arduino Mega or Arduino Uno which have 4.
Delete SoftwareSerial, replace all occurrences of bluetooth by Serial1, and rewire the Serial communication from pins 52|53 into pins 18|19 instead of (TX|RX)
Besides, the Arduino Due tends to be more "strict" than Arduino Mega compiler.
Besides that, your code will compile with no issues.
Also, remember Arduino Due is 3.3V and not 5V.


text:
how to set buzzer on and off
I have a project that require me to use magnetic contact sensor. I will put the sensor at the door. So the idea is i want every time someone open the door, the buzzer will make a sound, but it will only stay for 3 seconds. When the door is close, buzzer will do nothing and when someone open the door again, the buzzer will make a sound for 3 seconds again. That is the loop. Here is my code. Sorry it's messy. I changed it few times and it still not working like what I want.
const int buzzer = 13;
const int sensor = 4;

int state; // 0 close - 1 open switch

void setup()
{
  pinMode(sensor, INPUT_PULLUP);
}

void loop()
{
  state = digitalRead(sensor);

  if (state == HIGH){
    tone(buzzer,1000);
    delay(3000);
    noTone(buzzer);
  }

  else{
    noTone(buzzer);
  }

}

You have to make your requirement more clear... what after the last 3 seconds?

You could change the delays delay(1000); and delay(5000); to delay(3000);? No? Or what exactly seems to be the problem you are facing?

I'm still new here so I don't know how to write longer at my question or at least tell the detail. I'm using Magnetic contact sensor to put it at the door. So I want my buzzer to make a sound everytime someone open the door. But the sound will only stay for 3 seconds. Then when I close the door, and open back, it will make sound again.

being new here is no reason for not describing clearly what it is that you want to happen?

You have tried to cram your entire question into the subject line. That isn't all that helpful. Try reading how to ask a good question. The code is good to see, but it would also help to have you describe what happens, compared to what you expect to happen.

If you want a delay of 3 seconds, why does your code have a delay of 1000ms? That is one second. This seems to be an obvious problem to fix.

i change it multiple times to test. to save time, i change the delay so i don't have to wait. if it work, i can just change the delay.

When I have a state-machine problem such as this, I diagram it first - here's mine, based on how I understand your requirements:

Most state machines are only activated when an external event happens, so not much happens inside the state-boxes. But since your application only does this one thing, you can actually do your testing inside the states. This is the difference between between blocking- and non-blocking programming - we can afford to block (delay until something happens) because there is nothing else we have to do in the meanwhile.
And my code for the state-machine (which I haven't tested, but it compiles without error):
const int buzzer = 13;
const int sensor = 4;

int state; // 0 close - 1 open switch

void setup()
{
   pinMode(sensor, INPUT_PULLUP);
}

void loop()
{
   // Wait for sensor HIGH
   while( digitalRead(sensor) == LOW )
      ;

   // Sensor HIGH - Alarming
   tone(buzzer, 0.52);
   delay(3000);

   // Wait for sensor LOW
   noTone(buzzer);
   while( digitalRead(sensor) == HIGH )
      ;

   // (goes to Wait for sensor HIGH)
}

“diagram it first” is really the best advice.

I'm sorry for late reply. I'm new here so i don't really understand the concept. i thought your code belong to other person, so i reply to him. I tried your code. It works but I don't want any sound when the sensor is LOW. Your code make the buzzer on for 3 seconds when the sensor is LOW and HIGH. I just want the buzzer turn on when the sensor HIGH. But your code is really helpful. Thank you.

I edit your code a bit and it's working ! Thank you.
Serial.println("sensor: " + sensor);
while ( digitalRead(sensor) == LOW );
noTone(buzzer);
// Sensor HIGH - Alarming
tone(buzzer, 400);
delay(3000);
// Wait for sensor LOW
noTone(buzzer);
while( digitalRead(sensor) == HIGH )
;
// (goes to Wait for sensor HIGH)


text:
NodeMCU what is my esp3286 core version
How do I find out what my esp3286 core version using Arduino IDE?

Tools Menu -> Board -> Boards Manager - scroll down to the core and see what version it is.


text:
Arduino slave with 2 masters sharing the same I2C Bus?
Consider a scenario where two (or more) master devices (the NodeMCU's, in this case) share an I2C bus with one (or more) slave device(s), like thus:

Would this be a feasible setup?  In other words,  could both masters request (not simultaneously) from the slave?

Only if you can implement MultiMaster in the ESP8266's (software-based) I2C library.

care to elaborate an answer?  :)

The situation you describe is called MultiMaster. It is normally done in hardware using the I2C peripheral in the MCU. However the ESP8266 doesn't have one (or if it does, it's not used), and uses bit-banging to implement I2C in software. If you can add MultiMaster functionality to the ESP8266's Wire library then possibly yes, you could do it.
Another option is to have some other communication channel between the two masters (it could be as simple as a wire with a pullup resistor - see below) so that only one master communicates at a time.
Electrically there is no problem with your setup - I2C is a fully open-drain system (or should be implemented as such - hence the pullup resistors needed on the SCL and SDA pins), so multiple devices can drive the lines at the same time. It's just that if they do you will get data corruption and communication won't happen.

Example: Semaphore Wire Implementation

Connect any two GPIO pins together with a wire. Add a pullup resistor to the wire (10kΩ should suffice).
Both GPIO pins are set to INPUT.

When a master wants to send it first reads the GPIO pin:

If it is HIGH then it is "clear to send". So it sets the GPIO to OUTPUT and pulls the line LOW.
If it is LOW then it waits for a random amount of time and tries again.

Once communication is finished the master sets the GPIO pin to INPUT again.

would strict scheduling provide a workaround?

@tonygil Only if you have zero clock drift...  Simpler to have a semaphore signal. I have added more detail to my answer.

I try to keep drift to under 3 millis across the system (I sync a master with a network timeserver and then send the unixtime in my request) and my calls happen on the clock, every 60 seconds (plenty of time to avoid crashing).  Will check your semaphore protocol, tks.

GENIUS!   Semaphore protocol/rigging works perfectly.   will be bountified (as soon as I am allowed to open and then to award bounty (3 days, i guess).

Outstanding answer. (Voted). What (if any) Arduino boards have the hardware needed to support MultiMaster? And what library/libraries do you need to us in order to take advantage of it?

@DuncanC Most, but the software is what is lacking in (most if not) all cases.

How does the clock signal work when you have multiple masters and the semaphore approach? I thought the master generated the clock signal? Wouldn't the multiple masters fight over who asserts the clock pin unless you used some sort of switching to enable the clock signal on the active master and disable it on the others?

@DuncanC The clock signal is only there when the master is communicating. Whichever master is communicating is the one that controls both the IO lines at any moment in time.

@Majenko, when you say "Add a pullup resistor to the wire", does that mean a 10K Ohm resistor to GROUND?  Sorta like reading a reed switch?

No, that would be a pull-down. You want a pull-up. Connect it to +3.3V.

@Majenko, if the Nano is 5V shouldn't there be level conversion on SDA and SCL?

@Juraj No need. Since the ESP8266 is master the bus runs at 3.3V (the ESP8266 provides the pullups to 3.3V). The Arduino reads 3.3V just fine, and since I2C is an open drain protocol the Arduino just connects the signals to ground for 0 and releases them to the pullups (3.3V) for 1. If it were the other way around it would be trickier. You'd need to disable the internal pullups of the Arduino and manually pull the lines up to 3.3V.

@Majenko, thank you for the explanation

Changed diagram after comments and accepted answer:

Yes, except that the upper and lower ground rails on the breadboard aren't connected except via the internals of the Arduino.

adapted to reflect your comment above


text:
Reset NodeMCU master from Arduino slave
I designed a PWS (personal weather station) which will be placed in a difficult to access location.  In case of the master crashing and not requesting from the slave for a certain amount of time (stay alive protocol), is it possible to reset the master from the slave by powering a digital pin?

Note, I improvised a pull down circuit so that the Arduino Nano's D7 (or any other digital pin) 5V output could be pulled down to 3.3V.

for me it didn't work for Wemos D1 mini. with level shifter it worked. I don't know why. but you should have a level shifter for esp8266 RX too

care to elaborate into an answer?  tks @Juraj

I plan esp-01S wiring experiments this weekend and the reset of the esp8266 from Arduino is one of the goals

The "RST" (reset pin) should work, try it w/o the other device, to see if it actually resets.

@Juraj da man!  tell me how that goes, please!  Do you want me to post this fritzing diagram as an fzz somewhere?

There is no need for a voltage divider or a level conversion on the reset pin of the esp8266. The esp8266 has internal pull-up on reset pin. To reset the esp8266 the reset pin must be connected to ground for a very short moment.
To pull the reset pin LOW with pin of the other MCU we do:
void resetEsp() {
  pinMode(ESP_RESET_PIN, OUTPUT);
  delay(1);
  pinMode(ESP_RESET_PIN, INPUT);
}

ESP_RESET_PIN is the pin wired to reset pin of the esp8266. It is not configured in setup() and it is never set HIGH (we don't want to send 5 V to esp8266). Setting the ESP_RESET_PIN to OUTPUT connects it to ground, setting it back to INPUT hands the control of the line back to esp8266 reset pin's internal pull-up.

not sure i understand the wiring.  Does that mean that my Arduino (MCU) digital out is connected directly to NodeMCU RST pin?  If not, do you  mind posting a Fritzing diagram?  UPVOTED pending clarification for eventual ACCEPT AS CORRECT ANSWER.

i am posting a Fritzing as an answer, please comment if correct or incorrect.  Vote (up or down) if you will.

yes direct connection, because there is never 5 V from Nano side. it only pulls the reset LOW

ACCEPTED, tks!!

As per verification from Juraj, this would be correct wiring for his answer:

the point of reset from other MCU is not in wiring, but in code.

so is my original diagram correct, with the voltage divider?

I removed my comments about level conversion on I2C following Majenko's explanation here: https://arduino.stackexchange.com/questions/67461/arduino-slave-with-2-masters-sharing-the-same-i2c-bus/67462?noredirect=1#comment145475_67462

as I write in the answer you don't need voltage divider on reset because it has nothing to divide. there is never 5 V

so, this wiring would work?

yes. of course there is a risk that some other unintentionally to Nano uploaded sketch sets the pin as output high.


text:
one Arduino with RS485 and Ethernet shields: does this work?
I'm planning to wire a few Arduinos together via RS485, and have one of them act as a hub that collects information from the others and presents it via http on an Ethernet connection.
For instance an Aduino MKR with ETH shield and 485 shield. Can I expect these to work together? My worry is having 2 shields that potentially need lots of bandwidth, timing issues etc.

no problem for MKR

Should be no problem.
The ETH shield uses SPI to communicate with a W5500 chip. That chip does most of the network processing for you.
The 485 shield just connects to the UART TX and RX pins. It's just serial communications with a couple of control pins from there on out.
Neither use any pins that the other one uses.


text:
Arduino IDE display DEBUG PORT Serial1 output
How can I display / capture Arduino IDE's Serial1 output?
Can I display it using Arduino IDE or using a script in Python?
This python script (courtesy of Chad G) works for the Serial:
#!/usr/bin/env python3

import serial
import sys

if len(sys.argv)<2:
    print("Please give serial port number")
    exit()
port=sys.argv[1]
ser= serial.Serial('/dev/ttyUSB'+port,9600,timeout=5)

while True:
    try:
    stringMe = str(ser.readline().strip())
    if len(stringMe)>3:
        print(stringMe)

    except:
    print(sys.exc_info())
    ser.close()
    exit()

called as (for USB0):
python3 Arduino/tools/multiMonitor/monitorUsb1.py 0

or, if I want to save to a log file:
python3 Arduino/tools/multiMonitor/monitorUsb1.py 0 >> Arduino/tools/multiMonitor/log/usb00.txt

Serial1 (on most Arduino boards that have Serial1) is connected to a pair of pins on the GPIO headers and nowhere else.
To get it to your computer you will have to feed those TX and RX pins through a USB to TTL UART (FT232, CP2102, etc) adaptor.
From there on in it's exactly the same as using Serial but of course with a different device name.


text:
A proper way to get the roll, pitch and yaw values
TL, DR : What is the method (in terms of sensors and algorithm) to get the roll, pitch angles of an aircraft at any instant?
I am planning to build a hobby aircraft. I am so confused about which kind of sensors should I use and how to use them in order to get the roll, pitch and yaw angles of the aircraft.
I think I also have some problems understanding the concept. I consider these P, R, Y angles similar to the x,y,z coordinates as if they are able to describe the attitude of a body. If something in the below list contains "nonsense" arguments, please also enlighten me about them.
What I want is to be able to know at any instant:

What is the pitch angle of the aircraft, i.e how much degrees its nose pointing away from the horizontal plane of the earth.
What is the yaw angle, i.e to what direction(north, east etc) is the aircraft pointing through.
What is the roll angle, i.e what is the angle between aircrafts body surface ( wing to wing x tail to head surface ) and the horizontal plane of the earth/sky.

In some sources there is something going on as the importance of order of the application of roll, pitch and yaw. But I cannot understand why this is related.
I have used accelerometer values by inputting them into some formulas on the internet (those arctangent formulas, which everybody uses but nobody explains well) to get the roll and pitch values. However could not understand how to manipulate them in order to meet my requirements (different axis orientations of the sensor).
I also have basic understanding about what a gyroscope is.
I have an MPU6050(Accelerometer+Gyroscope).
P.S : my goal is to build a quadcopter but I guess in order to understand these concepts a fixed wing standard plane model.

In some sources there is something going on as the importance of order of the application of roll,pitch and yaw. But I cannot understand why this is related.

Take your right hand: point your thumb upwards, your index finger away from you, and your middle finger to the left. You now have a righthanded coordinate system: your thumb is the x axis, your index finger the y axis, and your middle finger the z axis.
First rotate +90° around the x axis (thumb). Your index finger now points to the left, and your middle finger towards you. Next, rotate +90° around the y axis (index finger). Your thumb now points away from you, your index finger to the left, and your middle finger upwards.
Now, move back to the initial position, and apply the same two rotations in a different order, first around the y axis and then the x axis:
Rotate +90° around the y axis (index finger). Your thumb is now pointing to the right, your index finger away from you, and your middle finger upwards. Next, rotate +90° around the x axis (thumb). Your thumb now points to the right, your index finger upwards, and your middle finger towards you.
This is different from the last result: order of rotation matters.

I have used accelerometer values by inputting them into some formulas on the internet(those arctangent formulas, which everybody uses but nobody explains well)

When the aircraft is moving at a constant velocity, the accelerometer just measures the acceleration due to gravity, which is a vector pointing exactly downward, (0, 0, -g) in the global coordinate system. This is always true, regardless of the orientation of the sensor.
If the sensor is perfectly level, the sensor's local coordinate system is aligned with the global coordinate system, so the sensor also measures (0, 0, -g).
When the sensor is tilted, the measured vector also has an x and y components.
To keep things simple, imagine the case where the sensor is tilted around the positive y axis.
The sensor now measures an x component as well as a z component: (x, 0, -z).
As you can see from the following image, the angle of rotation θ = atan2(x, z).

The black arrow is the acceleration due to gravity, and the red and blue arrows are the x and z axes of the coordinate system of the (tilted) sensor.

However, accelerometer measurements are not useful for determining the orientation when the sensor is accelerating, because then the measured vector no longer points exactly downward (in the global coordinate system).
Gyroscopes measure angular velocity. By integrating the angular velocity, you get the angle.
There's one caveat: it is impossible to integrate exactly, because we only have measurements at discrete points in time. This means we have to use something like Euler's method, which is known to result in drift of the orientation estimate. To make matters worse, the measurement is noisy, and this noise is integrated as well, resulting in an even larger error.
Luckily, you can combine both imperfect measurements into a single, better orientation estimate using a sensor fusion algorithm. I've successfully used Sebastian Madgwick's algorithm for my quadcopter.
It uses the measurements of the accelerometer to minimize gyro drift.
Note that this algorithm uses quaternions instead of Euler angles (roll, pitch, yaw), because the latter suffer from gimbal lock, and because quaternions geneally require less processing power.
Also note that you cannot determine the yaw angle using the accelerometer, so you'll get some drift on that measurement.
It's a good idea to do all of your calculations using quaternions. You probably won't need Euler angles for your quadcopter, except maybe for debugging purposes.
If you want to, you can also get the quaternion from the acceleration vector directly:
    Quaternion quaternionFromDirection(Vec3f v) {
        /*
         * Formula:
         * q = cos(ϑ / 2) + sin(ϑ / 2)·(x·i + y·j + z·k)
         * where (x y z) is a unit vector representing the axis about which
         * the body is rotated; ϑ is the angle by which it is rotated.
         *
         * Source:
         * https://en.wikipedia.org/wiki/Quaternions_and_spatial_rotation#Using_quaternion_as_rotations
         *
         * The rotational axis (x y z) can be calcuated by taking the normalized
         * cross product of (0 0 1) and the given vector. The angle of rotation
         * ϑ can be found using |A×B| = |A||B|·sin(ϑ).
         */

        // First check the edge case where v == (0 0 z), i.e. vertical
        if (v.x == 0 && v.y == 0)
            return {1, 0, 0, 0};

        // Calculate the cross product and its norm.
        Vec3f cross     = {v.y, -v.x, 0};
        float crossNorm = cross.norm();
        cross /= crossNorm;

        // Calculate the angle ϑ.
        float angle = std::asin(crossNorm / v.norm());

        // Calculate the resulting quaternion.
        return {
            std::cos(angle / 2),            //
            std::sin(angle / 2) * cross.x,  //
            std::sin(angle / 2) * cross.y,  //
            std::sin(angle / 2) * cross.z,  //
        };
    }

Well, what can I say, a very well explained answer. Thanks a lot.

One another mystery for me also related to something in your answer: while z axis is pointing upwards and xy plane is level, the accelerometer outputs +g in z component. But you mentioned it to be as -g. So how should I interpret the output of an accelerometer? As gravitional acceleration or the imaginary acceleration due to normal force act on the body?

@muyustan I usually just add minus signs to the appropriate coordinates when reading the accelerometer, so I have a righthanded coordinate system with the z axis pointing upwards (gravity pointing downward).

"To make matters worse, the measurement is noisy, and this noise is integrated as well, resulting in an even larger error."
I think this is incorrect when the noise distribution mean value is zero (no bias), and evenly distributed around it. Offset-corrected gyroscope values often follow this pattern.
In fact, in the long run, integration eliminates noise.
In my tests, I actually removed any filters and multi-sampling


text:
Connect 5v 30a relay with Arduino Uno
I have previously connected 5V 10A relay switches to my Arduino.
But for my new project I need to use a 5V 30A relay switch with my Arduino.
In 10A relay switches, we make connection with Arduino using GND, VCC and IN.
But for 30A switches, there are DC+, DC-, IN.
My question is that, how do I connect my Arduino to the relay using these pins?

DC+ = VCC. Dc- = gnd. In = in.

@Majenko Thank you! That answered my question. So, how do I close it?

You can mark Hobbes' answer as accepted. (Majenko was faster, but he does not seek the merits, obviously)

Plus I was in bed and using my phone, so it's easier to just drop a comment so the OP has the answer they need then later, if it's still needed, craft a proper answer. :)

From the Amazon page you linked to:

1 dc+ : Dc power supply positive pole
  2 dc- :Dc power supply negative pole (i.e. ground)

Arduino:
VCC: positive DC power supply
GND: ground
technically, VCC = the voltage at the collector of a transistor, these days it's used as shorthand for the positive output pin of an IC.


text:
Arduino DUE and 5V logic sensor?
For an application I use Arduino DUE and VNH2SP30 as the motor driver.I think this motor drive is only compatible with 5V logic but DUE provide 3.3V logic.Will my problem be solved if I use logic level shifter to convert 3.3V logic level to 5V?In the meantime, I control the speed and direction of the motor with the following code:
analogWrite(PWM_kare,head_analog);
digitalWrite(INB_kare, HIGH);
digitalWrite(INA_kare, LOW);

According to the datasheet (page 5) the "Input High Level Voltage" is 3.25V.  That means that any voltage over 3.25V will count as a HIGH.
That is kind of borderline for 3.3V logic which can drop below 3.3V for a HIGH depending on load and other circumstances.
So while it might work off 3.3V I would say for reliable operation you should use some form of level shifting in your circuit, yes.
A simple, cheap, MOSFET-based logic level shifter will do the job - there is no need for anything fancy.