# Question
Title: Why modem driver is loaded and used from my linux machine in order to communicate with Arduino?
Once I plugin an arduino to my linux machine the following response is retrieved (via `dmesg`):

```
[ 7250.906241] perf: interrupt took too long (2504 > 2500), lowering kernel.perf_event_max_sample_rate to 79750
[ 9517.599165] usb 1-3: new full-speed USB device number 5 using xhci_hcd
[ 9517.749504] usb 1-3: New USB device found, idVendor=2341, idProduct=0043, bcdDevice= 0.01
[ 9517.749510] usb 1-3: New USB device strings: Mfr=1, Product=2, SerialNumber=220
[ 9517.749513] usb 1-3: Manufacturer: Arduino (www.arduino.cc)
[ 9517.749516] usb 1-3: SerialNumber: 7533131313335170A061
[ 9517.780753] cdc_acm 1-3:1.0: ttyACM0: USB ACM device
[ 9517.781046] usbcore: registered new interface driver cdc_acm
[ 9517.781047] cdc_acm: USB Abstract Control Model driver for USB modems and ISDN adapters

```

The last line from dmesg caught my attention:

```
[ 9517.781047] cdc_acm: USB Abstract Control Model driver for USB modems and ISDN adapters

```

Also as far as I remember in order to communicate with arduino my user needs to be into `dialout` group. Does that mean that a modem communication protocol is used in order to communicate from/to arduino in order to communicate via USB?

# Answer
> 2 votes
The answer to that is one of history.

There was a time when the main purpose of the serial port (RS-232/UART) was to "dial out"; i.e. it had a serial connection to a modem, fax machine or a mainframe attached. Whatever it was, the primary function was to provide a data connection to the outer world, possibly incurring charges on a phone line. So, it is the other way round than you guessed: The computer communicated with the modem using a serial protocol named RS-232 or UART.

Therefore, all serial ports have been secured to not allow access, except for the user group "dialout". This has been retained as default, even for emulated and virtual serial ports -- like, for example, serial port over USB.

---
Tags: usb
---


# Question
Title: How do you remove a number of characters from a parsed string?
Using this code - `advertisedDevice.getServiceDataUUID().toString().c_str());` returns the following string - `0000feaa-0000-1000-8000-00805f9b34fb`

How can I adjust the code to do that it omits the first nine characters leaving only - `0000-1000-8000-00805f9b34fb`

Thank you.

# Answer
*Note: Even if this question is about general C++ programming, this might help other Arduino users, too. Better ask at StackOverflow the next time. ;-)*

The result of your chain of method calls returns a pointer to non-writable `char`s. You can add any offset to this, in the range from 0 to the number of characters.

In your case:

```
const char* result = advertisedDevice.getServiceDataUUID().toString().c_str() + 9;

```
> 1 votes

---
Tags: arduino-ide
---


# Question
Title: Is Arduino's USB communication protocol the same as USB modems use?
An Arduino Uno uses for the default USB communication either an FTDI chip in early versions or a microcontroller that emulates/replicates the FTDI chip communication.

Is this type of USB communications the same as the Conexxant CX930xx modems use as well?

What I want to achieve is to emulate the nessesary AT commands using the ATCommand library to replicate the modem's AT command instruction set. The things that I want to emulate are:

1. The modem USB communication
2. The subset of AT commands required for enabling/disabling an incomming call with Caller id
3. Returning a "fake" incoming call with or without CallerId depending on the provided options from the PC via the AT commands

For the last two I can somehow manage. But I don't know whether the existing FTDI chip/USB microcontroller uses the nessesary protocols that modems use as well. I mean would it be enough if I just replace the hardware and vendor ID or do I need to emulate another type of USB communication as well?

The modem that I want to emulate is the: https://support.lenovo.com/us/en/solutions/pd003647-lenovo-usb-modem-overview

What I want to achieve is to fake an incomming call instead of using the actual modem. The reason why is, because I want to provide my own data towards modem-interfacing desktop application that use CallerId. Instead of using the actual modem I would love to have a fake one where I can emulate various scenarios.

# Answer
> 1 votes
Commonly USB modems use two layers of communication that are relevant for your issue.

1. A virtual serial communication device, known as CDC/ACM, Communication Device Class, and Abstract Control Model, respectively.
2. Modem control protocol, known as Hayes command set, vulgo "AT command set", on top of this.

Both layers are generally independent of each other. You can use the virtual serial communication for any other purpose. And you can transport the Hayes commands and replies over any other communication stream.

Most Arduino compatible devices reveal themselves as CDC/ACM to a PC, you can check this for example on Windows in the Hardware Manager. Therefore, the underlying transport layer exists for you.

But to answer your concrete question: **No**, the second layer (AT commands) is missing. It is not necessary for the upload process or the serial monitoring.

But you can write a sketch that implements that set of commands you would like use use for your application.

---
Tags: arduino-uno, usb
---


# Question
Title: Get data from website with ESP8266 using AT commands
I'm trying to get data from a website by sending a HTTP GET request via AT commands for the ESP8266. Here is my current code:

```
#include <SoftwareSerial.h>

const byte rxPin = 2;
const byte txPin = 3;

SoftwareSerial ESP8266 (rxPin, txPin);

void setup() {
  Serial.begin(9600);
  ESP8266.begin(9600);
  delay(2000);
}

void printResponse() {
  while (ESP8266.available()) {
    Serial.println(ESP8266.readStringUntil('\n'));
  }
}

void loop() {

  ESP8266.println("AT+CIPMUX=1");
  delay(1000);
  printResponse();

  ESP8266.println("AT+CIPSTART=4,\"TCP\",\"192.168.1.19\",80");
  delay(1000);
  printResponse();

  String cmd = "GET /test.html HTTP/1.1";
  ESP8266.println("AT+CIPSEND=4," + String(cmd.length() + 4));
  delay(1000);

  ESP8266.println(cmd);
  delay(1000);
  ESP8266.println();
  delay(1000);
  printResponse();

  delay(5000);
}

```

Running this code I get the following response:

```
AT+CIPMUX=1

OK
AT+CIPSTART=4,"TCP","192.168.1.19",80
4,CONNECT

OK
AT+CIPSEND=4,27

OK
>
Recv 27 bytes

SEND OK

+IPD,4,

```

It looks like it gets a response, but nothing is printed.

I tried doing the same thing by sending the AT commands manually using this code:

```
#include <SoftwareSerial.h>

const byte rxPin = 2;
const byte txPin = 3;
SoftwareSerial ESP8266 (rxPin, txPin);

void setup() {
  Serial.begin(9600);
  ESP8266.begin(9600);
}

void loop() {
  if (ESP8266.available()) {
    Serial.write(ESP8266.read());
  }
  if (Serial.available()) {
    ESP8266.write(Serial.read());
  }
}

```

With this approach I actually get a response:

```
AT+CIPMUX=1

OK
AT+CIPSTART=4,"TCP","192.168.1.19",80
4,CONNECT

OK
AT+CIPSEND=4,27

OK
>
Recv 27 bytes

SEND OK

+IPD,4,275:HTTP/1.1 200 OK
Date: Thu, 22 Dec 2016 20:20:47 GMT
Server: Apache/2.4.23 (Win64) PHP/5.6.25
Last-Modified: Thu, 22 Dec 2016 19:37:22 GMT
ETag: "13-5444465f69339"
Accept-Ranges: bytes
Content-Length: 19
Connection: close
Content-Type: text/html

THIS IS MY WEBSITE!4,CLOSED

```

Does anyone know what is happening and how I can get this to work with my Arduino code?

Other ways to get data from a website are also welcome.

# Answer
As pointed out in the first comment, my `printResponse()` function was not working correctly when waiting for a response from a website. I changed my code to the following, and now it seems to work every time.

```
#include <SoftwareSerial.h>

const byte rxPin = 2;
const byte txPin = 3;

SoftwareSerial ESP8266 (rxPin, txPin);

unsigned long lastTimeMillis = 0;

void setup() {
  Serial.begin(9600);
  ESP8266.begin(9600);
  delay(2000);
}

void printResponse() {
  while (ESP8266.available()) {
    Serial.println(ESP8266.readStringUntil('\n'));
  }
}

void loop() {

  if (millis() - lastTimeMillis > 30000) {
    lastTimeMillis = millis();

    ESP8266.println("AT+CIPMUX=1");
    delay(1000);
    printResponse();

    ESP8266.println("AT+CIPSTART=4,\"TCP\",\"192.168.1.19\",80");
    delay(1000);
    printResponse();

    String cmd = "GET /test.html HTTP/1.1";
    ESP8266.println("AT+CIPSEND=4," + String(cmd.length() + 4));
    delay(1000);

    ESP8266.println(cmd);
    delay(1000);
    ESP8266.println("");
  }

  if (ESP8266.available()) {
    Serial.write(ESP8266.read());
  }

}

```
> 1 votes

# Answer
Slightly modified code. With the addition of a more correct query

```
#include <SoftwareSerial.h>

const byte rxPin = 2;
const byte txPin = 3;

SoftwareSerial ESP8266 (rxPin, txPin);

unsigned long lastTimeMillis = 0;

void setup() {
  Serial.begin(9600);
  ESP8266.begin(9600);
  delay(2000);
}

void printResponse() {
  while (ESP8266.available()) {
    Serial.println(ESP8266.readStringUntil('\n'));
  }
}

void loop() {

  if (millis() - lastTimeMillis < 3000) {
    lastTimeMillis = millis();

    ESP8266.println("AT+CIPMUX=1");
    delay(1000);
    printResponse();

    ESP8266.println("AT+CIPSTART=4,\"TCP\",\"192.168.0.79\",80");
    delay(1000);
    printResponse();

    String cmd = "GET / HTTP/1.1\r\nHost: 192.168.0.79\r\nConnection: close\r\n\r\n";
    ESP8266.println("AT+CIPSEND=4," + String(cmd.length() + 4));
    delay(1000);

    ESP8266.println(cmd);
    delay(1000);
    ESP8266.println("");
  }

  if (ESP8266.available()) {
    Serial.write(ESP8266.read());
  }

}

```
> 0 votes

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


# Question
Title: Trouble with Arduino Nano Every and radio transmission using RH_RF69.h
I give some help for students working on the Cansat Contest.

I am trying to connect a RFM69 Radio Module to an Arduino Nano Every.

Nothing works : compiling the simpliest program:

```
#include <RH_RF69.h>

void setup() {}

void loop() {}

```

gives the answer:

```
[BlaBlaBla...]
exit status 1
Erreur de compilation pour la carte Arduino Nano Every

```

while everythings works on arduino M0 Feather Express or Arduino Uno.

Is there a specific problem with the Nano Every?

# Answer
> 1 votes
The Nano Every uses an ATMega4809 processor, so it is different from most Arduino's. It could well be that it isn't supported by the Radiohead library.

The error you shortened to *\[BlaBlaBla...\]* could possibly give more information on that.

A full list of what is supported by the Radiohead library is here; you should check if the Arduino Nano Every or the ATMega4809 is on there; alternatively, all the `#define`s for the supported boards are in the header file.

If it turns out your board is not supported, you could ask the library's authors if they would consider supporting it, or you could use a different board (it should work with an Arduino Nano 33 IoT, I think, but please check first).

# Answer
> 0 votes
I was never able to make this work with the RadioHead library but did get it to work with LowPowerLab RFM69 library. Not here to debate which one is better just stating which one i got to work without having to change any of their code.

The environment used was VSCode on M2 Mac with latest PlatformIO plugin.

Transmitter MCU = Arduino Nano Every (just because i had it) Radio = Adafruit RFM69HCW (915Mhz) Breakout

Receiver MCU+Radio = Adafruit RFM69HCW Feather

For LowPowerLab libary there were two items that where gotchas for me. The first is that I was trying to use a different IRQ pin. Once i learned that the default defined in RFM69.h was 2 then things were easy going and more or less followed all the code examples that used no arg constructors for radio.

The second was that i needed to reset the radio. I got this from some example adafruit(thank you) code.

```
#define RFM69_RST     4
...
...
...
  pinMode(RFM69_RST, OUTPUT);
  digitalWrite(RFM69_RST, LOW);

  // manual reset
  digitalWrite(RFM69_RST, HIGH);
  delay(10);
  digitalWrite(RFM69_RST, LOW);
  delay(10);

```

So here is my working receiver code (with a bunch of other junk)

```
#include <Arduino.h>
#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
#include <RFM69.h>
#include <SPI.h>

#define SCREEN_WIDTH 128 // OLED display width, in pixels
#define SCREEN_HEIGHT 32 // OLED display height, in pixels

// Declaration for an SSD1306 display connected to I2C (SDA, SCL pins)
// The pins for I2C are defined by the Wire-library.
// On an arduino UNO:       A4(SDA), A5(SCL)
// On an arduino MEGA 2560: 20(SDA), 21(SCL)
// On an arduino LEONARDO:   2(SDA),  3(SCL), ...
#define OLED_RESET     -1 // Reset pin # (or -1 if sharing Arduino reset pin)
#define SCREEN_ADDRESS 0x3C ///< See datasheet for Address; 0x3D for 128x64, 0x3C for 128x32
Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, OLED_RESET);

#define NETWORKID     0   // Must be the same for all nodes
#define MYNODEID      3   // My node ID
#define FREQUENCY     RF69_915MHZ
#define RFM69_RST     4

// SPIClassMegaAVR ccc(12, 13, 11, RFM69_CS, 0);
RFM69 radio;//(RFM69_CS, RFM69_INT, true, &SPI);

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

  // put your setup code here, to run once:
  // pinMode(LED, OUTPUT);
  // digitalWrite(LED, HIGH);

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

  // manual reset
  digitalWrite(RFM69_RST, HIGH);
  delay(10);
  digitalWrite(RFM69_RST, LOW);
  delay(10);

  if(!radio.initialize(FREQUENCY, MYNODEID, NETWORKID)) {
    Serial.println(F("radio init failed"));
    for(;;); // Don't proceed, loop forever
  }
  radio.setHighPower(); // Always use this for RFM69HCW

  if(!display.begin(SSD1306_SWITCHCAPVCC, SCREEN_ADDRESS)) {
    Serial.println(F("SSD1306 allocation failed"));
    for(;;); // Don't proceed, loop forever
  }
  display.clearDisplay();
  display.display();
  delay(2000); // Pause for 2 seconds

  display.setTextSize(2);      // Normal 1:1 pixel scale
  display.setTextColor(SSD1306_WHITE); // Draw white text
  display.setCursor(0, 0);     // Start at top-left corner
  display.cp437(true);         // Use full 256 char 'Code Page 437' font

  display.print(F("Kris"));
  // display.startscrollright(0x00, 0x0F);

  display.display();
  Serial.println("Starting up");
  // radio.spyMode(true);
}

bool displayOnTop = true;
void displayMsg(char* msg) {
  display.clearDisplay();
  if (displayOnTop)
    display.setCursor(0,0);
  else
    display.setCursor(0, 16);
  displayOnTop = !displayOnTop;
  display.print(msg);
  display.display();
}

void loop() {

    if (radio.receiveDone()) // Got one!
  {
    // Print out the information:

    Serial.print("received from node ");
    Serial.print(radio.SENDERID, DEC);
    Serial.print(", message [");

    // The actual message is contained in the DATA array,
    // and is DATALEN bytes in size:

    for (byte i = 0; i < radio.DATALEN; i++)
      Serial.print((char)radio.DATA[i]);

    // RSSI is the "Receive Signal Strength Indicator",
    // smaller numbers mean higher power.

    Serial.print("], RSSI ");
    Serial.println(radio.RSSI);

    char rssi[12];
    sprintf(rssi, "RSSI: %d\0", radio.RSSI);
    displayMsg(rssi);

    // Send an ACK if requested.
    // (You don't need this code if you're not using ACKs.)

    if (radio.ACKRequested())
    {
      radio.sendACK();
      Serial.println("ACK sent");
    }
  }
}

#platformio
[env:nano_every]
platform = atmelmegaavr
board = nano_every
board_build.mcu = atmega4809
framework = arduino
lib_deps =
    adafruit/Adafruit SSD1306@^2.5.7
    lowpowerlab/RFM69@^1.5.2
monitor_speed = 115200

```

and here is my working tranmitter code (a little cleaner)

```
#include <Arduino.h>
#include <Wire.h>
#include <RFM69.h>
#include <SPI.h>

const int LED = 13;

#define NETWORKID     0   // Must be the same for all nodes
#define MYNODEID      4   // My node ID

// RFM69 frequency, uncomment the frequency of your module:

#define FREQUENCY     RF69_915MHZ

#define RFM69_RST     4

RFM69 radio;

void notifyme() {
  Serial.println("I got the call!");
}

void setup() {
radio.setIsrCallback(notifyme);
  Serial.begin(115200);

  // put your setup code here, to run once:
  pinMode(LED, OUTPUT);
  digitalWrite(LED, HIGH);

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

  // manual reset
  digitalWrite(RFM69_RST, HIGH);
  delay(10);
  digitalWrite(RFM69_RST, LOW);
  delay(10);

  pinMode(RFM69_INT, INPUT);

  if(!radio.initialize(FREQUENCY, MYNODEID, NETWORKID)) {
    Serial.println(F("radio init failed"));
    for(;;); // Don't proceed, loop forever
  }
  radio.setHighPower(); // Always use this for RFM69HCW

  Serial.println("Starting up");
}

void loop() {
  if (!radio.sendWithRetry(3, "hello", 5, 1)) {
    Serial.println("Failed to send on radio");
    digitalWrite(LED, LOW);
  } else {
    Serial.println("message sent");
    digitalWrite(LED, HIGH);
  }

  delay(5000);
}

```

Keep in mind, i'm a copy/paste warrior with the mindset of a Donkey. If I think it can be done then i will find a way, but it won't mean I understand anything about it. With that in mind, happy to answer any questions. :-)

---
Tags: arduino-nano, library
---


# Question
Title: How to get 3v3 pins on Arduino Mega Sensor shield v2.0?
I am using Arduino mega and a sensor shield (picture attached below). I need to connect three different wires to 3.3 V input. Can anybody suggest how can I achieve the same? What voltage do the VCC pins of all digital and analog pins on the sensor shield have?

# Answer
> 0 votes
They are all 5V as the Mega2560 uses 5 V logic. However, there is a `3V3` pin at the bottom, second pin from the left, that you could use:

However, unfortunately, the pin isn't protruding *above the shield*, so you'll have to make an ugly solder link to the top of the pin. Either that, or remove the row of pins and replace with a female header (carefully avoiding the `SD card` pins):

---

As an aside, the Iteaduino MEGA 2560 works at 3V3 but unfortunately the Mega shield that you have won't fit it.

The Uno equivalent of your shield will fit it though:

# Answer
> -1 votes
I fix it solding into the board sensor shield the point where there is the pin 3.3v

---
Tags: arduino-mega, sensors
---


# Question
Title: LM7805 gets very hot with four servo motors
I'm making a robotic arm using three SG90s and one Futaba s3003 servo motors and an ESP32 dev\_kit\_V4.

The problem is when I am controlling the arm, the voltage regulator gets so hot that I can't touch it. After a minute or so the servos stop rotating and I have to restart the ESP32 to control the servos and the cylce continues.

I tried to connect the ESP32 to a power bank alone but the issue isn't solved. Can you help me?

The schematic for wiring:

# Answer
> 4 votes
Depending on load, your servos can draw 250ma of current or more when actuated. This means that your 7805 may need to supply \>1 amp of current at 5V.

In order to get 5V from a 12V adapter the 7805 will need to drop 7V (The LM7805 is a linear regulator, essentially a variable resistor). 7V at 1 amp (peak) is 7 watts, which is what your regulator will dissipate during peak current draw.

With effective heat sinking your circuit will work. According to the datasheet, if you are running at room temperature with no heat sink you are limited to ~2.5 watts of dissipation.

If the 7805 chip temperature exceeds 150 degrees C it will go into thermal shutdown, which is probably what you're seeing.

Solutions would be to install an appropriate heat sink on the 7805, use a 7.5 volt power adapter (brings 7805 power dissipation down to ~2.5 watts), use multiple 7805 chips, or power everything with a 5V power adapter.

# Answer
> 1 votes
Linear regulators especially the older ones like to go into oscillation at a relative high frequency. This may be load dependent. The data sheet will recommend the appropriate capacitors to connect to it to prevent that. You would typically use a scope to see this. That oscillation will cause them to get hot rapidly even if they do not have a large load. You can look at the data sheet and determine the temperature rise of the die per watt of power. That you can determine by multiplying the drop across the regulator by the current. You can also apply this to heatsinks and pick one accordingly. There are conditions on this to be sure you have adequate ventilation to get rid of the heat on a air cooled heatsink. Liquid are similar but the numbers are much different.

In your case I would recommend you go to a switch mode regulator, commonly known as a buck or SEPIC regulator. The buck will drop the voltage from a higher voltage. The SEPIC does the same thing but if the input voltage goes below the output setpoint within its range it will boost the voltage keeping it at setpoint. As BobT explained the excess voltage is dropped through the regulator, it sort of acts like a variable resistor. This is dissipated as heat. The current on the input is about the same as the output. A switch mode regulator will operate in the efficiency range of maybe 80% - 95% efficiency, dissipating much less heat. They actually turn on and off very rapidly but the output is filtered so you do not see it.

# Answer
> 0 votes
I would recommend you to go with lm2596. That will solve your problem. Its output is adjustable. So set the output voltage first before connecting anything to it.

---
Tags: arduino-uno, esp32, servo, robotics
---


# Question
Title: AfMotor Shield Library does not work with template programming
I am able to move motors using AfMotor Shield Library. ( https://github.com/adafruit/Adafruit-Motor-Shield-library )

Like :

```
AF_DCMotor insertionMotor(1);
AF_DCMotor pumpMotor(2);

void setup()
{
  insertionMotor.setSpeed(255);
  pumpMotor.setSpeed(255);
  insertionMotor.run(RELEASE);
  pumpMotor.run(RELEASE);
  insertionMotor.run(FORWARD);
  pumpMotor.run(FORWARD);
}

```

But if I want to write it like this, only the motor with the template expansion that I called last works.

```
enum class direction {
  FRW = 0x01,
  BCKW,
};

template<int n, direction type>
class Motor : public AF_DCMotor {

public:

  Motor() : AF_DCMotor(n) {
    setSpeed(255);
    run(RELEASE);
    run(type);
  }
};
Motor<1, direction::FRW> fanMotor;
Motor<2, direction::FRW> pumpMotor;

```

Only the pumpmotor is running. Or if I call the fanMotor after the pumpMotor, it still works.If I remove pumpmotor and leave only fanMotor, the fanMotor also works. Is there something I overlooked?

# Answer
Your code gives me a compiler error: in

```
run(type);

```

the `run()` method expects a `uint8_t`, but it is given a `direction`. Adding an explicit cast to `uint8_t` makes it compile.

Now, as a general rule, I would advice you to never touch the hardware in a constructor. The problem is, if you create a global object (like you are doing here), the constructor gets called before `main()`, thus before the Arduino core has had a chance to initialize the hardware. If your constructor touches any hardware register, this may conflict with the initialization the core is going to perform right at the start of `main()`.

The usual idiom for doing any hardware initialization is to define in your object a method called `begin()`, and call it from `setup()`:

```
template<int n, direction type>
class Motor : public AF_DCMotor {
public:
  Motor() : AF_DCMotor(n) {}

  void begin() {
    setSpeed(255);
    run(RELEASE);
    run((uint8_t) type);
  }
};

```
> 2 votes

---
Tags: c++, arduino-motor-shield
---


# Question
Title: Can I use this approach so I can sniff both TX and RX signals using a Second arduino?
Based upon this answer I can hook up 2 arduinos like this:

But AFAIK The main microcontroller uses an RS232 protocol and AtMegau16 (or ATMegau8) converts it into USB one emulating an FTDI chip.

But in my case, I need just the RX port from the second in order to just sniff data. So I looked on how I can pirate the RS232 signal and I found this schematic:

Resulting to this monstrocity:

But would this allow me the secoind UNO to capture both RX AND TX signals?

# Answer
> 0 votes
This approach may work in some cases but will not work in all cases.

Assuming the intent is to listen to both the transmit and the receive side of an RS232 type signal.

An RS232 signal may swing from -12 to +12 Volts. Many logic inputs behave unexpectedly when driven by voltages higher than their supply rail. A resistor may mitigate this problem. A logic level shifter would be better.

The circuit diagram in the question is an example of a wired OR connection. If either serial transmit line is high the data from the other will be blocked. As illustrated in this diagram from wikipedia.org.

So this circuit diagram will only work reliably for half duplex communications. If full duplex monitoring is required, two independent receivers / monitors will have to be used.

---
Tags: serial, usb
---


# Question
Title: Only return button state once in X amount of time?
I want to detect if a button has been pressed, but what I don't want is for it to keep returning the "pressed" state more than once within a second or two.

For example, with this code:

```
void loop() {
  passButtonState = digitalRead(passButton);

  if (passButtonState == LOW) {
    Serial.println("PASSED!");
  }
}

```

Would spit out something like this with a single quick press of the button:

```
PASSED!
PASSED!
PASSED!
PASSED!
PASSED!
PASSED!
PASSED!
PASSED!
PASSED!

```

But what I want is for a single button press to just return `PASSED!` once for that single button press.

# Answer
> 0 votes
To avoid this problem you can use a boolean variable as a flag that permit to enter inside the `if` only once.

```
bool flag = true;

void loop() {
  passButtonState = digitalRead(passButton);

  if (passButtonState == LOW && flag) {
    Serial.println("PASSED!");
    flag = false;
  }
}

```

# Answer
> 1 votes
If I understand the problem correctly, I think the answer might be a pretty common one. Your circuit may be suffering from "bounce" and the solution is called "debounce."

Check out this link for a possible solution: Software Debounce

# Answer
> 0 votes
```
void loop() {
  passButtonState = digitalRead(passButton);

  if (passButtonState == LOW) {
    Serial.println("PASSED!");
    while (passButtonState == LOW) delay(1);
  }
}

```

# Answer
> -1 votes
You can add a delay.

```
void loop() {
  passButtonState = digitalRead(passButton);

  if (passButtonState == LOW) {
    Serial.println("PASSED!");
    delay(1000);
  }
}

```

---
Tags: arduino-uno, c++, button
---


title: Multiply char with float

text:
# Question
Title: Multiply char with float
I have a value for led brightness that is stored as an `unsigned char` (0-255)

```
unsigned char* colors[3];
colors[0] = 255;
colors[1] = 0;
colors[2] = 0;

```

I want to multiply a brightness percentage to that value.

```
float percent = 0.5;
auto red_brightness = colors[0] * percent

```

Since `colors[0]` is of type `char` and `percent` is of type `float`. It gives error `Invalid operands of types 'unsigned char*' and 'float' to binary 'operator*'`

```
unsigned char brightness;
float percent;
unsigned char* colors[3];

void setup() {
  Serial.begin(9600);
  colors[0] = 255;
  colors[1] = 0;
  colors[2] = 0;
}

void loop() {
    brightness = 127;
    float percent = (float)brightness / 255;
    float newRed = (float)colors[0] * percent;

    Serial.println(percent);
    Serial.print("red ");
    Serial.print(newRed);
    Serial.println("");
    delay(1000);
}

```

How can I multiply `colors[0]` (255) by `0.5` to get `127`?

---

## What I've tried

1. Cast `colors[0]` to a float or int

```
    # invalid cast from type 'unsigned char' to type 'float'

    float newRed = (float)colors[0] * percent;

```
2. strtod

Using this conversion website, I've tried converting like so:

```
    float tempColor = (float)strtod(colors[0],NULL);
    float newRed = tempColor * percent;

```

While this compiles, it always returns `0` (not `127` like I expect)

```
unsigned char brightness;
float percent;
unsigned char* colors[3];

void setup() {
  Serial.begin(9600);
  colors[0] = 255;
}

void loop() {
    brightness = 127;
    float percent = (float)brightness / 255;
    float tempColor = (float)strtod(colors[0],NULL); // <- returns 0.00

    Serial.print("tempColor");
    Serial.println(tempColor);
    delay(1000);
}

```

How can I multiply `255` by `0.5` to get `~127` ?

---

## Solution

Thanks to the pointer by st2000 and this sparkfun article on datatypes

I avoided floating point and char arrays and converted everything to `byte` and now my code works as expected. Thank you

```
byte brightness;
byte percent;
byte colors[3];

void setup() {
  Serial.begin(9600);
  colors[0] = 255;
}
void loop() {
      percent = 50;
      auto foobar = colors[0] * percent / 100;
      Serial.print("foobar: ");
      Serial.println(foobar);

```

```
11:12:19.833 -> foobar: 127

```

# Answer
Using "floats" is expensive both in required space and execution time. Consider avoiding the problem entirely and use uint8\_t or byte for everything.

Then just assume

```
percent = 50;

```

... is 50%. Then try:

```
tempColor =  colors[0] * percent / 100;

```

... where all variables are of type uint8\_t or byte.
> 1 votes

# Answer
You wrote:

> I have an led brightness that is stored as an `unsigned char` (0-255)
>
> ```
> unsigned char* colors[3];
>
> ```

This is not an array of `unsigned char`, this is an array of **pointers** to `unsigned char`. If you instead write

```
unsigned char colors[3];

```

Everything should work as expected.

But then, st2000 has very good advice on how to avoid expensive floating point operations.
> 4 votes

---
Tags: programming
---


title: ESP32, NTP and SW reset

text:
# Question
Title: ESP32, NTP and SW reset
After HW reset (button or power reconnect) I get the correct NTP shift, but when I use `ESP.restart()` via MQTT I get the correct time without 3 3 HRS shift due to Tz. What happens after SW reset that behaves in such manner and how to fix it?

```
bool myIOT2::_startNTP(const char *ntpServer, const char *ntpServer2)
{
    unsigned long startLoop = millis();
    while (!_NTP_updated() && (millis() - startLoop < 20000))
    {
#if defined(ESP8266)
        configTime(TZ_Asia_Jerusalem, ntpServer2, ntpServer); // configuring time offset and an NTP server
#elif defined(ESP32)
        configTzTime(TZ_Asia_Jerusalem, ntpServer2, ntpServer);
#endif
        delay(1000);
    }
    if (!_NTP_updated())
    {
        return 0;
    }
    else
    {
        return 1;
    }
}
bool myIOT2::_NTP_updated()
{
    return now() > 1640803233;
}

```

# Answer
Apparently, time in ESP32 survives a sw reset, while in ESP8266 doesn't. So in code, which is same for both - if clock is updated (a rough criteria that time is greater than some day in 2020 ), it skipped TZ update `configTzTime(TZ_Asia_Jerusalem, ntpServer2, ntpServer);`

So after a crash and/or sending a MQTT message to reboot, time was missing TZ update.

Hope it'll help someone.

Guy
> 0 votes

---
Tags: esp32, reset, ntpclient
---


# Question
Title: Arduino alternating between high and low signal without button press
I have connected my LCD with arduino uno. I am controlling contrast with the library and not the potentiometer. I am trying to read input from the button, it is connected to pin 9 of arduino. The resistor in the image is grounded, now arduino is not sensing signal from the button it keeps printing this even though in the timestamp below I have not touched the button. The resistor is 1k ohm.

```
20:03:30.808 -> button not pressed
20:03:31.816 -> button pressed
20:03:32.798 -> button pressed
20:03:33.827 -> button not pressed
20:03:34.821 -> button pressed
20:03:35.849 -> button not pressed
20:03:36.847 -> button not pressed
20:03:37.842 -> button pressed

```

```
#include <LiquidCrystal.h>

const int buttonNumPad1 = 9;

int buttonNumPad1State = 0;

int Contrast = 127.5;
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);

void setup()
{
  Serial.begin(9600);
  pinMode(buttonNumPad1State, INPUT);
  analogWrite(6, Contrast);
  lcd.begin(16, 2);
}
void loop()
{
  buttonNumPad1State = digitalRead(buttonNumPad1);

  if (buttonNumPad1State == HIGH){
    Serial.println("button pressed");
    lcd.setCursor(0, 1);
    lcd.print("pressed");
  } else {
    Serial.println("button not pressed");
  }

  lcd.setCursor(0, 0);
  lcd.print("Hello");

  delay(1000);

  lcd.clear();
}

```

Top view of my breadboard

is it something related to? https://docs.arduino.cc/learn/microcontrollers/digital-pins

> Input pins make extremely small demands on the circuit that they are sampling, equivalent to a series resistor of 100 megohm in front of the pin. This means that it takes very little current to move the input pin from one state to another

# Answer
Look at this breadboard image:

I have marked the power rail connections with green and red lines. Do you see, that they are not connected in the middle, right there where I've drawn the blue dotted line. Often the power rails of breadboards are not connected internally at that place. If that is the case for your breadboard you would need to bridge that gap with some jumper wires.

If you don't do that, your button and pulldown resistor are not connected to anything but the digital input pin. So there is nothing setting the state of that pin (HIGH or LOW). Its just like you simply connected a wire to the digital input pin. And that's called a **floating pin**. It is not actively pulled in one direction, so any noise, that comes by, might change the state of the input pin.

Make sure your button and pulldown resistor are actually electrically connected to ground. Bridge any gaps in the power rails, that your breadboard might have.
> 5 votes

---
Tags: arduino-uno, button
---


# Question
Title: ESP32, ArduinoOTA.h LittleFS.h and data file upload OTA
I'm having a sketch, that works perfectly fine - connects to WiFi, uploading files using `Esp32 LittleFS data Upload` using Arduino IDE (when still connected to my PC), and sketch updates via OTA (using `ArduinoOTA.h` library).

But when I try to `Esp32 LittleFS data Upload` when MCU is not connected to my PC, I get an error messages:

```
espota : /home/guy/snap/arduino/70/.arduino15/packages/esp32/hardware/esp32/1.0.6/tools/espota.py

[LITTLEFS] data   : /home/guy/Documents/Dropbox/Arduino/sketch_jul26a/data
[LITTLEFS] start  : 2686976
[LITTLEFS] size   : 1472
[LITTLEFS] page   : 256
[LITTLEFS] block  : 4096
/sketch_param.json
/sketch_param_32.json
/myIOT2_topics.json
/myIOT_param.json
/sketch_param_8266.json
[LITTLEFS] upload : /tmp/arduino_build_103180/sketch_jul26a.littlefs.bin
[LITTLEFS] IP     : 192.168.2.132

Sending invitation to 192.168.2.132 ..........
20:10:59 [ERROR]: No response from the ESP
LITTLEFS Upload failed!

```

Just to clarify:

A) sketch OTA works as expected (yes, I changed local USB to the remote one).

B) Tested on 2 different ESP32 MCU's, and failure is the same.

Question:

1. Is it possible to OTA data files using ESP32, `ArduinoOTA.h`, `LittleFS`, ArduinoIDE ? (It works when using ESP8266).

Guy

# Answer
I can confirm that I've uploaded littlefs data to an ESP32 over OTA using PlatformIO. I haven't tried with ArduinoIDE but it should be possible. Have you tried uploading while monitoring the serial output (i.e. leave it connected to the PC). If you see something in the output, it might be format error coming from the ArduinoIDE upload tool, but I suspect it's just failing to connect.

Is it definitely connecting with the same IP between sketch upload and file upload? When I have these types of problems, it's usually because I've done something in the sketch to disable WiFi or the OTA check. Have you tried uploading the sketch again over OTA?
> 1 votes

---
Tags: esp32, ota, littlefs
---


# Question
Title: boards.txt - how to create sub-menu (NOT new board!!!)
Arduino 1.8.19

Is it possible to create a sub-menu inside `boards.txt` that would allow having the boards grouped for example by the manufacturer? If it is possible, please provide an example or at least documentation for the language which is used for boards.txt.

I **don't** want to add a new board.

# Answer
No, it's not possible.

The board menu (defined here) is a single flat menu with "scroller" added to it.

To have multiple layers of menu you'd have to rewrite that entire part of the IDE.
> 0 votes

---
Tags: arduino-ide, ide, arduino-setup
---


# Question
Title: Convert Int to HEX, HEX to string and to byte? General converting problem
Since Cpp is not my main language, I struggle to find the best way to convert between types for my needs. So my starting point is

```
struct can_frame {
    canid_t can_id;  /* 32 bit CAN_ID + EFF/RTR/ERR flags */
    __u8    can_dlc; /* frame payload length in byte (0 .. CAN_MAX_DLEN) */
    __u8    data[CAN_MAX_DLEN] __attribute__((aligned(8)));
};

```

So first I needed it bo send to Serial as a hex string, so solution I've found and used was

```
String frame = "CAN:";
char dataString[1] = {0};
sprintf(dataString, "%03X", can1Msg.can_id);
frame += dataString;
for (int i = 0; i < can1Msg.can_dlc; i++) {  // print the data
  char dataString[1] = {0};
  sprintf(dataString, "%02X", can1Msg.data[i]);
  frame += " " + String(dataString);
}

```

Doesn't seem elegant byt it did the job.

But then I needed to do some checking of ID and specific bytes So I've saved all String ins `String bytes[8]` So now I could something like

```
if (id == "2A0" && bytes[0] == "A0") {

```

And that was almost over, but then I realized that I need to do some checking of Integer number that is saved on 3 bytes. E.G `byte[2] + byte[3] + byte[4]` which would something like `0020A0` whih will be `8352` as an Int

But converting things around gave all the problems such us `String to const char*` etc. I wanted to convert `__u8` to byte array so I can do checks and conversions and eventually convert it to string, but I've failed. Can anyone suggest best approach for this ?

# Answer
The main problem that you are having is a lack of understanding in what "hex", "byte", etc are.

You are trying to work with four data types (int, hex, string and byte) when in reality there are only two types: String and binary. Everything else is just a representation we as humans use to make easier sense of the binary data.

You have a "source" type (`can1Msg.data`) which is, at one and the same time, binary, integer, hex and byte. The only thing it is not is `String` and you create that manually with your `sprintf` calls.

To compare the third "hex pair" value in your data you simply:

```
if (can1Msg.data[2] == 0x42) { ...

```

That is, compare the 8-bit binary value stored in array slice 2 (arrays count from 0 so 2 is the third entry) with the binary value represented by the hex notation 42. The exact same thing can be done with:

```
if (can1Msg.data[2] == 66) { ...

```

66 is the decimal (base 10) equivalent of 0x42. You can also use binary or octal. These two are also exactly the same:

```
if (can1Msg.data[2] == 0102) { ... // octal
if (can1Msg.data[2] == 0b01000010) { ... // binary

```

If you need to examine groups of bytes, such as if you have two bytes that form a 16-bit integer, you simply combine those two bytes into an integer, taking care to obey the correct endianness of the values. For example if you have a 16 bit integer that is stored as `can1Msg.data[7]` and `can1Msg.data[8]` in *big endian* form, you can use:

```
uint16_t val = (can1Msg.data[7] << 8) | can1Msg.data[8];

```

Then simply compare the numeric (binary) integer value at will. All that line does is take the first 8 bit value and "shift" it 8 bits to the left to make it a 16 bit value with the lower 8 bits set to 0, then overlay the second value over those lower 8 zeroes, to make it a single 16-bit value.
> 1 votes

---
Tags: programming
---


# Question
Title: What components can be connected to pins 0/1 (RX/TX) without preventing uploading of code?
For a robot project I am using an Arduino Uno, and am running out of pins. The simplest solution would be to use digital pins 0/1. I know this means that I won't be able to use Serial communication (which is fine), but I also know that these pins are also used when uploading code to the board, and connecting components to these pins can interfere with the upload.

Are there certain types of components/interfaces that can be connected to these pins that won't interfere with the upload (without having to disconnect them every time I want to upload)?

In my case, I can choose between either using these pins to drive inputs for an L298N motor driver (TTL inputs), or to read quadrature motor encoder signals. My guess would be that the latter won't work, as these signals may be high and interfere (and I don't know whether applying a voltage to the encoder outputs would cause damage - I have no datasheets for them).

However maybe the TTL inputs of the L298N would be fine? Or do I have no choice but to either have a switch to disconnect the when uploading or find some other way to reduce pin usage (or go for a bigger Arduino)?

# Answer
> 4 votes
This is a general electronic problem, not specific to pins 0/1 of the Arduino.

The basic rule is:

* An input can only accept one signal

But

* One signal can go to many inputs

In other words any INPUT pin can only accept a signal from one place, but an OUTPUT pin can send its signal to many places at once.

The Arduino's serial connection has two signals - one input (RX) and one output (TX). The input pin (RX) can only get its signal from one place, and when programming that "one place" needs to be the USB to UART converter's TX pin. So anything connected to that pin that "sends a signal" will confuse everything and communication will fail.

Similarly the USB to UART converter's RX pin can only receive a signal from one place - in this case the Arduino's TX pin - connecting anything to this pin that could output a signal would confuse things and break communication.

So to round that up: you should be fine connecting anything that only *receives* a signal of some form (i.e., anything that is an INPUT, such as an RX pin or some form of control input like your motor controller) to either of those pins, but do not connect anything that can *send* a signal.

There is one caveat though: whatever you connect will receive the serial communication used while programming. That could have unintended consequences, like a motor spinning when you program the board.

---
Tags: arduino-uno, serial, motor, pins
---


# Question
Title: displaying double variable problem (Arduino)
so I have a problem with displaying a double variable in OLED & IR remote calculator, like this (using u8g2):

```
displayTextOnRight(String(100000, 0)); //ex. of an void and a number

```

It displays: " " But when I set to ex. 99999 it displays: "99999"

The same is with

```
displayTextOnRight(String(1000.00, 2));

```

It also displays nothing. (100.00 displays 100.00)

I tried values below zero and it crashes. When I try 6 it's empty whatever I type on my remote.

Please help.

# Answer
> 1 votes
When the first argument to the String constructor is an integer type, it tries to interpret the second argument as a number base and not as a number of decimal places.

So, in `String(100000, 0));`, it kind of thinks you're asking for the number to represented in the `String` in base 0 as opposed to decimal (`DEC`), hexadecimal (`HEX`), binary (`BIN`), etc and base 0 isn't a thing.

With a floating point type first argument like `1000.0` the second argument takes on the meaning of decimal places (seen an `decimalPlaces` in the documentation).

If you want `".00"` after an integer number when it's converted to a String it's probably better to just print it in a second `.print()` call, or to concatenate it to the string. And if you want you can manually type convert integer expressions to floating point type to force selection of the other constructor, e.g. `int a = 10000; whatever.print(String(float(a), 2));`

---
Tags: arduino-uno, display
---


# Question
Title: Why am I getting an 'invalid conversion' error on compile?
I have one of these NodeMCU ESP8266 OLED Arduino Wifi Modules which I am trying to load with SpaceHuhn's deauther software from Github

I am trying to compile the source code using Arduino IDE with the display enabled and have followed the instructions to do so from github repository here.

I initially downloaded the latest software but as I didn't know which display option to enable before compiling, I went for an earlier version, v1.6, which has a video on how you are supposed to install it on YouTube.

After uncommenting line 18 from:

`//#define USE_DISPLAY /* <-- uncomment that if you want to use the display */`

so that it reads:

`#define USE_DISPLAY /* <-- uncomment that if you want to use the display */`

and then trying to compile, I get this error:

```
D:\Documents\Innovateking-EU Nodemcu ESP8266\Deauther\esp8266_deauther-v.1.6\esp8266_deauther\esp8266_deauther.ino: In function 'void setup()':

esp8266_deauther:592:32: error: invalid conversion from 'const char*' to 'const uint8_t* {aka const unsigned char*}' [-fpermissive]

   display.setFont(Roboto_Mono_8);

In file included from D:\Documents\Arduino\libraries\esp8266-oled-ssd1306-master\src/SSD1306Wire.h:34:0,

                 from D:\Documents\Arduino\libraries\esp8266-oled-ssd1306-master\src/SSD1306.h:33,

                 from D:\Documents\Innovateking-EU Nodemcu ESP8266\Deauther\esp8266_deauther-v.1.6\esp8266_deauther\esp8266_deauther.ino:28:

    D:\Documents\Arduino\libraries\esp8266-oled-ssd1306-master\src/OLEDDisplay.h:243:10: error:   initializing argument 1 of 'void OLEDDisplay::setFont(const uint8_t*)' [-fpermissive]

     void setFont(const uint8_t *fontData);

Multiple libraries were found for "SSD1306.h"
 Used: D:\Documents\Arduino\libraries\esp8266-oled-ssd1306-master
 Not used: C:\Users\cos\AppData\Local\Arduino15\packages\deauther\hardware\esp8266\2.0.0-deauther\libraries\esp8266-oled-ssd1306-4.0.0
exit status 1
invalid conversion from 'const char*' to 'const uint8_t* {aka const unsigned char*}' [-fpermissive]

```

The youtube video shows the process working, assuming nothing was edited out.... As far as I can see I have done everything the same.

Has anyone had any experience of loading this on to these boards? Or know what the problem is?

# Answer
> 1 votes
go in the data.h TAB

find : `const char Roboto_Mono_8[] PROGMEM = {`

and replace with : `const uint8_t Roboto_Mono_8[] PROGMEM = {`

Voilà

---
Tags: esp8266, nodemcu
---


title: Share interrupt service between class

text:
# Question
Title: Share interrupt service between class
I would like to share interrupt routine between class. I followed this tutorial.

But I need to call a member function in callback function, I have the issue :

This is my code :

Timer.h

```
static void (*__handleISR)(void);

class Timer
{
    public:
        Timer();
        ~Timer();
        static void init();
        static void handleISR(void (*function)(void));
};

```

Timer.cpp

```
Timer::Timer()
{
}

Timer::~Timer()
{}

void Timer::init()
{
    TCCR2A = 0; //default
    TIMSK2 = 0b00000001; // TOIE2
}

ISR (TIMER2_OVF_vect)
{
    // 256-6=250 --> (250 x 16uS = 4mS)
    // Recharge le timer pour que la prochaine interruption se declenche dans 4mS
    TCNT2 = 6;

    __handleISR();
}

```

Device.h

```
class Device
{
    public:
        Device();

    private:
        void isr();
};

```

Device.cpp

```
Device::Device()
{
    Timer::init();
    Timer::handleISR(isr);
}

void Device::isr()
{
    // Do my stuff
}

```

If I set function isr() static, it works. But I need to call member from Device in isr().

How I can call non static member function ? Or another solution ?

# Answer
This is not an Arduino specific question but a C++ question, and as such you might get more or better answers on StackOverflow. Anyway, I'll suggest a possible solution.

A member method always receives a pointer to its object as a hidden first argument that we know as `this`. Only via this argument such a method is able to access member attributes or member methods.

A class method does not have this parameter.

The function type you define is compatible only to functions or class methods.

So you need to provide a pointer (or reference) to the `Device` object.

I reduced your example and replaced the interrupt macro with something a standard C++ compiler accepts, as this is not part of the issue.

Timer.h

```
#ifndef TIMER_H
#define TIMER_H

#include "Device.h"

class Timer
{
    public:
        static void setCallback(void (*function)(Device*), Device*);
};

#endif

```

Timer.cpp

```
#include "Timer.h"

#define ISR(f) void f()

static void (*_function)(Device*);
static Device* _device;

void Timer::setCallback(void (*function)(Device*), Device* device)
{
    _function = function;
    _device = device;
}

ISR(TIMER2_OVF_vect)
{
    _function(_device);
}

```

Device.h

```
#ifndef DEVICE_H
#define DEVICE_H

class Device
{
    public:
        Device();

    private:
        static void isr(Device* device);
        void isr();
};

#endif

```

Device.cpp

```
#include "Device.h"
#include "Timer.h"

Device::Device()
{
    Timer::setCallback(isr, this);
}

void Device::isr(Device* device)
{
    device->isr();
}

void Device::isr()
{
    // Do my stuff
}

```

**If** you don't need the `Device` object, you don't need a member method. Then go with a class method, as you already found out.
> 1 votes

---
Tags: arduino-nano, interrupt, callbacks
---


# Question
Title: String() vs char for simple flow control
I am newbie in Arduino and writing a program where I want to control the flow by using Serial monitor input (PI controller). I've read that using String() although easier it is slower than using char. But to use char I would need more lines of code to convert the input into a string for comparison and more knowledge to make the program robust. For the control I will enter small strings like Ramp, Increase, Decrease, Lock, Stop and any other inputs will not be used. Generally, there are not going to be much inputs. The strings are basically going to be put into if-statements leading to functions.

```
if(Serial.available()){

string = Serial.readString()
or some function to read out all the bytes of the string and return a char containing it;

if(string="Ramp") {
do_this();
}
else_if(string="Increase"){
do_that()
}
//If nothing matches, continue with code.
}

```

Since I need to finish this project soon, I am wondering if it's going to increase the loop time significantly if I use String() or I shouldn't bother learning and using char right now (at a later stage, for sure).

# Answer
Yes, `String` has a bit more overhead than plain c-strings (aka `char` arrays), though the additional execution time will be way too small for you to notice (especially when you type the commands in by hand).

It will be no problem to use `String` in your sketch, though you should do it right and use `String.reserve()` to allocate enough memory space in the `String` object to hold the longest string, that you have. Also don't just add `String`s together. That way you can avoid memory fragmentation (effectively making swiss cheese out of your RAM) and still use `String`.

Though when you are not in a hurry anymore, learning how to use c-strings will be worthwhile.
> 2 votes

# Answer
Using `Serial.readString()` will make your program *very* slow. This is because `readString()` does not know when to stop reading. When the serial input buffer gets empty, it will wait just in case more characters may come later. Only when it times out does it return the string that it could read. The default timeout is one second, so your program will be unresponsive for a full second after receiving a command and before acting on it.

You can shorten the timeout using `Serial.setTimeout()`, but this may make your program harder to test interactively by typing commands on a terminal emulator.

I recommend you add a terminating character (say, `'\n'`) to each of your messages, then replace `Serial.readString()` with `Serial.readStringUntil()`. This method will return immediately when it finds the terminating character. Note that this character will *not* appear on the returned string object. `readStringUntil()` also obeys a timeout, but only when it cannot find the terminating character.

Or you can learn the clean way to read Serial on the Arduino. Yes, it is a bit harder, but not a horrible thing to do.
> 4 votes

---
Tags: serial, string, serial-data, data-type, c-string
---


title: Char Array in PreProcessor

text:
# Question
Title: Char Array in PreProcessor
I need to define an array, that later on will be the name of a class, and will be pointed to.

For example (in a non pre-processor way):

`const char *button_names[4]={"b0","b1","b2","b3"};`

and later on (when it will be define in pre-processor), in a function it will be called as :

`static Button2 button_names[i]`

How can I define it that array to be in pre-processor?

**Edit2:**

```
Button2 *Buttons[8] = {nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr}; // Here I use an optional up to 8 Buttons.

```

and later on, after I read parameter file: i get the `numSW`

/\* Below example is only to check if I can use such technique - I know it is not a good coding. Example here is only for up to 4 Buttons\*/

```
void init_buttons()
{
        for (uint8_t i = 0; i < numSW; i++)
        {
                if (i == 0)
                {
                        static Button2 bt1;
                        Buttons[i] = &bt1;
                }
                else if (i == 1)
                {
                        static Button2 bt2;
                        Buttons[i] = &bt2;
                }
                else if (i == 2)
                {
                        static Button2 bt3;
                        Buttons[i] = &bt3;
                }
                else if (i == 3)
                {
                        static Button2 bt4;
                        Buttons[i] = &bt4;
                }

                Buttons[i]->begin(buttonPins[i]);
                if (buttonTypes[i] == 0) /* On-Off Switch */
                {
                        Buttons[i]->setPressedHandler(OnOffSW_ON_handler);
                        Buttons[i]->setReleasedHandler(OnOffSW_OFF_handler);
                }
                else if (buttonTypes[i] == 1) /* Momentary press */
                {
                        Buttons[i]->setPressedHandler(toggle_handle);
                }
                Buttons[i]->setID(i);
        }
}

```

# Answer
> 0 votes
```
void init_buttons()
{

        for (uint8_t i = 0; i < numSW; i++)
        {
                Buttons[i] = new Button2;   // <--- **Thnx to Juraj**!!!
                Buttons[i]->begin(buttonPins[i]);
                if (buttonTypes[i] == 0) /* On-Off Switch */
                {
                        Buttons[i]->setPressedHandler(OnOffSW_ON_handler);
                        Buttons[i]->setReleasedHandler(OnOffSW_OFF_handler);
                }
                else if (buttonTypes[i] == 1) /* Momentary press */
                {
                        Buttons[i]->setPressedHandler(toggle_handle);
                }
                Buttons[i]->setID(i);
        }
}

```

---
Tags: c-preprocessor
---


title: Converting 16bit to float

text:
# Question
Title: Converting 16bit to float
I am trying to communicate with AT30TS75A-MA8M-T with below code, the problem is converting the 16 bit output to float so I can read temp:

Base on data sheet  I suppose to remove first 5 bit in order to read correctly but I am not converting it correctly.

Ex: (0b001001001100000 AND 0 b0111111111100000) = 0b1001001100000 0b1001001100000 \>\> 5 = 0b10010011 = 147

```
    void Atemp::begin()
{

    Wire.begin();

    // Check if sensor temp sensor is avilable

    // if (mySensor.beginI2C() == false)
    // {
    //     data[9] = 5; // Error Code
    // }
    // Set registor for two decimal
    Wire.beginTransmission(_i2cAddress);
    Wire.write(1);
    Wire.write(0b01100000);
    Wire.endTransmission();
}

void Atemp::read()
{
    Wire.beginTransmission(_i2cAddress);
    Wire.write(0);
    result = Wire.endTransmission();
    // result is 0-4
    if (result != 0)
    {
        data[9] = 5; // Error Code
    }

    result = Wire.requestFrom(_i2cAddress, (uint8_t)2);
    if (result != 2)
    {
        data[9] = 5; // Error Code
    }
    else
    {
        uint8_t part1 = Wire.read();
        uint8_t part2 = Wire.read();

        data[7] = part1;
         data[8] = part2;
        int16_t rawval = (part1 << 8 | part2) ;
        // rawval >>= 6;
        float temp = rawval / 256.0f;
        floatconv(temp);
    }
}

```

# Answer
You need to do two things:

1. Right-shift the data to align it to the right of the variable, and
2. Multiply it by the value of one bit.

When right shifting be sure to do it in a *signed* data type so that C will *sign extend* the value and retain any negativeness to the value.

So taking the 12-bit examples from the datasheet you right shift 4 bits, so

```
SDDDDDDDDDDD0000

```

becomes

```
SSSSSDDDDDDDDDDD

```

(where S is the sign bit and D is a valid data bit, and 0 is padding)

Then simply multiply the value by 0.0625 to get the actual temperature.

In code that might look like:

```
int16_t rawval = part1 << 8 | part2;
rawval >>= 4; // Do this in the int16_t to preserve the sign
float temperature = rawval * 0.0625;

```

For different resolutions right shift by different amounts and multiply by the appropriate single-bit value for that resolution (hint: 11 bit is double the value of 12 bit, 10 bit is double the value of 11 bit, etc).
> 3 votes

# Answer
Just a complement to Majenko's answer. The temperature register is set in such a way that you can interpret it in the same way irrespective of the selected resolution:

```
int16_t rawval = part1 << 8 | part2;
float temperature = rawval * (1/256.0);

```
> 3 votes

---
Tags: convert
---


# Question
Title: PSF WiFi module - Is it similar to ESP8266
Some products (as TUYA and SONOFF) are using a PSF wifi module. In this link, PSF-B04 is reffers as ESP8285 design.

does anyone flash a sketch to such chip ? should it be reffered as ESP8285 when selecting chip type in Arduino IDE ?

Guy

# Answer
> 1 votes
ESP8285 is supported by esp8266 Arduino. You can select it in Tools menu.

---
Tags: esp8266
---


# Question
Title: Can you coax another I²C connection out of an Arduino Nano Every?
I'm looking to network a bunch of devices (boards in a Eurorack case) over I²C, but I don't want to compromise the address space available to each individual device for its own needs. The obvious solution here is to give each device its own I²C bus which it controls, and then connect them together over another.

Two independent I²C connections would be needed on a microcontroller in this setup, and if I understand the datasheet correctly, the MCU on the Arduino Nano Every can act as host on one bus and client on another using the Dual Mode setup of the Two-Wire Interface (see Chapter 25 of the linked datasheet), but the board only exposes two sets of I²C-capable pins and they are wired together in the schematic.

What steps would I need to take to coax another I²C connection out of an Arduino Nano Every?

# Answer
> 1 votes
Welcome!

Theoretically you can connect 127 devices to the I2C bus. I suggest you do a little reading on the I2C bus before you start your design. Hopefully all of these I2C devices are on the same board but since you want to network them I have a feeling you are making a very painful mistake. I2C was never intended to be used for networking.

For a bunch of devices I would seriously look at CAN, two wires to connect them is all that is needed even for well over 250 meters or 800 feet with the baud rate of 250 kbit/s. I usually also run a ground. This will be much faster than the I2C. CAN is a simplex communication mode that turns around very fast. Each node can send and receive under software control. It does its own arbitration no need to worry about it the controllers do it for you.

---
Tags: i2c, arduino-nano-every
---


# Question
Title: Own type definition using a struct does not name a type
I need to initialize several buttons and LEDs connected to my Arduino. To store data related to an individual button or LED, I decided to define my own data type using two different structs. One for a button and another one for a LED.

As I need to configure some GPIOs and other peripherals after instantiating each button/LED, I implemented a small factory function to get a clean interface and combine the required steps for instantiating and initialization.

Defining my own `button_t` type works as expected. The compiler does not throw any errors. However, I tried to implement the same approach for `led_t` type upon the compiler states the following error:

> example:25:1: error: 'led\_t' does not name a type
>
> led\_t ledFactory(uint8\_t pinNumber)
>
> ^~~~~
>
> exit status 1 'led\_t' does not name a type

My example code looks like this:

```
#include <Arduino.h>
#include <stdint.h>

struct button_t
{
    const uint8_t pin;
    uint8_t currentState;
    uint8_t lastState;
    uint32_t lastDebounceTime;
};

button_t buttonFactory(uint8_t pinNumber)
{
    button_t btn = {pinNumber, 0, 0, 0};
    // setting some MCU registers here
    return btn;
};

struct led_t
{
    const uint8_t pin;
    const uint8_t state;
};

led_t ledFactory(uint8_t pinNumber)
{
    led_t led = {pinNumber, 0};
    // setting some MCU registers here
    return led;
};

void setup()
{
}

void loop()
{
}

```

# Answer
This is a bug in the Arduino IDE: when converting your .ino file to a .cpp file, it added a declaration for the function `ledFactory()` *before* the declaration of the type `led_t`.

As it appears to be adding those declarations right before the first function of your sketch, a simple workaround is to put all your type definitions before your functions.
> 6 votes

# Answer
First create structure and after create function and after function declaration line c++ is bottom approach.
> -1 votes

---
Tags: compilation-errors, data-type, avr-gcc, struct, typedef
---


# Question
Title: Read Multiple Sensors Data from a text file located in SD Card in Arduino/ESP32
I am working on a small home project 'glucose meter' via non invasive techniques. I am using four sensors like RGB color sensor, two multi-wavelength photo diodes (A & B) and temperature sensor (K-Type Thermocouple). I am using Multi Regression algorithm to estimate Glucose level in human body by calculate all four readings from sensors.

I am using ESP32 and I am saving all my sensors data in a CSV file (or text) after taking more than 20 calibration data from my family and friends. I can read this file after writing but I am facing a problem in reading all calibration data from this text/CSV file in the following particular manner.

```
Y,Sensor1,Sensor2,Sensor3,Sensor4
92,103,25,65,9875
91,104,26,62,9805
105,92,30,66,9600
150,60,40,75,9233
...,...,...,.....

```

Above pattern indicates 'Y' values (Blood Sugar value mg/dl) and corresponding sensors value on that time. I am facing problem in reading these object like:

```
Y1 = 92, S1 = 103, S2 = 25, S3 = 65, S4 = 9875
Y2 = 91, S1 = 104, S2 = 26, S3 = 62, S4 = 9805
....................AND so forth..............
Y1000 = XX, S1 = XX, S2 = XX, S3 = XX, S4 = XX

```

Can any one help me how would I read and categorize each sensor values from the text/CSV File?

Thanks.

# Answer
Let's say you want to read this line from the file.

```
92,103,25,65,9875

```

code is

```
String one_line_data = file.readStringUntill("\n");
int y,s1, s2, s3, s4;
sscanf(one_line_data.c_str(), "%d,%d,%d,%d,%d", &y, &s1, &s2, &s3, &s4);

```

this way to read the one line of data from file you can expand to multiple line based on application.
> 1 votes

# Answer
Function file.parseInt(), will skip non numeric characters and then parse the number stopping on non numering character. So you need only call file.parseInt() for every value in row, process the data and then loop to next row.

```
Y1 = file.parseInt();
S1 = file.parseInt();
S2 = file.parseInt();
S3 = file.parseInt();
S4 = file.parseInt();

```
> 0 votes

---
Tags: arduino-uno, arduino-ide, c++, c, esp32
---


title: Can I run Arduino code on a 6502?

text:
# Question
Title: Can I run Arduino code on a 6502?
I've been doing projects with the arduino boards for a long time and accordingly also with the libs from adafruit etc. But that was too boring for me and I wanted to get more into the matter, so I used youtube and acquired knowledge about the microcontrollers eeproms etc. itself . But now my question is whether I, if I have the necessary interface adapters, etc., can compile the libs from adafruit, etc. and flash the hex file directly onto an eeprom and then use it with e.g. connect and use a 6502. but I need the corresponding settings in the IDE so that the code can be executed correctly, right? and what is the best way to do this? and general tips would also be nice thanks in advance

# Answer
No, you can't.

You would fail at the first hurdle: you would need to find a 6502 C++ compiler, and AFAICT there is no such thing.

Without a C++ compiler for the 6502 you would never be able to compile C++ code for the 6502.

The closest you would come is to program in pure C for the 6502, which means you won't be able to use 99% of the Arduino libraries (not counting the fact that many use architecture-specific register access) since they are written in C++ not in C.
> 2 votes

---
Tags: arduino-ide, library, eeprom
---


# Question
Title: Is it possible to remove the bootloader while flashing using the bootloader?
The question is meant as in, can I lock myself out of the Arduino using the bootloader, if I flash a hex file that doesn't contain the bootloader?

Or does the bootloader automatically add the flashed file after itself, so that it's never overwritten?

The device in question is an Arduino Pro Micro (ATMega32u4). Asking, because I don't have an ISP available right now, and I have to flash pre-compiled hex files.

# Answer
> 3 votes
If you don't play around ISP programming and have not already been playing around with ISP programming, your bootloader is fine and will remain fine no matter what you try to upload. The bootloader has its own protected section, so it's not necessary to tack it onto your sketch code on every upload. The Pro Micro bootloader can't be updated via itself anyway.

Worst case what you try to upload your precompiled binaries and they simply don't work.

You *can* upload code that fails to respond to the 1200 baud touch request that is used to reset the board into the bootloader, which may make you think you've screwed up the board, but you haven't. The Pro Micro version of Caterina bootloader supports a double-tap reset for an 8-second upload window no matter what you've put (or tried putting) on the chip.

Practically speaking, the existing bootloader is immutable and will always work for you until ISP becomes involved at some point.

---
Tags: bootloader, arduino-pro-micro, atmega32u4, programmer
---


# Question
Title: Using Millis instead of delay to reboot relay
I want to reboot relay (turn off , waiting 4 seconds and turn ON) it works perfectly if I use delay(4000), but code is blocked while delay (4 seconds) and I cant start relay 2. How can I use Millis instead of delay to reboot relay 1 and start relay 2 same time?

```
#include <SPI.h>
#include <Ethernet.h>
#include <Wire.h>
#include <EthernetUdp.h> //Load the Udp Library

//Ethernet
byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED}; //Assign mac address
IPAddress ip(192, 168, 1, 178); //Assign the IP Adress
unsigned int localPort = 80; // Assign a port to talk over
char packetBuffer[UDP_TX_PACKET_MAX_SIZE]; //dimensian a char array to hold our data packet
String datReq; //String for our data
int packetSize; //Size of the packet
EthernetUDP Udp; // Create a UDP Object                            //server port
String readString;

bool relayState = false;
//define relay pins
int relay_1 = 22;
int relay_2 = 24;

void setup() {
  Serial.begin(9600);
  Ethernet.begin(mac, ip);
  Udp.begin(localPort); //Initialize Udp
  delay(2000);

  //Initial state of the relay
  pinMode(relay_1, OUTPUT); digitalWrite(relay_1, LOW); //relay 1 is On
  pinMode(relay_2, OUTPUT); digitalWrite(relay_2, HIGH);//relay 2 is Off

}

void loop() {

  packetSize = Udp.parsePacket(); //Reads the packet size
  if (packetSize > 0) { //if packetSize is >0, that means someone has sent a request
    Udp.read(packetBuffer, UDP_TX_PACKET_MAX_SIZE); //Read the data request
    String datReq(packetBuffer); //Convert char array packetBuffer into a string called datReq
    //Serial.println(datReq);

    if (datReq == "relay1reboot") { //reboot relay
      digitalWrite(relay_1, HIGH);//relay off
      delay(4000);
      digitalWrite(relay_1, LOW);//relay on

      Udp.beginPacket(Udp.remoteIP(), Udp.remotePort()); //Initialize packet send
      Udp.print("relay 1 reboot");
      Udp.endPacket(); //End the packet

    }
    if (datReq == "relay2on") {
      digitalWrite(relay_2, LOW);//relay 2 on
      Udp.beginPacket(Udp.remoteIP(), Udp.remotePort()); //Initialize packet send
      Udp.print("relay 2 on");
      Udp.endPacket(); //End the packet
    }
    if (datReq == "relay1on") {
      digitalWrite(relay_1, LOW);//relay 2 on
      Udp.beginPacket(Udp.remoteIP(), Udp.remotePort()); //Initialize packet send
      Udp.print("relay 1 on");
      Udp.endPacket(); //End the packet
    }
    // Use the snapshot to set track time until next event
    //previousMillis = currentMillis;
  }
}

//}
memset(packetBuffer, 0, UDP_TX_PACKET_MAX_SIZE); //clear out the packetBuffer array

}

```

# Answer
> 2 votes
A general approach to remove a `delay()` is to replace it by some code that:

* takes note that some action (whatever follows the `delay()`) will have to be performed in the future
* takes note of the current time.

Then, somewhere else in `loop()`, you check whether that “some action” has to be done right now and, if this is the case, does it.

In this particular case, I would add a global boolean variable named `relay1isRebooting`. When it is true, that means that the relay has been turned off and will have to be turned on in the near future.

```
bool relay1isRebooting = false;
unsigned long relay1rebootStarted;

void loop() {
  packetSize = Udp.parsePacket();
  if (packetSize > 0) { //we have received a packet
    // ...
    if (datReq == "relay1reboot") {
      digitalWrite(relay_1, HIGH); //relay off
      relay1isRebooting = true;
      relay1rebootStarted = millis();
    }
    // ...
  }

  // Switch back the relay 1 on if needed.
  if (relay1isRebooting && millis() - relay1rebootStarted >= 4000) {
      digitalWrite(relay_1, LOW); //relay on
      relay1isRebooting = false;
      Udp.beginPacket(Udp.remoteIP(), Udp.remotePort());
      Udp.print("relay 1 reboot");
      Udp.endPacket();
  }
}

```

Please note that the test for whether the relay 1 should be turned back on is performed outside the `if (packetSize > 0)` block. Also note that `relay1rebootStarted` has a valid value only when `relay1isRebooting` is `true`.

---
Tags: arduino-mega, relay, millis, delay
---


title: Input on the Nano RP2040 does not float

text:
# Question
Title: Input on the Nano RP2040 does not float
I am using the Nano RP2040 with MicroPython and run the following code:

```
import machine
import time

p0 = machine.Pin(0, machine.Pin.IN)
while True:
    print(p0.value())
    time.sleep(0.3)

```

The Nano has built-in pull-up and pull-down resistors. If I do not specify `machine.Pin.PULL_xx`, then these built-in resistors are not activated. If they are not activated, then shouldn't the signal received be floating, i.e., shouldn't the environment interfere with the input signal and make the code above print random series of 0s and 1s on the REPL? What actually happens is the REPL prints all 0s.

I read of how input pins are interpreted as high-impedance output and while I suspect this may be the cause, I do not not understand what that means.

# Answer
> 1 votes
That you'll get noise on a floating input observable in the read value isn't something you can rely on. The AVR like the ATMega328P seems to readily couple house/mains frequency noise onto inputs. However, I went to demonstrate this sort of thing for someone with a NodeMCU(ESP8266) board and found it was much harder to influence.

As I understand it the RP2040 has configurable Schmitt trigger inputs with a minimum hysteresis of 0.1 * IOVDD, 330 mV minimum, I think. And that these are on by default. So your noise has to be bouncing across this threshold to affect the read value, which it may easily not be doing. If you turn off the Schmitt trigger feature, you *may* see more noise. I don't know how to disable them in MicroPython. The PicoSDK has a function called `gpio_set_input_hysteresis_enabled` that should do it.

You can also try running something like an old vacuum cleaner next to it to throw lots of noise into the environment.

For my own curiosity I may try playing with this on an RPI Pico, though perhaps not in MicroPython (we'll see) and if I do I'll show what I found.

---
Tags: input, arduino-nano-rp2040
---


title: Looking for a very simple board

text:
# Question
Title: Looking for a very simple board
I’ve worked with esp8266/esp32 boards in the past and they were great. But now I have a very simple project where both of these are way too powerful.

I want to read one analog input over USB per COM. That’s it. No wifi, no Bluetooth, no 32 bit or any of these *fancy things*. It should be programmable without any hardware other than a computer though. It doesn’t need to be Arduino. All it has to do is to read the input and respond to serial communication.

But I’m absolutely overwhelmed by all these microcontrollers. Most of them are feature packed.

So I’m asking for a way to find a proper controller/board on my own. Feel free to recommend one though.

# Answer
> 1 votes
Since you require USB, nano/micro are your way forward. being mass produced anything smaller would actually turnout to be more expensive.

If you for those reading this message latter: If you do not need USB then you have a pro-miny (needs USB-\>ttl for programing)

If you are going really minimalist you can go with MSP430 chips (arduino programming available via PlatformIO). Atmega32u4 can although run on its own without crystal, but I find Crystal free (using builtin crystal) run of MSP430 much better with timing. Problem with MSP430 is that TI software development dedepartment is stuck in middle ages. (I am not sure if they even employ a full-time programmer) and if you are programming on arm, you might Have a problem compiling it from arm platform.

# Answer
> 0 votes
Since you seem to have some experience, seemingly these are valid options:

1. Obtain the smallest Arduino you can get. For example, a DigiSpark original or clone, or a DFRobot Beetle. Use the Arduino IDE to program it.
2. Obtain the smallest AVR board you can get. For example, with an ATmega32u4. Download ASF, the Atmel Software Framework, learn how to use it. It provides a lot of sources for ADC and USB.

---
Tags: input, board
---


title: avr_boot change LED pin

text:
# Question
Title: avr_boot change LED pin
I would like to know how can I change LED pin for avr\_boot bootloader.

I can see there is option in variants folder but in the manual it mention "if using USE\_LED adapt LED-pins in asmfunc.S" which is not clear. I am using pin PC3 how do I write it.

# Answer
Near the top of asmfunc.S, you have these lines:

```
; LED Pins
#define DDR_SS  _SFR_IO_ADDR(DDRD), 5   // SS pin (PIN, PORT)
#define PORT_SS _SFR_IO_ADDR(PORTD), 5

#define DDR_PW  _SFR_IO_ADDR(DDRD), 6   // Power pin (PIN, PORT)
#define PORT_PW _SFR_IO_ADDR(PORTD), 6

```

These define the “write” or “slave select” LED pin as PD5 (registers DDRD and PORTD, bit 5), and the “power” LED as PD6 (registers DDRD and PORTD, bit 6).

These are the lines you have to change if using different pins. For example, pin PC3 is: registers DDRC and PORTC, bit 3.
> 2 votes

---
Tags: bootloader
---


title: GY-521 output and degrees

text:
# Question
Title: GY-521 output and degrees
I am trying to make an observatory through 2 GY-521 gyroscopes and using the outputs I have to make a motor move, but I have a problem.

When I move one of the two gyroscopes the outputs change, but then as soon as I leave it it returns to the initial value, the data I see via an ESP8266 on an internet site, this is the code:

```
#include <Wire.h>
#include "WiFiEsp.h"
// Emulate Serial1 on pins 6/7 if not present
#ifndef HAVE_HWSERIAL1
#include "SoftwareSerial.h"
SoftwareSerial Serial1(18, 19); // RX, TX
#endif

char ssid[] = "Vodafone-A61356555";            // your network SSID (name)
char pass[] = "YgtHnkJHNpFAcPfH";        // your network password
int status = WL_IDLE_STATUS;     // the Wifi radio's status
int reqCount = 0;                // number of requests received

WiFiEspServer server(80);

int MPU = 0x69;
int MPU1 = 0x69;
int16_t AcX, AcY, AcZ, Tmp, GyX, GyY, GyZ;
int16_t AcX1, AcY1, AcZ1, Tmp1, GyX1, GyY1, GyZ1;
int gyro_state = 2;
int gyro_state_1 = 3;
int RED_LED = 8;
int GREEN_LED = 9;

void setup(){
  pinMode(gyro_state, OUTPUT);
  pinMode(gyro_state_1, OUTPUT);
  pinMode(RED_LED, OUTPUT);
  pinMode(GREEN_LED, OUTPUT);
  digitalWrite(gyro_state, HIGH);
  digitalWrite(gyro_state_1, HIGH);
  Wire.begin();
  Wire.beginTransmission(MPU);
  Wire.write(0x6B);  // PWR_MGMT_1 register
  Wire.write(0);     // set to zero (wakes up the MPU-6050)
  Wire.endTransmission(true);
  Serial.begin(115200);
  // initialize serial for ESP module
  Serial1.begin(9600);
  // initialize ESP module
  WiFi.init(&Serial1);

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

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

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

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

void loop() {
  // listen for incoming clients
  WiFiEspClient client = server.available();
  if (client) {
    Serial.println("New client");
    // an http request ends with a blank line
    boolean currentLineIsBlank = true;
    while (client.connected()) {
      if (client.available()) {
        char c = client.read();
        Serial.write(c);
        // if you've gotten to the end of the line (received a newline
        // character) and the line is blank, the http request has ended,
        // so you can send a reply
        if (c == '\n' && currentLineIsBlank) {
          Serial.println("Sending response");

          // send a standard http response header
          // use \r\n instead of many println statements to speedup data send
          client.print(
            "HTTP/1.1 200 OK\r\n"
            //"Content-Type: text/html\r\n"
            "Connection: close\r\n"  // the connection will be closed after completion of the response
            "Refresh: 5\r\n"
            "\r\n");
          client.print("<!DOCTYPE HTML>\r\n");
          client.print("<html>\r\n");
          client.print("<br>\r\n");
          client.print("Accelerometro Telescopio X: ");
          client.print(AcX);
          client.print("  Accelerometro Cupola X: ");
          client.print(AcX1);
          client.print("<br>\r\n");
          client.print("<br>\r\n");
          client.print("Accelerometro Telescopio Y: ");
          client.print(AcY);
          client.print("  Accelerometro Cupola Y: ");
          client.print(AcY1);
          client.print("<br>\r\n");
          client.print("<br>\r\n");
          client.print("Accelerometro Telescopio Z: ");
          client.print(AcZ);
          client.print("  Accelerometro Cupola Z: ");
          client.print(AcZ1);
          client.print("<br>\r\n");
          client.print("<br>\r\n");
          client.print("Giroscopio Telescopio X: ");
          client.print(GyX);
          client.print("  Giroscopio Cupola X: ");
          client.print(GyX1);
          client.print("<br>\r\n");
          client.print("<br>\r\n");
          client.print("Giroscopio Telescopio Y: ");
          client.print(GyY);
          client.print("  Giroscopio Cupola Y: ");
          client.print(GyY1);
          client.print("<br>\r\n");
          client.print("<br>\r\n");
          client.print("Giroscopio Telescopio Z: ");
          client.print(GyZ);
          client.print("  Giroscopio Cupola Z: ");
          client.print(GyZ1);
          client.print("<br>\r\n");
          client.print("<br>\r\n");
          client.print("Temperatura Telescopio: ");
          client.print(Tmp);
          client.print("  Temperatura Cupola: ");
          client.print(Tmp1);
          client.print("<br>\r\n");
          client.print("<br>\r\n");
          client.print("</html>\r\n");
          break;
        }
        if (c == '\n') {
          // you're starting a new line
          currentLineIsBlank = true;
        }
        else if (c != '\r') {
          // you've gotten a character on the current line
          currentLineIsBlank = false;
        }
      }
    }
    // give the web browser time to receive the data
    delay(100);

    // close the connection:
    client.stop();
    Serial.println("Client disconnected");
  }
  digitalWrite(gyro_state, HIGH);
  digitalWrite(gyro_state_1, LOW);

  do {
    Wire.beginTransmission(MPU);
    Wire.write(0x3B);  // starting with register 0x3B (ACCEL_XOUT_H)
    Wire.endTransmission(false);
    Wire.requestFrom(MPU, 14, true);       // request a total of 14 registers
    AcX = Wire.read() << 8 | Wire.read();  // 0x3B (ACCEL_XOUT_H) & 0x3C (ACCEL_XOUT_L)
    AcY = Wire.read() << 8 | Wire.read();  // 0x3D (ACCEL_YOUT_H) & 0x3E (ACCEL_YOUT_L)
    AcZ = Wire.read() << 8 | Wire.read();  // 0x3F (ACCEL_ZOUT_H) & 0x40 (ACCEL_ZOUT_L)
    Tmp = Wire.read() << 8 | Wire.read();  // 0x41 (TEMP_OUT_H) & 0x42 (TEMP_OUT_L)
    GyX = Wire.read() << 8 | Wire.read();  // 0x43 (GYRO_XOUT_H) & 0x44 (GYRO_XOUT_L)
    GyY = Wire.read() << 8 | Wire.read();  // 0x45 (GYRO_YOUT_H) & 0x46 (GYRO_YOUT_L)
    GyZ = Wire.read() << 8 | Wire.read();  // 0x47 (GYRO_ZOUT_H) & 0x48 (GYRO_ZOUT_L)

    Tmp = Tmp / 340 + 36.53;

    Serial.println("First Gyro");
    Serial.println(GyZ);

    digitalWrite(gyro_state_1, HIGH);
    digitalWrite(gyro_state, LOW);
    delay(1000);

  } while(digitalRead(gyro_state)== HIGH);

  do {
    Wire.beginTransmission(MPU1);
    Wire.write(0x3B);  // starting with register 0x3B (ACCEL_XOUT_H)
    Wire.endTransmission(false);
    Wire.requestFrom(MPU1, 14, true);       // request a total of 14 registers
    AcX1 = Wire.read() << 8 | Wire.read();  // 0x3B (ACCEL_XOUT_H) & 0x3C (ACCEL_XOUT_L)
    AcY1 = Wire.read() << 8 | Wire.read();  // 0x3D (ACCEL_YOUT_H) & 0x3E (ACCEL_YOUT_L)
    AcZ1 = Wire.read() << 8 | Wire.read();  // 0x3F (ACCEL_ZOUT_H) & 0x40 (ACCEL_ZOUT_L)
    Tmp1 = Wire.read() << 8 | Wire.read();  // 0x41 (TEMP_OUT_H) & 0x42 (TEMP_OUT_L)
    GyX1 = Wire.read() << 8 | Wire.read();  // 0x43 (GYRO_XOUT_H) & 0x44 (GYRO_XOUT_L)
    GyY1 = Wire.read() << 8 | Wire.read();  // 0x45 (GYRO_YOUT_H) & 0x46 (GYRO_YOUT_L)
    GyZ1 = Wire.read() << 8 | Wire.read();  // 0x47 (GYRO_ZOUT_H) & 0x48 (GYRO_ZOUT_L)

    Tmp1 = Tmp1 / 340 + 36.53;

    Serial.println("Second Gyro");
    Serial.println(Gy1);

    digitalWrite(gyro_state, HIGH);
    digitalWrite(gyro_state_1, LOW);
    delay(1000);

  } while(digitalRead(gyro_state_1) == HIGH);

  if (GyY > GyY1) {
    digitalWrite(9, HIGH);
    digitalWrite(8, LOW);
  }
  else if (GyY < GyY1) {
    digitalWrite(8, HIGH);
    digitalWrite(9, LOW);
  }
}

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

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

  // print where to go in the browser
  Serial.println();
  Serial.print("To see this page in action, open a browser to http://");
  Serial.println(ip);
  Serial.println();
}

```

Output:

```
First Gyro
1503
Second Gyro
3730
First Gyro
1558
Second Gyro
-162
First Gyro
1498
Second Gyro
-164

```

Can anyone explain to me why once I stop moving the gyroscope, the value returns to the initial position? And if it is possible to convert to degrees?

# Answer
> 1 votes
The GY-521 and the MPU6050 are the same functionally, and you need to use one of the several libraries to get what you want. It appears you are retrieving angular rate values, but what you want is relative heading. The angular rate will return to zero (or whatever the initial value was) once it stops moving, but the heading will (with proper treatment) stay constant.

I have used the MPU6050 in several projects with success, using Jeff Rowberg’s I2CDevLib library, and although getting everything set up is complicated, I recommend it. See this post for basic setup.

Also, I note that most of your program has nothing at all to do with the gyroscope. I recommend you use the smallest and simplest possible program to work out the hardware issues *before* adding the more complex bits.

---
Tags: atmega2560, gyroscope
---


title: No GPS data Neo 6M DFRduino Nano

text:
# Question
Title: No GPS data Neo 6M DFRduino Nano
I checked several answers for same question but none of them help.

I also changed the nano board and GPS module but without luck. I ran it outdoor.

This post question had same issue except my date **does not display the correct date and time**.

My connection:

```
vcc->5V
rxd->d4
txd->d3
gnd->gnd

```

FullExample program from TinyGPS++, I get following types of entries

```
Sats HDOP  Latitude   Longitude   Fix  Date       Time     Date Alt    Course Speed Card  Distance Course Card  Chars Sentences Checksum
           (deg)      (deg)       Age                      Age  (m)    --- from GPS ----  ---- to London  ----  RX    RX        Fail
----------------------------------------------------------------------------------------------------------------------------------------
0    100.0  ********** *********** **** 00/00/2000 00:00:00 152  ****** ****** ***** ***   ******** ****** ***   324   0         0
0    100.0  ********** *********** **** 00/00/2000 00:00:00 230  ****** ****** ***** ***   ******** ****** ***   486   0         0
0    100.0  ********** *********** **** 00/00/2000 00:00:00 308  ****** ****** ***** ***   ******** ****** ***   648   0         0
0    100.0  ********** *********** **** 00/00/2000 00:00:00 384  ****** ****** ***** ***   ******** ****** ***   810   0         0
0    100.0  ********** *********** **** 00/00/2000 00:00:00 463  ****** ****** ***** ***   ******** ****** ***   972   0         0
0    100.0  ********** *********** **** 00/00/2000 00:00:00 541  ****** ****** ***** ***   ******** ****** ***   1134  0         0

```

NMEA read from serial

```
$GPGGA,,,,,,0,00,99.99,,,,,,*48
$GPGSA,A,1,,,,,,,,,,,,,99.99,99.99,99.99*30
$GPGSV,1,1,01,05,,,20*7F
$GPGLL,,,,,,V,N*64
$GPRMC,,V,,,,,,,,,,N*53
$GPVTG,,,,,,,,,N*30

$GPGGA,,,,,,0,00,99.99,,,,,,*48
$GPGSA,A,1,,,,,,,,,,,,,99.99,99.99,99.99*30
$GPGSV,1,1,01,14,,,29*76
$GPGLL,,,,,,V,N*64
$GPRMC,,V,,,,,,,,,,N*53
$GPVTG,,,,,,,,,N*30

```

**UPDATE:**

I change the antenna. At some time I got this. From the GPGSV sentence I know that there are about 15 16 satellites in view but the FullExample only show 0.

```
$GPRMC,,V,,,,,,,,,,N*53
$GPVTG,,,,,,,,,N*30
$GPGGA,,,,,,0,00,99.99,,,,,,*48
$GPGSA,A,1,,,,,,,,,,,,,99.99,99.99,99.99*30
$GPGSV,4,1,15,04,,,31,07,,,33,09,,,34,11,,,30*74
$GPGSV,4,2,15,12,,,33,13,,,30,14,,,33,15,,,27*7D
$GPGSV,4,3,15,16,,,33,19,,,34,20,,,30,21,,,33*70
$GPGSV,4,4,15,22,,,32,23,,,33,33,,,35*7B
$GPGLL,,,,,,V,N*64

$GPRMC,,V,,,,,,,,,,N*53
$GPVTG,,,,,,,,,N*30
$GPGGA,,,,,,0,00,99.99,,,,,,*48
$GPGSA,A,1,,,,,,,,,,,,,99.99,99.99,99.99*30
$GPGSV,4,1,16,04,,,32,07,,,33,08,,,31,09,,,33*7A
$GPGSV,4,2,16,11,,,29,12,,,33,13,,,30,14,,,34*73
$GPGSV,4,3,16,15,,,32,16,,,33,19,,,33,20,,,31*73
$GPGSV,4,4,16,21,,,33,22,,,33,23,,,34,33,,,35*7D
$GPGLL,,,,,,V,N*64

```

My idea now is to supply external power for the DFRduino Nano

Any idea how I can continue. Should I changed to other type of gps module?

# Answer
> 2 votes
The ceramic antenna is the issue. I changed to the external 1.5GHz one. It got fix under 5 seconds

---
Tags: serial, arduino-nano, softwareserial, gps, tinygps
---


# Question
Title: Deep sleep hangs when used with gpio 16 when we connect to reset pin
I have a node MCU and it hangs when I used a deep sleep, as shown in the image attached. My code looks like this:

```
/*
 * ESP8266 Deep sleep mode example
 * Rui Santos
 * Complete Project Details https://randomnerdtutorials.com
 */

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

  // Wait for serial to initialize.
  while(!Serial) { }

  // Deep sleep mode for 30 seconds, the ESP8266 wakes up by itself when GPIO 16 (D0 in NodeMCU board) is connected to the RESET pin
  Serial.println("I'm awake, but I'm going into deep sleep mode for 30 seconds");
  ESP.deepSleep(30e6);

  // Deep sleep mode until RESET pin is connected to a LOW signal (for example pushbutton or magnetic reed switch)
  //Serial.println("I'm awake, but I'm going into deep sleep mode until RESET pin is connected to a LOW signal");
  //ESP.deepSleep(0);
}

void loop() {
}

```

Please help!

# Answer
I had the same issue, and I realized I didn't connect GPIO 16 (or D1) to the RST. Sounds trivial, but happens to me.

Old topic I know, but I tried to figure out my mistake and came across this topic, so this might be helpful to some people.
> -1 votes

---
Tags: arduino-ide, nodemcu, sleep
---


# Question
Title: Reading bytes from a file on SD Card - Understanding Buffer
I have the following piece of code which opens a Bitmap from the SD card and outputs the width to the serial monitor.

```
#include <SPI.h>
#include <SD.h>

File bitmap;

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

  Serial.println("Initializing SD card...");
  if (!SD.begin(4)) {
    Serial.println("initialization failed!");
    while (1);
  }
  Serial.println("initialization done.");

  bitmap = SD.open("/TEST2.BMP");

  int width[0]; // why can't I just write "int width;"
  bitmap.seek(18);
  bitmap.read(width, 4);
  Serial.println(width[0]); // and "Serial.println(width);"
}

void loop() {

}

```

It works perfectly fine but I don't understand why I have to declare the buffer for the width as `int width[0];`. I tried `int width;` but then the output is just 0.

# Answer
> 6 votes
You don't *have* to, it's just one way of doing it.

Basically the `read` function needs a pointer to a buffer to store the data in. By using an array with one entry you get a pointer to a buffer that is big enough for one (32-bit) integer. And you then get an "easy" way of accessing that one integer within that buffer.

Another way would be to just use a simple integer and pass a pointer to that integer to `read`:

```
uint32_t width; // Use a fixed size integer for portability
bitmap.seek(18);
bitmap.read(&width, sizeof(width)); // Use sizeof for portability
Serial.println(width);

```

# Answer
> -1 votes
I think I have a bit of insight:

An array *is* a pointer. Thus,

int arr\[0\];

is equivalent of

int * simple;

So. read(arr... or read(&simple...

---
Tags: sd-card
---


title: ESP8266 GET request code -1

text:
# Question
Title: ESP8266 GET request code -1
I've read several other posts but I still couldn't solve the issue. I'm trying to connect to a website which is HTTP (not HTTPS) but I always get code -1 as response. If I open the link in the browser it works well. Not sure what I am missing? Here's my full code:

```
#include <ESP8266HTTPClient.h>
#include <esp8266wifi.h>

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

void setup() {
  Serial.begin(115200);
  WiFi.begin(ssid, password);

  while (WiFi.status() != WL_CONNECTED) {

    delay(1000);
    Serial.print("Connecting..");

  }
}

void loop() {

  if (WiFi.status() == WL_CONNECTED) {
    HTTPClient http;
    http.begin("www.francescosoave.com/blind/getTime.php");
    http.addHeader("Content-Type", "text/html");
    int httpCode = http.GET();

    Serial.print("HTTP CODE: ");
    Serial.println(httpCode);

    if(httpCode > 0){
      String payload = http.getString();
      Serial.print("PAYLOAD: ");
      Serial.println(payload);
    }

    http.end();
  }

  delay(2000);
}

```

# Answer
You omitted the protocol part of the url. The HttpClient implementation requires it.

Use `http.begin("http://www.francescosoave.com/blind/getTime.php");`

Do not use `Content-type` header. You do not send any content.

Turn-on debug in Tools menu. Set Debug Port to Serial and Debug Level to HTTP\_CLIENT to see the error messages.
> 4 votes

# Answer
to add an additional point to @juraj answer these are the `HTTP` code for various errors written in `ESP8266HTTPClient.h`

```
#define HTTPCLIENT_DEFAULT_TCP_TIMEOUT (5000)

/// HTTP client errors
#define HTTPC_ERROR_CONNECTION_FAILED   (-1)
#define HTTPC_ERROR_SEND_HEADER_FAILED  (-2)
#define HTTPC_ERROR_SEND_PAYLOAD_FAILED (-3)
#define HTTPC_ERROR_NOT_CONNECTED       (-4)
#define HTTPC_ERROR_CONNECTION_LOST     (-5)
#define HTTPC_ERROR_NO_STREAM           (-6)
#define HTTPC_ERROR_NO_HTTP_SERVER      (-7)
#define HTTPC_ERROR_TOO_LESS_RAM        (-8)
#define HTTPC_ERROR_ENCODING            (-9)
#define HTTPC_ERROR_STREAM_WRITE        (-10)
#define HTTPC_ERROR_READ_TIMEOUT        (-11)

```

`-1` usually indicate `bad URL` or bad `wifi connection`
> 1 votes

---
Tags: esp8266, http
---


# Question
Title: Will I need the internal pullup resistor if no button is used?
Given I have two Arduinos that are supposed to primitively communicate with each other using digital pins. On Arduino Ar1, pin D13 is to be used as an input, connected to Ar2's D2 pin.

Will I need to use the internal pullup resistor of Ar1 on pin 13, or is an outputted signal of LOW/HIGH already dragged to 0V/5V?

# Answer
> 1 votes
If you set a pin to output mode in Arduino, it is "push-pull". This means, that any value, 0 or 1, is actively driven.

Therefore, you do not need a pull-up or pull-down resistor on the receiving input.

---

You need such a resistor, only if the driver does not drive the voltage actively. For example, this is the case with buttons or switches, which simply open and close a contact.

Some output modes exist like "open-drain" that only drive to GND at a value of 0, but do not drive the output pin at a value of 1. Such modes are not used if you call `pinMode()`.

---
Tags: pull-up
---