text:
Problem with multi-client ASCII text parser (TCP)
I have been having a heck of a time getting my Arduino Uno Rev2 application to work as intended, which is to parse commands from multiple clients sending in ASCII-based commands over WiFi in order to control and read remote I/O from various I/O->ethernet servers.
The code compiles and runs, but it seems to be distributing my incoming client->read() character pulls across my full 2D array that I am calling inputs[][], which was intended to store the full contiguous message from a single client in one row of the array.
#include <stdlib.h>
#include <SPI.h>
#include <WiFiNINA.h>

char ssid[] = "***";                // House -- Network SSID (name)
char pass[] = "***";              // House -- SSID password (WPA2-PSK)

#define MAX_CLIENTS 5
#define MAX_LINE_LEN 50
char inputs[MAX_CLIENTS][MAX_LINE_LEN] = {0}; // Instantiate 2D array of
client/received data
int msg_array[] = {0,0};
int net_status = WL_IDLE_STATUS;              // The Wifi radio's status
WiFiServer server(80);           // Create server object on port of WiFi
                                 // server, which will be used to
                                 // respond to commands

WiFiClient *clients[MAX_CLIENTS] = {NULL};    // Create client objects
                                              // limited to size of
                                              // MAX_CLIENTS

byte mac[] = {0xDE,0xAD,0xBE,0xEF,0xFE,0xED}; // Arduino's physical MAC
byte ip[] = {192,168,9,25};              // IP of this controller
byte gateway[] = {192,168,0,1};          // Router address (internet)
byte subnet[] = {255,255,0,0};           // Subnet mask

unsigned long wd_Dside, wd_Cside = millis();   // Gather current tstamp
unsigned long wd_Delap, wd_Celap = 0;          // Create an elapsed time
                                               //counter

void setup(){

   pinMode(4, OUTPUT);                 // pin selected to control D SIDE
   pinMode(5, OUTPUT);                 // pin selected to control C SIDE

   //enable serial data print
   Serial.begin(9600);
   while (!Serial){
       Serial.println("No serial.");
   }

      Serial.println("Serial.begin was initiated.");

   if (WiFi.status() == WL_NO_SHIELD) {  // check for the WiFi module:
      Serial.println("Wi-Fi: Communication with NINA has failed!");
      // do nothing here
      while (true);
   }

   String fv = WiFi.firmwareVersion();
   if (fv < WIFI_FIRMWARE_LATEST_VERSION) {
      Serial.println("Please upgrade the firmware");
   }

   while (net_status != WL_CONNECTED) {
      Serial.print("Attempting to connect to WPA SSID: ");
      Serial.println(ssid);

      // Connect to WPA/WPA2 network:
      net_status = WiFi.begin(ssid, pass); // Attempt to join this SSID

      // wait 5 seconds for connection:
      delay(5000);

      listNetworks();

      server.begin();                      // Start Wi-Fi server
      Serial.print("Server started on ");
      Serial.println(WiFi.localIP());
    }
}

void loop() {

    delay(5);

    WiFiClient newClient = server.available(); // Begin listening for
                                               // client messages
    if (newClient) {
        Serial.println("New client discovered."); // Could use this as
                                                  // an ACK/handshake on
                                                  // client-side host
        for (int i=0; i<MAX_CLIENTS; i++) {
          if (clients[i] == NULL) {
            clients[i] = new WiFiClient(newClient);
            break;
      }
   }
}

    for (int i=0; i<MAX_CLIENTS; i++){    // Check client for data
      if (clients[i] != NULL && clients[i]->available()){
              // If the data isn't garbage and the data is available..
        char newChar = clients[i]->read();         // Read the data

        if (newChar == '\0') {  // Check for termination char for separation
          char delimiters[] = ",";   // Parse to get command parameterization
          char* valIndex;
          valIndex = strtok(inputs[i], delimiters);
          for (int j=0; j < 2; j++){
            // Expand later to largest anticipated character count
            msg_array[j] = atoi(valIndex);
            Serial.print(msg_array[j]);
            valIndex = strtok(NULL, delimiters);
          }

          switch(msg_array[0]) {
          // Determine type of message received (Character 0 parsed as
          // Message Type)

            case '3':
            // Examine string for client cmds to turn sides on or off.
            if(msg_array[1] == '1')
            // Msg type 3, Instruction 1: Turn D side ON
              {
                // Last good heartbeat from client device on D side.
              }
            if(msg_array[1] == '2')
            // Msg type 3, Instruction 2: Turn D side OFF
              {
                // Last good heartbeat from client device on D side.
              }
            if(msg_array[1] == '3')
                // Msg type 3, Instruction 3: Turn C side ON
              {
                // Last good heartbeat from client device on C side.
              }
            if(msg_array[1] == '4')
                // Msg type 3, Instruction 4: Turn C side OFF
              {
                // Last good heartbeat from client device on C side.
              }
            break;

            case '6':

                // Examine string for another message type TBD
            break;

            default:
              Serial.println("Default break. Received crap.");
            break;

          }

        for (int m=0; m<2; m++){
        Serial.print("Characters detected as: ");
        Serial.print(msg_array[m]);
        }
        Serial.println();
        inputs[i][0] = '\0';
        // Clear out this array element for the next message
        // clients[i]->stop();
        // By default, kill client session, just wait for new TCP open
        // delete clients[i];
        // Remove client element's data
        // clients[i] = NULL;
        // Reset to NULL

        }

        else {

           if (strlen(inputs[i]) > MAX_LINE_LEN) {
                // First check for size compliance
           Serial.println("Max line length exceeded from client.");
           inputs[i][0] = '0';
                // Clear out this array element for the next message
           }
           else {
           size_t l = strlen(inputs[i]);
           inputs[i][l] = newChar;
           inputs[i][l + 1] = 0;
                // Add character to the received string
           }

          Serial.print("inputs[i]:");
          Serial.println(inputs[i]);
        }
      }
   }
}

I usually end up with the following output. This is from just one single device submitting the text ",3,2\0" over TCP. I try to tokenize the ",3,2" portion using strtok and then detect "\0" to signal the system to begin parsing the tokens. My apologies for utilizing the code box, but the quote box was not displaying it how I'd prefer:
Serial.begin was initiated.
Please upgrade the firmware
Attempting to connect to WPA SSID: ATT7YLd4JE
Server started on 192.168.1.98
** Scan Networks **
number of available networks:6
0) ATT7YLd4JE   Signal: -61 dBm Encryption: WPA2
1) DIRECT-F8-HP OfficeJet 4650  Signal: -62 dBm Encryption: WPA2
2) mocha        Signal: -87 dBm Encryption: WPA2
3) Scott        Signal: -92 dBm Encryption: WPA2
4) a5231978     Signal: -92 dBm Encryption: WPA2
5) LReusserWifi_EXT     Signal: -94 dBm Encryption: WPA2
New client discovered.
Client: 0
Triggered NULL client
inputs[i]:,
New client discovered.
Client: 0
Client: 1
Triggered NULL client
inputs[i]:,3
inputs[i]:,
New client discovered.
Client: 0
Client: 1
Client: 2
Triggered NULL client
inputs[i]:,32
00Default break encountered. Received gibberish.
Characters detected as: 0Characters detected as: 0
inputs[i]:,32,
inputs[i]:3
inputs[i]:,
New client discovered.
Client: 0
Client: 1
Client: 2
Client: 3
Triggered NULL client
inputs[i]:,32,2
30Default break encountered. Received gibberish.
Characters detected as: 3Characters detected as: 0
inputs[i]:,
New client discovered.
Client: 0
Client: 1
Client: 2
Client: 3
Client: 4
Triggered NULL client
inputs[i]:,32,23
inputs[i]:,
inputs[i]:,2
00Default break encountered. Received gibberish.
Characters detected as: 0Characters detected as: 0
New client discovered.
Client: 0
Client: 1
Client: 2
Client: 3
Client: 4
inputs[i]:,32,23,
inputs[i]:,3
inputs[i]:,2,
inputs[i]:2
00Default break encountered. Received gibberish.
Characters detected as: 0Characters detected as: 0

..and so forth. Is there a graceful way to confine all the data to one row of the array so I can proceed with parsing it as it should look? I feel like I'll need to store additional information coming from my targets, such as their MAC, so I know how to append each character to the appropriate row.
Thanks,
Hopeless

I am afraid server.available always returns the first client in 'connected' state. test it with WiFiChatServer example. Ethernet library has server.accept presented in AdvancedChatServer example.

If I could control the devices sending data, perhaps starting n number of servers across unique ports would resolve the issue?

does it always return the same first client? (I can't test it right now)


text:
Dc motor backvoltage, how to place the diode correctly?
My previous questions have been anwsered, so thank you all for that!
I make a new question post because I have some other problems with my setup. I use a esp12s 8266 chip. It sends a PWM signal to a n-channel mosfet, so I can regulate the speed of the dc motor that is attached to the drain of the mosfet. The DC motor has extra power from a 9v battery and this battery negative is connected to the GND of the 8266. I can control it with bluetooth hc-05 module, it has 3 options, 40%, 0% (off) and 100% (full power).
Here's the problem:
I can control everything and it seems like it works all fine, but when the motor starts spinning I see a yellow led flashing on my 8266 chip and I can't control it anymore. I read about backvoltage from the motor. So I think maybe the backvoltage is causing the chip not to function anymore. To make it work again I need to disconnect and reconnect the chip for it to work again.
So my question is: could this be the backvoltage or something else?
And if it's the backvoltage how do I need to connect the diode (1n4001) in this circuit?
I read when a motor stops then the backvoltage happens, but in my case the led on the 8266 starts flashing when it spins. So maybe I hooked something the wrong way. here I have some pictures of the different setups I tried.
Of course I will solder everything nicely, but for now it's just to get a quick impression of the hookup.
Hopefully someone can help me out, thanks in advance!

More likely your weak 9v battery is unable to supply enough power.

I read when a motor stops then the backvoltage happens,

That is not true. With a brushed DC motor the back-EMF ("backvoltage") occurs at least twice (often more, depending on the number of commutator segments) per revolution of the motor.  Brushed DC motors are very noisy.
While you can use a diode (connected as you would for a relay) it's not the best solution.  Instead you really need a proper EMI-absorbing circuit.
This consists of three capacitors - all very small values, in the range 1-10nF, which connect all parts of the motor together and bleed off any induced voltages safely.
The first capacitor connects directly across the terminals.  This will safely remove the back-EMF created in the windings as the voltages switch back and forth due to the rotation of the commutator.
The other two capacitors each connect from one terminal to the metal housing of the motor (one to each side of the housing).  This will safely couple the housing to the rest of the circuit and cause it to act as a shield containing the magnetic fields better within the motor.

Thank you. I will try this out and let you know if it worked! I also added another picture that I found on the internet. On the picture you see between the negatief en positive of the motor there is a little capacitor 1uF ceramic capaciter. So you say I need to connect it like that right? and also one on the negative to the housing and the positive to the otherside of the housing, right? :)

Yes, that's right.  The housing-connected ones are less important than the one across the terminals, but still recommended if you can.

Thank you! I don't have the blinking Led on the 8266 and no data noise!

You're looking for something called a "flyback diode."
What happens is, during "normal use" (when the DC motor is being powered by the system), you have a DC motor.  But, when the system stops giving input, and the DC motor "spins down," it can become a power generator -- generators and motors are actually very much the same, it just depends on if they're generating the power, or using the power.
The idea with the flyback diode is that it doesn't let that generated current "back" into the system, and burn up your MCU.  I've seen them in series with a small resistance, to help quickly bleed off any current/voltage the DC motor ends up generating.  With it in series, the diode stops any power from being "wasted," as current will never flow "backwards" through the diode, and thus the resistor.
When you "cut the power" to the DC motor, current can then flow through the "mini-loop" and decay through the resistor (which is not pictured in this example).

Thank you, it gave me a better understanding of a dc motor!

Okay, I'm not sure what you're trying to accomplish, electrically, but the diagram you added doesn't make sense.  It also doesn't match any of the pictures you've posted.  In the diagram, you have your emitter and collector tied together with a diode... but your pictures don't have ANYTHING attached to your emitter leg... you have things "wrapped" around your heatsink/ground, for some reason?
So we'll ignore the pictures that don't make actual circuits, and focus on your diagram.  In the diagram, you've accomplished this:

If you look at this, the diode is doing nothing -- your BJT already has Miller resistance between the emitter and collector, so the diode does nothing for you, here.  You also don't need any capacitors, as you are not looking to store any power, for any reason.  Because of this, I've changed it to a resistor (R4).
What you're really looking for is something more along these lines:

With this, your 9V battery will only power the motor when the BJT is on (your Pin10 is HIGH).  This completes the circuit, and current flows through your motor.  The diode (D1) prevents any current from flowing through the resistor (R2), and no power is lost.
When you turn your motor "off" by setting Pin10 to LOW, kinetic energy will cause your motor to "continue spinning" a little bit -- it's not going to just stop dead, since that energy needs to go somewhere.  This little bit of remaining spin turns your DC motor into a DC generator, and it provides its own power.  This current/voltage needs to go somewhere, or you'll burn things up.
This is where the diode (D1) and resistor (R2) come in handy.  That current can now flow through the mini-loop, and bleed-off this induced power -- or flyback voltage spike -- which is why it's called a "flyback diode."  You're trying to bleed-off that power, not store them, so you need a resistor instead of a capacitor.
So lose the caps, substitute with a resistor, and move your flyback diode.

I am sorry I was not clear about the diagram, I don't use the diagram. I only wanted to point out that the guy from the diagram used a capacitor. So I am not using a BJT but a mosfet. I don't know if that makes a big differents. Also I can't read a circuit diagram, well only the very basic ones. So I didn't really understand what you mean only a small portion of it. I will first try the capacitor and if it not works I can always dive deeper in your story, so thanks!

@Bart BJT's and MOSFETS are both transistors, one is a voltage-controlled voltage source, the other is a current-controlled current source -- Either way, you're connecting to the heatsink (the big plate) and not the collector.  You're not making a complete circuit in either of your pictures.  I would recommend you understand how basic transistors (BJT's and MOSFETS) work before you try to wire them up -- you have not made any complete circuits, and I'm surprised your motor is spinning at all.

I followed a part of this video https://www.youtube.com/watch?v=T9Zpir5hidw&t=100s

source: Stack Exchange

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

sort: votes


text:
Can connect to esp8266 AP which is connected to Arduino UNO but no response
I am new to arduino and am trying to connect the esp8266 to arduino UNO and send commands to the arduino using an android phone.
I have double, triple checked the connections and I am sure they are 100% correct. I have connected esp GND to arduino GND, esp VCC to arduino 5V, esp TX to arduino SoftwareSerial RX and esp RX to arduino SerialSoftware TX and CH_PD to 5V. I can connect to esp using my phone but I can't send commands to it. I am using TCP/UDP Terminal on android to test the connection. Phone is connected to the AP but in the app it is not. I configured the app with 192.168.4.1 IP and 333 Port and I know that app works correctly because I have tested its integrity several times before.
I have searched so much and tried so many but non worked.
My code:
#include <SoftwareSerial.h>
SoftwareSerial ESP8266(2,3);

boolean FAIL_8266 = false;

#define BUFFER_SIZE 128
char buffer[BUFFER_SIZE];

void setup() {

  Serial.begin(9600);
  ESP8266.begin(115200);  // change this value to your wifi module (esp8266) baud rate

  do{
  ESP8266.println("AT");
    delay(1000);
    if(ESP8266.find((char*)"OK"))
    {
      Serial.println("Module is ready");
      delay(1000);

      //configure ESP as AP
      Serial.println("AT+CWMODE=2");
      delay(1000);

      //Set multi connections
      Serial.println("AT+CIPMUX=1");
      delay(1000);

      Serial.println("Server setup finish");
      delay(1000);

      FAIL_8266 = false;

    }
    else{
      Serial.println("Module have no response.");
      delay(500);
      FAIL_8266 = true;
    }
  }while(FAIL_8266);

  ESP8266.setTimeout(100);

}

void loop() {

  if(ESP8266.available()){
    String msg = ESP8266.readString();
    Serial.println("MSG: "+msg);
  }
}

Could anyone please tell me what is wrong?

You can't use SoftwareSerial reliably at 115200 baud. The Arduino just can't keep up with the speed to the data coming in. That said, you should write a simple serial echo program to allow you to communicate with the esp8266 manually via the Arduino to test that communication is actually happening.

@Majenko Thanks about the answer, I did a little research about what you said on the internet and it looks correct. I have read about changing the esp8266 baudrate to a lower amount but I didn't do it because many have reported that doing it have bricked their esp8266. Now, do you have anything in mind to fix the problem?

You really want to reduce the ESP8266 baud rate. You should get yourself set up for reflashing the ESP8266 first though. It's something you should get into anyway - it's far more efficient writing software to run directly on the ESP8266 rather than struggling with a ropey AT command set.

@Majenko I flashed my esp8266 and now it is working. Thanks for the Assist.

it's virtually impossible to brick an esp; all you need to do is put it in flash mode and reflash.

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


text:
Why do we need this resistor?
What is the purpose of it and on what bases its value is calcuated in ohms ?

use INPUT_PULLUP mode for a simpler wireup


text:
Mega2560 has 2 Crystal Oscillator?
Who knows this Mega2560 with two Crystal Oscillators: 12 000 MHz and 16 000 MHz? What is the use of them?

there is an ATmega16u2 as USB converter. it has the 12 MHz oscilator

Don't the 16U2s also use 16 MHz, while the CH340 use 12 MHz?  The 2560 itself more typically use a  smaller 3-pin16 MHz resonator.

Please expand on your question.

There are two devices on an Arduino board than need a clock source:

The ATMega328 / ATMega2560 main MCU (16MHz)
The USB interface.

The USB interface crystal speed depends on what device is used on your board. Genuine Arduino boards use an ATMega16U2 which uses a 16MHz crystal.  Cheap Chinese clones use a CH340G which takes a 12MHz crystal.
Note that normally it's one crystal and one ceramic resonator.  USB requires very precise timing, so a crystal is used for that. The main MCU doesn't need quite such precise timing, so a cheaper (and less accurate) ceramic resonator is used.


text:
expected initializer before 'RF24'
The code i make is this
    */
#include <SPI.h>
#include <nRF24L01.h>
#include <RF24.h>
#include <Servo.h>
#define CE_PIN   9
#define CSN_PIN 10

const uint64_t pipe = 0xE8E8F0F0E1LL;
int servoy;
int servox;
Servo Yservo;
Servo Xservo;

RF24 radio(CE_PIN, CSN_PIN);

int joystick[2];

void setup()RF24
{
  Serial.begin(9600);
  delay(1000);
  radio.begin();
  radio.openReadingPipe(1,pipe);
  radio.startListening();
  Xservo.attach(3);
  Yservo.attach(5);
}

void loop()
{
  if ( radio.available() )
  {
    bool done = false;
    while (!done)
    {
done = radio.read( joystick, sizeof(joystick) );
servox= joystick[0]/5.683;
servoy= joystick[1]/5.683;
      Serial.println(servoy);
      Yservo.write(servoy);
      Serial.println(servox);
      Xservo.write(servox);
    }
  }
  else
  {
      Serial.println("NO RADIO CONECTION");
  }

}

and i don't know what  happen it's said that
 sketch_aug20b_rc_rc_rc_22:33:13: error: expected initializer before 'RF24'

 void setup()RF24

             ^

C:\Users\ASUS\Documents\Arduino\sketch_aug20b_rc_rc_rc_22\sketch_aug20b_rc_rc_rc_22.ino: In function 'void loop()':

sketch_aug20b_rc_rc_rc_22:51:6: error: void value not ignored as it ought to be

 done = radio.read( joystick, sizeof(joystick) );

      ^

exit status 1
expected initializer before 'RF24'

It's basically saying "Why have you got a random "RF24" in the middle of your code like that?" - and I'm asking the same thing...

You have two problems:
sketch_aug20b_rc_rc_rc_22:33:13: error: expected initializer before 'RF24'

void setup()RF24

         ^

It's basically saying "I don't understand what you mean by RF24 here". That RF24 in that line should not exist. I assume you made some kind of typo or copy-pasta error.
Second:
C:\Users\ASUS\Documents\Arduino\sketch_aug20b_rc_rc_rc_22\sketch_aug20b_rc_rc_rc_22.ino: In function 'void loop()':
sketch_aug20b_rc_rc_rc_22:51:6: error: void value not ignored as it ought to be

 done = radio.read( joystick, sizeof(joystick) );

That is saying that radio.read doesn't return a value - yet you are trying to assign that value that doesn't exist to something.
According to the documentation for RF24::read():

Read the available payload
The size of data read is the fixed payload size, see getPayloadSize()
Note
I specifically chose 'void*' as a data type to make it easier for beginners to use. No casting needed.
No longer boolean. Use available to determine if packets are available. Interrupt flags are now cleared during reads instead of when calling available().
Parameters

buf   Pointer to a buffer where the data should be written
len   Maximum number of bytes to read into the buffer
if(radio.available()){
   radio.read(&data,sizeof(data));
  }

Returns
No return value. Use available().


text:
Arduino Ultrasonic Sensor and LCD - Help Needed-
I just recently purchased an Arduino Uno 3 and I wanted to make an ultrasonic distance sensor that outputs the readings to a 16x2 LCD. I followed this guide:
http://www.mertarduino.com/using-ultrasonic-distance-sensor-hc-sr04-with-lcd-display-and-arduino/2018/11/22/ but it gave an error when I uploaded the code. The error was: a function definition is not allowed here before '{' token. I don't know too much about Arduinos, so I need help.
Thanks to whoever responds!
Here is the code:

// put your setup code here, to run once:
#include <LiquidCrystal.h> //Please replace the single quote characters ('') with the parenthesis character (<>)

LiquidCrystal lcd(1, 2, 4, 5, 6, 7); // Creates an LCD object. Parameters:
(rs, enable, d4, d5, d6, d7)

const int trigPin = 9;
const int echoPin = 10;
long duration;
int distanceCm, distanceInch;

void setup() {

lcd.begin(16,2); // Initializes the interface to the LCD screen, and
specifies the dimensions (width and height) of the display
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);

}

void loop() {

digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);

duration = pulseIn(echoPin, HIGH);
distanceCm= duration*0.034/2;
distanceInch = duration*0.0133/2;

lcd.setCursor(0,0); // Sets the location at which subsequent text written to
the LCD will be displayed
lcd.print("Distance: "); // Prints string "Distance" on the LCD
lcd.print(distanceCm); // Prints the distance value from the sensor
lcd.print("  cm");
delay(10);
lcd.setCursor(0,1);
lcd.print("Distance: ");
lcd.print(distanceInch);
lcd.print("inch");
delay(10);
}

your comments are broken. please take a coding course

The root of your problem is this bit:
LiquidCrystal lcd(1, 2, 4, 5, 6, 7); // Creates an LCD object. Parameters:
(rs, enable, d4, d5, d6, d7)

I think in copying-and-pasting you ended up with a line split across two giving you an error. It should read:
LiquidCrystal lcd(1, 2, 4, 5, 6, 7); // Creates an LCD object. Parameters: (rs, enable, d4, d5, d6, d7)

You have a similar problem here:
lcd.begin(16,2); // Initializes the interface to the LCD screen, and
specifies the dimensions (width and height) of the display

Again that has split across two lines and should read:
lcd.begin(16,2); // Initializes the interface to the LCD screen, and specifies the dimensions (width and height) of the display

And a third:
lcd.setCursor(0,0); // Sets the location at which subsequent text written to
the LCD will be displayed

which should be:
lcd.setCursor(0,0); // Sets the location at which subsequent text written to the LCD will be displayed

When those three are corrected the code compiles properly.

Why the downvote? Is there something wrong with this answer?

Thanks for the answer! the code now works and I don't know who gave the downvote as I don't actually have an account.

Upvoted; nothing wrong with the answer (as usual).


text:
SD Card store struct: force big-endian / little-endian?
Following MAJENKO's tutorial on sd card file optimization and data integrity, can I force the SDCard to read and write in either big-endian or little-endian?
I need this in order to maintain backup data integrity across a wide array of IoThings, using various boards (Arduino UNO, MEGA, Nano, NodeMCU, etc) for future parsing.

Many full C libraries have an sys/endian.h header file. This defines a number of macros so you can find out what the endianness of your device is.  It also usually defines a number of handy macros that can convert the endianness for you.
htobe16(x)
htobe32(x)
betoh16(x)
betoh32(x)

These convert Host to Big Endian values and back again.
htole16(x)
htole32(x)
letoh16(x)
letoh32(x)

And these convert Host to Little Endian values and back again.
Not many embedded C libraries provide it, though, and not all that do provide the handy macros.
It's not too hard to implement yourself, but it does mean you deciding what to do depending on the target architecture. Which kind of negates the handiness of the endian.h file.
So really you want to re-implement the functionality in a form you can include in all your sketches.
Fortunately the compiler provides a set of macros defining the endianness that you can use though:
#define __ORDER_LITTLE_ENDIAN__ 1234
#define __FLOAT_WORD_ORDER__ __ORDER_LITTLE_ENDIAN__
#define __ORDER_PDP_ENDIAN__ 3412
#define __ORDER_BIG_ENDIAN__ 4321
#define __BYTE_ORDER__ __ORDER_LITTLE_ENDIAN__

So you can examine the __BYTE_ORDER__ macro to see what byte order it equates to and use that to select whether htobe32(x) has to do anything to the byte order or not.
In the PIC32 compiler it's done as a set of macros that either call swap32 / swap16, or pass the value unchanged:
#if __BYTE_ORDER__ == __LITTLE_ENDIAN__

#define htobe16 swap16
#define htobe32 swap32
#define betoh16 swap16
#define betoh32 swap32

#define htole16(x) (x)
#define htole32(x) (x)
#define letoh16(x) (x)
#define letoh32(x) (x)

#endif /* __BYTE_ORDER__ */

#if __BYTE_ORDER__ == __BIG_ENDIAN__

#define htole16 swap16
#define htole32 swap32
#define letoh16 swap16
#define letoh32 swap32

#define htobe16(x) (x)
#define htobe32(x) (x)
#define betoh16(x) (x)
#define betoh32(x) (x)

#endif /* __BYTE_ORDER__ */

So now depending on the byte order it will either swap the bytes around, or leave them unchanged.  It's now just a matter of implementing swap16 and swap32 - which I'll leave to you (hint: it just returns the value with the bytes in the reverse order - bit shifting and masking is good for that).
Then you need to decide on an endianness for your file.  Maybe choose little-endian since that is probably the most common.  So whenever you place a value into a struct for writing you pass it through either htole32(...) or htole16(...) depending on the data type.  Then whenever you read from a struct that has been read you pass the value through either letoh32(...) or letoh16(...) to get it in the host's endianness.


text:
Remote Arduinos polling a master Ardrino over ethernet/wifi
I'm setting up a "Panic Button" for our Front Office. The concept is to have a master Arduino with the button and 4 other Arduinos with Strobes and/or alarms to alert the rest of the staff. The bells and whistles are fairly straight forward. My only block is how to have the remote Arduinos poll the master and receice a simple on/off value over the existing ethernet/wifi network (necessary because we are physically 2 different buildings so bluetooth or standard serial communicaitons would be prohibitive). Master will be hardwired to ethernet while the remotes will need to be wifi. Any and all suggestions would be greatly appreciated.

This sounds like a job for Multicast UDP to me...

after some research. that appears to be the solution, Thank you!


text:
FS100A works when Arduino connected to PC but not when connected to Raspberry Pi
I am building a simple circuit which monitors soil humidity in a flower pot. I was able to measure it and send it from one Arduino Nano to another Nano via FS100A transmitter and receiver and VirtualWire library.
As this is prototype so far I connected 1st (measuring) Nano to a powerbank and it works fine: I see the data is send and received by 2nd Arduino.
2nd Nano receives the data (it is less than 50 bytes) and send send it to PC via USB serial connection. All works fine as long as 2nd Arduino is connected to anything but Raspberry PI. Then it is not able to receive any data.
I modified source code of my program to blink built-in LED right after data is read. When 2nd Nano is powered by another powerbank it blinks (the data is read). The same happens using any other PC. But when I try to use it with RPi there is no blinking.
RPi is model B+ and I tried two different devices.
I suspect that Raspberries don’t provide stable power to usb or they cause a lot of noise preventing radio from reading the data. Is there any way to overcome this?

Try to power your Arduino with external power supply and use only RPi to receive/display your data. You will prove this way that the problem lays in the insufficient voltage. If you have a DMM you can check this by measuring voltage on RPi USB port.

After some attempts I finally made it work.
I tried to use a level shifter. It worked somehow but I could not find any library which would work with Arduino's VirtualWire.
I just put a 220µ capacitor on power lines to the radio receiver. It filtered all the noise and Arduino is able to interpret signals correctly.


text:
can I check if why my motor isn't working?
I am currently using the arduino Uno connected with L298N(green pcb) connected to a dc motor rated 12V. I provided dedicated 12v power supply to the dc motor and the arduino board's power is supplied by usb connected to my pc. I connected Pin 9 of arduino uno to 'ENA' on L298N , Pin 7 & 8 (UNO) to 'INA' & 'INB' of L298N. Connected '-' polarity of Motor power supply to GND of L298N, while also connecting the 'GND' of L298N to the GND of Arduino UNO. Last but not least, connecting the 'OUT B'to the dc motor. This is the picture of how L298N(green) look like https://sea.banggood.com/Green-Board-L298N-DC-Motor-Driver-Board-Stepper-Motor-p-974549.html?cur_warehouse=CN
Can i check why my motor isn't running? Thanks in advance.
char data = 0;
int enB = 9;
int InC = 8;
int InD = 7;

void setup()
{
    Serial.begin(9600);
    Serial.println("Motor test !");
  pinMode(enB, OUTPUT);
   pinMode(InC, OUTPUT);
  pinMode(InD, OUTPUT);

}

void loop()
{Serial.println("Entered loop, should start moving now !");
  digitalWrite(InC, HIGH);
  digitalWrite(InD, LOW);
   digitalWrite(enB, HIGH);
   analogWrite(enB, 255);
 }

the code that is inside the loop() block needs to run only once ... you can move it into the setup() block

Well, your wiring is OK, but I think the
'digitalWrite(enB, HIGH);
in the loop() code is causing your problem.  You don't want to try to use the same pin for both digital and analog functions.
I wired up a Uno here with your setup and a L298N, and got a motor to run fine with the following sketch that doesn't use the loop() at all - it does everything in setup().
char data = 0;
int enB = 9;
int InC = 8;
int InD = 7;

void setup()
{
    Serial.begin(9600);
    Serial.println("Motor test !");
    pinMode(enB, OUTPUT);
    pinMode(InC, OUTPUT);
    pinMode(InD, OUTPUT);

    Serial.println("motor should start moving now !");
    digitalWrite(InC, HIGH);
    digitalWrite(InD, LOW);
    //digitalWrite(enB, HIGH);

    for (size_t i = 0; i < 10; i++)
    {
        analogWrite(enB, 20*i);
        Serial.print("motor speed = "); Serial.println(20 * i);
        delay(2000);
    }

    Serial.println("quitting!");
    while (true)
    {

    }

}

void loop()
{
    //Serial.println("Entered loop, should start moving now !");
    //digitalWrite(InC, HIGH);
    //digitalWrite(InD, LOW);
    //digitalWrite(enB, HIGH);
    //analogWrite(enB, 255);
}

If you can't get your motor working with the above program, then you most likely have a connection or power supply or component problem that you'll need to troubleshoot.
Hope this helps,
Frank

Hi Frank, thanks for your help, after using the code you have shared, it still doesnt work. I'm suspecting that this green L298N is different from the regular "red" ones, On my L298N board only shows "5v" led lit up, all "A" "B" "C" "D" aren't.

Bypass everything and MOMENTARILY connect +12V to the motor Does the motor run?  Do you have a multimeter?  If so, you can ohm out the motor to see if you maybe have an open winding.  If the motor runs when connected directly to 12V, Try a different PWM output pin instead of pin 9.  Try connecting the motor to the other L298N output.  If you have a DVM, measure the DC voltage at the L298N motor output; it should read almost the full supply voltage when the program runs.  If you don't have a DVM, you should consider getting one - they are invaluable tools for troubleshooting ;-)

@user10748500 can you add another picture (the existing link doesn't work)? I only know the green one, not the red...


text:
Slave to Send Data after Receiving Command using I2C
I want to have my Slave Arduino to send signal to Master after the command was made. But the Slave Arduino does not proceeds to sending the signal after doing the command. What is wrong with my code?
Slave

void receiveEvent(int bytes) {
  dir = Wire.read();    // direction
  dis = Wire.read();    // distance
  spe = Wire.read();    // speed
  eStop = Wire.read();    // 1 or 0
  Serial.println(dir);
  Serial.println(dis);
  Serial.println(spe);
  mov = true;
}
void loop() {
    Wire.onReceive(receiveEvent);
  if (dir == 1 && mov == true && eStop == false){
      motor.Distance(dis);
      motor.Speed(spe);
      motor.Forward();
       Wire.onRequest(requestEvent);
      mov = false;
      fin = true;
    }
  if (dir == 2 && mov == true && eStop == false){
    motor.Distance(dis);
    motor.Speed(spe);
    motor.Reverse();
      Wire.onRequest(requestEvent);
    mov = false;
    fin = true;
  }

  else{
    motor.Stop();
  }
}
void requestEvent(){
    Wire.write(1);
    fin = false;
    Serial.println("sent");
}

Master

#include <Wire.h>

const byte interruptPin = 2;
byte dir = 0;
byte dis;
byte spe;
bool upd;

bool state= false;

void setup() {

  Wire.begin();
  pinMode(interruptPin, INPUT_PULLUP);
  attachInterrupt(digitalPinToInterrupt(interruptPin), emergencyStop, CHANGE);
  Serial.begin(9600);

}
void loop() {
       if( state == false ){
       dir = 1;
       dis = 30;
       spe = 2;
       Wire.beginTransmission(9); // transmit to device #9
       Wire.write(dir);
       Wire.write(dis);
       Wire.write(spe);
       Wire.write(0);
       Wire.endTransmission();    // stop transmitting
       state = true;
       }
       if (state == true){
        if(Wire.available() > 0){
       Wire.requestFrom(9,2);   //6bytes from slave 9
          bool upd = Wire.read();
          Serial.println(upd);
        }
      }
}
void emergencyStop(){ // not working
  Wire.beginTransmission(9); // transmit to device #9
       Wire.write(0);
       Wire.write(0);
       Wire.write(0);
       Wire.write(1);
       Wire.endTransmission();    // stop transmitting

}

Please wdit your question to include the full sketch

Typically Wire.onReceive(callbackFunction) is called once in the setup().

Serial print in the callback function can cause issues.

found my solution for this. although not verified yet, but i removed Serial print and moved the Wire.onRequest outside of the if loop. and uses a ledPin for checkups
void loop() {

        Wire.onReceive(receiveEvent);
        Wire.onRequest(requestEvent);
  if (dir == 1 && mov == true && eStop == false){
      motor.Distance(dis);
      motor.Speed(spe);
      motor.Forward();
      mov = false;
      fin = true;
    }
  if (dir == 2 && mov == true && eStop == false){
    motor.Distance(dis);
    motor.Speed(spe);
    motor.Reverse();
    mov = false;
    fin = true;
  }

  else{
    motor.Stop();
  }
}

void requestEvent(){
    if ( fin == true){
      Wire.write(1);
     fin = false;
    digitalWrite(ledPin, HIGH);
    }

}

Yes, you should not do serial prints inside an interrupt service routine.


text:
LCD shield submenu
I need to make an app that does various functions regarding IR signals (remote-like)
I need to create a sub menu in order for me to access multiple functionalities.
Arduino-Uno-Menu-Template
I used the link above to create a menu and it works great! The problem is I can not do a sub menu without messing with the loop that display the original one. Any ideas?
This is the code I got so far:
https://pastebin.com/Vh5R2JVp
I'm trying in menuItem1() function to add a routine to create the submenu.
I tried to use a variable that changes when the menu does but it didn't work.

Can you show us the code you've written so far?

The code is the same one as the one from the link I've provided. I just modified the items so it would fit what my menu needs. The link above is a simple template but has no submenus whatsoever. That's what I need !

I added the code !

What you can do (but there are many solutions):

Keep a variable (e.g. subMenu that has the state of the current menu option selected (make this an enum).
Whenever a sub menu is entered, assign the subMenu variable with the current sub menu value.
Use a switch around the current switch statement for first switching subMenu (make different functions for clearity).

So the pseudo code would look like
enum ESubMenu { MainMenu, Page1, Page2 };
ESubMenu subMenu;

void setup()
{
  subMenu =  MainMenu;
}

void loop()
{
   switch (subMenu)
   {
   case MainMenu : showMainMenu() ; break;
   case Page1Menu: showPage1Menu(); break;
   case Page2Menu: showPage2Menu(); break;
   }
}

void showMainMenu()
{
   if (`sub menu 1 selected`)
   {
      subMenu = Page1Menu;
   }
   else if (`sub menu 2 selected')
   {
      subMenu = Page2Menu;
   }
   else
   {
      // Show/handle main menu
   }
}

void ShowPage1()
{
   if `back'
   {
     subMenu = MainMenu;
   }
   else
   {
      // Show/handle page 1 menu options
   }
}

I will try this. I hope I understood the concept. I am new in Arduino

What type should my variable be?

Of type ESubMenu

It didn't work. I think it's probably because of how the loop works

It's not a full code, you have to add code for getting the buttons yourself; also I couldn't test it; it's more like a pseudo code template

I know, I've tried to adapt it to the menu template. For some reason it won't let me come back to the first menu page. I believe it's because of the loop.

If submenu is MainMenu, it should show the main menu, maybe you can add some print statements to print out the value of submenu to see if it has the expected value. Also in a submenu, when going back, make sure to assign MainMenu to subMenu to revert back to the main menu.

Can I show you the code in some way?

Add it to your question (so anybody can respond)


text:
Why is observed clock rate < 3MHz on Arduino Uno?
I wrote a simple loop to test the processor speed on my Arduino Uno. The numbers I'm getting are much worse than the 16MHz advertised, by a factor of ~5. Trying to figure out what I'm missing.
long counter = 0;
int sum = 0;
uint32_t t = 0;

void setup() {
  Serial.begin(9600);
  t = micros();
}

void loop() {
  sum += counter;

  if (counter == 10000) {
    float usecsPerIteration = (micros() - t) / (counter * 1.0);
    Serial.print(usecsPerIteration);
    Serial.println(" microseconds per iteration");

    // Print result to avoid loop getting optimized away
    Serial.println(sum);
  }

  ++counter;
}

The output is:
3.77 microseconds per iteration

Here's how I'm estimating clock rate from this. The body of the loop involves two additions and an equality check. Even if we assume that these simple operations take 10 clock cycles, the implied clock rate is still just (1 iter / 3.77 us) * (1e6 us / sec) * (10 cycles / iter) = 2.65 MHz.
What am I missing?

You forgot that the printing itself also contributes to the equation. This is VERY EXPENSIVE. You should reset your time after every printing.

I only print once after 10,000 iters and it is after I compute time elapsed.

As Michael says there is a lot more going on than you think.
Firstly there are interrupts triggering which can slow things down (used to calculate milllis()).
Secondly you vastly under estimate the number of instructions that are being called.  For a start the loop is being called from a for(;;) loop in main():
    for (;;) {
        loop();
4   572:    0e 94 73 00     call    0xe6    ; 0xe6 <loop>
        if (serialEventRun) serialEventRun();
2   576:    20 97           sbiw    r28, 0x00   ; 0
2   578:    e1 f3           breq    .-8         ; 0x572 <main+0x10>
-   57a:    0e 94 1d 01     call    0x23a   ; 0x23a <_Z14serialEventRunv>
2   57e:    f9 cf           rjmp    .-14        ; 0x572 <main+0x10>
10 total

Then for the call to loop() the registers used get pushed to the stack, then your code executed, and the registers popped off again before returning.  This is the code for loop when disassembled:
000000e6 <loop>:
    // Save the registers to the stack
2   e6:     cf 92           push    r12
2   e8:     df 92           push    r13
2   ea:     ef 92           push    r14
2   ec:     ff 92           push    r15
8 total

    // Add to the sum
2   ee:     40 91 44 01     lds r20, 0x0144 ; 0x800144 <counter>
2   f2:     50 91 45 01     lds r21, 0x0145 ; 0x800145 <counter+0x1>
2   f6:     60 91 46 01     lds r22, 0x0146 ; 0x800146 <counter+0x2>
2   fa:     70 91 47 01     lds r23, 0x0147 ; 0x800147 <counter+0x3>
2   fe:     80 91 42 01     lds r24, 0x0142 ; 0x800142 <sum>
2   102:    90 91 43 01     lds r25, 0x0143 ; 0x800143 <sum+0x1>
1   106:    84 0f           add r24, r20
1   108:    95 1f           adc r25, r21
2   10a:    90 93 43 01     sts 0x0143, r25 ; 0x800143 <sum+0x1>
2   10e:    80 93 42 01     sts 0x0142, r24 ; 0x800142 <sum>
18 total

    // Check the value to see if it's time to print
1   112:    40 31           cpi r20, 0x10   ; 16
1   114:    57 42           sbci    r21, 0x27   ; 39
1   116:    61 05           cpc r22, r1
1   118:    71 05           cpc r23, r1
2   11a:    d1 f5           brne    .+116       ; 0x190 <loop+0xaa>
6 total

    // From here on is the "IF" section - skipped by the BRNE above
-   11c:    0e 94 f5 04     call    0x9ea   ; 0x9ea <micros>
-   120:    c0 90 3e 01     lds r12, 0x013E ; 0x80013e <__data_end>
-   124:    d0 90 3f 01     lds r13, 0x013F ; 0x80013f <__data_end+0x1>
-   128:    e0 90 40 01     lds r14, 0x0140 ; 0x800140 <__data_end+0x2>
-   12c:    f0 90 41 01     lds r15, 0x0141 ; 0x800141 <__data_end+0x3>
-   130:    6c 19           sub r22, r12
-   132:    7d 09           sbc r23, r13
-   134:    8e 09           sbc r24, r14
-   136:    9f 09           sbc r25, r15
-   138:    0e 94 68 06     call    0xcd0   ; 0xcd0 <__floatunsisf>
-   13c:    6b 01           movw    r12, r22
-   13e:    7c 01           movw    r14, r24
-   140:    60 91 44 01     lds r22, 0x0144 ; 0x800144 <counter>
-   144:    70 91 45 01     lds r23, 0x0145 ; 0x800145 <counter+0x1>
-   148:    80 91 46 01     lds r24, 0x0146 ; 0x800146 <counter+0x2>
-   14c:    90 91 47 01     lds r25, 0x0147 ; 0x800147 <counter+0x3>
-   150:    0e 94 6a 06     call    0xcd4   ; 0xcd4 <__floatsisf>
-   154:    9b 01           movw    r18, r22
-   156:    ac 01           movw    r20, r24
-   158:    c7 01           movw    r24, r14
-   15a:    b6 01           movw    r22, r12
-   15c:    0e 94 c7 05     call    0xb8e   ; 0xb8e <__divsf3>
-   160:    ab 01           movw    r20, r22
-   162:    bc 01           movw    r22, r24
-   164:    22 e0           ldi r18, 0x02   ; 2
-   166:    30 e0           ldi r19, 0x00   ; 0
-   168:    88 e4           ldi r24, 0x48   ; 72
-   16a:    91 e0           ldi r25, 0x01   ; 1
-   16c:    0e 94 a9 04     call    0x952   ; 0x952 <_ZN5Print5printEdi>
-   170:    60 e0           ldi r22, 0x00   ; 0
-   172:    71 e0           ldi r23, 0x01   ; 1
-   174:    88 e4           ldi r24, 0x48   ; 72
-   176:    91 e0           ldi r25, 0x01   ; 1
-   178:    0e 94 0b 03     call    0x616   ; 0x616 <_ZN5Print7printlnEPKc>
-   17c:    60 91 42 01     lds r22, 0x0142 ; 0x800142 <sum>
-   180:    70 91 43 01     lds r23, 0x0143 ; 0x800143 <sum+0x1>
-   184:    4a e0           ldi r20, 0x0A   ; 10
-   186:    50 e0           ldi r21, 0x00   ; 0
-   188:    88 e4           ldi r24, 0x48   ; 72
-   18a:    91 e0           ldi r25, 0x01   ; 1
-   18c:    0e 94 b0 03     call    0x760   ; 0x760 <_ZN5Print7printlnEii>

 // All this is just counter++
2   190:    80 91 44 01     lds r24, 0x0144 ; 0x800144 <counter>
2   194:    90 91 45 01     lds r25, 0x0145 ; 0x800145 <counter+0x1>
2   198:    a0 91 46 01     lds r26, 0x0146 ; 0x800146 <counter+0x2>
2   19c:    b0 91 47 01     lds r27, 0x0147 ; 0x800147 <counter+0x3>
2   1a0:    01 96           adiw    r24, 0x01   ; 1
1   1a2:    a1 1d           adc r26, r1
1   1a4:    b1 1d           adc r27, r1
2   1a6:    80 93 44 01     sts 0x0144, r24 ; 0x800144 <counter>
2   1aa:    90 93 45 01     sts 0x0145, r25 ; 0x800145 <counter+0x1>
2   1ae:    a0 93 46 01     sts 0x0146, r26 ; 0x800146 <counter+0x2>
2   1b2:    b0 93 47 01     sts 0x0147, r27 ; 0x800147 <counter+0x3>
20 total

 // Get the registers back and return
2   1b6:    ff 90           pop r15
2   1b8:    ef 90           pop r14
2   1ba:    df 90           pop r13
2   1bc:    cf 90           pop r12
4   1be:    08 95           ret
12 total

That's more than 10 instructions.  I make it 74 clocks to run one full iteration. (counter++ alone is 20 clock cycles - double your estimation for the total...)
You have to remember two important things:

AVR is a RISC CPU - that means that seemingly simple operations can take multiple instructions to perform.
AVR is an 8-bit CPU - that means that working with any variables bigger than 8 bits in size require far more complex code, and you work with 32-bit variables (and floats, but that's outside the timing loop section of your code).

I am counting 72 clock cycles per iteration in your disassembly (20 for counter++). It looks like you compiled without -flto.

@EdgarBonet Quite possibly, yes. I use UECIDE which may not use the same compilation flags as Arduino if they decide to change things like that randomly - also probably not the same version of the compiler (I have lots of versions to choose from).

@EdgarBonet ADIW is two clocks not one I see, even though it only needs one read from the flash. I was counting flash reads as clocks. So yes, there's even more than at first it appears.

Indeed, the Arduino folks changed the compilation flags, adding LTO in 1.6.10.

@EdgarBonet I should add that to the arduino core in UECIDE then really. It's time to build a new version anyway I guess.  Any way - I have listed (and summed) the actual clock cycle values in the answer now.

@EdgarBonet Oh... and for a "RISC" system, the AVR sure has a lot of instructions...

The loop function is called within the framework of the Arduino IDE.
Beyond the code you write, also an interrupt check is done, which also cost time, and explains the difference.
The following function CAN be called after every loop call.
See Majenko's answer about the details.
/*
  SerialEvent occurs whenever a new data comes in the hardware serial RX. This
  routine is run between each time loop() runs, so using delay inside loop can
  delay response. Multiple bytes of data may be available.
*/
void serialEvent() {
  while (Serial.available()) {
    // get the new byte:
    char inChar = (char)Serial.read();
    // add it to the inputString:
    inputString += inChar;
    // if the incoming character is a newline, set a flag so the main loop can
    // do something about it:
    if (inChar == '\n') {
      stringComplete = true;
    }
  }
}

See SerialEvent for more info.
However, as Kwasmich's comment says, you can easily circumvent this by performing your test inside a while  loop.

Does the interrupt loop check really take ~50 cycles?

Repeat your experiment by moving the loop code into a while(1) {} loop inside of setup(). That way you can eliminate the contribution of the arduino framework.

I'm trying to find the code.

SerialEvent is an optional function the user may implement in their sketch if they want. If they don't implement it then nothing gets called. It does, however, do a quick check to see if the function has been defined or not though, which takes a couple of clock cycles.

@Majenko ... thanks, I will update my answer, and upvote yours.


text:
12V dc fan motor rpm finding using tacho out
I need an Arduino program to find the RPM of a 12V DC fan motor.
I don't want to control the speed. I only want to find the speed of the motor using tacho out.

https://www.instructables.com/id/Arduino-Frequency-Counter/

How is this related to my question? Sorry i am new to this.. help me.. i wanna know only fan motor rpm

RPM is just frequency. You want to know the frequency of the pulses from the fan. The simplest way is "frequency counting" - counting the number of pulses over a defined time. Frequency = Pulses Per Second.  Pulses Per Second = Revolutions Per Second. Revolutions Per Second * 60 = Revolutions Per Minute.

do you have a fan that has a tachometer output?

Thank you buddy....

@Majenko you should flesh out your answer a little bit and post it as an answer. That way the OP can accept it and we can up-vote it. That link you posted is 90% of the way there.


text:
What is the fastest way to data to another Arduino SAMD21 boards
Hello I would be needing to transmit data from one arduino to another as fast as possible? how do I achieve this?
Since my application need a lot of pins (its a compact system so mega and due are not suitable) i am going to use 2 arduino nano 33 IOT (basically a SAMD21 uC) and one of them is just going to read from the sensors convert it to binary ( around 32-40 bits long) and send it to the other arduino.
So parameters are:

must be sent via wires
maximum number of pines used is 6
must be able to repeatedly send data ( like this is the only job the arduino does read from sensors and send it to the other one, repeatedly and endlessly)
must be reliable enough

Thank you Very much !

SPI is probably the fastest.

@Majenko Does SPI communication affect/interrupts PWM ?  because  I need to use PWM  on the "master" arduino, and the PWM must not be intterrupted

No, PWM is (unless the board is crap and uses software PWM) hardware driven and runs in the background.

what do you mean by "the board is crap"? i mean replica to the arduino boards are using the same chip and schematics as arduino right? they have the schematics on their site

I mean I am not familiar with the samd21 and how it is used for Arduino.

can't you use port expanders or multiplexers with one MCU? btw. Nano 33 IoT has two MCU connected by SPI. a SAMD21 and a ESP32

@juraj It is a custom Nano 33 , so i only have the SAMD21 left, and removed the Nina. Port expanders first time i have hear of those. Do you want to post that as an answer? Because i think it solves my problem and as a bonus making my circuit less complex

then it is a MKR Zero and not Nano 33 IoT like board

You are right, but i am following the nano 33's schematics just without the nina. I am not really sure if its the same as the zero. for example i dont have a bms.

So when looking for port expanders what should i look out for? (exempt for the number of pins)


text:
Set PWM by period? And have it variable?
In this other stack QA I'm asking about generating a pulse signal with a period ranging from 63 ms to 6.5 ms. There is a popular PWM library however it doesn't compile and also since 63 ms is 15.8 Hz, that library's integer Hz setting isn't of help.
Is there a definitive process that isn't waving incense bundles in the corners of the room? There is an over abundance of "how tos" on the internet, however, none seemed to get me to a solution.
I've got a Mega and am using TIMER5. It's "just like" TIMER1 in that it is a 16 bit timer.

I stumbled upon a solution via trial and error coupled with watching the results on an o'scope.
The best guidance came from a Stack Exchange QA. Setup isn't particularly special, however the combination of WGM bits here worked and I didn't investigate further. Of the biggest importance are the prescaler divider bits, the least three significant bits of TCCRxB. 001 means no dividing or prescaling of the clock.
It all boiled down to 4 registers and the pinMode() call. Ultimately, seven lines of code:

#define PULSE_PIN 45
void setup() {
    // IMPORTANT: Clear Timer/Counter Control Registers
    TCCR5A = 0;
    TCCR5B = 0;

    // Set Timer/Counter Control Registers
    TCCR5A = B00101001; // Phase and frequency correct PWM change at OCRA
    TCCR5B = B00010010; // least sig bits sets "carrier frequency" by dividing CPU clock
    //  Observation:
    //  TCCR5B = B00010010 and OCR5A = 16667 results in period of 16.70 mSec
    //  meaning OCR5A is period in uSec when TCCR5B = B00010010
    //  TCCR5B = B00010001 : OCR5A = 20000 results in period = 2.5 mSec 399.3Hz

    pinMode(PULSE_PIN, OUTPUT);
}

In the sketch, I watch an analog pin with a potentiometer on it and map its sweep to an effective RPM range of 950 to 9000 RPM. Hence the arbitrary range of periods I want to handle. When loop() sees the ADC change, the below code adjusts the PWM accordingly.
Note that no floating point data types are used. The magic numbers below were chosen by trial and error in a spreadsheet with values rounded to whole numbers.
void setRpm(){
    //  Getting to period in uSec from rpm the long way to keep
    //  the answer in range of the data type:
    unsigned int rpm = map(pot_adc, 0, 1023, RPM_MIN, RPM_MAX);
    unsigned long period = rpm/50;
    period = 24000/period;
    period = period*50;
    //  The trigger lasts 26°, so the PW is 26/360 * period.
    dwell = period/36;
    dwell = dwell*26;
    dwell = dwell/10;

    //  OCR5A is a counter the carrier frequency counts up to,
    //  which sets output period / frequency
    //  meaning OCR5A is period in uSec when TCCR5B = B00010010
    OCR5A = period; //  OCR5A is period in uSec when TCCR5B = B00010010
    //  OCR5B is the width of the pulse. If we used floats,
    //  we could use duty cycle * period.
    OCR5B = dwell;
}

Obviously, this code will have limitations to the range of frequencies it can handle, but the Internet has plenty of means for higher frequency PWM, especially when the desired PWM is fixed and doesn't need varying.
The most helpful way to see the control registers is as binary positions and not to rely upon macros, masks, and bit shifting. This comment block helped greatly:
 // WGM modes:
 // TCCR1A
 // Bit              7      6      5      4      3     2     1     0
 // Bit Name         COM1A1 COM1A0 COM1B1 COM1B0 ----- ----- WGM11 WGM10
 // Initial Value    0      0      0      0      0     0     0     0
 // changed to       1      1      1      1      0     0     0     1

 // TCCR1B
 // Bit            7      6      5       4        3        2        1        0
 // Bit Name       ICNC1  ICES1  -----   WGM13    WGM12    CS12     CS11     CS10
 // Initial Value  0      0      0       0        0        0        0        0
 // changed to     0      0      0       0        1        0        0        1
 // CS12,CS11,CS10 = (0,1,1) = prescaler divide by 64

I like bit-shifting in groups.  E.g. TCCR1A = (0b11 <<COM1A0) | (0b11 <<COM1B0) | (0b01 << WGM10) ; and TCCR1B = (0b11 <<WGM12)| (0b001 <<CS10) -- then the trial-and-error of flipping bits is more clear and self-documenting -- If you want to try the /64 prescaler, it's a 1 bit edit to 0b011


text:
How to detect V-SYNC on the SparkFun MicroView?
Is there a way to detect the start of the OLED screen refresh cycle (V-SYNC) on the SparkFun MicroView? There is no code for this functionality in the Arduino library; in fact it looks like the Arduino library is only set up to send data over SPI to the display, and not receive any data/status back.
Do you know how to access the internal state of the OLED screen directly, by polling some kind of status bit over SPI?
The only datasheet I can find of this OLED screen does not have SPI command details.
Update: here's a movie taken with an iPhone on "slo-mo" video, showing a full screen (all pixels on). There is clearly a screen refresh going on, which interlaces with the video frame rate.

What do you need that for? I'm not even sure "screen refresh" is a term that applies to OLED displays.

@Gerben when I photograph the screen with a fast shutter speed, it is clear that there is a periodic refresh going on. I'd like to synchronize some things with that.

The scenario you describe is called the Tear Effect. On the SSD1306, which the device you are interested in is based around, a Frame Synchronisation pulse can be emitted on the FR pin.
However it would appear that the specific SSD in use by SparkFun does not provide this pin from the SSD1306 on the external FPC connector, so there is no way of getting it.  Probably owing to the small size of the display a reduced size connector without extra pins like FR was used.
So no, you can't combat the Tear Effect with that display.
There is nothing you can do over SPI, either. That is simply because SPI is just too slow for such things. You would use the FR pin because it's instantaneous.  With SPI you would have to make a request to read a register, then read that register's value back. In that time, coupled with the question of exactly when would the register say it was at the start of a frame, the information would be completely meaningless anyway.

Thanks @Majenko, I learned a lot today. For completeness here's the SSD1306 datasheet. It turns out that this controller is write-only over SPI, so no status queries possible anyway. There is a section in the datasheet about FR synchronization (section 8.4) so maybe for the next bigger project this will be a possibility. Cheers!


text:
Running out of GPIO & looking for suggestions
I'm working on a project using a NodeMCU and am quickly running out of GPIO pins. I'm trying to decide which way to go to complete it.
Right now, I have the MCU connected to a MAX31856 PT100 thermocouple (SPI), a PWM output, a transistor (acting as a switch), a single button and a single LED. I'm needing to add at least 2 more of the MAX31856, a display (either I2C or SPI) and a rotary encoder/button.
I've looked into GPIO expanders, but I'm doubtful that the available libraries for the additional hardware will work through the expanders. I have a Mega that will work without a doubt, but then I will have issues with WiFi & MQTT. I looked at the Mega's with onboard WiFi, but I got so confused in reading how to program it, setting the DIP switches, etc that it doesn't seem like a valid choice.
Can anyone offer guidance?

MAX31856 is SPI so use an SPI display

i would move less-used interface hardware to the app to keep cost down and free up pins. i would also use i2c everything. You can use GPIO10 as an input. you can use A0 for the button. You can use GPIO3 for input and GPIO1 for output if you don't use Serial. You can use GPIO0 for the rotary encoder button, if it's never pressed on boot.

Two main solutions comes to my mind:

GPIO expander (as you mentioned). It is really easy to use them as digital inputs or outputs. So you can connect button, LED, transistor and maybe even display (you did not specified type of the display, so I assume standard LCD 1602 or 2004 display). You can also connect SPI-CS signals to the expander, but this depends on used libraries...
Auxiliary Arduino e.g. Nano. Arduino can be used for measurement of the temperature and other stuff and NodeMCU for communication. In this case you have to implement some kind of communication between these two boards (SPI, I2C or UART).


text:
Upload application from Visual Studio 2019 with PlatformIO
How upload application from Visual Studio? I can’t find upload process from standard VS in documentation https://docs.platformio.org/en/latest/ide/visualstudio.html
I hate VS Code.

Sorry but your question is far from both Arduino hardware and Arduino IDE.

I have final solution for uploading application from VS 2019.

Visual Studio have Tools > External Tools... where is possible add the PlatformIO command for uploading application pio run -v -t upload

After that is possible adding custom button to Toolbar
Fantastic thing is, that during upload you can Stop the process

I am using Visual Studio Code, but I suppose the plugin works similar in Visual Studio. Look at the screenshot below.

In red rectangle you have "Project tasks options", where you can find "Upload" button. This will not work, if you have not set at least one environment in platformio.ini file – see the documentation.
Example of the simple environment for Arduino Uno created in  platformio.ini file:
[env:uno]
platform = atmelavr
board = uno
framework = arduino

Of course, I use VS Code for Arduino, but this IDE is unworkable for my. My primary IDE for other development is full Visual Studio. There is support Resharper and many other features, that are on one place, and not in hundred extensions like in VS Code.
I hate VS Code

Ok, sorry, I missed the note about your relationship to VSCode O:-) In Visual Studio I was using Visual Micro plugin to handle Arduino boards, but I suppose that is not what you wanted to hear...

It's ok, I edited my post:) PlatformIO is OpenSource,therefore is better for hobby users than Visual Micro.
I will try PlatformIO CLI pio run -t upload. It is not what I want, but maybe it will enough.


text:
Sim800 FTP Arduino
I've been unable to FTP anything using an Arduino and SIM800L. I have reduced the code as far as possible:
#include <SoftwareSerial.h>

//Create software serial object to communicate with SIM800L
SoftwareSerial mySerial(3, 2); //SIM800L Tx & Rx is connected to Arduino #3 & #2

String moduleAnswer = "";

void setup()
{
  //Begin serial communication with Arduino and Arduino IDE (Serial Monitor)
  Serial.begin(9600);

  //Begin serial communication with Arduino and SIM800L
  mySerial.begin(9600);

  Serial.println("Initializing...");
  delay(1000);

  SoftwareATCommand("AT"); //Once the handshake test is successful, it will back to OK
  SoftwareATCommand("AT+CSQ"); //Signal quality test, value range is 0-31 , 31 is the best
  SoftwareATCommand("AT+CCID"); //Read SIM information to confirm whether the SIM is plugged
  SoftwareATCommand("AT+CREG?"); //Check whether it has registered in the network

  //APN and GRPS Setup
   SoftwareATCommand("AT+SAPBR=0,1"); //Close GPRS before connecting
   SoftwareATCommand("AT+SAPBR=3,1,\"Contype\",\"GPRS\""); //Configure bearer profile

  SoftwareATCommand("AT+SAPBR=1,1"); //Connect to GPRS

  //FTP Connection
  SoftwareATCommand("AT+FTPCID=1");
  SoftwareATCommand("AT+FTPSERV=127.189.249.205"); //Not real IP
  SoftwareATCommand("AT+FTPPORT=21");
  SoftwareATCommand("AT+FTPUN=user");
  SoftwareATCommand("AT+FTPPW=pass");

  //FTP Upload
  uploadFTP();

 }

void loop()
{
}

void uploadFTP()
{
  SoftwareATCommand("AT+FTPPUTNAME=\"test.txt\""); //Filename
  SoftwareATCommand("AT+FTPPUTPATH=/home/arduino/SolarDataLogger/"); //Path
  SoftwareATCommand("AT+FTPPUT=1"); //Start FTP
  delay(10000);
  SoftwareATCommand("AT+FTPPUT=2,100"); //Send 100 bytes of data
  delay(10000);
  SoftwareATCommand("Hello12345"); //Send Data
  SoftwareATCommand("AT+FTPPUT=2,0"); //Close FTP

}

String SoftwareATCommand(String strAT)
{

  String strNotice = "Sending: " + strAT;
  Serial.println(strNotice);
  mySerial.println(strAT);

  delay(500);
  moduleAnswer = "No Response";

  while(mySerial.available())
  {
    moduleAnswer = mySerial.readString();

    char* buf = (char*) malloc(sizeof(char)*moduleAnswer.length()+1);
    moduleAnswer.toCharArray(buf, moduleAnswer.length()+1);
    Serial.write(buf);//Forward what Software Serial received to Serial Port
     - Module answer sent to screen
    free(buf);
   }

   return moduleAnswer;
}

The serial output where the trouble is:

I've tried waiting longer for the +FTPPUT: 1,1,1360 response or sending something twice, but nothing seems to work. The file gets created but no other data is ever sent.

Maybe its too late to respond but the line +FTPPUT: 1,65 indicates a server error.
https://www.elecrow.com/wiki/images/2/20/SIM800_Series_AT_Command_Manual_V1.09.pdf - page 275.
Please check a sequence of commands , maybe something is missing ?
I use the following sequence :
"AT+CREG?"
"AT+SAPBR=3,1,\"Contype\",\"GPRS\""
"AT+SAPBR=3,1,\"APN\",\"NAME OF YOUR PROVIDER \""
"AT+SAPBR=1,1"
"AT+SAPBR=2,1"
"AT+FTPCID=1"
"AT+FTPSERV=\"SERVER ADDRESS\""
"AT+FTPPORT=21"
"AT+FTPTYPE=\"I\""
"AT+FTPUN=\"USERNAME\""
"AT+FTPPW=\"PASSWORD\""
"AT+FTPPUTNAME=\"" + NAME OF FILE + "\""
"AT+FTPPUT=1"
"AT+FTPPUT=2," + STRING OF BUFFER SPACE ( Get from response of FTPPUT=1 )
"AT+FTPPUT=2,0"

Look on the manual for the commands above.
Sorry about my grammar

Thanks for the input. I posted this after moving to a Pi instead for anybody else that might run into the same issue and I think your input will be useful to someone.

what I observed in your code-I think you did not follow the proper sequence of connecting the GPRS context mentioned in the sim800l datasheet.
Please follow the section 3.1. bearer configuration. I also attached the screenshot herewith. So you missed setting the Access Point Name(APN). After you query the GPRS context(last step in the image), if you get the proper IP address, then you are sure to send the data over FTP. Please follow the FTP sequence mentioned in the datasheet.


text:
How to Work Two Linear Actuator Synchronously by Using Arduino and VNH5019 Motor Driver?
I am newbie and I want to build a project that contains two linear actuator that move synchronously. Two of them will lift up and down at same time. I use arduino mega and VNH5019 motor driver. I have thompson electrac ELD linear actuator. I have never tried to synchronize two linear actuator. Linear actuator have encoder output ( it is hall effect encoder -( not absolute. So it cannot keep last position in case of power cut )). Encoder type is hall effect type. Encoder output voltage levels low (logical zero), typical / max is 0.1/0.25 Vdc. Also it has output fully extented/retracted signal. I tested it with H-Bridge motor driver made of 4 SSR relays and push button switches to retract and extract. There is a synchronization problem.The system will stop when actuators extracted 500 mm ( actuators have 900 mm stroke length) How should I solve that synchronozation problem could you help me ? What should I do?

It sounds like you need to watch both encoder outputs and don't let one get ahead of the other. Naturally, they won't sync exactly (i.e., pulse simultaneously) but you can set a limit on how many counts to let them differ by, before pausing the faster actuator while the slower one catches up.
If you need to save positions across a power failure, you'll need to 1) provide enough backup power to keep the system alive past the supply failure to give you time to stop both actuators and store both of their positions in EEPROM; and 2) provide a signal to the Arduino that the supplied power (not the backup) is going down, so it can begin its orderly shutdown.


text:
Charge lipo battery while using
I have a system that uses Arduino and some modules. The system needs 5v dc power with 3A current at maximum(The system needs 3A current for some seconds every 5 minutes and after that the current will get back to 300-400mA) and on the other side i have a 5v dc charger with 400-500 mA current. So my problem is lack of amperage and i can't run correctly Arduino with 5v dc charger. For solving this problem i want to use a Lipo battery to connect to Arduino but the battery will ran out and i can't get energy from battery so i want to connect the battery to my charger while the Arduino uses the battery, How can i do that? Is there any module to do this work? Can i use TP4056 with protection version to do this work?(Note: I can't change charger)

You really shouldn't charge a lithium battery whilst discharging it. The charger may either never know that it has finished charging and overcharge it, or shut off early and never charge it up properly at all.
Instead you should arrange that your MCU is powered directly from the PSU so that it always has stable power, and feed that same power into a normal charger via some form of electronic switch so it can be turned on and off. The output of the battery can then be fed through another switch into your heavy load.
When it comes time for your load to be activated you switch off the power from the charger and switch on the connection from the battery to the load.
What you use to do the switching is entirely up to you - whether you choose P-channel MOSFETs or relays entirely depends on your situation.
Here's a block diagram to better illustrate it to you:

simulate this circuit – Schematic created using CircuitLab

If i can't charge while discharging so what is load-sharing battery charger circuit(like this https://learn.adafruit.com/adafruit-powerboost-1000c-load-share-usb-charge-boost)?

That is one which will pass the incoming power across to the load when charging (so the incoming power goes to both charging the battery and powering the load) and then switches to the battery to power the load when the incoming power is removed.

Can i use this circuit (https://www.amazon.in/CentIoT-TP4056-lithium-Charging-Protection/dp/B01MV1FAQP)?

That circuit is the single box in the diagram above called "Charger". It is up to you to provide the rest of the circuit.

I think this circuit has battery output and you can use while charging you can see in this video (https://www.youtube.com/watch?v=Qw4psECqpwI).

The critical thing with those circuits is the output current is not from the battery when there is a supply being fed to it. If you feed 400mA you will never be able to exceed 400mA. You don't draw any power from the battery when charging. Ever. It will not do what you want without all the additional components detailed in the block diagram in my answer.


text:
SparkFun BasicAHRS_I2C giving unstable readings
SparkFun BasicAHRS_I2C giving unstable readings.
I am using the SparkFun Arduino Sketch from here.
It is giving me these results:
X-acceleration: 91.43 mg Y-acceleration: 249.51 mg Z-acceleration: 1042.05 mg
X-gyro rate: -0.549 degrees/sec Y-gyro rate: 0.557 degrees/sec Z-gyro rate: 1.595 degrees/sec
X-mag field: -164.35 mG Y-mag field: -240.16 mG Z-mag field: -20.73 mG
Temperature is 27.9 degrees C

and then the next result (when MPU9250 is still) is:
X-acceleration: 91.49 mg Y-acceleration: 252.75 mg Z-acceleration: 1039.49 mg
X-gyro rate: -0.076 degrees/sec Y-gyro rate: -0.130 degrees/sec Z-gyro rate: -0.008 degrees/sec
X-mag field: -175.07 mG Y-mag field: -222.24 mG Z-mag field: -27.64 mG
Temperature is 27.9 degrees C

Notice how the temperature has remained constant, acceleration has remained constant (although im not why there is a reading if the MPU9250 is stationary) and the mag field is fairly close. However, the Gyro values are not close.
Could I have a bad MPU9250?
I am using the Mega.
Edit: Added a complementary filter from here, however they have not added a comp filter for the z value as can be seen from my screenshot of the serial monitor:

I think this is because they have the MPU6050 and not the MPU9250. I believe the MPU9250 has the magnetometer which can be used to 'help' the drift?
How could I use the magnetometer to help counter the drift?
End goal: rotate a gameobject in unity with the MPU9250 with minimal drift and maximum accuracy.

Have you tried posting a question to SparkFun's customer service department?

If you haven’t noticed the difference in the two is minuscule.
For example, the change in degree is <1. Also the acceleration is measured in g’s which is acceleration due to gravity. The data says the measures are in mg which is 0.01g.
This is normal with accelerometers and all sensors when they pick up residual voltage from random vibrations or other sources of noise. It also could be with the error margin within SparkFun’s product since the product is more on the lower end of quality which once again is normal.
TLDR: everything is working fine.

When I use them values in Unity, the object rotates fast almost as if its random.

The values seem fine to me. Generally these MPU chips are really noisy, that is totally normal. Ti really use the data to the the current orientation, you have to use a filter to combine the data from accelerometer and gyroscope.
There are multiple possible filters, that can help. The easiest one to implement is a Complementary filter. It gives you pretty good results. You should be able to find corresponding tutorials on the web.

The code from your link does not use a complementary filter for the z axis. In the comment it says, that the accelerometer doesn't provide z angle data, and that is correct. Since gravity always goes down, you cannot distinguish the angles around that axis.
But - as you already stated - you can use the magnetometers data for this. But you will need the inclination angle of the earths magnetic field (the angle between ground and field vector).  You can google the inclination angle for your place and use it as constant. But most likely you will want to use the device inside of buildings. The magnetic field can be very disturbed there due to much steel nearby. Thus it is better to do a calibration step before use, while the device lies flat on the ground.
When you have calculated the angle around the z axis from the magnetometer data, you can use it in a complementary filter, like it was done in the linked code with the accelerometer data.
Note: Due to all the steel, the inclination angle does not have to be constant, when moving around in a building. So this is better for use inside a small space range.

When I use them gyro values to rate an object in Unity it moves so much as if it is random.

Then you are doing something wrong in your unity game. With that rate from the gyro a full rotation would need about 360 seconds (well over 5min). At least not so fast, that is is random. Please don't use the unity game to test the accelerometer. Instead you should watch the values directy on the serial monitor, to see, how they behave. With a complementary filter you get the absolute orientation. Do this on the arduino, output the calculated orientation, and check, this these values are good over th serial monitor

The above values are from the serial monitor however I haven’t calculated the absolute orientation with the serial monitor.

The above values don't correspond with rapid movement. Try the complementary filter

@Jordan Savage  I added a small explanation about using the magnetometer.

Thank you for the informative edit. My inclination angle constant is 66.31 deg, on this website here: http://autoquad.org/wiki/wiki/configuring-autoquad-flightcontroller/autoquad-calibrations/calibration-faq/magnetic-declination-and-inclination/ it states to make a sign change. From your edit: "calculated the angle around the z axis from the magnetometer data", is this angle the 66.31 deg that the website above is telling me for my location?

"You can use it in a complementary filter" how could I do this? I have the Z mag value (with calibration) and I have my local magnetic inclination angle. How would I use these values in the complementary filter as it is now the magnetometer and not the accelerometer?

@Jordan Savage I think you need to calculate the angle around the gravity angle by taking the magnetic field vector, using only the components perpendicular to the gravity direction and calculating the difference between this vector and the standard/calibration angle. I've not really wrapped my head around the exact calculations. Maybe it will help, when you draw the geometrical setup. I currently don't have time to do so. When you have the angle, you can simply use it instead of the accelerometer angle, like in the calculations for the other components.


text:
Possible to put the ESP8266 in bootloader mode without a FTDI?
I am trying to upload something directly to the ESP8266 using the ESP8266 IDE.
I have configured the ESP8266 to communicate at 9600 using UART_DEF and I have set the ESP8266 IDE at 9600. I see some tutorials that say to use a FTDI but I only have a Serial to TTL cable (note it even says at the bottom that it's not good for Arduinos :( ) and  am making the following connections:

ESP8266 RX - TTL cable TX
ESP8266 TX - TTL cable RX
ESP8266 GND - common GND
ESP8266 VCC - External 3.3V
GND from External 3.3V - common GND
ESP8266 GPI0 (through a 10k resistor) - common GND
ESP8266 GPI2 (through a 10k resistor) - External 3.3V
EPS8266 CH_PD - External 3.3V (sorry, that was wrong before)

However, when I upload that sketch I get an error that the board cannot be found. I have read online that the ESP has some bootloader mode that needs to be activated but haven't found great instructions on how to do that. Any advice would be appreciated.
FYI I also have an Uno if that is any help. I have communicated with the ESP8266 through the Uno before (connecting the Uno reset to ground) .

wire io 0 to gnd without resistor for the moment of esp8266 startup. esp8266 is put into flashing mode with io 0 LOW at startup. but the module can have a pull-up on io 0 to start normally.

AT firmware UART baud rate has nothing to do with bootloading baud rate. bootloader detects the baud rate

Connecting CH_PD to ground turns off the ESP8266.

The cable you point to is fine for programming the ESP8266. The only reason it's not "good" for an Arduino is the lack of a DTR signal to trigger a reset for you - which you can do manually anyway and still use it for an Arduino (if your reactions are fast enough).
You have no such problem with the ESP8266. Once you have it in bootloader mode it stays in bootloader mode until you tell it to exit bootloader mode.
First make sure that the ESP8266 is actually set up to run properly. That means:

Connect CH_PD to 3.3V, not GND, through a pull-up resistor.
Connect GPIO0 to 3.3V via a pull-up resistor.
Connect RST to 3.3V via a pull-up resistor.

Then for simplicity of programming:

Connect a button between RST and GND
Connect a button between GPIO0 and GND

To enter bootloader mode simply hold the GPIO0 button in, tap the RST button, then release the GPIO0 button.  When you have successfully uploaded your firmware just tap the RST button to exit bootloader mode.
ESP8266 boards with a built-in USB interface usually use both the DTR and the RTS pins to control both those buttons virtually. That's somewhat complex to arrange for an external USB to TTL UART adaptor, so it's simpler to just press the buttons manually.

Here's a link to a website that details the circuit and operation using an ESP-01 as an example.

the new esp-01S modules have a pull-up on io 0 and CH-PD wired to Vcc 'on board'

@Juraj Indeed they do - however the OP never mentioned which ESP8266 module (if any) they are using.

Wow this is a great start! It's still not working for me. I am using a lower resistor on the CH_PD and GPIO2 - VCC connection (500 Ohms) could that be a reason? Here is a picture of my setup if that's any help...https://imgur.com/a/miZuQN9

It's no help at all. All I see is a bundle of meaningless wires. Not even an ESP8266 in there. What module are you using?

According to this site, I think I have ESP8266-01 but I am not really sure how to check just from looking at it. https://www.esp8266.com/wiki/doku.php?id=esp8266-module-family

The ESP-01 is the plugin module with the 2x4 pins on one end. That's what you have, correct?

Grab yourself one of these: https://www.ebay.co.uk/itm/322466871464 - or something similar. Make sure it's one with the switch on it for switching between programming and normal running mode.

Yes, I have the 2x4 pins. So it's not possible to program the ESP8266-01 without one of those?

It is possible - as long as you follow the instructions properly. That adaptor just makes things a lot easier - no wires to mess with. I have three of them ;)

Yeah, I still haven't been able to get it to work. The closest I got was by doing everything you wrote up above but unplugging GPIO2, then at least it starts uploading and says Writing at 0x00000000... (8 %)Traceback (most recent call last):..but then I get 'File "C:/Users/nickc/AppData/Local/Arduino15/packages/esp8266/hardware/esp8266/2.5.2/tools/pyserial\serial\serialwin32.py", line 323, in write
raise writeTimeoutError'

Update: miracle of miracles, it works! Thanks for your help. What I had to do was 1) unpower/repower the ESP8266 before going through the bootload sequence and 2) set the IDE BUILTIN LED to pin 1, then it worked!


text:
arithmetic operation outcome differs from the expected outcome
I am writing a function
void Sound_Play(int frequency,int millisec)

A part of this function is:
  counting=(millisec*frequency/1000);  //counting is type int
  Serial.println((String)"millisec="+millisec+" frequency="+frequency+" (millisec*frequency/1000)="+(millisec*frequency/1000)+" counting set to="+counting);

But when I call the function with millisec=500 and frequency=220, the result on the Serial Monitor is:
millisec=500 frequency=220 (millisec*frequency/1000)=-21 counting set to=-21

Shouldn't counting should be 110 instead.I tried casting the result to int but in vain. What am I doing wrong and how to correct it?
Thanks!
Bhuvnesh

Once again an example to Why should I learn C/C++ first before learning Arduino.
The main point here is: know your data types.
Your calculation millisec*frequency/1000 would work if it was a compile time constant that is evaluated by the pre processor. In any other case this is a runtime value and so the limitations of the datatype apply.
Unless stated otherwise I assume your variables millisec, frequency and counting are of type int. int has a platform specific width. On Arduino this is 16-bit. (Other platforms have other widths)
It is also signed, that is why it can hold values between -32768 and 32767.
You calculation millisec*frequency evaluates to 500 * 220 = 110000 which is many times larger than the value that can be represented.
You can do two things:

Use long which is 32-bit on Arduino. But actually I'd prefer to use a type with an obvious width. As you don't seem to need negative values I'd prefer uint32_t.
If milliseconds is a constant, you can make it smarter by reducing your calculation to a division by two (or better a single right shift).

Thankyou for your Answer. I was a bit distracted could not see the fact that you mentioned. Changing millisec and frequency to type long solved the issue

You forgot the negative  sign in the range for int. Otherwise great answer. Upvote


text:
Why sometimes parsed data is null in WiFiEsp?
I'm setting up web server with args. As host.com/?pin=9. I parsed the response by indexOf and substring functions. In first connection response has been successfully
parsed and  number has been parsed too. But in second connection it is null. Why I don't know.
And sometimes it writes TIMEOUT: 25/625 and m.
code:
/*
 WiFiEsp example: WebServer

 A simple web server that shows the value of the analog input
 pins via a web page using an ESP8266 module.
 This sketch will print the IP address of your ESP8266 module (once connected)
 to the Serial monitor. From there, you can open that address in a web browser
 to display the web page.
 The web page will be automatically refreshed each 20 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
String response = "";
char ssid[] = Twix";            // your network SSID (name)
char pass[] = "123456789";         // your network password
int status = WL_IDLE_STATUS;     // the Wifi radio's status
int reqCount = 0;                // number of requests received

WiFiEspServer server(5000);

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();

  // start the web server on port 80
  server.begin();
}

void loop()
{
  // listen for incoming clients
  WiFiEspClient client = server.available();
  if (client) {
    Serial.println("New client");
    // an http request ends with a blank line
    boolean currentLineIsBlank = true;
    while (client.connected()) {
      if (client.available()) {

        char c = client.read();

        Serial.write(c);
        response += c;

        // if you've gotten to the end of the line (received a newline
        // character) and the line is blank, the http request has ended,
        // so you can send a reply
        if (c == '\n' && currentLineIsBlank) {
          Serial.println("Sending response");
                  int f= response.indexOf("turnon")+11;
        int s = f+2;
        String sh = response.substring(f,s);
        int pin = sh.toInt();
      if(pin !=0){
       pinMode(sh.toInt(),OUTPUT);
      digitalWrite(sh.toInt(),HIGH);
      }
          // send a standard http response header
          // use \r\n instead of many println statements to speedup data send
          client.print(
            "HTTP/1.1 200 OK\r\n"
            "Content-Type: text/html\r\n"
            "Connection: close\r\n"  // the connection will be closed after completion of the response
                  // refresh the page automatically every 20 sec
            "\r\n");

          client.print("<!DOCTYPE HTML>\r\n");
          client.print("\r\n");
          client.print("
Hello World!
\r\n");
          client.print("Requests received: ");
          client.print(++reqCount);
          client.print("
\r\n");
          client.print("Analog input A0: ");
          client.print(analogRead(0));
          client.print("
\r\n");
          client.print("
\r\n");
          client.print("pin is: ");
          client.print(sh);
          client.print("
\r\n");
          client.print("\r\n");
          break;
        }
        if (c == '\n') {
          // you're starting a new line
          currentLineIsBlank = true;
        }
        else if (c != '\r') {
          // you've gotten a character on the current line
          currentLineIsBlank = false;
        }
      }
    }
    // give the web browser time to receive the data
    delay(10);

    // close the connection:
    client.stop();
    Serial.println("Client disconnected");
  }
}

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 where to go in the browser
  Serial.println();
  Serial.print("To see this page in action, open a browser to http://");
  Serial.println(ip);
  Serial.println();
}

you call the variable for storing the request response?

Yeah. I'm crazy

I have got only 2.0.0 and 3.0.0 SDK Version.

I can use it with 2.0.0 SDK?

AT firmware? OR SDK?

OK..............

It ssays Communication wih module failed

Let us continue this discussion in chat.

if hit from a browser, favicon.ico will also be requested, without any query params.

Yes it requested.

But I created Telnet server it says me TIMEOUT too.


text:
I think I just bricked my Arduino. Any ideas how?
I think I have a short circuit in my Arduino Uno R3. The symptoms are:

It does not seem to be responding as before.
The orange "L" LED does not blink on boot-up, but just stays on continuously.
If I plug in a 12V source, then the voltage between the 5V and GND pins starts out around 5V, but then starts dropping rapidly. In the meantime, the underside of the board heats up a lot. If I plug in the USB source, the voltage between the 5V and GND pins stabilizes at around 4.28V ... but again, nothing seems to work.
After all this, I also checked continuity between the 5V and GND pins, and heard a beep. However, subsequent reading told me that this is not a reliable (or well-advised) test.

It seems like I have a short on my Arduino, right?  Any idea of how this could have happened?  I can only think of the following possibilities:

I was running the Arduino off a lead-acid 12V battery. At some point, the negative terminal wire disconnected and there was some sparking at the battery when I reconnected it (the pattery was also powering other things). Could this have damaged the Arduino?
I am using the Arduino to run 3 IR LED . To minimize wiring, I had wires these LED in series, rather than in parallel, which (at least at first) seemed to work. Is there any possibility this would have damaged it?

Thanks for any help.

Did these 3x IR LEDs have current limiting resistors?

Yes, there was one resistor in series with them.

the pattery was also powering other things - what other things?

A couple of video projectors, drawing about 4.5 amps total.

See my answer here. A 12V battery doesn't necessarily provide you with 12V any more than a 1.5V battery provides 1.5V.
See here for example. A 12V lead-acid battery may well provide 12.7V which is out of spec for the Uno.
See the page about the Uno.
You have too much voltage going into the voltage regulator, it tries to dissipate it, it gets hot and either shuts down or fails.
I suggested in the answer above to use a buck converter to down-convert the voltage, and my answer (which was accepted) said that "it is working like butter".

"Working like butter" is an idiom I have never come across before. How does butter work?

Smoothly. Like butter spreading on a nice warm piece of toast, where you have the marmalade ready to go on top. :)

I don't eat toast... too many carbs...

https://www.urbandictionary.com/define.php?term=like%20butter

The voltage limits for the Arduino are 6-20V. I know that 12V is max "recommended" but I thought the issue was heating (I'm running very few watts through the things, so I don't think it should be an issue normally).

See my answer about have I bricked my Arduino.

@NickGammon Thanks for the pointer to your other answer -- that is a great resource! I will keep in mind those diagnostics, though probably I won't use them now as my Arduino seems so obviously toast (L light doesn't blink, just starts getting hot when plugged into either 12V or USB power, etc.)

Nonetheless, I am still confused by the situation I encountered. All specs I have found for Arduino Uno R3 say 20V is the max (not 12V), and I previously ran it without problems for many hours off the Lead Acid battery. I'm trying to understand what happened. I suspect there might have been a large voltage spike when connecting to the battery, but I don't know if that something that actually happens. In any case, when rebuilding I will definitely add a buck converter .

If I plug in a 12V source, then the voltage between the 5V and GND pins starts out around 5V, but then starts dropping rapidly. In the meantime, the underside of the board heats up a lot. If I plug in the USB source, the voltage between the 5V and GND pins stabilizes at around 4.28V ... but again, nothing seems to work.

That sounds like the LDO is overheating and going into thermal shutdown.

After all this, I also checked continuity between the 5V and GND pins, and heard a beep. However, subsequent reading told me that this is not a reliable (or well-advised) test.

If it's just a brief "pip" then it's just a capacitor charging or discharging. To qualify as a short it has to be a continuous "beeeeeeeeeeeeeeeeeeeeeee".

I was running the Arduino off a lead-acid 12V battery. At some point, the negative terminal wire disconnected and there was some sparking at the battery when I reconnected it (the pattery was also powering other things). Could this have damaged the Arduino?

It sure could. If other things are connected both to the battery -ve and the Arduino then the power could have passed through the Arduino in many strange ways killing things internally.
Chances are it's dead, yes. It may just be the main MCU which (if it's a DIP version) you could pop off and replace (with one with the bootloader already installed). But there's no guarantee it's only that chip that's gone. The USB chips are also a common failure point, especially the cheap Chinese CH340G.
In the long run it's safer just to replace the entire board unless you've got plenty of spare components and the skills to diagnose and replace them as needed.

Thanks! It was definitely beeeeeeeeeeeeeeee-type continuity. Can you elaborate "If other things are connected both to the battery -ve and the Arduino then the power could have passed through the Arduino in many strange ways killing things internally."? I have a large 12V battery powering the Arduino, plus some projectors (drawing about 5 amps) which run running through a relay on the Arduino. Is this a dangerous setup?

It sounds safe enough, but without seeing a full schematic I can't really say for sure.

If you have the Arduino connected to ground but not 5V, but other things are connected to 5V, then power can be fed into GPIO lines on the unpowered Arduino, whicih is bad. Similarly, when you did connect the battery and saw a spark you might have sent a spike into places a spike should not go. (Which is pretty much everywhere. The voltage regulator is only designed for 12V max, if memory serves, so pushing more than that into it might have fried it.)

Thanks for the suggestions. The voltage regulator is designed for 20V max. Is there a voltage spike that occurs when a battery sparks?


text:
Serial throughput using AltSoftSerial on Arduino
My project involves a commercially available device that can be remotely controlled by a computer over RS232. I'd like to put an Arduino Pro Mini, which has a second serial port provided by the AltSoftSerial Library, between the device and the computer. One of the Arduino's serial ports will connect to the device under control, and the other will connect to the computer. One function of the Arduino will be to simply read incoming data on one port and immediately write it to the other port. I'm not yet sure how heavy the serial traffic will be, although my early impression is that it will come from sporadic, user-initiated commands and resulting responses.
Assuming all baud, stop bit, data bits and parity are configured correctly, is what I'm proposing possible with the AltSoftSerial Library? Is it likely that this approach will introduce delays and/or errors that are prohibitive?

That would depend on unspecified details.  There are plenty of cheap MCUs with two hardware UARTs or a UART and USB you can use as a proxy to present another virtual one to a PC if the timing is sufficiently loose.

Did you consider Arduino mega? It has more than 1 true hardware UART which means there is no software involved in transmission and reception. Otherwise, you have to go with the best software library to simulate the second serial port. All depends on what you want to achieve which is still not clearly mentioned in the question