# Question
Title: Arduino Uno + SIM808 EVB 3.2.4 not working properly?
So recently I found this tutorial online about the SIM808. It looked super cool so I ordered the sim808 evb 3.2.4 off amazon. Hooked up the module and connected the RX (11) and (10) TX pins.

Here is the code I'm working with tried to follow along as best I could with the tutorial but now I am completely confused, purchased a SIM card activated the SIM card and it seems to be connecting just fine

In the serial monitor sometimes I receive this: 14:05:06.243 -\> Init Success, please send SMS message to me!

But most of the time I'm receiving this: 14:04:37.586 -\> Sim808 init error

#include \<DFRobot\_sim808.h\> #include \<SoftwareSerial.h\>

#define MESSAGE\_LENGTH 160 char message\[MESSAGE\_LENGTH\]; int messageIndex = 0; char MESSAGE\[300\]; char lat\[12\]; char lon\[12\]; char wspeed\[12\];

char phone\[16\]; char datetime\[24\];

#define PIN\_TX 10 #define PIN\_RX 11 SoftwareSerial mySerial(PIN\_TX,PIN\_RX); DFRobot\_SIM808 sim808(&mySerial);//Connect RX,TX,PWR,

void sendSMS(); void getGPS(); void readSMS();

void setup() { mySerial.begin(9600); Serial.begin(9600);

//\******** Initialize sim808 module \************* while(!sim808.init()) { Serial.print("Sim808 init error\r\n"); delay(1000); } delay(3000);

Serial.println("SIM Init success");

Serial.println("Init Success, please send SMS message to me!"); }

void loop() { //\*********** Detecting unread SMS \************************ messageIndex = sim808.isSMSunread();

//\*********** At least, there is one UNREAD SMS \*********** if (messageIndex \> 0) {

```
  readSMS();
  getGPS();
  sendSMS();

  //************* Turn off the GPS power ************
  sim808.detachGPS();

  Serial.println("Please send SMS message to me!");

```

} }

void readSMS() { Serial.print("messageIndex: "); Serial.println(messageIndex);

sim808.readSMS(messageIndex, message, MESSAGE\_LENGTH, phone, datetime);

//\***********In order not to full SIM Memory, is better to delete it********** sim808.deleteSMS(messageIndex); Serial.print("From number: "); Serial.println(phone);
Serial.print("Datetime: "); Serial.println(datetime);
Serial.print("Recieved Message: "); Serial.println(message); }

void getGPS() { while(!sim808.attachGPS()) { Serial.println("Open the GPS power failure"); delay(1000); } delay(3000);

Serial.println("Open the GPS power success");

while(!sim808.getGPS()) {

}

Serial.print(sim808.GPSdata.year); Serial.print("/"); Serial.print(sim808.GPSdata.month); Serial.print("/"); Serial.print(sim808.GPSdata.day); Serial.print(" "); Serial.print(sim808.GPSdata.hour); Serial.print(":"); Serial.print(sim808.GPSdata.minute); Serial.print(":"); Serial.print(sim808.GPSdata.second); Serial.print(":"); Serial.println(sim808.GPSdata.centisecond); Serial.print("latitude :"); Serial.println(sim808.GPSdata.lat); Serial.print("longitude :"); Serial.println(sim808.GPSdata.lon); Serial.print("speed\_kph :"); Serial.println(sim808.GPSdata.speed\_kph); Serial.print("heading :"); Serial.println(sim808.GPSdata.heading); Serial.println();

float la = sim808.GPSdata.lat; float lo = sim808.GPSdata.lon; float ws = sim808.GPSdata.speed\_kph;

dtostrf(la, 4, 6, lat); //put float value of la into char array of lat. 4 = number of digits before decimal sign. 6 = number of digits after the decimal sign. dtostrf(lo, 4, 6, lon); //put float value of lo into char array of lon dtostrf(ws, 6, 2, wspeed); //put float value of ws into char array of wspeed

sprintf(MESSAGE, "Latitude : %s\nLongitude : %s\nWind Speed : %s kph\nMy Module Is Working. Mewan Indula Pathirage. Try With This Link.\nhttp://www.latlong.net/Show-Latitude-Longitude.html\nhttp://maps.google.com/maps?q=%s,%s\n", lat, lon, wspeed, lat, lon); }

void sendSMS() { Serial.println("Start to send message ...");

Serial.println(MESSAGE); Serial.println(phone);

sim808.sendSMS(phone,MESSAGE); }\`

# Answer
> 1 votes
I recommend you to use AT command ..then using some kind of library. You need to dig into library for better information.

https://randomnerdtutorials.com/sim900-gsm-gprs-shield-arduino/ Go through this link....this will give you a rough idea.

---
Tags: arduino-uno, gsm, gps
---


# Question
Title: How to connect neo 6m 6pin module with nodemcu v3
I got this neo 6m gps module from a broken drone. and i would like to connect it to nodemcu v3 board. most of the gps module that i have seen are with 4 pins (vcc,gnd,tx,rx) , but this module has 6 pins (gnd,vcc,txd,rxd,scl,sda) .

i am not sure how to wire it up and what library to use.

# Answer
The 4 pins VCC/GND/TX/RX are the same as any other GPS module.

The other two pins, SCL and SDA, are nothing to do with the GPS. They connect to the HMC5883L compass chip.

Use the normal TinyGPS library for the GPS, and a HMC5883L library (such as this one) for the compass.
> 0 votes

# Answer
Rx and tx pin are for UART communication and SCL and SDA are for I2C communication. Most common gps module use UART communication method .... You can go with UART too this will help you to choose better library option. Most library file are coded for UART method. I recommend you to use vcc , gnd ,rx and tx pin. Escape scl and sda pins.
> 0 votes

---
Tags: nodemcu, gps, wires
---


# Question
Title: Do Arduino Nano Every devices short out?
I have an Arduino Nano Every device that seems to have shorted out.

I use a lighted USB hub with buttons that turn connections on and off. Each button has its own LED that indicates power state for its associated port.

Anyway, when I plug my Arduino Nano Every into that USB hub, the lighted buttons turn off for half of the hub, like the Arduino is shorting out the hub.

I use a different Arduino and have no problems, so it's definitely the Arduino.

Any idea what could have caused this? I was using the Arduino with a TMUX1511 switch chip and using pins D9-D12 to turn on and off the 4 internal switches in the chip. It's using very low voltage (5v) and amperage is (25 mA). I used the 5v and gnd pins on the Arduino to power the TMUX1511 chip, but with such low amperage, I can't see how that could have caused the Arduino to fry.

Any ideas?

# Answer
> 1 votes
this might because of powering issue...try using different source having a good number of current capability. likely up

---
Tags: arduino-nano
---


title: ISR Issue: Arduino Pro Micro

text:
# Question
Title: ISR Issue: Arduino Pro Micro
I'm trying to do a small test where I am using the ISR on the Arduino Pro Micro it up from sleep mode. I'm using a Force Sense Resistor (FSR, a resistor that changes it's resistance depending on how hard you press it) with a voltage divider circuit with the output of the voltage divider connected to an analog pin and the digital interrupt pin. I'm not able to get the interrupt to trigger no matter what condition I have. I don't believe the Vout on the voltage divider is too low since the ADC registers values between 0 to 1000 (0V to about 4.8V) when the FSR is pressed. Is there anything wrong with my code that is preventing my test from working properly?

```
uint8_t LED = 9;
uint8_t wakeup = 2;
uint8_t enable = 0;

void Wakeup(void);

void setup() {
  // put your setup code here, to run once:
  pinMode(LED, OUTPUT);
  pinMode(wakeup, INPUT);
  attachInterrupt(digitalPinToInterrupt(1), Wakeup, RISING);
  Serial.begin(115200);
}

void loop() {
  // put your main code here, to run repeatedly:
  //Serial.println(analogRead(A2));
  if (enable == HIGH)
    digitalWrite(LED, HIGH);
  else if (enable == LOW)
    digitalWrite(LED, LOW);
  if (analogRead(A2) < 700)
    enable = 0;
}

void Wakeup(void) {
  enable = 1;
  Serial.println("Interrupt");
}

```

# Answer
> 1 votes
* Don't do serial prints inside an ISR.
* Your variable `enable` should be declared `volatile` as it changes inside an ISR. The compiler is entitled to cache the variable value if you don't do that.
* You are inconsistent in your use of `enable`. You test for LOW or HIGH but set it to 0 or 1. Now they happen to be the same, but someone might wonder. If you are going to test for LOW or HIGH, then assign LOW or HIGH to it.

See my reference question How do interrupts work on the Arduino Uno and similar boards?.

> I thought 0 and 1 were serial pins. I'm using digital pin 2

Not in the code you are not:

```
attachInterrupt(digitalPinToInterrupt(1), Wakeup, RISING);

```

Do you mean:

```
attachInterrupt(digitalPinToInterrupt(wakeup), Wakeup, RISING);

```

It's kind of confusing to have two names which differ only in case.

---
Tags: interrupt, arduino-leonardo, arduino-pro-micro, resistor
---


# Question
Title: double type sensor data is not displayed on bluetooth terminal app on phone
Hi I am working on a project in which I am supposed to tell if a person is running/standing/walking and going upstairs/downstairs or he is on straight road. The person will carry a arduino uno module to which gps,bluetooth and altitude sensor is attached. Also I am trying to send my phone his speed and current altitude he is experiencing using HC-05 bluetooth module. I am sure that there is no problem with altitude sensor. Also I must note that my gps module(GY\_NE06MV2) is not acting proper when it comes to speed of the person. I believe this is because I experimented in my house and not outside. The problem is that I cannot see speed and altitude data on bluetooth terminal app"ArduTooth" on my phone. It is just like a blank space which should have been my data. I am presenting my code which is not very long and I hope you could help me get through this.

```
#include <SoftwareSerial.h>
#include <TinyGPS++.h>
#include <Wire.h>
#include <Adafruit_Sensor.h>
#include <Adafruit_BME280.h>

TinyGPSPlus gps; //gps object to be used
SoftwareSerial BTserial(10, 11); //bluetooth serial connection
SoftwareSerial gps_serial(4,3); //gps serial connection
Adafruit_BME280 bme; //altitude measuring sensor object

#define SEALEVELPRESSURE_HPA (1011) //sea level pressure in Turkey/Eskisehir

double speed = 0; //speed of a moving body
double current_altitude = 0;
double previous_altitude = 0;

void setup() {
Serial.begin(115200); // serial connection to computer
BTserial.begin(9600);
gps_serial.begin(9600);
bme.begin(0x76);

delay(3000);

previous_altitude = bme.readAltitude(SEALEVELPRESSURE_HPA);

}

void loop() {
//data from gps device is fed to gps object
while (gps_serial.available() > 0){
    gps.encode(gps_serial.read());
}

if(gps.speed.isValid()){
speed = gps.speed.kmph();
BTserial.write(speed); // this is where the problem-1 is, this data is not shown on mobile phone
bluetooth terminal application
BTserial.write(",");

  if(speed <= 5 && speed > 0.5){
    BTserial.write("walking");
    BTserial.write(",");
  }
  if(speed <= 0.5){
    BTserial.write("standing");
    BTserial.write(",");
  }
  if(speed > 5){
    BTserial.write("running");
    BTserial.write(",");
  }

  }else{
    BTserial.write("m.s.n.n"); //stands for "moving status not known"
    BTserial.write(",");
  }

current_altitude = bme.readAltitude(SEALEVELPRESSURE_HPA);
BTserial.write(current_altitude); //this is where problem-2 is, this data also is not displayed
on phone
BTserial.write(",");
//this part determines either the body goes upstairs or downstairs or he is on straight road
if(current_altitude - previous_altitude >= 0.7){
  BTserial.write("going ups.");
  previous_altitude = current_altitude;
}
if(previous_altitude - current_altitude >= 0.7){
  BTserial.write("going downs.");
  previous_altitude = current_altitude;
}
if((current_altitude - previous_altitude <= 0.3) || (previous_altitude - current_altitude <=
0.3)){
  BTserial.write("on s.r");
  previous_altitude = current_altitude;
}
BTserial.write(";");

delay(1000);

}

```

I must note that purpose of BTserial.write(","); is that every seperate entry sent to phone via bluetooth must be seperated by ",".

# Answer
You can convert you double data to string type.this trick may help. And you also can just sent a byte for different positions and decode them in app.
> 1 votes

# Answer
`SoftwareSerial` is a very badly behaved library. It blocks interrupts while sending or receiving bytes. Using it with whatever depends on interrupts is asking for trouble. Using two instances of `SoftwareSerial` concurrently is doubly asking for trouble. It is very likely that they are interfering with one another, as each one blocks interrupts for an unreasonably long time, and each one relies on interrupts for detecting incoming data.

You don't seem to be using the hardware serial interface (`Serial`), which is a shame, as it is the only serial port you have that works really well. I suggest you try to use this interface for one of your devices (maybe the GPS), and a single software interface for the other one.

Or, better yet, use `Serial` for both. The transmit and receive parts of a serial port are fairly independent, save for the fact that they work at the same speed. You could use the transmit part for the Bluetooth module and the receive part for the GPS. This should ensure reliable communication with both devices, without ever blocking interrupts for too long.
> 0 votes

---
Tags: bluetooth, gps
---


title: Estimating CPU load of a task scheduler

text:
# Question
Title: Estimating CPU load of a task scheduler
First off, I should note that I'm not sure what tags best apply here, and I can't seem to find any that relate to schedulers, etc. Please inform me if they are not the right ones.

I have a simple, portable task scheduler (it only relies on millis(), and runs on different Arduino-supported systems) that is called via a function in loop() and that picks and then runs a function pointer (the "task") from a list of tasks with status, sleep, and priority information.

I would like to have a way to determine and to tell the user how much CPU time is being spent on running tasks vs. being idle.

The problem is that there can be other functions being called from loop(), not just my scheduler. It would thus be a bad idea to track total time vs. time spent in a task. If I did, the CPU use would always read low, since the actual task time cannot use all of the CPU time since the other tasks in loop() would be quietly using some of it.

However, if I specifically track time in the scheduler vs. time spent in task, I run into a new issue. I would use more memory (a few more bytes, but I'm using a lot already...) and more CPU\*, since I'd have to keep track of the total so far *and* also the current runtime for that iteration of the scheduler. That's on top of the similar construct determining the runtime of the task. Mainly, though, the issue is that the loop() function and scheduler run fast enough that the millis() timer can tick slower than the changeover between my scheduler and the loop() function. This causes the timing to also be off, since it would be counted if it ticks in the scheduler even if it was mainly loop()'s fault.

Is there a general methodology for computing the CPU time? It would be difficult to time-slice the scheduler, and that would run slower anyway. I could count the proportion of scheduler calls that run/don't run tasks, but that won't work because tasks take longer than the no-op that happens if a task doesn't run, and it makes no accounting for task length.

\*On an AVR system, the 8-bit CPU uses a surprising aggregate time on all those 32-bit operations, between the sleep time calculations (on sleeping tasks only, to be fair) and the elapsed time calculations that fed into my prior CPU use attempt. It wasn't the only cause, but I saw quite a bit of timing slip on one attempt of coding the scheduler because of a similar issue.

# Answer
> 0 votes
The only metric you have is time. The only thing you can do is compare that time over iterations / task calls. The typical approach is to note the time at the start of a task "tick", and note it at the end. Then add the difference to the total for that task.

When you want to then look at usage percentages you can compare those totals to the total time the system has been running.

The total runtime is already done for you, in the form of `millis()`, so you don't need to worry about that.

Recording each task's total runtime in microseconds is simple enough, but of course will entail an overhead. That is unavoidable no matter what strategy you take. It's kind of quantum: the act of measuring changes the results.

If you treat your "idle" task the same as any other task (which is the normal way of doing things - the idle task is just a task that does nothing) then the sum of all the time counts for all the tasks = (within a certain granularity) the total amount of time your task scheduler has been running. The difference between that and the system runtime (`millis()`) is the proportion of the time your scheduler has been running compared to other things happening in `loop()`.

Whether you compare to `millis()` or `micros()` for the system runtime is up to you. By storing `micros()` per task you're getting a reasonable resolution for each tasks's runtime (but with a limit to how long before it wraps - but you can handle that in software by carrying over to another lower resolution counter if you want), but you can then discard some of that resolution when doing your calculations if you don't need it at the time.

Estimating runtime in a co-operative multitasking system like this is never good, and often not bothered with because of that. It's always a guestimate with the results being skewed by the measuring, since the measuring is synchronous with the execution of the tasks.

In a proper context-switching multitasking system you would normally operate on the number of "ticks" of the system rather on time. That is, simply count 1 each time a task is switched in by the context switcher. Since each task has a fixed runtime controlled by the granularity of the scheduler it's then trivial to know that task X has been running for X/TOTAL\_TICKS % of the time. Any calculations will be themselves done in a task - maybe the idle task, or a system accounting task.

# Answer
> -1 votes
The cheapest (in every sense) way I know to display "idleness" is to set an output pin when you enter the scheduler and clear it again when you dispatch a task (other than your idle task, if there is one). Or reverse this, if you want to display load instead. These can be accomplished with a single instruction each. Low impact on your memory, execution time, assembly time, and wallet.

How precisely do you want to report this?

* An LED on the output will fade and brighten according to the load. If you need damping (perhaps the load is brief and "peak-y") add an R-C filter to the LED circuit.
* Connect a DVM, or even better, a mechanical VOM if you can find one, to the output and read load from the meter. A mechanical meter would do some damping for you. A DVM will probably need the filter from the previous suggestion.
* Loop the filtered output back into an analog input and read the load to a precision of ~ 0.1%! That's way more significance than is justified so round it as you see fit.

---
Tags: arduino-uno, esp8266, task
---


title: I can't upload codes to my ESP8266

text:
# Question
Title: I can't upload codes to my ESP8266
,this is the error I encounter when i try to upload my code

```
#include <ESP8266WiFi.h>
#include <ESP8266WiFiMulti.h>

#ifndef STASSID
#define STASSID "your-ssid"
#define STAPSK  "your-password"
#endif

const char* ssid     = STASSID;
const char* password = STAPSK;

const char* host = "192.168.1.1";
const uint16_t port = 3000;

ESP8266WiFiMulti WiFiMulti;

void setup() {
  Serial.begin(115200);

  // We start by connecting to a WiFi network
  WiFi.mode(WIFI_STA);
  WiFiMulti.addAP(ssid, password);

  Serial.println();
  Serial.println();
  Serial.print("Wait for WiFi... ");

  while (WiFiMulti.run() != WL_CONNECTED) {
    Serial.print(".");
    delay(500);
  }

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

  delay(500);
}

void loop() {
  Serial.print("connecting to ");
  Serial.print(host);
  Serial.print(':');
  Serial.println(port);

  // Use WiFiClient class to create TCP connections
  WiFiClient client;

  if (!client.connect(host, port)) {
    Serial.println("connection failed");
    Serial.println("wait 5 sec...");
    delay(5000);
    return;
  }

  // This will send the request to the server
  client.println("hello from ESP8266");

  //read back one line from server
  Serial.println("receiving from remote server");
  String line = client.readStringUntil('\r');
  Serial.println(line);

  Serial.println("closing connection");
  client.stop();

  Serial.println("wait 5 sec...");
  delay(5000);
}

```

# Answer
Try updating the Serial Driver in your system or try using lesser baud rate, i.e. 9600 instead of 115200.
> 1 votes

---
Tags: esp8266, upload
---


title: Sea level pressure for BMP280

text:
# Question
Title: Sea level pressure for BMP280
I have a BMP280 and BMP180 pressure sensor and I have both of them connected via I²C to a ESP8266.

For the BMP180, I can get the sea level air pressure when I pass the pressure and altitude like so:

```
// https://github.com/sparkfun/BMP180_Breakout_Arduino_Library
#include <SFE_BMP180.h>
SFE_BMP180 bmp180;
[...]
Serial.print(bmp180.sealevel(pressure, 800));

```

Is there a similar thing for the BMP280? Reading pressure and temperature works fine:

```
#include <Adafruit_BMP280.h>
Adafruit_BMP280 bmp280;
[...]
double temperature = bmp280.readTemperature();
double pressure = bmp280.readPressure() / 100;

```

# Answer
> 1 votes
It seems this was planned for the Adafruit BMP280 library but not implemented. Looking at `Adafruit_BMP280.h` we see commented code that has a method `seaLevelForAltitude()`:

```
/*
class Adafruit_BMP280_Unified : public Adafruit_Sensor
{
  public:
    Adafruit_BMP280_Unified(int32_t sensorID = -1);

    bool  begin(uint8_t addr = BMP280_ADDRESS, uint8_t chipid = BMP280_CHIPID);
    void  getTemperature(float *temp);
    void  getPressure(float *pressure);
    float pressureToAltitude(float seaLevel, float atmospheric, float temp);
    float seaLevelForAltitude(float altitude, float atmospheric, float temp);
    void  getEvent(sensors_event_t*);
    void  getSensor(sensor_t*);

  private:
    uint8_t   _i2c_addr;
    int32_t   _sensorID;
};

*/

```

In another library, BMP280-arduino-library, I found a function that seems to work:

```
double BMP280::sealevel(double P, double A)
// Given a pressure P (mb) taken at a specific altitude (meters),
// return the equivalent pressure (mb) at sea level.
// This produces pressure readings that can be used for weather measurements.
{
    return(P/pow(1-(A/44330.0),5.255));
}

```

First, I just copied that function into my code (without the class name), due to the friendly pizza license. Later I switched to that library and it also worked fine.

# Answer
> 2 votes
Try this following segment: I used it myself and it worked fine.

As you don't get any default Method for returning the sea-level pressure from BMP280, I had to calculate on my own.

```
#include <Wire.h>
#include "SPI.h" //Why? Because library supports SPI and I2C connection
#include <Adafruit_Sensor.h>
#include <Adafruit_BMP280.h>

//Setup connection of the sensor
Adafruit_BMP280 bmp; // I2C
/*//For SPI connection!
#define BMP_SCK 13
#define BMP_MISO 12
#define BMP_MOSI 11
#define BMP_CS 10
//Adafruit_BMP280 bme(BMP_CS); // hardware SPI
//Adafruit_BMP280 bme(BMP_CS, BMP_MOSI, BMP_MISO,  BMP_SCK);
*/

//Variables
float pressure;       //To store the barometric pressure (Pa)
float temperature;    //To store the temperature (oC)
float SLpressure_mB;
int ELEVATION = 9;  //PUT HERE THE ELEVATION OF YOUR LOCATION IN METERS

void setup() {
  bmp.begin();    //Begin the sensor
    Serial.begin(9600); //Begin serial communication at 9600bps
    Serial.println("Equivalent Sea Level Pressure Test:");
}

void loop() {
  //Read values from the sensor:
  pressure = bmp.readPressure();
  temperature = bmp.readTemperature();
  SLpressure_mB = (((pressure * 100.0)/pow((1-((float)(ELEVATION))/44330), 5.255))/100.0)
  //Print values to serial monitor:
  Serial.print(F("Pressure: "));
    Serial.print(pressure, 2);
    Serial.print(" Pa");
    Serial.print("\t");
    Serial.print(("Temp: "));
    Serial.print(temperature);
    Serial.print(" oC");
  Serial.print("\t");
    Serial.print("Equivalent Sea Level Pressure: ");
    Serial.print(SLpressure_mB, 2);
    Serial.println(" mB");

    delay(5000); //Update every 5 sec
}

```

---
Tags: sensors
---


# Question
Title: How to change wifi credentials of multiple ESP8266 together
I need to change WiFi credentials of multiple ESP8266 in one go, without needing to change passwords for each of them individually. I know there is a WiFiManager library, which makes your ESP8266 access point when not connected to any network, but that will require me configure each of them individually.

How can I save the fatigue of changing their wifi credentials individually? All of them needs to connect to the same network, whose password is recently changed.

# Answer
> 1 votes
you can reconfigure your router, or whatever network mode you are using, with auto-login to the MAC addresses of your ESPs.

And then if you provide the MACs of the corresponding ESPs, and change your WiFi credentials, then you don't need to configure the ESPs individually. It will auto-connect itself.

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

---
Tags: esp8266, wifi, library, network
---


# Question
Title: How can I set two PWM at two different frequencies?
I'm using the arduino uno hooked up to two LEDs. One is in pin 3 and the other one in pin 5. I know that pin 3 is controlled by timer3 and pin 5 by timer 1. I've tried a lot of things to have two independent frequencies. I really don't care about the PWM, I have it to 50% (constant).

There are resources to set the frequency (http://playground.arduino.cc/Main/TimerPWMCheatsheet), but these are predefined frequencies. I need to have one PWM at 650Hz and the other at 850Hz.

Any recommendations on how to approach this problem?

# Answer
> 4 votes
The ATMega PWM hardware underlying the Arduino primarily supports changing the duty cycle; the frequencies can only be selected from a few fixed choices. Typically the timers run from 0 to 255 or 65535 and loop back to 0, and you can select where within that full cycle the output changes on and off.

Since what you want is a simple 50% duty cycle with fine control of frequency, the PWM functions are not very useful. What you want is tone or frequency control. The ATMega timers support this too, but it's a different function than PWM. For frequency control, the timer will cycle from 0 to your choice of upper limit. So for example, you might count up to 200 instead of 255; or to 201 - so you get much finer control of frequency.

Unlike PWM, on the ATMega328p used in the Uno, you can only get one frequency per timer (you can get two PWM outputs per timer - both at the same frequency). And if you want millis() and microseconds() and delay() to continue to work, you don't want to mess with timer 0 for frequency control (you can get PWM from timer 0 if you accept the default frequencies).

So that leaves you with two frequency controllable timers - timer 1 (16 bit resolution) and timer 2 (8 bit resolution).

See the tone() function in the Arduino library for examples of a single tone at a time.

For multiple simultaneous frequencies (on different pins) see this library: https://code.google.com/p/rogue-code/wiki/ToneLibraryDocumentation. You can have two tones at a time, or three if you don't need millis() etc.

# Answer
> 0 votes
There is a great library with functions to change PWM frequency on Arduino microcontrollers, called arduino-pwm-frequency-library. I hope this helps you.

# Answer
> 0 votes
IF you need to dim leds use:

```
/*PWM signal on most pins is approximately 490 Hz
On the Uno and similar boards, pins 5 and 6
have a frequency of approximately 980 Hz
brightness1, brightness2 = from 0(0v) to 255(5v)
So make eqution to calculate needed frequency*/

//LED are connected to:
const int ledPin1 = 5;
const int ledPin2 = 6;
byte brightness1 = 100; // ~2v
byte brightness2 = 200; // ~4v
void setup()
{
  // initialize the ledPin as an output:
  pinMode(ledPin1, OUTPUT);
  pinMode(ledPin2, OUTPUT);
}

void loop() {
    // set the brightness of the LED:
    analogWrite(ledPin1, brightness1);
    analogWrite(ledPin2, brightness2);

}

```

# Answer
> 0 votes
I recommend you to use two PWM signal with different duty cycles with the same frequency using timer1 and output pins 9 and 10. The next sketch was tested and it works very well.

```
 /*
 * Este programa genera 2 PWM signals a partir del timer 1. Las dos señales tienen la misma frecuencia (250Hz)
 * lo que varia es el duty cycle independiente para cada señal. Una sale por el pin 9 y la otra por el pin 10.
 */
#include <avr/io.h>
#include <avr/interrupt.h>

void setup() {
  Serial.begin(115200);
  // put your setup code here, to run once:
  //******** PWM Variable Definitions
**********************************************************
  // Register initilisation, see datasheet for more detail.
  TCCR1A = 0b10100010;
  //Timer/Counter1 Control Register A COM1A1 COM1A0 COM1B1 COM1B0 - - WGM11 WGM10
  // COM1A1 COM1A0 COM1B1 COM1B0
  //   1      0      1      0       Clear OC1A/OC1B on Compare Match, set OC1A/OC1B at BOTTOM (non-inverting mode)
  TCCR1B = 0b00011001;
  //Timer/Counter1 Control Register B ICNC1 ICES1 - WGM13 WGM12 CS12 CS11 CS10
  // ICR1 Register is not double buffered. Using the ICR1 Register for defining TOP works well when using fixed TOP values.
  // By using ICR1, the OCR1A Register is free to be used for generating a PWM output on OC1A. That's why, I am using WGM 14.
  // WGM13 WGM12 WGM11 WGM10
  //   1     1    1     0           Fast PWM ICR1 - fixed TOP, update of OCR1x at BOTTOM. WGM 14 (Table 13-4).
  // ICNC1 is 0                     the Input Capture Noise Canceler is disable
  // ICES1 is 0                     falling (negative) edge is used as trigger
  // CS12 CS11 CS10
  //  0    0    1                   No prescaling
  TIMSK1 = 0b00000001; // Timer/Counter1 Interrupt Mask Register. The Timer/Counter1 Overflow interrupt is enabled.
  // TOP value is put in ICR1 and is equal to 64000, it means that 16000000 / 64000 = 250Hz (since no prescaling), the frequency of PWM signals
  ICR1   = 64000;
  DDRB = 0b00000110; // Set PB1(DB9) and PB2(DB10) as outputs.
  interrupts ();
}
 void loop() {
  // put your main code here, to run repeatedly:
}

 ISR(TIMER1_OVF_vect) {
  // change duty-cycle every period.
  OCR1A = 16000;// in OCR1A is put the value corresponding to duty cycle, OCR1A output pin is 9. Duty cycle 25%. 16000 / 64000 = 0.25
  OCR1B = 48000;// the output pin of OCR1B is 10, duty cycle 75%. 48000 / 64000 = 0.75
}

```

---
Tags: arduino-uno
---


# Question
Title: Problem with serial input from android serial usb app
I'm using two (nrf24L01 + Arduino Uno) nodes to communicate with each other. Serial input from node1 will be sent to node2. A special character 'p' when sent to node2, it will reply that it's available. It is working fine when using arduino ide serial monitor on pc. When I use serial usb app on android to get serial input only the text is sent to another node and the special character sent does nothing and prints like any other message.

# Answer
I solved this problem by turning off CR+LF and selecting None for newline in send section. CR+LF was adding something extra to my input. By removing that program works fine with Android.

About CR,LF : "Newline is a control character or sequence of control characters in a character encoding specification that is used to signify the end of a line of text and the start of a new one. Some text editors set this special character when pressing the ↵ Enter key." - (Wikipedia)
> 1 votes

---
Tags: arduino-uno, serial, arduino-ide
---


# Question
Title: Difference between these two NodeMCU boards?
I recently received a NodeMCU (identical to the one shown in the first picture below) and originally, I was unable to connect it to my computer which eventually turned out to be driver issues; however, during my initial panic, I found that there seems to be two variations of the NodeMCU board.

As you can see from the pictures below, at first glance there seems to be no difference to the boards, however, some of the more noticeable differences are that the first one has only one "orange" chip whereas the second one has two. Moreover, the first one has a large square chip towards the USB port wheareas the second seems to have a rectangular one.

First one:

Second one:

I would really appreciate if someone could enlighten me to what these small differences are between the two boards are and also what are the implications of these differences (if there are any).

Thank you in advance for any help,

Kind regards, John

# Answer
The top one is a real NodeMCU version 1 board (ESP-12E module).

The bottom one is a knock-off copy - looks like the same module on it.

The biggest difference is the USB interface. The real one uses a CP2102 USB to UART bridge. The copy uses a CH340G chip. The CH340G is notoriously unstable and liable to die at a moments notice. The CP2102 is far more reliable. I recently accidentally nuked a Wemos D1 Mini pro which has the same CP2102 on it with 12V. It took out the voltage regulator. It took out the ESP8266 chip. I replaced both those, and the CP2102 was proved to still be working fine. More than could be said for a CH340G - glance at one of those wrong and they die.
> 22 votes

# Answer
I have several of the second version and they all have the CP2102 USB to UART bridge. So I wouldn't say it's a copy or a clone. These are now made by several manufacturers, mine came from DOITING not AI Thinker, so the components can vary and come in different colours ! AND, Chinese is Good !
> 1 votes

---
Tags: esp8266, nodemcu, hardware, pcb-design
---


title: L298N Motor Driver with Nodemcu/ESP32

text:
# Question
Title: L298N Motor Driver with Nodemcu/ESP32
I have seen a lot tutorials on L298N motor driver with nodemcu and ESP 32, which are 3.3v logic boards where the motordriver is a 5v logic board, now in Arduino while doing speed control 255 means 5v or even a high means 5v but in nodemcu/ESP32 this means 3.3v, so my question is how it will work ?

# Answer
> 0 votes
It's not a question of voltage. You make a basic mis-assumption:

> in Arduino while doing speed control 255 means 5v

No, it doesn't. 255 means "Provide a logic HIGH signal all the time".

128 means "Provide a logic HIGH signal 50% of the time".

The 255 (or whatever number) is the "duty cycle" of a PWM signal. That is a digital signal that can be LOW or HIGH which is switching on or off rapidly. The duty cycle defines the ratio of ON time to OFF time.

You're not providing a voltage - you're providing an ON/OFF signal.

As long as the HIGH voltage of that signal is above the *threshold* of the receiving device (the L298N in this case) then it will see it as an ON/OFF signal.

According to the datasheet for the L298 the HIGH logic threshold (VIH) is 2.3V. That means anything above 2.3V is seen as ON and anyting below that is seen as OFF (actually there is hysteresis, so it has to drop below 1.5V to switch to OFF).

So your 3.3V from the NodeMCU is above that ON threshold, so the ON/OFF PWM signal is received properly as such.

Incidentally, it's because of this PWM signal that motors make a whining sound when they start up slowly. Because of this most proper motor drivers run the PWM at above 25kHz instead of the 500-ish Hz of the Arduino, so that whine is above the threshold of human hearing.

---
Tags: arduino-uno, nodemcu, esp32, l298n
---


# Question
Title: Is AT command the only way to connect from Arduino to esp2866?
If I am programming an arduino and I wanted to communicate with the internet thru the esp2866 then is AT command the only thing that I can do?

I see a lot of this in the web

```
void loop() {
 valSensor = getSensorData();
 String getData = "GET /update?api_key="+ API +"&"+ field +"="+String(valSensor);
sendCommand("AT+CIPMUX=1",5,"OK");
 sendCommand("AT+CIPSTART=0,\"TCP\",\""+ HOST +"\","+ PORT,15,"OK");
 sendCommand("AT+CIPSEND=0," +String(getData.length()+4),4,">");
 esp8266.println(getData);delay(1500);countTrueCommand++;
 sendCommand("AT+CIPCLOSE=0",5,"OK");
}

```

If I set my Board -\> Arduino Uno, I was thinking I can use the following library https://arduino-esp8266.readthedocs.io/en/2.7.4\_a/esp8266wifi/readme.html

```
#include <ESP8266WiFi.h>

const char* ssid     = "my-ssid";
const char* password = "my-password";

void setup() {
  Serial.begin(115200);
  // We start by connecting to a WiFi network

  Serial.println();
  Serial.println();
  Serial.print("Connecting to ");
  Serial.println(ssid);

  WiFi.begin(ssid, password);

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

```

But I am getting

```
exit status 1
ESP8266WiFi.h: No such file or directory

```

Looks like the following library is only available when you set the Board-\> Generic ESP8266 Module and is only used when you want to program the ESP8266 in the Arduino IDE? Is this correct?

So in my question, does it mean that to communicate from the Arduino into the internet, I will be sending the AT command and communicate thru the SoftwareSerial.h?

# Answer
> 2 votes
> is AT command the only thing that I can do?

No. The AT commands are provided by the AT command firmware. You can replace that firmware with whatever you want.

It is common to write your own software for the ESP8266 to do your communication for you and communicate with other devices (including an Arduino) in whatever way is suitable.

Many times you don't even need the Arduino any more as the ESP8266 can do everything (it struggles with analog signals as there is only one rather inferior ADC pin).

> Looks like the following library is only available when you set the Board-\> Generic ESP8266 Module and is only used when you want to program the ESP8266 in the Arduino IDE? Is this correct?

That is correct. That is for when you are writing your own ESP8266 firmware to replace the AT firmware.

> So in my question, does it mean that to communicate from the Arduino into the internet, I will be sending the AT command and communicate thru the SoftwareSerial.h?

Only if you retain the AT firmware on the ESP8266. To be honest that firmware is terrible and all the tutorials are bad. You should at the first available opportunity learn to program the ESP8266 directly and maybe retire the Arduino unless you need to use it as a glorified IO expander.

---
Tags: arduino-uno, esp8266
---


# Question
Title: Making two Arduinos/MKR1000s communicate
I am trying to create a project in my free time just for a bit of fun. It consists of two MKR1000s (one acting as a web server connected to one laptop, and the other acting as a web client connected to a different laptop - so I can view the Serial Monitor).

One MKR1000 has a potentiometer attached to it (therefore I can change the value of it), and sends the potentiometer value to the serial monitor every 4 seconds.

**THE AIM:** Once the web server sets up the w WifFi network, and the web client connects to that WiFi network, I want to send the potentiometer value across to the web client every time it gets updated. However, I am clueless on how to achieve this.

**This is my web server void loop code** (the rest is similar to the https://www.arduino.cc/en/Tutorial/Wifi101WiFiWebServer):

```
void loop() {
  WiFiClient client = server.available();
  // listen for incoming clients
  if (client) {
    // if you get a client,
    Serial.println("new client");
    // print a message out the serial port
    String currentLine = "";
    // make a String to hold incoming data from the client
    while (client.connected()) {
      // loop while the client's connected
      if (client.available()) {
        // if there's bytes to read from the client,
        char c = client.read();
        // read a byte, then
        Serial.write(c);
        // print it out the serial monitor
        if (c == '\n') {
          if (currentLine.length() == 0) {
            client.println("HTTP/1.1 200 OK");
            client.println("Content-type:text/html");
            client.println();
            // the content of the HTTP response follows the header:
            client.print("Click <a href=\"/showValue\">here</a> showValue of the potentiometer <br>");
            // The HTTP response ends with another blank line:
            client.println();
            // break out of the while loop:
            break;
          } else {
            // if you got a newline, then clear currentLine:
            currentLine = "";
          }
        } else if (c != '\r') {
          currentLine += c;
          // add it to the end of the currentLine
        }
        if (currentLine.endsWith("GET /showValue")) {
          Serial.println(sensorValue);
          delay(2000);
        }
      }
    }
    client.stop();
  }
}

```

**And this is my web client code I use this** https://www.arduino.cc/en/Tutorial/Wifi101WiFiWebClient \- I am not sure how I should modify this in order to receive the potentiometer value across from the web server MKR1000. Any tips or hints would be hugely appreciated!

I am sorry if this is a simple question, however I am just starting with the Arduino idea, and I'm new to coding!

# Answer
> 1 votes
At the bottom of the page for the client code link you provided, there's a link to a Chat Server example. If you study the code I think you'll see how to send and receive the potentiometer reading. Hint: Look in the code where it echoes what it receives.

mkr1000 WiFi Chat Server

# Answer
> 0 votes
You don't have to use a webserver/webclient for this; a raw socket would also work. If you do want to use "web technology":

You can either have the webclient poll the webserver periodically for a new value (ask for a new value every few seconds, and interpret the response), or have the webserver initiate the communication every time a new value is available.

For the latter, you could use Server-Sent Events (SSE) or a Websocket, both of which are very google-able.

I have made examples for both, but these examples are fairly large and have extra functionality. Still, they may give you some pointers and/or code to reuse.

These examples are here:

https://github.com/ocrdu/arduino-webinterface-sse

and here:

https://github.com/ocrdu/arduino-webinterface-websocket-ap

Note that the client side in the examples is a webpage in a webbrowser, but the principle is the same.

---
Tags: arduino-uno, arduino-ide, wifi, communication, mkr1000
---


title: Counter program

text:
# Question
Title: Counter program
I'm an absolute beginner, and lately I had some problem with this program I was trying to do. Basically I wanted with the Arduino to count 3 pulses from an oscillator and store the time of these 3 pulses, but as I said I am a beginner so I have no Idea on how to do it, I would appreciate your help.

# Answer
While this is likely to need tweaks for your needs, it should get you looking at the right things - millis, interrupts, etc. Official references at: https://www.arduino.cc/reference/en/language/functions/external-interrupts/attachinterrupt/ https://www.arduino.cc/reference/en/language/functions/time/millis/

```

#define pulsesToStore 3
#define interruptPin 2
volatile unsigned char index;
unsigned long storedTimes[pulsesToStore];

void restartStorage() {
 index = 0;
 attachInterrupt(digitalPinToInterrupt(interruptPin), storeTime, RISING);
}

void storeTime() {
 storedTimes[index] = millis();
 index = index + 1;
 if(index >= pulsesToStore) { //stop storage
  detachInterrupt(digitalPinToInterrupt(interruptPin));
 }
}

void setup() {
 pinMode(interruptPin, INPUT_PULLUP);
 restartStorage();
}

void loop() {
  // does nothing for now.  this is where you would do something with the stored pulses, print to serial, etc.
}

```
> 1 votes

# Answer
Simple code

```
int pin = 7;
unsigned long duration;

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

void loop() {
long duration = pulseIn(pin, HIGH);
 Serial.println(duration);
//delay(100);
}

```

Assuming that you are mentioning a squrewave this code mesures the time that squrewave pulse stays in `HIGH` and prints out in computer serial monitor.

You should send the signal to digital pin 7 (or put any pin you won't modify code `int pin = 7;`) 5 V HIGH and 0 V LOW.

The time unit measuring in here is in microseconds. If you won't to measure low then `pulseIn(pin, LOW);`

**I took the example from Arduino official site you can refer more here**

https://www.arduino.cc/reference/en/language/functions/advanced-io/pulsein/

Remember this is the basic example there are other good methods than this...

Analog wave is bit too complex.
> 1 votes

---
Tags: programming, arduino-nano, c++
---


# Question
Title: Is there a method of figuring out whether or not my stepper drivers are dead?
I'm working on a project that involves stepper motors, and I'm mainly using DRV8825 stepper drivers. At the moment, it seems like only one of my drivers actually gives the motors any current. The others usually return 0s when I measure their VREFs. One returns a value but still can't pull the motors. After checking all of my DRV8825s and finding only two returned VREFs, I checked my A4988s and none of them gave anything (aside from power supply voltage when measuring different pins). Is there a way I can figure out whether my stepper drivers are actually fried? I have a suspicion that maybe the potentiometers on the drivers are thrown off or there's some other issue I can't place. I'm happy to give more information if that can help to figure out what's going on here. Thank you!

# Answer
> 1 votes
Most surefire way to tell if your drivers work is to wire them up CORRECTLY and try them out. You should not be frying them if you have the correct setup (including current limit) for your conditions. That said, conditions include your heat sink install and the environmental temperature.

The usual gotchas:

* Note that DRV8825 and A4988s may have different pin locations so be sure to orient them correctly (check their EN pin location) if using a shield.
* Also note that the gains from the voltage to the current limits will be different for the different model #s. Be sure to use an appropriately sized screw driver and attach the meter to the screw driver as you turn to adjust the current limit.

---
Tags: stepper
---


# Question
Title: What is the logic behind Arduino inlining `HardwareSerial::_rx_complete_irq()` for receiving serial data (but NOT `_tx_udr_empty_irq()`)?
Q: What is the logic behind Arduino inlining `HardwareSerial::_rx_complete_irq()` for receiving serial data (but NOT `_tx_udr_empty_irq()`), and when is it advisable?

From the bottom of the `HardwareSerial` class in HardwareSerial.h:

```
// Interrupt handlers - Not intended to be called externally
inline void _rx_complete_irq(void);  // <======= inline!
void _tx_udr_empty_irq(void);        // <======= NOT inline! Why?

```

Furthermore, what is the design logic behind putting one of the serial ISR function definitions in a header file vs in a source file? Also, when is this good design and what are the tradeoffs, and when is it illegal or not permitted by the language, compiler or anything else?

Here is the exact scenario that made me think of this question:

---

See here for the HardwareSerial implementation files: https://github.com/arduino/ArduinoCore-avr/tree/master/cores/arduino

Here is the main header file. https://github.com/arduino/ArduinoCore-avr/blob/master/cores/arduino/HardwareSerial.h

# The inline ISR `_rx_complete_irq()`:

* Line 138 of "HardwareSerial.h" declares the inline ISR for when serial data is received:

```
 inline void _rx_complete_irq(void);

```

+ This ISR is called whenever "there are unread data present in the receive buffer." (ATmega328 Datasheet 20.7.3 p190)
    + Line 40 and 48-50 of "HardwareSerial0.cpp" is where the ISR is set up:

    ```
       ISR(USART_RX_vect)  // line 40
       {                   // line 48
         Serial._rx_complete_irq();  // line 49
       }                   // line 50

    ```
    + Line 101-121 of "HardwareSerial\_private.h" implements the inline `_rx_complete_irq()` function:

    ```
      void HardwareSerial::_rx_complete_irq(void)
      {
        if (bit_is_clear(*_ucsra, UPE0)) {
          // No Parity error, read byte and store it in the buffer if there is
          // room
          unsigned char c = *_udr;
          rx_buffer_index_t i = (unsigned int)(_rx_buffer_head + 1) % SERIAL_RX_BUFFER_SIZE;

          // if we should be storing the received character into the location
          // just before the tail (meaning that the head would advance to the
          // current location of the tail), we're about to overflow the buffer
          // and so we don't write the character or advance the head.
          if (i != _rx_buffer_tail) {
            _rx_buffer[_rx_buffer_head] = c;
            _rx_buffer_head = i;
          }
        } else {
          // Parity error, read byte but discard it
          *_udr;
        };
      }

    ```

# The NON-inline ISR `_tx_udr_empty_irq()`:

* Line 139 of "HardwareSerial.h" declares the ISR for transmitting serial data: `void _tx_udr_empty_irq(void);`
    + This ISR is triggered by the "USART Data Register Empty" flag and is called whenever the transmit buffer has passed its value to the shift register and now is "ready to receive new data" (ATmega328 Datasheet 20.11.2 p200)
    + Its implementation is on lines 89-113 of "HardwareSerial.cpp"

    ```
       void HardwareSerial::_tx_udr_empty_irq(void)
       {
         // If interrupts are enabled, there must be more data in the output
         // buffer. Send the next byte
         unsigned char c = _tx_buffer[_tx_buffer_tail];
         _tx_buffer_tail = (_tx_buffer_tail + 1) % SERIAL_TX_BUFFER_SIZE;

         *_udr = c;

         // clear the TXC bit -- "can be cleared by writing a one to its bit
         // location". This makes sure flush() won't return until the bytes
         // actually got written. Other r/w bits are preserved, and zeroes
         // written to the rest.

       #ifdef MPCM0
         *_ucsra = ((*_ucsra) & ((1 << U2X0) | (1 << MPCM0))) | (1 << TXC0);
       #else
         *_ucsra = ((*_ucsra) & ((1 << U2X0) | (1 << TXC0)));
       #endif

         if (_tx_buffer_head == _tx_buffer_tail) {
           // Buffer empty, so disable interrupts
           cbi(*_ucsrb, UDRIE0);
         }
       }

    ```

**Why the difference? Why inline one ISR and not the other?**

Again, from the bottom of the `HardwareSerial` class in HardwareSerial.h:

```
// Interrupt handlers - Not intended to be called externally
inline void _rx_complete_irq(void);  // <======= inline!
void _tx_udr_empty_irq(void);        // <======= NOT inline! Why?

```

**Why the somewhat complicated set of 3+ files? Mainly:**

* HardwareSerial.h
* HardwareSerial\_private.h
* HardwareSerial.cpp

I first documented this to myself and wondered about it on 31 Jan. 2018, while studying the Arduino source code. I'd like to hear some more insight on the topic from other developers.

# Answer
> 7 votes
> What is the logic behind Arduino inlining HardwareSerial::\_rx\_complete\_irq() for receiving serial data (but NOT \_tx\_udr\_empty\_irq()), and when is it advisable?

There's a couple of reasons which end up with this arrangement:

1. The RX interrupt has to be fast as we're reacting to an external stimulus. The TX interrupt doesn't have to be fast as it's only used to move data from the buffer to the UART.

We need to be able to respond rapidly to incoming data so we can store it away in the RX ring buffer in time to handle the next byte that arrives. Not really a problem at low baud rates, but when it comes to higher ones every cycle that can be shaved off that interrupt time is beneficial. The TX interrupt, though, really doesn't matter. All it does is load the next byte into the outgoing UART buffer, and it doesn't matter if that takes a little longer, so there's no need to shave off the extra instruction cycles consumed by making a function call.

2. The TX interrupt is called from multiple places but the RX isn't.

The RX interrupt code is only ever called when the interrupt fires. That means it's only ever going to be called through one execution path. However the TX interrupt code is not only called by the interrupt itself, but by other areas of the code. For example, if interrupts are disabled then the `write` function will manually poll the UART for the buffer state and manually call the interrupt function to send the data (see line 262 of HardwareSerial.cpp).

If the TX interrupt code were inlined then there would be lots of places throughout the code where that block would be duplicated causing code bloat. That's code bloat with no reason (See point 1) so it's something to be avoided.

> Furthermore, what is the design logic behind putting one of the serial ISR function definitions in a header file vs in a source file?

Inlining can only be done within a single *translation unit*. If you want a function to be inlined in multiple translation units (HardwareSerial0.cpp, HardwareSerial1.cpp, etc) then you would have to have it within those translation units. And that means that you need it in the header1. Since the TX interrupt is not wanted to be inlined it can be put in a CPP file instead.

> Why the somewhat complicated set of 3+ files?

Simple: management. It's easier to manage the (rather complex UART) code if it's broken down into different areas. You have a common base object in HardwareSerial.cpp which is then used by the code for each individual UART in the HardwareSerial\[0-3\].cpp files. You have a single header file that defines the class and all its methods and data (HardwareSerial.h). And then you have the "private" header with any inline functions in it that is included where it's needed.

True you could merge the HardwareSerial.h and the HardwareSerial\_private.h into one, but this way the inline functions are excluded from translation units where they aren't needed. This way you don't get those chunks of code included in your sketch. True the linker will discard them as they're not used, but it's just tidier this way - the functions are only included in those translation units where those function are actually used.

---

Notes:

1. This code was written before the compiler had support for *Link Time Optimization* which allows inlining between translation units. The compiler may have moved on, but there is no point in changing code that works perfectly fine.

---
Tags: c++, header, inline
---


title: Controling 5V relay with Wemos D1 R1

text:
# Question
Title: Controling 5V relay with Wemos D1 R1
I would like to control a 5V relay with Wemos D1 R1 module through webserver. I'm using the following modules:

* Tongling 5vdc Relay
* Wemos D1 R1

I'm using the following schematic:

and here is the code I'm using:

```
#include <ESP8266WiFi.h>

const char* ssid = "Myssidname";
const char* password = "Myssidpass";

int ledPin = D3;
WiFiServer server(80);

void setup() {
 Serial.begin(9600);
 delay(10);

 pinMode(ledPin, OUTPUT);
 digitalWrite(ledPin, LOW);

 // Connect to WiFi network
 Serial.println();
 Serial.println();
 Serial.print("Connecting to ");
 Serial.println(ssid);

 WiFi.begin(ssid, password);

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

 // Start the server
 server.begin();
 Serial.println("Server started");

 // Print the IP address
 Serial.print("Use this URL : ");
 Serial.print("http://");
 Serial.print(WiFi.localIP());
 Serial.println("/");

}

void loop() {
 // Check if a client has connected
 WiFiClient client = server.available();
 if (!client) {
   return;
 }

 // Wait until the client sends some data
 Serial.println("new client");
 while(!client.available()){
   delay(1);
 }

 // Read the first line of the request
 String request = client.readStringUntil('\r');
 Serial.println(request);
 client.flush();

 // Match the request

 int value = LOW;
 if (request.indexOf("/LED=ON") != -1) {
   digitalWrite(ledPin, HIGH);
   value = HIGH;
 }
 if (request.indexOf("/LED=OFF") != -1){
   digitalWrite(ledPin, LOW);
   value = LOW;
 }

 // Return the response
 client.println("HTTP/1.1 200 OK");
 client.println("Content-Type: text/html");
 client.println(""); //  do not forget this one
 client.println("<!DOCTYPE HTML>");
 client.println("<html>");

 client.print("Led pin is now: ");

 if(value == HIGH) {
   client.print("On");
 } else {
   client.print("Off");
 }
 client.println("<br><br>");
 client.println("Click <a href=\"/LED=ON\">here</a> Turn relay ON<br>");
 client.println("Click <a href=\"/LED=OFF\">here</a> Turn relay OFF<br>");
 client.println("</html>");

 delay(1);
 Serial.println("Client disconnected");
 Serial.println("");

}

```

After uploading the code **successfully** and watching the monitor, the light gets turned on and I get the following message:

```
16:02:20.400 -> WiFi connected
16:02:20.425 -> Server started
16:02:20.479 -> Use this URL : http://192.168.100.7/
16:02:41.680 -> new client
16:02:41.680 -> GET / HTTP/1.1
16:02:41.680 -> Client disconnected

```

However, when I turn on or off the relay using the browser, nothing happens:

```
19:38:56.010 -> new client
19:38:56.010 -> GET /LED=ON HTTP/1.1
19:38:56.010 -> Client disconnected
19:38:57.016 -> new client
19:38:57.016 -> GET /LED=OFF HTTP/1.1
19:38:57.063 -> Client disconnected

```

However nothing happens to the light and relay doesn't click.

**a few more notes:**

* I tried in upload the code with relay at high to disconnect the circuit but light is still on
* Wemos Network name appears in my network list
* It doesn't not respond to AT Commands

# Answer
The issue lies with Wemos Module where it only outputs 3.3V which insufficient to 5V Relay so this can be solved by implementing 2N2222 Transistor as per schematic below.
> 1 votes

# Answer
Is the Wemos D1 R1 a 5V board, or 3.3V? If it's a 3.3V board, that's your problem. Get a 3.3V relay.

(From a little digging it looks like the Wemos is a 3.3V device. If so, that is your problem. Those "digital relays" are available in 5V and 3.3V models. Replace your 5V relay with a 3.3V relay.)

What are the current requirements of the relay, and what is the max current you can draw out of the Wemos? How are you powering the Wemos?

I would say break this into pieces and solve them separately. Put a multimeter (OR an LED with a current limiting resistor) on pin D3 and make sure the pin is turning on and off. If it is, it is a problem with your relay. If it's not, it's a problem with your sketch or your Arduino.

If the pin is turning on and off, try attaching the IN pin on your relay directly to +5V. Does your lightbulb light then?
> 0 votes

---
Tags: esp8266, arduino-ide, wifi, relay, web-server
---


title: How to fix serial communication?

text:
# Question
Title: How to fix serial communication?
I am trying to use serial communication to open and close a Blue Robotics Newton gripper. The gripper works with normal commands, but when I try to use serial communication to control it, it is extremely slow and my commands do not correspond to the action I would like. For example, I'll write a "o" in the serial monitor and the gripper will not open.

Does anyone know what is wrong?

```
#include "Servo.h"

#define GRIPPER_PWM_PIN   10    // Gripper PWM output pin
#define OPEN_TIME         5.0   // Gripper open time (seconds)
#define CLOSE_TIME        5.0   // Gripper close time (seconds)

#define OPEN_PWM_US       1100  // Gripper open PWM output (us)
#define CLOSE_PWM_US      1900  // Gripper close PWM output (us)
int incomingByte =0; // for incoming serial data
Servo gripper;

void setup() {
 // Attach gripper to proper pin
 gripper.attach(GRIPPER_PWM_PIN);
 Serial.begin(9600); // opens serial port, sets data rate to 9600 bps

}

void loop() {
 if (Serial.available() > 0){
   incomingByte = Serial.read();
   if (incomingByte == 'o')
   {
     // Open the gripper
     gripper.writeMicroseconds(1100);
     // Let the gripper open up (microseconds)
     delay(OPEN_TIME*1000);
   }

   if (incomingByte == 'c')
   {
     // Close the gripper
     gripper.writeMicroseconds(1900);
     // Let the gripper close for a while (microseconds)
     delay(CLOSE_TIME*1000);
   }
 }
}

```

# Answer
You have a big 5s delay in your code, right after both serial commands. You don't need a delay there; it does not do anything. But it makes your code unresponsive. So you can simply remove it.

I guess you wanted to do some timed thing there and accidentally left it there. But in general you should not use any big `delay()` in any code. As you have seen, it makes your code unresponsive, as the Arduino doesn't do anything during this time. Instead look at the `BlinkWithoutDelay` example, that comes with the Arduino IDE (Its a really important principle to learn). It uses the `millis()` function (or alternatively the `micros()` function) to check, if it is time to do something. If yes, it will execute this, if not, it will exit fast and give the rest of the code an opportunity to execute. Much like you would bake a pizza: You start the baking and then regularly check the clock, if it is time to take the pizza out. In between you can do other things, like reacting go messages on your phone. Its the same principle, just in code.
> 0 votes

---
Tags: serial
---


# Question
Title: Arduino MKR GSM 1400: Can I tell from code if the power has tripped
Is there a way to tell if an Arduino MKR GSM 1400 has lost power and has to rely on the connected battery?

Ideally, I'd like to do this without adding additional circuitry. Alternatively, can I connect VIn to an analogue input pin?

On the schematic, there are two lines that seem promising. One named VBATT\2.4B that go into PB09 of U1 via a voltage divider and another named VBAT\1.4B. Also the BQ24195L is an I2C device which would probably be connected the the main micro controller.

What I need to do is to send an SMS as soon as the incoming power is lost to notify a user that the power supply has tripped. Does anyone have any code samples?

# Answer
> 2 votes
`VBATT/2.4B` is used for measuring the batter voltage using the internal ADC of the MCU. It can't really tell if the battery is being used or not - except by maybe monitoring it over time and see if the voltage goes up or down.

However the BQ24195 is where all your hope lies. It has a status register that can tell you all sorts of things.

For example it can tell you if there is incoming power, and what that incoming power is coming from (a USB host, a USB power adaptor, or operating in OTG mode). It can also tell you what the battery is doing - if it's charging, or not for example.

A quick google search throws up this library specifically for the purpose.

---
Tags: power, mkr-gsm-1400
---


# Question
Title: Can we control other servos with common servo code Arduino
I am trying to control MG996R using code for a typical servo (SG90)

I used an external power supply, 5V,2A
I connected the servo signal line to Arduino slot 7, servo positive to external power supply positive, servo ground to external power supply ground, while leaving the Arduino power supply and ground unconnected.

I tried the below code.
it works for SG90, while MG996R is not moving at all.

```

#include <Servo.h>
Servo myservo;

void setup()
{
  myservo.attach(7);  //pin 7 is the one control servo

}

void loop()
{

  for (int pos=0; pos<=60; pos++)
  {
    myservo.write(pos);
    delay(15);
  }

}

```

Is it because the different servos need different code?

# Answer
They work with same control signal, so the same code should work for both of them

You need make sure the ground of servo is both connected with the Arduino ground and the power supply ground (power supply ground for power supply positive, Arduino ground for the signal line)

I think SG90 worked even not connecting the Arduino ground is because the difference in design.

But you should always connect Servo ground to the Arduino ground.
> 1 votes

# Answer
@jsotola's comment is the answer, so I'll just quote it here:

> the two servos use the same control signal ... if one works, then the other should work also ... recheck your power and ground connections ... make sure that servo ground is connected to arduino ground ... confirm that the power supply stays at 5 V under load ... measure the voltage while trying to move the servo ... if the voltage holds at 5 V, then the servo is suspect

Also, make sure you're using the pin you set with `myservo.attach()`. Your comment says pin 9 but your code says pin 7, which is confusing. This code is using pin 7 as the servo signal:

> ```
> myservo.attach(7);  //pin 9 is the one control servo
>
> ```
> -1 votes

# Answer
I note on the manufacturers website for the MG996R that it has an operating voltage of 4.8V to 6.6V.

Your problem could be that your voltage (at the motor) is below the minimum voltage of 4.8V.

Try driving the motor with 6V.

Also make sure you are testing the motor with no load connected to the output.
> -1 votes

# Answer
The operating current (running current for the MG996R (~650 mA) is higher than SG90 (~220 mA) but definitely well in the capacity of a 5 V, 2 A. Unless there is a mechanical load on the servo motor, the motor is not limited by the current supply.

## The MG996R is a power beast. it is good idea to consider rechecking the supply voltage as well as trying with the supply greater than ~5 V.

PS: The code is definitely fine. Here is the simulation for the code you have posted which works fine with an emulator
> -1 votes

---
Tags: servo
---


title: Reset a UART connection on a Due

text:
# Question
Title: Reset a UART connection on a Due
I have a system that involves an Arduino Due connected to a Raspi 4 through UART in which the Due sends a heartbeat signal over UART for the pi to receive and send back as confirmation. One of the events that I need to handle is re-establishing the UART connection between the two devices if the program receiving UART on the pi (or the pi itself) fails for any reason and reboots. At the moment, I have the initial heartbeat working (as long as the pi program starts first) but when I stop the pi program to simulate a fatal error and restart it, the Due doesn't seem to receive heartbeat confirmation until it's reset as well.

Is there a clean way to reset just the one Serial connection from the Arduino script? I thought of using `Serial.end()` and `Serial.begin()` but that's really ugly and I'd prefer to avoid it. None of the other Serial library methods seem to provide the ability to reset the connection.

I'm using Serial2 at 115200 baud.

Edit: Including relevant heartbeat code:

```
#include <DueTimer.h>

bool heartbeat = true;

void rx_heartbeat() {
  int received_data;

  if (Serial2.available() > 0) {
    received_data = Serial2.read();
    heartbeat = true;
    Serial.println("beat");
  }
}

void setup() {
  Serial2.begin(115200);
  Timer1.attachInterrupt(heartbeat_ISR).setFrequency(1).start();
}

void loop() {
  rx_heartbeat();
}

void heartbeat_ISR() {
  if (heartbeat) {
    heartbeat = false;
  } else {
    // no heartbeat returned - stop normal operation
  }
  Serial.println("heart");
  Serial2.write(255);
}

```

# Answer
Silly me forgot to actually upload the code that fixed my issue. The code shown in the question is correct and works as intended.
> 1 votes

---
Tags: serial, arduino-due, uart, raspberrypi
---


# Question
Title: Can I program for Arduino without having a real board?
I would like to start the development of some basic Arduino projects but I don't own an Arduino board yet. Is there a way I can write my code and emulate/test it using a desktop computer so after my board arrives I just have to upload and run my project on it?

# Answer
There are a whole slew of Arduino simulators out there, many free, and some paid products as well.

* The CodeBlocks Arduino development environment includes a free Arduino simulator, still under development but functional.
* Simuino simulates the Arduino Uno and Mega pins - not a pretty-looking realistic simulator, but it works.
* The Python based Arduino Simulator is another option, that plays well with the official IDE
* Virtronics Simulator for Arduino looks promising, but I don't see why I would pay $14.99 for it, when I could buy one or more actual Arduino clones for that price

Many other Arduino simulators are out there if you search, and new ones are being announced, even crowdfunded, all the time.
> 140 votes

# Answer
I like to use circuits.io aka TinkerCAD for this.

It's cloud based and has some nice features including PCB design and collaboration.

IMO the Arduino simulation and capability is impressive and intuitive.
> 93 votes

# Answer
Plenty of options exist in the world of electronics simulators, but circuits.io aka TinkerCAD is probably the most versatile one out there.

* You can compose your circuit on a virtual breadboard which looks just like real.
* You can actually watch a LED blinking or press a button during real-time simulation rather than struggling with abstract waveforms.
* You can combine digital devices like a 555 timer or shift registers with (interactive) analog components like resistors and LEDs.
* You can program an Arduino and simulate the microcontroller together with your analog circuit around it.
* You can debug an Arduino: when the simulator reaches your breakpoint, the simulation is paused and you can easily check every variable in your code and every voltage or current in your circuit.
* You can use and observe different communication protocols like UART, I2C and SPI.
* You can pause the simulation in the middle of an I2C sequence by putting a breakpoint in the driver code (e.g. interrupt service routine for I2C events)
* It's FREE!

This is an example circuit that has with an IR Remote and an LCD Screen.

Disclaimer: We are the makers of 123D Circuits
> 44 votes

# Answer
Be aware that no simulator will reproduce real-life situations. There have been plenty of posts on the Arduino forum about problems with code or electronics, which turn out to be something subtle, such as:

* Timing issues
* Race conditions (related/dependent events not always happening in the same order)
* Voltage levels, eg. floating input pins
* Driving motors which drop the Arduino voltage enough that it resets
* Not having decoupling capacitors
* Input pins being in an "undefined" state (eg. 2.5V on a pin where 2 or less V is LOW and 3V or more is HIGH)
* Problems with interrupt handlers, such as variables not being declared volatile
* Voltage spikes due to not having flyback diodes on motors
* The processor resetting once more than 10 LEDs are turned on because the current draw exceeds the amount the hardware can supply
* Interrupt handlers taking 10 µS to process an interrupt when only 9 µS is available.

By their nature simulators can't reproduce all of this. Even if they could, would you think to toggle the "insert random noise from motors" option?

---

As for getting ready for the board to arrive, download the IDE and start programming. You can get libraries installed, code written and free of syntax errors, organize it neatly, and be generally ready for the big day when the hardware is in your hands.

---

Have fun and enjoy experimenting with your Arduino!
> 18 votes

# Answer
You can use Yenka (free for home use) to simulate Arduino, PIX, PIXACE and other boards with digital, analog and serial I/O. It provides a lot of components and sample projects.

Screenshot:
> 14 votes

# Answer
**Edit 2:** Please hit the like button to support free Arduino simulator

I am working with the new Wokwi Arduino Simulator. Wokwi Arduino simulator is based on AVR8js engine which is made open-source. You can find the link here

Following are the main features of the simulator

• Supports **multiple file** projects

• Supports the Arduino libraries

• Whatever compiles on the Arduino IDE will compile on the simulator

• Supported by **all browsers**

• Compiles with **latest Arduino IDE**

• Supports **FastLED** and many other peripherals

**No** download or installation needed

**Easy to share** the code and project with just a single click

• Smart - Code **Autocompletion**, Code **auto-formatting** are supported

• Provides standard library **demo examples**

• Project can be compiled on **RUN on Mobile browsers** as well

• Tries to be closer to real circuits – Example – **Button bounce** like in real hardware

• Supports Arduino Mega, Arduino Nano, Arduino UNO, **ATtiny85**

• Supports **assembly instruction** execution

• Provides **LED power** and **FPS features** for FastLED projects

• Supports a **plethora of Arduino peripherals** for the project – Ultrasonic sensors, Slide switches, NeoPixel matrix, Potentiometer, Servo motors, SSD1306 OLED displays, temperature and humidity sensors, rotary dialer, membrane keypad and more

**Serial monitor** is supported as well

# A few Arduino Examples

## Simon game using ATTiny85, buttons, buzzer, and LEDs

Project link: https://wokwi.com/arduino/projects/285525640477671948

• Note the use of the same pins for both output and input • The code can be written for ATTiny85 the same way how it is written for Arduino

---

## Slide switch demo example

Project link: https://wokwi.com/arduino/projects/292033853022798344

The slide switch can also be used as an ON-OFF switch

---

## Simple Piano Example

Project link: https://wokwi.com/arduino/projects/291958456169005577

Plays several notes based on Arduino built-in library support

---

## Max7219 LED dot matrix Arduino UNO project Example

Project link: https://wokwi.com/arduino/projects/290144516831183368

Supports concatenation of the Max7219 modules

---

## HC-SR04 Ultrasonic sensor Example

Project link: https://wokwi.com/arduino/projects/290056311044833800

A very useful project to build several interesting projects (RADAR 3D mapping and more )

---

## Bounce feature example in Arduino Simulator

Project link: https://wokwi.com/arduino/projects/288332630964830728

Bounce is the basic problem in most beginner projects. That can create multiple input triggers, unwanted noise and makes the project to misbehave. Sometimes can be difficult to identify without proper debug or measurement tools. Knowing about the bounce in switches and tips and tricks on how to solve it is an interesting study for every beginner hobbyist.

---

## LCD1602 display example in Wokwi Arduino Simulator

Project link: https://wokwi.com/arduino/projects/287736345015616008

LCD1602 is one of the best HMI and has been here for a long time. It helps in debugging projects during run time, we can also use it along with a keypad to make a completely practical HMI (human-machine interface). Very easy to use, and easy to learn about programming.

---

## FastLED example with FPS and LED power

Project link: https://wokwi.com/arduino/projects/287736345015616008

Second link: https://wokwi.com/arduino/projects/281176629596652040

FastLED is a second revolution in the history of LEDs. It was never easier than now to program multiple LEDs with just one Arduino Pin. With the growing FastLED community (reddit, wokwi-Discord, and others) and FastLED examples and libraries, This is one of the most important elements in the wokwi Simulator.

---

## Temperature and humidity sensor, Real time clock module example

Project link: https://wokwi.com/arduino/projects/287736345015616008

---

## Serial Monitor example

Project link: https://wokwi.com/arduino/projects/286653669554782732

The serial plotter is a very useful feature when working with analog peripherals.

---

The Arduino simulator is free for the Arduino Community to use. We are adding more elements one after the other. It is free and we invite you to try it as well.

Please leave a comment to add more libraries or features as well
> 14 votes

# Answer
Yes, you can, try using Proteus ISIS for simulating your code...

For full emulation of Arduino, there is a shareware program called VBB (Virtual BreadBoard), I tried it too and it was nice.

**Edit:** You can check my detailed tutorial **here** on how to simulate on Proteus ISIS
> 13 votes

# Answer
I believe this website has a list of both emulators and simulators along with their price and availability.

Update:

Since some users mentioned there are broken links in that website, here's a selection of emulators I found. Note that some descriptions may have been taken from the mentioned link:

* Emulino: Is an open source linux based software in early development that emulates Arduino-specific MCUs.
* Emulare: is a general purpose hardware emulator. It aims to provide a central interface to build electronic simulations for embedded software development. At present emulare focuses on the ATMega line of microcontrollers (Arduino UNO has the ATMega processor).
* SimAVR: is a new AVR simulator for linux, or any platform that uses avr-gcc. The simulator loads ELF files directly, and there is even a way to specify simulation parameters directly in the emulated code using an .elf section. It supports emulation of many ATMega processors and it is mentioned that it's easy to even add new ones.
* Amtel Studio: This doesn't seem to mention the term emulation, but it is a sophisticated IDE to debug your code for many platforms specially Arduino. Atmel Studio 7 features seamless one-click import of projects created in the Arduino development environment. Your sketch, including any libraries it references, will be imported into Studio 7 as a C++ project. Once imported, you can leverage the full capabilities of Studio 7 to fine-tune and debug your design. Atmel Studio 7 fully supports the powerful embedded debugger on the Arduino Zero board. For other Arduino boards, shield-adapters that expose debug connectors are available, or switch to one of the many available Xplained-Mini/PRO boards to fully leverage the Atmel HW eco-system.

You can still use simulators such as EasyEDA to test your code and in most cases be able to run it on the device. But note that given the nature of electronic components, you may have to provide external resistors, capacitors etc to get the expected results.
> 11 votes

# Answer
Virtualbreadboard has a new VBB4Arduino 'Two Arduino's' edition which includes BOTH a JVM Arduino emulator AND a AVR Instruction set simulator with examples that cover almost all of the Arduino distribution examples and a bunch of peripheral hardware - LCD's, WS2812 Neo LEDS, Motors, Servo's, Logic Analyser and more.

http://www.virtualbreadboard.com

Disclaimer: I am the author of Virtual Breadboard
> 8 votes

# Answer
You could e.g. use my simulator. It is especially suitable for PLC-like applications, where multitasking is achieved by cyclic evaluation of interconnected circuit-like objects: Timers, Markers, Latches, Oneshots and Registers. You can use it to simulate your controlled system as well, as becomes clear from the examples in the download. It has modest visualisation capacities, can draw timing charts, and allows you to access and alter c.q. force all variables in real time during a running simulation. Also you can freeze time. When you're satisfied with the behavior of your control it generates the C code to be uploaded to an actual Arduino.

https://pypi.python.org/pypi/SimPyLC
> 5 votes

# Answer
> a way I can write my code and emulate/test it using a desktop computer

If you mean being able to "unit test" using a desktop computer, I can offer a library I wrote called arduino\_ci.

It doesn't offer emulation. You would express your tests in code. For example, here is a test pulled from the reference documentation that validates the data written to a port:

```
unittest(pin_history)
{
  GodmodeState* state = GODMODE();
  int myPin = 3;
  state->reset();            // pin will start LOW
  digitalWrite(myPin, HIGH);
  digitalWrite(myPin, LOW);
  digitalWrite(myPin, LOW);
  digitalWrite(myPin, HIGH);
  digitalWrite(myPin, HIGH);

  // pin history is queued in case we want to analyze it later.
  // we expect 6 values in that queue.
  assertEqual(6, state->digitalPin[1].size());
  bool expected[6] = {LOW, HIGH, LOW, LOW, HIGH, HIGH};
  bool actual[6];

  // convert history queue into an array so we can verify it.
  // we expect to find 6 values: the 5 we set, plus the initial LOW
  // and this is where/how we assert that
  int numMoved = state->digitalPin[myPin].toArray(actual, 6);
  assertEqual(6, numMoved);

  // verify each element
  for (int i = 0; i < 6; ++i) {
    assertEqual(expected[i], actual[i]);
  }
}

```

In practice, you would probably not be calling the `digitalWrite` functions directly -- you'd call a function in your library, then verify that the "world state" (represented here by the `GODMODE` construct) matches what you expected your library to do.
> 3 votes

# Answer
Yes you can, and fairly easily. There is a wonderful online simulation (completely free) called TinkerCAD. It has an excellent breadboard simulation, with parts like transistors, LEDs, ICs, and Arduino. You can program the Arduino and run it all in a live simulation that includes interactive inputs (pushbuttons, DIP switches, etc.).

---

\[Edit: The following text refers to functionality that has been moved to Circuits.io, namely Eagle PCB\]

That's not all. It also includes in a separate tab schematics for your circuit, and another tab for PCB design of your breadboard circuit! Or, you can just make your schematics from scratch and make your PCB from there.

You can have your circuit designs made and you can buy them. You can do all of this in circuits.io, and you aren't risking messing up your actual Arduino. It also has warning indicators in the simulation (for example, if you didn't use enough resistance on an LED, or an IC).
> 1 votes

# Answer
An alternative to simulators are services similar to online compilers like coliru, which allow users to build and run their code on a remote system. This approach has the same limitations as online compilers:

* The hardware configuration and state cannot be altered remotely, except for explicitly defined interfaces.
* The changes to the hardware state cannot be observed, again, except for explicitly defined interfaces.

Typically, most online compilers provide users with access to command line and process STDOUT. On Arduino, providing remote access to the serial port would provide a similar degree of control: users would be able to observe and control their running sketch through UART, but would not be able to connect/remove wires, push buttons, act on external sensors, etc.

Surprisingly, I couldn't find any such online services, so I ended up writing my own - HW Farm. If you have a web server and Arduinos you can connect to it, you can install HW Farm on it and let people access those Arduinos through a web interface. I also host such a server myself, which has a single Arduino Mega with a bunch of I2C devices connected to it. You can try it out, but don't expect it to be online and available all the time.
> 1 votes

---
Tags: emulation, testing
---


title: A word after function arguments braces

text:
# Question
Title: A word after function arguments braces
I'm just reading through a header files for task code in ESP8266 SDK.

I found this line and wondering what does the word `PRIVILEGED_FUNCTION` after the function arguments braces means ?

```
void vTaskDelay( const TickType_t xTicksToDelay ) PRIVILEGED_FUNCTION;

```

`PRIVILEGED_FUNCTION` is defined here, but why it's used after the function braces ?

```
/* Ensure API functions go in the privileged execution section. */
#define PRIVILEGED_FUNCTION __attribute__((section("privileged_functions")))
#define PRIVILEGED_DATA __attribute__((section("privileged_data")))

```

# Answer
> 1 votes
That's impossible to tell without looking in the source code for that SDK.

However it will just be a pre-processor macro which probably expands out to one or more *attributes*, some of which may be specific to the XTensa LX106 compiler.

---

Update after your edit:

It places the function in the `privileged_function` section. That section is then placed into a specific area of memory by the linker.

To further examine what it does you will have to look in the linker script to see how it handles that section, and what that means from the chip's perspective, by cross-referencing that with the chip's technical datasheet.

---
Tags: functions, espressif
---


# Question
Title: How to send and receive multiple integer values through serial comm for Arduino Micro and HC05 bluetooth?
I need to send gyroscope values and a voice command flag and counter with a start and end marker through serial in the format \<2,4,5,6\> through Arduino Software serial using the HC05 Bluetooth module between Arduino Micro boards. I can send values in the struct format. But it seems that the order of the struct gets changed after a few seconds of receiving on the other side. How can I send these values in the mentioned format? I am new to this. Please help me out. It would also help if I could get suggestions on how to receive and parse this data of this format in the correct order/way.

# Answer
> 1 votes
Try Google Protobuf it's really awsome. I use it every time when I connect C# app to STM but it can be used in this case as well. U use Protobuf to encode your message and COBS do remove zeros from message so you can slap it on the end to know when the packet ends

---
Tags: bluetooth, softwareserial, arduino-micro, hc-05
---


# Question
Title: Can you power the ESP8266E-12 with any of the 3.3V pins?
If I want to operate the NodeMCU on the 3.3V input with 2.5V to 3.6V; can I use any of the 3.3V pins to do so?

# Answer
On the nodeMCU board all the 3.3v pins have continuity. That means they all do the same thing. And yes, you can apply ~3.3v to them. I have trouble with voltages under ~2.8 though, 2.5v is likely not going to work.

Use a buck+boost to keep it 3.3v if needed. For cheap dc/dc converters, I strongly prefer ones with XL semi chips; clean enough to please the ESPs.
> 3 votes

---
Tags: esp8266, power, nodemcu, pins
---


# Question
Title: How to extract the binary from STM32 MCU
I have an already programmed STM32MCU. But I don't have the source code. I understand it is difficult to get the source code from the IC. I have heard some people can get the binary file from the IC which I can flash to another Arduino. Any guide or material will be helpful. I tried my luck with google. but didn't find any good resources on this matter.

# Answer
> 3 votes
you can download the flash content using a ST-Link probe and STM32CubeProg tool. you can't flash it to just "any" arduino board; it must be the exact same chip or same family MCU, if the IOs and peripherals used are the same.

---
Tags: arduino-uno, stm32
---


# Question
Title: Run function concurrent to server.available()
I have a Arduino UNO WiFi Rev2 board that runs WiFiServer serving as a web server. The server listens and accepts clients using `server.available()`. I also want a loop that controls a servo in concurrent of the server.

I looked at ArduinoThread and tried to implement my web server with it.

```
class WebServer : public Thread
{
private:
    // Some method definition omitted
    WiFiServer server;
    void accept_and_process();

public:
    void run() override;
}

void WebServer::accept_and_process()
{
    Serial.println("Waiting for client");
    // listen for incoming clients
    WiFiClient client = server.available();
    // Process client
}

void WebServer::run()
{
    this->accept_and_process();
    this->runned();
}

```

But the code does not run in parallel with code in `void loop()` it only ran code inside loop function and does not accept client as expected
This is the code I ran the server with

```
void setup()
{
    Serial.begin(9600);
    WebServer webserver = WebServer();;

    webserver.setInterval(100);
    webserver.run();
}

void loop()
{
    Serial.println("Hello");
    delay(1000);
}

```

How would I run the server concurrent to another function.

# Answer
> 2 votes
There is no “parallel” on a single core arduino. All you need to do is program both things in a non blocking fashion. Don’t use delay or while loops waiting on things and you can do both things so fast it seems like they are parallel. Put a call to server.available() in loop and then if it returns an invalid client object then the rest of the loop runs. If it returns a valid client object then you can quickly do what you need with the server and then get back to everything else.

As noted in the comments, server.available is not blocking. It doesn't wait for anything to come, it simply returns whether there is a connection available or not.

---
Tags: web-server, arduino-uno-wifi
---


title: SPI transactions in Arduino

text:
# Question
Title: SPI transactions in Arduino
I have a task where I should do SPI transactions in interrupt mode. Means I have to handle data in IRQ handler (both for tx and rx bytes). How should I approach? I have a arduino board (2560) and a CAN shield (seeed studio) with SPI interface.

Edit: From the website: https://www.arduino.cc/en/reference/SPI

> With most SPI devices, after SPI.beginTransaction(), you will write the slave select pin LOW, call SPI.transfer() any number of times to transfer data, then write the SS pin HIGH, and finally call SPI.endTransaction()

My question is - the function SPI.transfer() is handled in what way? Are the bytes transfered/received in interrupt handler or by polling?

# Answer
> 2 votes
I have a lengthy reference question about SPI which may help you.

To transfer **outwards** you do not need to use an interrupt. Nor is it polled. The data is simply placed in the SPI register and the hardware clocks the data out at the defined SPI rate.

To transfer **inwards** you are just reading the register. However to know **when** you need to read it, you would probably put the reading inside an interrupt routine.

I suggest you read the link above, and then if you want, you might expand your question more.

The source for the SPI transfer which I think applies to the Atmega2560 is as follows:

```
// Write to the SPI bus (MOSI pin) and also receive (MISO pin)
  inline static uint8_t transfer(uint8_t data) {
    SPDR = data;
    /*
     * The following NOP introduces a small delay that can prevent the wait
     * loop form iterating when running at the maximum speed. This gives
     * about 10% more speed, even if it seems counter-intuitive. At lower
     * speeds it is unnoticed.
     */
    asm volatile("nop");
    while (!(SPSR & _BV(SPIF))) ; // wait
    return SPDR;
  }

```

You can see that there is brief polling (the "while" line) for the register which the processor maintains to show whether the transmission has ended. Then the register is read and returned. So yes, there is polling there.

Now if you use an interrupt (see link above) then you will know that the flag has been set, and therefore there will be no delay (in the polling).

---
Tags: interrupt, spi, atmega2560, can-bus
---


# Question
Title: How compile an Arduino program for a desktop PC
I have an arduino program that only does serial communications with a little bit of math, and I am writing another one to communicate with it on a second arduino. For testing purposes I was hoping I could run the serial only program on my desktop. I know it is possible to run on a raspberry pi but I have never done that. Can I do something similar on windows? If not, can anybody recommend the easiest way to do this with a regular C++ program that would require very little editing? Here is a copy of my code if it's helpful. It basically increments a variable up and down between 0 and 100.

```
int pos = 60;
bool flag=0;
int dly=50;
int vel=0;

const int buttonPin =  12;      // the number of the LED pin

// variables will change:
int buttonState = 0;         // variable for reading the pushbutton status

void setup() {
  pinMode(buttonPin, INPUT_PULLUP);

Serial.begin(115200);
}

void loop() {
    dly=50;
    buttonState = digitalRead(buttonPin);
    if (buttonState==0)dly=12;
    Serial.print(vel); //speed
    Serial.print(",");
    Serial.println(pos); //position
    delay(dly);
    if (pos==30)flag=1;
    if (flag==1) pos+=1;
    if (pos==100)flag=0;
    if (flag==0) pos-=1;
    vel=1000/dly;
    if (flag==0) vel*=-1;

}

```

# Answer
> 3 votes
If you want to run the Arduino sketch on your desktop, you just have to implement the Arduino core library for your PC.

It may not be as bad as it sounds. If your program makes only minimal use of the Arduino core, you may implement only the parts you really need. For example, this partial implementation is enough to run your program:

```
#include <cstdint>
#include <iostream>
#include <unistd.h>  // for usleep()

using std::cout;
using std::endl;

#define INPUT_PULLUP 2

void pinMode(uint8_t, uint8_t) {}

uint8_t digitalRead(uint8_t) { return 0; }

void delay(int t) { usleep(t * 1000UL); }

struct {
    void begin(int) {}
    template<typename T> void print(T x) { cout << x; }
    template<typename T> void println(T x) { cout << x << endl; }
} Serial;

int main()
{
    void setup();
    void loop();
    setup();
    for (;;) loop();
}

```

I tested this on Linux, by simply appending your program right below this. If you are using Windows, you will have to replace the `usleep()` function with the appropriate Windows call (and `<unistd.h>` with the appropriate header). The serial stream goes to the standard output. You may redirect it to the USB serial port if you wish (trivial to do in Linux, I assume it should be doable on Windows). You may also want to replace `digitalRead()` with something that simulates a more realistic user interaction.

Keep in mind that the sizes of the basic data types can be different on the Arduino and on the PC. On an AVR-based Arduinos, `int` and pointers are 16 bits while `long` is 32 bits. This is an “IP16” data model. An ARM-based Arduino would typically be ILP32, whereas a 64-bit PC is LP64, unless it runs Windows, in which case it's LLP64. This can make a difference, especially if some of your calculations are prone to overflow with the smaller data models.

---

**Edit**: I recently stumbled upon NCORE, a native core for Arduino. It may be a good fit for what you are trying to do. From the page description:

> The native core allows you to compile and run Arduino sketches on the PC, generally with no modification. It provides native versions of standard Arduino functions, and a command-line interpreter to give inputs to your sketch that would normally come from the hardware itself.

# Answer
> 0 votes
It depends on what exactly you wanna test. I guess you want to run the "Serial & math only" sketch on the PC, while communicating over Serial (via USB) with the other real Arduino. It can be done, but you would have to change quite a lot. The Serial libraries for a PC are different than for an Arduino. Also you cannot simply compile Arduino code for a PC, they are totally different devices.

Mostly the Serial code is better tested with the real hardware, by checking, what actually is send. You can do this by connecting to the Arduino over Serial/USB with a corresponding program (Arduino Serial Monitor, Putty, ...), so that you can test the functionality by hand. Or write a simple test sketch for the second Arduino.

For testing the math part, you could relatively easy write a so called unit test on the PC. A unit test tests a confined code part without or only with few dependencies. Most math is the same on Arduino and PC (as long as you use variables of the same size and type). So you could put all the math code into a function, which does not contain Arduino specific code, like `Serial` code. Just the math. Then you can copy that function into the source code of a C++ PC programm and use it, to test the math function unit without involving the Arduino.

A further option would be using an Arduino Simulator. But keep in mind, that these simulators can never be as good as the real hardware and you can see differences in the behavior of simulated and real Arduinos. Though it should work, as long as your program is simple and does not rely on too much outer hardware or events. Your current program is simple enough, so that a simulator should be able to work with it.

All in all: Testing your code outside of the real Arduino mostly only makes sense, when you have a complex program, that does not involve Arduino specific code, which would need the hardware to work. If your project is not very complex, you are mostly better off with testing directly with the real hardware.

# Answer
> 0 votes
There is also arduino\_ci, a framework for running unit tests against an Arduino library (maybe also sketch) on your computer. It contains mock implementations of most Arduino functions and some libraries, and gives the unittest control of things like Serial buffers and I/O pin values.

For your example, you could maybe write a unittest that just use stdin/stdout as a serial port and then connect two of these programs together, or maybe you could generalize your communication code a bit into an object and then instantiate that twice.

---
Tags: serial, debugging, windows, testing, emulation
---


# Question
Title: Can I program the Arduino without having an actual board with the able to emulate a COM connection to the computer?
I have ordered my Arduino, but it is not going to arrive until 2 months, and I would like to be able to emulate a COM connection to the emulated Arduino. I am writing a program that listens on the com port, and would like to test it.

The program needs to run on Windows, and emulate a COM connection, and a breadboard with a LED, and motors on it.

# Answer
> 2 votes
You could use the Simulator in Atmel Studio or something like Virtual Breadboard which looks good

The Atmel Studio simulator might take a bit of work to simulate your devices but if you have 2 months then maybe that's okay :) If you want to use the simulator in Atmel Studio then you might also find the Arduino plugin for Atmel Studio useful.

I think there are quite a few other solutions if you search google.

# Answer
> -1 votes
To verify communication via COM port (to send messages as well as to receive) you can use arduino emulator from wokwi.com

with the Wokwi arduino emulator, it is easy to do the changes, add input devices as well.

**To create a COM port**
You just need to have a

```
Serial.begin(9600);
Serial.println("Text message");

```

you will be able to see the virtual serial window in the bottom right where you can see the messages printed out as well as you will be bale to key in the serial data you want to send to Arduino.

---
Tags: led, motor, communication, emulation
---