body:
In my project, I have to read the input pin number(send by RPi), where 8 sensors are attached to Arduino Nano, after reading Arduino Nano send the real-time values of all sensors through serial USB communication. All is fine, but my problem is that I need to speed up the sending of data since it takes to long to read from Rasberry pi.
I put the delay of 70 milliseconds but if I try to reduce more than that, I encounter a problem i.e data overwrites. My baud rate is 115200.
Kindly help me with the code to make it fast.
```
int analogInputPin;
float voltage;

void setup() {
  // initialize serial communications at 9600 bps:
  Serial.begin(115200);
}

void loop() {
  // if any data on the serial port are available
  // read it and try to update the analogInputPin
  // based on the number that was read on the serial
  if (Serial.available() > 0) {
    analogInputPin = Serial.parseInt();
  }

  // read the analog value:
  int analogInputPinValue = analogRead(analogInputPin);
  voltage=(5./1023.)*analogInputPinValue;

  // print the results to the serial port:
  // the output should have the following form: INPUTPIN:VALUE
  // followed by a newline character
  Serial.print(analogInputPin);
  Serial.print(":");
  Serial.print(voltage);
  Serial.println("");

  // wait 50 milliseconds before the next loop
  delay(50);
}
```

title: to increase the reading and writing/printing speed of data from Arduino Nano to Raspberry Pi 3B+

Answers: 1

body:
`parseInt` reads digits and stops after a non-digit characters occurs or the function times out because no next characters arrives. The timeout is at default 1 second. So this is where you loose time.

Simplest solution for your code is to send some non-digit character after the number sent from Raspberry. This will terminate parseInt immediately. Usual is to send a new line character. It will separate the numbers nice if you debug the communication with prints to serial terminal.

Not a very good option, but I mention it, is to set the timeout of blocking read functions like the `parseInt` to a smaller time with `Serial.setTimeout(ms)`.

To really speed up the communication you would send the numbers in binary form and not as text like you do now.


body:
Sometime I write Arduino code on a slow Windows laptop that I use for controlling hardware projects and 3D printing.

My main Windows computer and also my Linux home server are located somewhere else but are much faster and I would like to use those for compilation.

Remote Desktop or equivalent are not practical due to different screen resolutions. Also, my main Windows machine is not always on, only the server is, but it has no GUI installed.

The sources are already located on a shared network folder and I use an external editor for the code. Arduino IDE just does compilation and sometimes upload (which often I could do via OTA).

How to delegate compilation of Arduino projects to a remote machine?

title: How to delegate code compilation to a remote machine?

Answers: 1

body:
If you don't have a GUI, you can still compile and upload sketches by using the [Arduino CLI][1]. With it you can do most things, that you can do with the Arduino IDE. I'm using this myself to upload new code to a Nano, that is connected to a Raspberry Pi in a project in use.

You can connect via ssh to the remote server and let it compile/upload the sketch. I wrote a simple bash script to first copy the source to the server (since you are using a network share, this is not necessary for you) and invoke the compilation and upload.

Note: Before you can actually compile with the Arduino CLI, you have to download the correct core for your chip. This is described in the README of the linked github project.

  [1]: https://github.com/arduino/arduino-cli


body:
I would like to connect a CO2 sensor to the Wemos D1. I would like it to work via UART (RX, TX) and not the PWM pin. I've encountered numerous libraries on Github, but I can't seem to get it working. I've connected the following things:

[![enter image description here][1]][1]

I've tried a lot of snippets from all over the internet, and a lot of libraries on Github, but I can't seem to get it working. For the sake of this question, I am going to use this [advanced library][2].

This is my code:

    #include <Arduino.h>
    #include "MHZ19.h"                                         // include main library
    #include <SoftwareSerial.h>                                // Remove if using HardwareSerial or non-uno library compatable device

    #define RX_PIN D1                                          // Rx pin which the MHZ19 Tx pin is attached to
    #define TX_PIN D2                                          // Tx pin which the MHZ19 Rx pin is attached to
    #define BAUDRATE 9600                                      // Native to the sensor (do not change)

    MHZ19 myMHZ19;                                             // Constructor for MH-Z19 class
    SoftwareSerial mySerial(RX_PIN, TX_PIN);                   // Uno example
    //HardwareSerial mySerial(1);                              // ESP32 Example

    unsigned long getDataTimer = 0;                             // Variable to store timer interval

    void setup()
    {
        Serial.begin(9600);                                     // For ESP32 baudarte is 115200 etc.
        mySerial.begin(BAUDRATE);                               // Uno example: Begin Stream with MHZ19 baudrate
        //mySerial.begin(BAUDRATE, SERIAL_8N1, RX_PIN, TX_PIN); // ESP32 Example
        myMHZ19.begin(mySerial);                                // *Important, Pass your Stream reference
        myMHZ19.autoCalibration();                              // Turn auto calibration ON (disable with autoCalibration(false))
    }

    void loop(){
        if (millis() - getDataTimer >= 2000)                    // Check if interval has elapsed (non-blocking delay() equivilant)
        {
            int CO2;                                            // Buffer for CO2

            /* note: getCO2() default is command "CO2 Unlimited". This returns the correct CO2 reading even
            if below background CO2 levels or above range (useful to validate sensor). You can use the
            usual documented command with getCO2(false) */

            CO2 = myMHZ19.getCO2();                             // Request CO2 (as ppm)
            Serial.print("CO2 (ppm): ");
            Serial.println(CO2);

            int8_t Temp;                                         // Buffer for temperature
            Temp = myMHZ19.getTemperature();                     // Request Temperature (as Celsius)
            Serial.print("Temperature (C): ");
            Serial.println(Temp);

            getDataTimer = millis();                            // Update interval
        }
    }

I am constantly getting this:

```
19:39:59.750 -> !Error: Timed out waiting for response
19:39:59.784 -> !ERROR: Failed to verify connection(1) to sensor. Failed to stablise
19:39:59.853 -> !ERROR: Initial communication errorCode recieved
19:40:00.272 -> !Error: Timed out waiting for response
19:40:00.758 -> !Error: Timed out waiting for response
19:40:00.792 -> CO2 (ppm): 0
19:40:01.280 -> !Error: Timed out waiting for response
19:40:01.315 -> Temperature (C): -17
```

Am I connecting something wrong or what am I doing wrong?

**EDIT:**
Version using only the serial instead of library that also doesn't work:

```
#include <SoftwareSerial.h>
SoftwareSerial co2Serial(3, 1);
unsigned long startTime = millis();

void setup() {
  Serial.begin(9600);
  co2Serial.begin(9600);
  pinMode(9, INPUT);
}

void loop() {
  Serial.println("------------------------------");
  Serial.print("Time from start: ");
  Serial.print((millis() - startTime) / 1000);
  Serial.println(" s");
  int ppm_uart = readCO2UART();
  delay(5000);
}

int readCO2UART(){
  byte cmd[9] = {0xFF,0x01,0x86,0x00,0x00,0x00,0x00,0x00,0x79};
  byte response[9]; // for answer

  Serial.println("Sending CO2 request...");
  co2Serial.write(cmd, 9); //request PPM CO2

  // clear the buffer
  memset(response, 0, 9);
  int i = 0;
  while (co2Serial.available() == 0) {
    Serial.print("Waiting for response ");
    Serial.print(i);
    Serial.println(" s");
    delay(1000);
    i++;
  }

  if (co2Serial.available() > 0) {
      co2Serial.readBytes(response, 9);
  }

  // print out the response in hexa
  for (int i = 0; i < 9; i++) {
    Serial.print(String(response[i], HEX));
    Serial.print("   ");
  }
  Serial.println("");

  // checksum
  byte check = getCheckSum(response);
  if (response[8] != check) {
    Serial.println("Checksum not OK!");
    Serial.print("Received: ");
    Serial.println(response[8]);
    Serial.print("Should be: ");
    Serial.println(check);
  }

  // ppm
  int ppm_uart = 256 * (int)response[2] + response[3];
  Serial.print("PPM UART: ");
  Serial.println(ppm_uart);

  // temp
  byte temp = response[4] - 40;
  Serial.print("Temperature? ");
  Serial.println(temp);

  // status
  byte status = response[5];
  Serial.print("Status? ");
  Serial.println(status);
  if (status == 0x40) {
    Serial.println("Status OK");
  }

  return ppm_uart;
}

byte getCheckSum(byte *packet) {
  byte i;
  unsigned char checksum = 0;
  for (i = 1; i < 8; i++) {
    checksum += packet[i];
  }
  checksum = 0xff - checksum;
  checksum += 1;
  return checksum;
}
```

  [1]: https://i.stack.imgur.com/kpCD2.png
  [2]: https://github.com/WifWaf/MH-Z19

title: Wemos D1 won't work with MH-Z19B (CO2 sensor)

Answers: 1

body:
I know it is rather late to respond. What worked for me working with a *WEMOS D1 mini* and  the *MH-Z19C* was reassigning the Software Pins used *SoftwareSerial co2Serial(D1, D2);*
In that case the second sketch posted works atleast for me.

The problem might be that the ESP8266 uses the hardware serial lines for connection to the USB-to-Serial bridge (usually a CH340 or CP2102 in most designs) which means you might encounter problems if you want to use the same serial line for more than one device.


body:
**Function**

    char* getConnectDetail(int starting){
      String data;
      for(int i=0;i< 1024 ;i++) {
        if(EEPROM.read(i+starting) != 0){
        data += char(EEPROM.read(i+starting));
        }
       }

       int str_len = data.length() + 1;
      char char_array[str_len];
      data.toCharArray(char_array, str_len);
      return char_array;
    }
When I call it I get the garbage value... without creating the function there isn't any error.. Kindly solve it.
I just want to know whats wrong with my returning method.

title: How to return Char Array Value in Arduino IDE Function?

Answers: 1

body:
`char char_array[str_len];` is local to the function - it is created on function entry and its memory is released on function exit. The contents of that memory are undefined once it has been released and its data may or may not be valid.

If the caller creates `data` and passes it to the function, it survives the entire function call-and-return, and the caller will find the correct data in it. Another (less elegant) way to do it is to make `data` a global object, which again, gives it a lifetime greater that that of the function, but globals are subject to accidental over-writes and abuse by other functions, so they are not recommended unless they are truly the best solution in a given situation.


body:
I am trying to write to serial to control the brightness of an LED. When I initially type in a value such as '50' or '100', the LED lights up, but then the 'ppm' value drops down to '10' and just stays there (regardless of what I enter in initially. **Any idea why this is occurring?**
<!-- language-all: lang-cpp -->
```
int ledpin1 = 3;
int pwm = 0;

void setup() {
  // initialize serial communication at 9600 bits per second:
  Serial.begin(9600);
  pinMode(ledpin1, OUTPUT);
}

// the loop routine runs over and over again forever:
void loop() {
  // reads input to serial monitor
  if (Serial.available() > 0) {
    pwm = Serial.read();
  }

  analogWrite(ledpin1, pwm);
  Serial.print("PWM value is: ");
  Serial.println(pwm);
  delay(1000);

}
```

title: Why Won't my Serial Read value stay the same

Answers: 1

body:
When you type "100" you aren't sending the number 100. You're sending the characters "1", "0", "0", and whatever selected line ending you have (CR, LF, or CR and LF).

So if you have CR+LF for your line ending you're reading the numbers 49, 48, 48, 13 then 10.

You need to read the characters as they arrive and group them into a representation of the number (up until you get the line ending), then convert that representation into an actual number.

* [Reading Serial on the Arduino](https://majenko.co.uk/blog/reading-serial-arduino)


body:
> I use sfm-27 dc 3-24v Buzzer. It sounds fine if i close the buzzer using my palm but if i doesn't close it, it will make a screeching noise. I play melody using the buzzer so the sound is important. This is the code that i use.

        const int buzzer = 4; //Define pin 13, can use other PWM pins  (5,6 or 9)
                           //Note pins 3 and 11 can't be used when using the tone function in Arduino Uno
    const int songspeed = 1.5; //Change to 2 for a slower version of the song, the bigger the number the slower the song
    //*****************************************
    #define NOTE_C4  262   //Defining note frequency
    #define NOTE_D4  294
    #define NOTE_E4  330
    #define NOTE_F4  349
    #define NOTE_G4  392
    #define NOTE_A4  440
    #define NOTE_B4  494
    #define NOTE_C5  523
    #define NOTE_D5  587
    #define NOTE_E5  659
    #define NOTE_F5  698
    #define NOTE_G5  784
    #define NOTE_A5  880
    #define NOTE_B5  988
    //*****************************************
    int notes[] = {       //Note of the song, 0 is a rest/pulse
       NOTE_E4, NOTE_G4, NOTE_A4, NOTE_A4, 0,
       NOTE_A4, NOTE_B4, NOTE_C5, NOTE_C5, 0,
       NOTE_C5, NOTE_D5, NOTE_B4, NOTE_B4, 0,
       NOTE_A4, NOTE_G4, NOTE_A4, 0,

       NOTE_E4, NOTE_G4, NOTE_A4, NOTE_A4, 0,
       NOTE_A4, NOTE_B4, NOTE_C5, NOTE_C5, 0,
       NOTE_C5, NOTE_D5, NOTE_B4, NOTE_B4, 0,
       NOTE_A4, NOTE_G4, NOTE_A4, 0,

       NOTE_E4, NOTE_G4, NOTE_A4, NOTE_A4, 0,
       NOTE_A4, NOTE_C5, NOTE_D5, NOTE_D5, 0,
       NOTE_D5, NOTE_E5, NOTE_F5, NOTE_F5, 0,
       NOTE_E5, NOTE_D5, NOTE_E5, NOTE_A4, 0,

       NOTE_A4, NOTE_B4, NOTE_C5, NOTE_C5, 0,
       NOTE_D5, NOTE_E5, NOTE_A4, 0,
       NOTE_A4, NOTE_C5, NOTE_B4, NOTE_B4, 0,
       NOTE_C5, NOTE_A4, NOTE_B4, 0,

       NOTE_A4, NOTE_A4,
       //Repeat of first part
       NOTE_A4, NOTE_B4, NOTE_C5, NOTE_C5, 0,
       NOTE_C5, NOTE_D5, NOTE_B4, NOTE_B4, 0,
       NOTE_A4, NOTE_G4, NOTE_A4, 0,

       NOTE_E4, NOTE_G4, NOTE_A4, NOTE_A4, 0,
       NOTE_A4, NOTE_B4, NOTE_C5, NOTE_C5, 0,
       NOTE_C5, NOTE_D5, NOTE_B4, NOTE_B4, 0,
       NOTE_A4, NOTE_G4, NOTE_A4, 0,

       NOTE_E4, NOTE_G4, NOTE_A4, NOTE_A4, 0,
       NOTE_A4, NOTE_C5, NOTE_D5, NOTE_D5, 0,
       NOTE_D5, NOTE_E5, NOTE_F5, NOTE_F5, 0,
       NOTE_E5, NOTE_D5, NOTE_E5, NOTE_A4, 0,

       NOTE_A4, NOTE_B4, NOTE_C5, NOTE_C5, 0,
       NOTE_D5, NOTE_E5, NOTE_A4, 0,
       NOTE_A4, NOTE_C5, NOTE_B4, NOTE_B4, 0,
       NOTE_C5, NOTE_A4, NOTE_B4, 0,
       //End of Repeat

       NOTE_E5, 0, 0, NOTE_F5, 0, 0,
       NOTE_E5, NOTE_E5, 0, NOTE_G5, 0, NOTE_E5, NOTE_D5, 0, 0,
       NOTE_D5, 0, 0, NOTE_C5, 0, 0,
       NOTE_B4, NOTE_C5, 0, NOTE_B4, 0, NOTE_A4,

       NOTE_E5, 0, 0, NOTE_F5, 0, 0,
       NOTE_E5, NOTE_E5, 0, NOTE_G5, 0, NOTE_E5, NOTE_D5, 0, 0,
       NOTE_D5, 0, 0, NOTE_C5, 0, 0,
       NOTE_B4, NOTE_C5, 0, NOTE_B4, 0, NOTE_A4
    };
    //*****************************************
    int duration[] = {         //duration of each note (in ms) Quarter Note is set to 250 ms
      125, 125, 250, 125, 125,
      125, 125, 250, 125, 125,
      125, 125, 250, 125, 125,
      125, 125, 375, 125,

      125, 125, 250, 125, 125,
      125, 125, 250, 125, 125,
      125, 125, 250, 125, 125,
      125, 125, 375, 125,

      125, 125, 250, 125, 125,
      125, 125, 250, 125, 125,
      125, 125, 250, 125, 125,
      125, 125, 125, 250, 125,

      125, 125, 250, 125, 125,
      250, 125, 250, 125,
      125, 125, 250, 125, 125,
      125, 125, 375, 375,

      250, 125,
      //Rpeat of First Part
      125, 125, 250, 125, 125,
      125, 125, 250, 125, 125,
      125, 125, 375, 125,

      125, 125, 250, 125, 125,
      125, 125, 250, 125, 125,
      125, 125, 250, 125, 125,
      125, 125, 375, 125,

      125, 125, 250, 125, 125,
      125, 125, 250, 125, 125,
      125, 125, 250, 125, 125,
      125, 125, 125, 250, 125,

      125, 125, 250, 125, 125,
      250, 125, 250, 125,
      125, 125, 250, 125, 125,
      125, 125, 375, 375,
      //End of Repeat

      250, 125, 375, 250, 125, 375,
      125, 125, 125, 125, 125, 125, 125, 125, 375,
      250, 125, 375, 250, 125, 375,
      125, 125, 125, 125, 125, 500,

      250, 125, 375, 250, 125, 375,
      125, 125, 125, 125, 125, 125, 125, 125, 375,
      250, 125, 375, 250, 125, 375,
      125, 125, 125, 125, 125, 500
    };

    void setup() {
      for (int i=0;i<203;i++){              //203 is the total number of music notes in the song
      int wait = duration[i] * songspeed;
      tone(buzzer,notes[i],wait);          //tone(pin,frequency,duration)
      delay(wait);}                        //delay is used so it doesn't go to the next loop before tone is finished playing
      //You can click reset on Arduino to replay the song
    }

    void loop() {

    }

title: How to stop the screeching noise that comes from buzzer?

Answers: 0


body:
This question is somewhat similar to https://arduino.stackexchange.com/questions/56026/how-to-pass-non-static-class-member-to-callback, but there are a few differences, especially since a lot of my uses have "interesting" additional complexities. I'd like to understand better my options in using them, since I have not gained enough understanding from other answers (and I need to write both the callback and the function that calls it).

I have a number of libraries that produce "events" that I'd like to be able to write separate classes or functions to respond to (so I don't need to customize every library every time I develop something). The annoying part is that I've long-since discovered the `this` pointer that's hidden in class method calls, which prevents me from passing `currentgui.leftbutton` as a function to `menu.leftbuttonpressed(void (*callbackfuncptr)(void))`.

I'm **also** using the ESP8266 web server library, which needs a callback in the context of the server object that can call the server as a global to actually get the data sent to it! (Unless the server passes its *own* `this` as a parameter to the callback, *which I don't know* since the documentation consists almost solely of a small number of "examples" which don't show the majority of the actual features of the web server, rather than a real explanation.)

I could use some variant of a pointer to a class method, but the syntax for that is eye-gouging and I'm using more than one class to provide callbacks to (especially for the task scheduler), so this would require customizing the library to handle pointers to every class I use again. **I can't use polymorphism, either**, since some classes contain *multiple* scheduler callbacks to be done on different times/conditions.

*How do I handle these callbacks?* My current method is to write a function that wraps the method's function, but that relies on a specific instance of that method, so it can't be reused. It's also really awkward since I'm now dealing with multiple functions/methods that are now very similar.

I would **also** like to be able to have a class, that when passed a web server object, registers itself as a callback to a particular page event (I want to write a network connection manager similar to the WiFiManager library, but with the ability to integrate with an existing webpage. I have all the code, but it currently can't be nicely integrated into a standalone class because of this issue). It needs to store a pointer to the server object to get the data once the callback's called, but it also needs to be attached to the callback of the class that holds that particular pointer AND the other handler functions once the data's retrieved.
There is already a library that does something similar, but I can't figure out at all how this works, since I was under the impression that this is not possible. Can someone help me understand how the following class operates?
https://github.com/esp8266/Arduino/tree/master/libraries/ESP8266HTTPUpdateServer/src

title: Callback functions when using a class

Answers: 2

body:
The ESP8266WebServer uses callback functions to handle HTTP request by your code. This callback functions can't be members of a class. But you can use [anonymous functions][1] to implement this callbacks. And if you like you can implement them as 'redirects' to functions of your objects.

    server.on("/leftbutton", []() {
      currentgui.leftbutton(server);
    }

Note: this anonymous functions are called lambda functions and they can do some tricks with parameters too

  [1]: https://en.wikipedia.org/wiki/Anonymous_function#C++_(since_C++11)

body:
> They call the same instance of the class' member functions to get data back.

Yes, but if they eventually call the class' member function to get data, other than static data, then the need to know what *instance* of the class to get the data from.

>  I'd like to know how to get a class I wrote (nothing special about it, but how do I connect it?) to register itself as a callback so IT gets data and I don't need a bunch of disconnected non-class functions around

If function X (not a member of this class) needs to be able to access the data from instance A or instance B then clearly X needs to know which instance it is looking at (the `this` pointer). This is not a syntax thing, you need to have a way of solving this problem.

In fact, when you say "a class I wrote" then that would also have instance data (its own `this`) so now you are trying to connect two instances of two classes.

How many server objects do you have? If just one in this particular case you might be able to fudge your way around it by storing its `this` somewhere, or making some glue routines.


body: % characters are used for [template processing](https://github.com/me-no-dev/ESPAsyncWebServer#template-processing) but I want it to just send the % through. How do you tell it to do that?

title: ESPAsyncWebServer how do you escape the % character?

Answers: 1

body:
You'd use `%%` to get a single `%` as output.

From the source code: [double percent sign encountered, this is single percent sign escaped.](https://github.com/me-no-dev/ESPAsyncWebServer/blob/fc71230a31c25ddebec7462d60cd495c919244c8/src/WebResponses.cpp#L402)


body:
I am trying to time sync my arduino hardware to NTP server. I have a `setSyncProvider(getNtpTime)´ function to do it and called inside the void setup. I have another function (mainFunction) inside the main loop, that calls every minute. I have added a function to display time inside this mainFunction so that time will update every minutes.  Code works fine for first five minutes. Then it calls the getNtpTime again even though it is not inside the loop. Why is it happening?
<!-- language-all: lang-cpp -->
~~~
time_t getNtpTime()
{
  while (Udp.parsePacket() > 0) ; // discard any previously received packets
  Serial.println("Transmit NTP Request");
  sendNTPpacket(timeServer);
  uint32_t beginWait = millis();
  while (millis() - beginWait < 1500) {
    int size = Udp.parsePacket();
    if (size >= NTP_PACKET_SIZE) {
      Serial.println("Receive NTP Response");
      Udp.read(packetBuffer, NTP_PACKET_SIZE);  // read packet into the buffer
      unsigned long secsSince1900;
      // convert four bytes starting at location 40 to a long integer
      secsSince1900 =  (unsigned long)packetBuffer[40] << 24;
      secsSince1900 |= (unsigned long)packetBuffer[41] << 16;
      secsSince1900 |= (unsigned long)packetBuffer[42] << 8;
      secsSince1900 |= (unsigned long)packetBuffer[43];
      return secsSince1900 - 2208988800UL + timeZone * SECS_PER_HOUR;
    }
  }
  Serial.println("No NTP Response :-(");
  return 0; // return 0 if unable to get the time
}

~~~

title: Why does a function inside void set up is repeating after some minutes

Answers: 1

body: The `setSyncProvider` function of the TimeLib sets a function which will be called by the library every `interval` seconds. The `interval` is set with `setSyncInterval`. Default interval is 300 seconds.


body:
I'm setting up a "Smart House" project with Arduino+Esp01F(Serial Communication).
But I want to make it global server. For it I use WiFiEsp library. But for it I must Get any port (neither 80 nor 443), then make port forwarding on router. But there are no port forwarding in my router. I think how can I do it?
Code:
```cpp
#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[] = "Nazim";            // your network SSID (name)
char pass[] = "eminmamedov1";         // your network password
int status = WL_IDLE_STATUS;     // the Wifi radio's status
int reqCount = 0;                // number of requests received

WiFiEspServer server(5000);

 WiFiEspClient client;

void setup() {
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");
Serial.println(WiFi.localIP());

WiFi.config(IPAddress(192,168,0,165));
  // start the web server on port 80
  server.begin();

}

void loop() {
   WiFiEspClient client = server.available();
   if(client){
    String res = "";
     Serial.println("New client");
      while (client.connected()) {
      if (client.available()) {
        char c = client.read();

        res+=c;

        if (c == '\n') {
          Serial.println("Sending response");
           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
               "\r\n");
               if(res.indexOf("on?") >=0){
               int s = res.indexOf("on?")+7;
               int f = s+2;
               String ss = res.substring(s,f);
                  int i = ss.toInt();
                 if(i != 6 && i != 7&& (i>=2)&&(i<=13)){

                  pinMode(i,OUTPUT);
                  digitalWrite(i,HIGH);
                  bool s = digitalRead(i);
                  String state = s ? "OFF\r\n" : "ON\r\n";
                  client.println(state);
                 }else{
                  client.println("ERROR\r\n");
                 }
               }else if(res.indexOf("off?") >=0){
                 int s = res.indexOf("off?")+8;
               int f = s+2;
               String ss = res.substring(s,f);
                  int i = ss.toInt();
                 if(i != 6 && i != 7&& (i>=2)&&(i<=13)){

                  pinMode(i,OUTPUT);
                  digitalWrite(i,LOW);
                  bool s = digitalRead(i);
                  String state = s ? "OFF\r\n" : "ON\r\n";
                  client.println(state);
                 }else{
                  client.println("ERROR\r\n");
                 }
               }else if(res.indexOf("state?") >=0){
                 int s = res.indexOf("state?")+9;
               int f = s+2;
               String ss = res.substring(s,f);
                  int i = ss.toInt();
                 if(i != 6 && i != 7&& (i>=2)&&(i<=13)){

                  bool s = digitalRead(i);
                  String state = s ? "OFF\r\n" : "ON\r\n";
                  client.println(state);
               }
               }

                   client.stop();

      }
      }

   }

}

```

title: Creating global webserver without port forwarding

Answers: 0


body:
I have a question regarding SIM800L and HTTP GET request. I'm using this [https://exploreembedded.com/wiki/Setting_up_GPRS_with_SIM800L][1] simple code to communicate with SIM800l with AT commands. To perform the HTTP request, I use the following set of AT commands:

    AT+CFUN=1
    OK

    AT+CSTT="internet","",""
    OK

    AT+CIICR
    OK

    AT+CIFSR
    10.180.xxx.xx

    AT+CIPSTART="TCP","84.42.xxx.xx",80
    OK

    CONNECT OK

    AT+CIPSEND=52
    >
    GET /bakalarka.php/? HTTP/1.1
    Host:84.42.xxx.xx

    SEND OK
    HTTP/1.1 200 OK
    Date: Mon, 19 Aug 2019 16:20:27 GMT
    Server: Apache
    X-Frame-Options: SAMEORIGIN
    Vary: Accept-Encoding
    Transfer-Encoding: chunked
    Content-Type: text/html; charset=UTF-8

    10
    time201908191820
    0

    CLOSED

The problem is that sometimes. Or every other time, I don't get the whole HTTP answer. I usually get only the beginning. Something like this:

    AT+CIPSEND=52
    >
    GET /bakalarka.php/? HTTP/1.1
    Host:84.42.xxx.xx

    SEND OK
    HTTP/1.1 200 OK
    Date: Mon, 19 Aug 2019 16:20:27 GMT
    Server: Apac

and then after a couple of seconds, the connection closes.

    CLOSED

Do you know what could cause that? It's literally random. I need the information from the webpage (it's the current time) and currently, it's really unreliable.

Another question. What does the "10" and "0" mean in the HTTP request? The "time201908191820" is the current time from printed from PHP.

Thank you very much!

  [1]: https://exploreembedded.com/wiki/Setting_up_GPRS_with_SIM800L

title: SIM800L HTTP request is not reliable

Answers: 3

body:
> Do you know what could cause that? It's literally random.

Could be your code, could be your network provider / signal. It's impossible to tell without you providing your code for us to inspect.

> Another question. What does the "10" and "0" mean in the HTTP request? The "time201908191820" is current time from printed from PHP.

Those look to be part of the response body - so they are printed by whatever the PHP script is that you are requesting. Either that or they are generated by your undisclosed Arduino program.

body:
Thank you for your answer. The code is as follows:

    #include <SoftwareSerial.h>

    String Arsp, Grsp;
    SoftwareSerial gsm(12, 8); // RX, TX

    String GET = "GET /bakalarka.php/? HTTP/1.1\r\nHost:84.42.xxx.xx\r\n\r\n";

    void setup() {

      Serial.begin(115200);
      Serial.println("Testing GSM SIM800L");
      gsm.begin(19200);

    }

    void loop() {

      AT("AT+CFUN=1");
      AT("AT+CSTT=\"internet\",\"\",\"\"");
      AT("AT+CIICR");
      AT("AT+CIFSR");
      AT("AT+CIPSTART=\"TCP\",\"84.42.xxx.xx\",80");

      int get_length;
      get_length = GET.length();

      AT("AT+CIPSEND=" + String(get_length));
      AT(GET);
    }

    void AT(String AT){

      gsm.println(AT);

      if(gsm.available()){

        Grsp = gsm.readString();
        Serial.println(Grsp);
      }
    }

I was thinking about a couple of things that could cause this.
1. Hardware design - some noise could cause a freeze of the GSM module while getting the answer from the server. After thinking through I don't think it's likely to be that. The power supply is made to be really beefy and there are enough bypass caps to reduce the noise and provide enough energy during current spikes. Also, the module doesn't freeze. It's still connected to the server, after a couple of seconds it closes the connection exactly as it should be.

2. Serial buffer gets somehow full. This was just a quick thought. The buffer of Arduino could get somehow full so it's not able to save any more incoming data. I think it's nonsense, but...

Thank you for your answers.

Krystof

body: I've figured it out. The answer to HTTP GET request was read as a string. The string has aroud 284 bytes. Since it's so big, string gets to be saved fragmented, which is apparently a problem. The solution is to create a buffer and save the characters there from the Serial.


body:
Is there a way to control 3 relays with 1 button?

My idea is: There are 3 modes; mode 1 for relay 1, mode 2 for relay 2 and mode 3 for relay 3.

With a long press you switch between modes (After 3 comes 1) and with a short press you activate the relay which is in the activated mode.

I need this for my wheelchair so please help me.

Thank you, Michael

---

Further question:
Does the relays really need a external power supply?
Because I have a small amount of power to control with the relays.

title: control 3 relays with 1 button

Answers: 2

body:
Sure you can. This site isn't a great place for open-ended questions like this though. Since you have a serious real-world need I'll give you some guidance anyway.

You'd need to break it into pieces and solve each one in turn.

First create code that recognizes long and short presses (not using `delay()`.) You'll probably want to respond on releasing the button, since at that point it's easy to tell if it was a long or a short press.

The pseudo-code might look something like this:

    void loop()
       if button_is_pressed
          if !press_in_progress
             press_in_progress = true
             start = millis()
       else
          if press_in_progress //Button has been released
             elapsed = millis() - start
             press_in_progress = false
             if elapsed > long_press_threshold
                long_press_function()
             else
                short_press_function()

For controlling the relays, I suggest getting "digital" relays that are made to be controlled with 5V logic signals. Relays [**like this**][1] work well. (Link). Since you need to control 4 relays, a 4 channel model like [this one][2] would be a better choice. Note that you'll need a fairly high current power supply. A 2A 5V regulated supply should be plenty for both your Arduino and your relays, although it's more of a sure thing if you use separate power supplies for the arduino and the relays (that way the voltage to the arduino doesn't bounce around as the relays energize and de-energize.

You'll need a global variable for the currently active relay. The long press would increment that value modulo 4: (going from 0 to 3 and then back to 0)

    relay_index = (relay_index + 1) % 4;

You'd need an array of 4 bools for the states of each relay:

    bool relay_states[4];

The short press would toggle the state of the current relay

    relay_states[relay_index] = !relay_states[relay_index];

Note that if you're more interested in solving your wheelchair problem cost-effectively than tinkering, this is the sort of thing that a maker space would be ideal for. There are lots of tinkerers there who love a challenge, and would likely pitch in and help you.

  [1]: https://www.amazon.com/Tolako-Arduino-Indicator-Channel-Official/dp/B00VRUAHLE/ref=asc_df_B00VRUAHLE/?tag=hyprod-20&linkCode=df0&hvadid=309803885710&hvpos=1o1&hvnetw=g&hvrand=941850642207041054&hvpone=&hvptwo=&hvqmt=&hvdev=c&hvdvcmdl=&hvlocint=&hvlocphy=9007580&hvtargid=pla-568715033020&psc=1
  [2]: https://www.amazon.com/JBtek-Channel-Module-Arduino-Raspberry/dp/B00KTEN3TM/ref=sr_1_3?crid=1GPWH2OQM8ERY&keywords=arduino 4 channel relay&qid=1566257466&s=electronics&sprefix=arduino 4 ,electronics,134&sr=1-3

body:
Yes, it is possible to do that and there are libraries for that purpose. Check for example  [ObjecButton library][1], which supports click, press and double click action. It is well documented and comes with many examples...

And does the relays really need a external power supply? It depends, what kind of relays you want to use, what kind of power supply is available on wheelchair, what is the load switched by these relays and so on...

  [1]: https://github.com/JSC-electronics/ObjectButton


body:
I have a project that uses a nodemcu and it includes an rf receiver, I created the pcb board already etc etc... so I've already chosen D7 (GPI013) before reading on connecting the rf receiver and found that a lot of people are saying to connect it to the interrupt pin and for the case of an Arduino it was pin 2 and for the nodemcu it's D3 (GPIO0).

**UPDATE:** the pin in question is the data pin for the rf receiver, this would be connected to D7 (GPIO13) because of the trace on the board. it is purely used for receiving the data it picks up and giving it to the nodemcu to handle.

Can I just use a different pin which in my example is D7 (GPIO13) or does it **HAVE** to be an interrupt pin?

*Side note: I'm aware of the advantage of using an interrupt pin where that it takes priority over code running.*

title: Can I use an RF Receiver to any pin on an Arduino?

Answers: 0


body:
Is it possible to program chips like the Arduino uno's Atmega328P directly with USB serial from your computer?
Where can i find information on the protocols/standards to do such a thing?

More specifically, I want to be able to make a custom pcb for my Attiny85 chips with a usb connector. I would prefer not to use the arduino IDE.
Is it possible to program this chip like so?

title: How to program micro chips directly with USB

Answers: 2

body:
> Is it possible to program chips like the Arduino uno's Atmega328P directly with USB serial from your computer?

The bare chip? Generally, no.

*Some* chips that include USB hardware also may include a DFU bootloader in ROM. If your chosen chip has this, then yes you can - you just need to wire it up and use a suitable DFU firmware upload program to install your compiled code into the chip.

However chips that don't have USB will *never* have a USB DFU bootloader in them. In such cases is is *your* responsibility to create (or otherwise obtain) a suitable bootloader that *you* will install into the chip.

Digispark and Adafruit both do that.  They take a chip that doesn't have USB and install software that tries to (poorly) emulate USB over GPIO pins1.

For chips that do not have actual USB hardware in them it is far more common to use a UART-based bootloader - simply because this is a much lighter and more "correct" way of doing it.

If you want to use a direct USB connection for your device you should be selecting a chip that has USB built into it (AVR "U" series2, most PIC32, many ARM-based chips) which will allow you to have *proper* USB communication instead of slow HID and custom (non-standard) protocols only3.

Note that at no point does your choice of bootloader, or method of communication with the bootloader, tie you in to using the Arduino IDE.  The IDE just compiles the code then runs an external program that communicates with the bootloader (different bootloaders need different programs to communicate with them). How you compile the software is up to you. How you execute the bootloader upload program is up to you.

----

1. Personally I think that's a *horrible* idea and should *NEVER* be done. I'm a purist though.
2. Such as the ATMega32U4 used on the Leonardo and Micro boards.
3. VUSB can only (barely) run fast enough for USB 1.1. That means only HID protocols are officially supported (keyboard and mouse), and anything else is non-standard and requires special supporting software to work with it.

body:
>Is it possible to program chips like the Arduino uno's Atmega328P directly with USB serial from your computer?

Put a bootloader on the chip first, then an offboard USB/Serial adapter can be used for the serial programming.   That's basically what a ProMini is - a bootloaded '328P (in SMD form) with a resonator & decoupling caps and a small voltage regulator - and a header to accept an FTDI Basic for programming serially.  If you notice the Black and Green colors next to the FTDI header, those are to match the wire colors on the the FTDI cables that were originally used, before seperate USB cable and FTDI modules became more popular.
https://www.sparkfun.com/products/9718
[![enter image description here][1]][1]

Instead of the 6-pin FTDI header, you could make an adapter board to go from FTDI to a USB-A 5-pin connector, then on your board have a USB-B-Mini or USB-B-Micro 5-pin connector to bring in the FTDI's 5V, Gnd, DTR, Tx, and Rx signals.

USB wouldn't be coming in directly, but you would have the spacing advantage of the small USB connector, and could program serially from a PC USB port.

Too bad you don't want to use the Arduino IDE, there are supported core codes to add to the IDE for the Attiny85 and other chips like that. Attiny85 with bootloader could then be serially programmed with an offboard USB/Serial adapter.

https://github.com/SpenceKonde/ATTinyCore

>ATtinyCore Universal
>
>This core supports the following processors - essentially every ATtiny processor that makes sense to use with Arduino. Click the processor name for part-specific information:
>
>ATtiny2313, 4313
>
>ATtiny24, 44, 84 (With or without Optiboot bootloader)
>
>ATtiny25, 45, 85 (With or without Optiboot bootloader)
>
>ATtiny261, 461, 861 (With or without Optiboot bootloader)
>
>ATTiny87, 167 (with or without Optiboot bootloader)
>
>ATTiny48, 88 (With or without Optiboot bootloader)
>
>ATTiny441, 841 (With or without Optiboot bootloader)
>
>ATTiny1634 (With or without Optiboot bootloader)
>
>ATTiny828 (With or without Optiboot bootloader)
>
>ATtiny43 (no bootloader)

  [1]: https://i.stack.imgur.com/atLEm.jpg


body:
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

title: Problem with multi-client ASCII text parser (TCP)

Answers: 0


body:
[![enter image description here][1]][1]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!

[![Version 1][2]][2]

[![Version 2][3]][3]

  [1]: https://i.stack.imgur.com/UelsX.png
  [2]: https://i.stack.imgur.com/bf66r.jpg
  [3]: https://i.stack.imgur.com/KrVN8.jpg

title: Dc motor backvoltage, how to place the diode correctly?

Answers: 3

body:
> 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.

body:
You're looking for something called a "[flyback diode](https://cdn.sparkfun.com/assets/9/8/6/0/f/51770c5bce395f3149000000.png)."

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).

body:
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:

[![enter image description here][1]][1]

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:

[![enter image description here][2]][2]

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.

  [1]: https://i.stack.imgur.com/haQSw.png
  [2]: https://i.stack.imgur.com/vmqb2.png


body:
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?

title: Can connect to esp8266 AP which is connected to Arduino UNO but no response

Answers: 0


body:
What is the purpose of it and on what bases its value is calcuated in ohms ?

[![enter image description here][1]][1]

  [1]: https://i.stack.imgur.com/3rfzf.png

title: Why do we need this resistor?

Answers: 0


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

title: Mega2560 has 2 Crystal Oscillator?

Answers: 1

body:
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.


body:
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'

title: expected initializer before 'RF24'

Answers: 1

body:
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().


body:
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/][1] 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:
<!-- language-all: lang-cpp -->

    // 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);
    }

  [1]: http://www.mertarduino.com/using-ultrasonic-distance-sensor-hc-sr04-with-lcd-display-and-arduino/2018/11/22/

title: Arduino Ultrasonic Sensor and LCD - Help Needed-

Answers: 1

body:
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.


body:
Following MAJENKO's tutorial on [sd card file optimization and data integrity][1], 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.

  [1]: https://hackingmajenkoblog.wordpress.com/2016/03/25/fast-efficient-data-storage-on-an-arduino/

title: SD Card store struct: force big-endian / little-endian?

Answers: 1

body:
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 **H**ost **to** **B**ig **E**ndian values and back again.

    htole16(x)
    htole32(x)
    letoh16(x)
    letoh32(x)

And these convert **H**ost **to** **L**ittle **E**ndian 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.


body: 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.

title: Remote Arduinos polling a master Ardrino over ethernet/wifi

Answers: 0


body:
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?

title: FS100A works when Arduino connected to PC but not when connected to Raspberry Pi

Answers: 1

body:
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.

[![wiring][1]][1]

  [1]: https://i.stack.imgur.com/hRIKJ.jpg


body:
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);
     }

title: can I check if why my motor isn't working?

Answers: 1

body:
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


body:
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**
<!-- language-all: lang-cpp -->
```
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

}
```

title: Slave to Send Data after Receiving Command using I2C

Answers: 1

body:
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);
        }

    }


body:
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][1]

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?

  [1]: https://www.instructables.com/id/Arduino-Uno-Menu-Template/

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.

title: LCD shield submenu

Answers: 1

body:
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
       }
    }


body:
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?

title: Why is observed clock rate < 3MHz on Arduino Uno?

Answers: 2

body:
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][1] for more info.

However, as Kwasmich's comment says, you can easily circumvent this by performing your test inside a `while`  loop.

  [1]: https://www.arduino.cc/en/Tutorial/SerialEvent

body:
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).


body:
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.

![arduino 3wired fan rpm finding connection]
(https://i.stack.imgur.com/hZ9vd.jpg)

title: 12V dc fan motor rpm finding using tacho out

Answers: 0


body:
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 !

title: What is the fastest way to data to another Arduino SAMD21 boards

Answers: 0


body:
In [this other stack QA][1] 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.

  [1]: https://electronics.stackexchange.com/questions/452219/

title: Set PWM by period? And have it variable?

Answers: 1

body:
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][1]. 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:
<!-- language-all: lang-cpp -->

 #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

  [1]: https://stackoverflow.com/questions/48873501


body:
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][1]; 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][2] 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.

[![enter image description here][3]][3]

  [1]: https://github.com/sparkfun/SparkFun_MicroView_Arduino_Library/blob/V_1.0.0/src/MicroView.cpp
  [2]: https://github.com/sparkfun/SparkFun_MicroView_Arduino_Library/blob/V_1.0.0/extras/OLED-Datasheet_SAS1-02007-A UG-6448HLBEG03 (WiseChip).pdf
  [3]: https://i.stack.imgur.com/qodx6.gif

title: How to detect V-SYNC on the SparkFun MicroView?

Answers: 1

body:
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.


body:
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?

title: Running out of GPIO & looking for suggestions

Answers: 1

body:
Two main solutions comes to my mind:

 1. 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...
 2. 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).


body:
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.

title: Upload application from Visual Studio 2019 with PlatformIO

Answers: 2

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

[![this ][1]][1]

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][2].
Example of the simple environment for Arduino Uno created in  platformio.ini file:

    [env:uno]
    platform = atmelavr
    board = uno
    framework = arduino

  [1]: https://i.stack.imgur.com/2kbk3.png
  [2]: https://docs.platformio.org/en/latest/projectconf.html

body:
I have final solution for uploading application from VS 2019.

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

[![VS External Tools settings by PlatformIO][1]][1]

 1. After that is possible adding custom button to Toolbar [![enter image description here][2]][2]
 2. Fantastic thing is, that during upload you can Stop the process [![enter image description here][3]][3]

  [1]: https://i.stack.imgur.com/nUJo9.jpg
  [2]: https://i.stack.imgur.com/fJwLI.png
  [3]: https://i.stack.imgur.com/ySQ2A.png