# Question
Title: How do I properly use an ISR inside a class definition?
I want to write a class for a model bike.

For controlling the steering I use a DC motor with two encoders. To get the steering angle `stAng` of the bike, I attach a interrupt to the pin `ST_ENC_A` where one of the encoders is connected to. This interrupt is attached when the bike is initialized with the function `bike.begin()`. When the interrupt is triggerd, the increment-steering-angle-function `incStAng` is triggerd. Said function is member of the class `Bike`. To make the whole code compile and upload I had to make the increment-steering-angle-function `static void incStAng()` and the steering-angle-variable `volatile static float stAng` static.

The code is running, there are no errors or warnings.

Now, when I provide pin `ST_ENC_A` with 3.3V the interrupt should be triggerd and I should see the printed value of `stAng` increse in the Serial Monitor. This is not the case. It stays at 0.00.

This is my first real class I am writing. I only want to create one instance of my bike so the static definition of `stAng` and `incStAng` should be no problem.

So far I found the following websites helpful for information on 'static' and ISR.

I would be glad if someone could help me and give me a hint why the steering angle is not increasing when I give said pin 3.3V!

Board: Arduino Nano RP2040 Connect

Below you will see the .ino, .h, .cpp files in this order.

```
// myBike.ino - main file

#include "Bike.h"

Bike bike;

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

void loop() {
  float val = bike.getStAng();
  Serial.println(val);
}

```

```
// Bike.h - header file for the Bike library

#ifndef Bike_h
#define Bike_h

#include "Arduino.h"

class Bike {
  public:
    Bike();
    void begin();
    float getStAng();
  private:
    volatile static float stAng;
    static void incStAng();
};

#endif

```

```
// Bike.cpp - implementation file for the Bike library

#include "Bike.h"

#define ST_ENC_A      12
#define ST_ENC_B      11

#define DEG_PER_CNT   0.51428571428

Bike::Bike() {
  pinMode(ST_ENC_A, INPUT);
  pinMode(ST_ENC_B, INPUT);
}

void Bike::begin() {
  attachInterrupt(digitalPinToInterrupt(ST_ENC_A),incStAng,RISING);
}

void Bike::incStAng() {
  volatile float stAng;
  int b = digitalRead(ST_ENC_B);
  if(b==HIGH){
    stAng = stAng - DEG_PER_CNT;
  }else{
    stAng = stAng - DEG_PER_CNT;
  }
}

float Bike::getStAng() {
  volatile float stAng;
  return stAng;
}

```

# Answer
You have *three* different variables named `stAng` here:

* a static member of the `Bike` class, which has been declared but not defined, and is never used
* a local variable of the `Bike::incStAng()` method
* a local variable of the `Bike::getStAng()` method

There should be only one such variable. For this, you should define the first one: in Bike.cpp

```
volatile float Bike::stAng;

```

and get rid of the other two.

Side note: I would recommend avoiding floating point computations within an ISR, as these can be quite slow. Instead, count the *integer* number of encoder steps in the ISR, and convert to an angle within `Bike::getStAng()`.
> 3 votes

---
Tags: class, isr
---


# Question
Title: Passing function as argument, with capture, what type to declare in function?
This probably has a simple resolution, but can't find the right combination.

I'm trying to setup a function (`setupScreen`) to take as an argument a function to do the actual setup:

```
void ScreenHelpers::setupScreen(void (*setupFunc)(ThinkInk_290_Tricolor_Z10*)){
    ScreenHelpers::waitTilCanRefreshScreen();

    (* setupFunc)(&display_two);

    lastUpdateTime = millis();
}
//...
void ScreenHelpers::displayErrorMessage(const String message){
    const char* text = message.c_str();
    ScreenHelpers::setupScreen([text](ThinkInk_290_Tricolor_Z10* screen) {
        screen->clearBuffer();
        ScreenHelpers::simpleDisplayText(
            screen,
            text,
            EPD_RED
        );
     });
}

```

This works, until I added the `[text]` to capture the `text` variable in the lambda, where it resulted in:

```
ScreenHelpers.cpp: In static member function 'static void ScreenHelpers::displayErrorMessage(String)':
ScreenHelpers.cpp:45:4: error: no matching function for call to 'ScreenHelpers::setupScreen(ScreenHelpers::displayErrorMessage(String)::<lambda(ThinkInk_290_Tricolor_Z10*)>)'
   });
    ^
ScreenHelpers.cpp:21:6: note: candidate: 'static void ScreenHelpers::setupScreen(void (*)(ThinkInk_290_Tricolor_Z10*))'
 void ScreenHelpers::setupScreen(void (*setupFunc)(ThinkInk_290_Tricolor_Z10*)){
      ^~~~~~~~~~~~~

```

What should my function declaration look like to accept this?

# Answer
`ScreenHelpers::setupScreen()` expects its argument to be a plain function. A capturing lambda is not a plain function: it is rather a functor, i.e. an object that is callable like a function.

The standard way of passing such a lambda in C++ is to declare the parameter to be of type `std::function`:

```
#include <functional>

void ScreenHelpers::setupScreen(std::function<void(ThinkInk_290_Tricolor_Z10*)> setupFunc) {
    ...
}

```

This may or may not work depending on the Arduino board you are using. AVR-based boards rely on a C library that only minimally supports C++. You cannot use `<functional>` on those boards. If you are using one of those boards, your options are:

1. Try to find an implementation of of the C++ STL for AVR-based boards. I have seen at least one floating around in the Net.
2. Use the standard C idiom for defining a callback with a `void*` parameter:

```
void ScreenHelpers::setupScreen(
      void (*setupFunc)(ThinkInk_290_Tricolor_Z10*, void*),
      void *callback_data) {
   setupFunc(&display_two, callback_data);
   //...
}

// elsewhere:
ScreenHelpers::setupScreen([](ThinkInk_290_Tricolor_Z10 *screen, void *data) {
   const char *text = (const char *) data;
   // ...
}, (void *) text);

```
> 2 votes

---
Tags: c++
---


# Question
Title: Arduino, problem with interrupt and SSD1306 OLED
I'm not that good at this. Calculates RPM through Peripheral Speed and Interrupt.

Everything works fine when I show this in the IDE with `Serial.print` without OLED. When I connect an SSD1306 OLED I2C, the interrupt stops working. No `serial.print`.

If I uncomment the `display.display()`, Same problem with `display.setRotation(90)`: everything is fine and `serial.print` starts working, but of course not the OLED.

In the code I have a `void` addressing, `visadisplay()`. If I put this addressing in `void loop ()` then everything works but then there is a risk of unsynchronization, wrong values. I have also removed `visadisplay();` without change.

Help...

```
#include <SPI.h>
#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.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)
#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);

// Function for serial display.
// Connections for Nano.
// Hall sensor connection: (Signal out) --- (D2).
// Display connection: (SDA) --- (4A) / (SCL) --- (A5)

volatile unsigned long PulsTid = 0UL;
volatile unsigned long StartTid = 0;
volatile unsigned long SlutTid = 0;
volatile unsigned long CalcTid = 0;
volatile float omkrets = 7.5;
volatile float HastighetPerferi = 0;
volatile unsigned long Rpm = 0;
volatile float Vinkel = 0UL;

void isr() { // interrupt service routine
  Vinkel = 0;
  StartTid = millis();
  CalcTid = SlutTid;

  detachInterrupt(0);             //detaches the interrupt while calculating

  PulsTid = (StartTid - SlutTid);
  HastighetPerferi = (omkrets / PulsTid);
  SlutTid = StartTid;
  Rpm = ((HastighetPerferi / (omkrets / 1000) * 60) / 2); // Calculate speed

  visadisplay();
  attachInterrupt(0, isr, FALLING);  //attaching the interrupt again
}

void visadisplay(void) {
  Serial.print("Varvtal: ");
  Serial.println(Rpm);

  display.setRotation(90);
  display.clearDisplay();
  display.setTextSize(1);              // Text size.
  display.setTextColor(SSD1306_WHITE); // White text.
  display.setCursor(0, 0);             // Start position
  display.println("RPM: ");
  display.setCursor(40, 10);
  display.setTextSize(2);
  display.print(Rpm);
  display.display();
}

void setup() {
  Serial.begin(115200);
  attachInterrupt(0, isr, FALLING);  //attaching the interrupt

  //SSD1306_SWITCHCAPVCC = generate display voltage from 3.3V internally
  if (!display.begin(SSD1306_SWITCHCAPVCC, 0x3C)) { // Address 0x3C for 128x32
    Serial.println(F("SSD1306 allocation failed"));
    for(;;); // Don't proceed, loop forever
  }
}

void loop(){
}

```

# Answer
Your problem is (most likely) that you are doing *everything* from an interrupt. That is not only bad practice, but on Arduinos it is generally impossible.

On small microcontrollers you typically only have one interrupt priority (occasionally two). That means that only one interrupt can run at a time, and if an interrupt is running then no other interrupt can interrupt it.

So anything that relies on interrupts to operate can never be used inside an interrupt service routine, or it will never function.

That includes things like `delay()` and, depending on the implementation, such things as `Wire` (I2C) and `SPI`.

Instead your ISR really should be as short as possible. It should at most do any short calculations and store results, and then indicate (through the use of a *semaphore*) to the main thread that it should do some work.

The simplest "fix" to your problem would be to move `visadisplay()` into `loop()` and in `isr()` simply set a `bool` flag when there is data to display. Your `loop()` then checks that flag and, if set, resets it and calls `visadisplay()`.

Also, you don't need to detach and re-attach the interrupt all the time - if the ISR is running then interrupts can't happen anyway.

```
// ... snip ...
volatile bool doDisplay = false;

void isr()          //interrupt service routine
{
  Vinkel = 0;
  StartTid = millis();
  CalcTid = SlutTid;

  PulsTid = (StartTid - SlutTid);
  HastighetPerferi = (omkrets/PulsTid);
  SlutTid = StartTid;
  Rpm = ((HastighetPerferi/(omkrets/1000)* 60)/2);  //Calculate speed

  doDisplay = true; // Signal to the main thread there's data to display
}

// ... snip ...

void loop() {
    if (doDisplay) {       // If there is something to display
        doDisplay = false; // then clear the flag for next time
        visadisplay();     // and display the data.
    }
}

```
> 2 votes

# Answer
About rotating text on OLED, rotation codes are 0, 1, 2, 3 (see Adafruit web site).

So your code should look like:

```
  Serial.print("Varvtal: ");
  Serial.println(Rpm);

  display.setRotation(1);
  display.clearDisplay();

```
> 0 votes

---
Tags: interrupt, ssd1306
---


# Question
Title: How to prevent the garbage data when the serial port is initialised?
I use Arduino Uno. I get garbage in Serial Monitor or HyperTerminal right after I connect to the port. Here is an example code:

```
void setup() {
  // initialize serial:
  Serial.begin(57600);

}

void loop() {

    Serial.println("Test");
}

```

An example screenshot of the output. When port is re-connected the first received data is not Test:

So my problem is when the port is initialised the first data received is garbage. Is there a way to prevent this happening? Is that something to do with bootloader baud rate? I tried other baud rates and get same issue and I really want to use 57600 or 115200 baud rate.

# Answer
Your use of the terminology in your edited post and comments is problematic because you are not being clear enough. For example:

"*I mean during Serial.begin(57600); I get garbage values. How can I skip this?* " and "*If I comment out I get nothing*".

"*By "When port is re-connected" means clicking "call" in HyperTerminal or openning Arduino serial monitor. First data is always garbage"*. There are others."

"*An example screenshot of the output. When port is re-connected the first received data is not Test:*" - But, the first received data you are showing is, in fact, the word Test.

There are others.

I will try to help by answering your main question which seems to be "**How to prevent the garbage data**" and note that I have not included "*when the serial port is initialized*".

Firstly, when I use my Uno and V 1.8.13 of the IDE, and I compile and run your sample program, I get the usual output showing progress of the compilation and upload to the board, and that text ends with "avrdude done. Thank you." At this point, the program is running and println is doing its thing.

When I open the serial monitor (by clicking on the box in the upper right corner of the full IDE screen - baud rate=57600, no line ending), I get corrupt characters at first. This always happens and I believe that is what you are seeing.

This happens because when you open the serial monitor, the UNO is being reset, but it is not the complete reset that is done when you upload code and begin execution. To be a bit simplistic, when you open the serial monitor, your program is running and the reset from opening the serial monitor is not the clean start that is done when you compile, upload and begin to execute the program.

Use either of these programs to test out what I am getting at.

```
void setup() {
  // initialize serial:
  Serial.begin(57600);
}

void loop() {
    delay(10000);
    while(1){
    Serial.println("Test");
    }
}

```

or

```
void setup() {
  // initialize serial:
  Serial.begin(57600);
  delay(10000);
}

void loop() {
  Serial.println("Test");
}

```

Go through your steps with either of these modified versions and open the serial monitor during the 10 second delay (unclick autoscroll to make it easier to see) and you will not get any corruption.

If, however, you compile/load/execute the program and then start opening and closing the serial monitor, you will start to see corruption in subsequent opens of the serial monitor - again because the reset when you open the serial monitor is not the clean reset that is done when you compile/load/execute.

Why doesn't everybody complain like crazy about the problem that you are experiencing? I think because folks learns to work with/around the way the UNO works. Your code just sends out serial data, so it is a prominent illustration of the issue, but it is not an insurmountable issue.

You can go deep into the serial monitor code and learn all about what is going on and come up with an elegant and likely tedious solution - I'm not sure, but I don't doubt that some have done this and it may even involve some hardware manipulation of serial control lines.

Alternatively, you can write the program to allow time to complete the serial monitor opening before you start sending out the data. You can even clean out any residual data (as long as you know what you are doing) if you anticipate multiple opening and closings.

Hope it helps.
> 1 votes

# Answer
There are probably a number of reasons that might contribute to the problem that you are observing:

1. You are trying to send the string "Text" within the main loop without any delay between println calls. So the microprocessor is running at full speed and trying to send the string "Text" much faster than the baud rate can accommodate. The serial interface has a finite I/O buffer, which is probably filling very fast and overwriting old values in the middle of serial transmission. Hence potentially garbage characters.
2. Even when HyperTerminal is not running, the PC and Arduino are exchanging serial messages. So when you start HyperTerminal at some arbitrary time, the data in the serial buffer might not correspond cleanly to the start or end of a transmission.

As an alternative, you may want Arduino wait for a serial command from the PC before starting to send the serial data. For example, when using the Serial Monitor, you may send a key press to Arduino, which would then start sending data so that no data is lost while there is no body listening on the PC side or while a terminal program is not running.

Finally, flushing the serial buffers on either side of the serial connection might help you clear partial serial messages.
> -1 votes

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


title: Carbon dioxide sensor MG 811

text:
# Question
Title: Carbon dioxide sensor MG 811
I am using MG811 carbon dioxide sensor with ESP8266 module. CO2 values is being read inside closed room. The value comes around 400 ppm. Using CO2 generator does not make increase in reading. Checked with pSense RH co2 Temp handheld meter. It shows around 750-800 ppm. But ESP8266 still shows around 420 ppm on oled display.

```
#include "CO2Sensor.h"
CO2Sensor co2Sensor(A0, 0.99, 100);

void setup() {
Serial.begin(9600);
Serial.println("=== Initialized ===");
co2Sensor.calibrate();
}

void loop() {
int val = co2Sensor.read();
Serial.print("CO2 value: ");
Serial.println(val);
delay(1000);
}

```

What is the meaning of (A0, 0.99, 100) in second line of code. Is any calibration needs to be done for correct value ?

# Answer
Your code appears to come from an example in the library you are using https://github.com/solvek/CO2Sensor/blob/master/examples/ReadCO2/ReadCO2.ino

To answer your questions:

***What is the meaning of (A0, 0.99, 100) in second line of code.*** Inspection of the library source code shows: CO2Sensor::CO2Sensor(int analogPin, float inertia, int tries)

Of course, if you don't understand how the library is using the variables inertia and tries, this alone will make no sense to you.

***Is any calibration needs to be done for correct value ?***

In my opinion, the answer is YES. Furthermore, I think that calibration is necessary but not sufficient to appropriately use the sensor to the extent that you can have a good idea about what a "correct value" means.

I like that you get the fundamental idea of testing, or validating, a sensor. I like the idea that you are using another monitor (assuming it is a good one) as a "standard" and I like that you use a CO2 generator - assuming you are doing that safely.

What is lacking, again, in my opinion, is any understanding of how the sensor works. It is not that I am an expert on this particular sensor, but even a brief look at what passes as a data sheet https://sandboxelectronics.com/files/SEN-000007/MG811.pdf and the text of the library usage https://github.com/solvek/CO2Sensor and a few other sources that are freely available; makes it clear to me that you need to dig into this much more before you will have success understanding and appropriately using this sensor.

It is complicated. I hope that my response is not off putting and instead points you in the right direction.
> 2 votes

---
Tags: esp8266, c++, analogread, oled, calibration
---


# Question
Title: Can I power Lilygo TTGo T-display from 5v and still use USB for communication?
I have a project which needs a 7-9V power source. I use a battery, and plan to use a small regulator to supply 5V to a Lilygo TTGO T-Display V1.1 (1.14 inch display) via the 5V and GND pins.

I need to connect the Lilygo to USB from time-to-time to upload data. *Will there be any conflict between the USB power and the 5V supply ?*

I have peered for a long time at the schematic, and I see that there are MOSFETs doing some kind of protection, but I do not understand it well enough to be sure. **Schematic**: here

1. Q5 appears to disconnect the battery (VBAT) from +5V when the USB is connected.
2. Q4 also seems to disconnect the battery (BAT) from +5V when the USB is connected. *What is the difference between VBAT and BAT ?*
3. VBUS (the USB power) is connected to +5V via a Zener diode. This appears to allow the USB to supply 5V, but prevent current flowing back to the PC. I think there could be an issue with high current through the Zener if my 5V regulator gave a voltage that was lower than the USB.

# Answer
What are you trying to achieve? For how long is the board supposed to function? The simplest solution in this case is to simply get a 4.2V battery for the LilyGO board itself, most likely not just in terms of effort, but economically.

From your edits, I (now) assume you want to use the 5V pin on the board? I don't think that'll work the way you'd want it to, as it doesn't seem that it was intended for that (if it was, the VIN pin would've been brought out).

1. > Q5 appears to disconnect the battery (VBAT) from +5V when the USB is connected.

Yeah, that makes sense to me as well.

2. > Q4 also seems to disconnect the battery (BAT) from +5V when the USB is connected. What is the difference between VBAT and BAT ?

Yes, looking at the datasheet for the battery charger and the schematic for the LilyGO board, VBAT is the batteries voltage, while the BAT terminal is the one coming out of the charger and the one that usually supplies the current to both charge the battery and to possibly drive the system load.

3. > VBUS (the USB power) is connected to +5V via a Zener diode. This appears to allow the USB to supply 5V, but prevent current flowing back to the PC. I think there could be an issue with high current through the Zener if my 5V regulator gave a voltage that was lower than the USB.

Yeah, it prevents the current going back into the USB port if you have the battery connected. You need a pretty substantial voltage to overcome that Schottky\* barrier.

One issue you'll probably encounter is that if you connect a 5V source to that pin, the system will think it's powered on by a battery and you can damage the BAT terminal. If you have more than 1 of those boards and you're willing to experiment, you could try cutting the trace to BAT terminal altogether and connecting the 5V source and seeing if that works.

Another issue is that for safety reasons, it'd be prudent to switch that source off when you're connecting the USB; you'd also want to protect that 5V source from being damaged by the VUSB once it's on. There are probably ways you could keep the 5V on if you desolder the USBC connector and try to manually attach a probe to the datalines and ground the two together, but dealing with USBC is not easy and you're rapidly venturing into territory where it's just easier to get a different board and the screen separately or just use a LiPo battery to power the board in the first place (you could probably find a way to use multiple LiPo packs if you need your application to last longer as well).

Note: I didn't spend too much time looking at the schematic and it is a bit confusing, so a possible good exercise would be to simulate those two circuits in a SPICE program. And again, these types of questions are covered more-so by the EE SE. If you'd have posted it there, I'm sure you'd get more (and most likely, better) answers.
> 0 votes

---
Tags: esp32
---


title: Is ESP8266 dropping an interrupt?

text:
# Question
Title: Is ESP8266 dropping an interrupt?
I want to use interrupts on my ESP 8266 to monitor the digital outputs of a power meter and water meter.

The idea is to increment a counter in the ISRs and at some point to take the value of the counter and to set the counter back to 0 in the loop() function. I've red about critical sections, noInterrupts() and interrupts() and then I started to wonder if an ISR will be executed while the code is between noInterrupts() and interrupts(). On theory it should be because the interrupt flag in the chip will be raised and the ISR will be invoked after the code exits the critical section. I wrote a program to test it, but my findings prove the opposite.

```
#include <Arduino.h>

#define REPORT_TIME 5000
#define INTERRUPT_PIN D1

unsigned long base_time;

volatile unsigned int interrupt_counter = 0;

void IRAM_ATTR isr() {
  interrupt_counter++;
}

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

  // The interrupt will be FALLING EDGE
  pinMode(INTERRUPT_PIN, INPUT_PULLUP);
  pinMode(LED_BUILTIN_AUX, OUTPUT);
  digitalWrite(LED_BUILTIN_AUX, HIGH);
  attachInterrupt(digitalPinToInterrupt(INTERRUPT_PIN), isr, FALLING);

  base_time = millis();
}

bool written = false;

void loop() {

  if (!written)
  {
    written = true;
    for (int i = 0; i < 100; i++)
    {
      digitalWrite(LED_BUILTIN_AUX, LOW);
      digitalWrite(LED_BUILTIN_AUX, HIGH);
    }
  }

  unsigned long time_now = millis();
  if (time_now - base_time >= REPORT_TIME)
  {

    written = false;

    base_time = time_now;

    unsigned int interrupt_counter_local;

    //Guard the critical section
    noInterrupts();
    interrupt_counter_local = interrupt_counter;
    interrupts();

    digitalWrite(LED_BUILTIN_AUX, LOW);
    digitalWrite(LED_BUILTIN_AUX, HIGH);

    Serial.print("counter ");
    Serial.println(interrupt_counter_local);
    Serial.println();
  }
}

```

Using a wire I attached the pin of the builtin led to the interrupt pin and in the serial monitor I could see the values are:

```
counter 100
counter 201
counter 302

```

When I modify the critical section to be like:

```
noInterrupts();
interrupt_counter_local = interrupt_counter;
digitalWrite(LED_BUILTIN_AUX, LOW);
digitalWrite(LED_BUILTIN_AUX, HIGH);
interrupts();

```

I expect the same output as above but the values are:

```
counter 100
counter 200
counter 300

```

Am I missing something or the interrupts doesn't work as I expect?

# Answer
> 1 votes
After some additional experiments I found that moving

```
digitalWrite(LED_BUILTIN_AUX, HIGH);

```

utside the critical section gives me the expected result, so I'm not blocked anymore and **more importantly the chip will not drop an interrupt**. If someone knows why it doesn't work with my initial version I will be happy to hear the answer.

---
Tags: esp8266, interrupt, isr
---


# Question
Title: UDPSendReceiveString example using Arduino Due with ENC28J60 Ethernet Module
I was trying to learn how to use UDP protocol to use in my automation project to send commands to an Arduino Due on ethernet with an ENC28J60 breakout board which I have connected to the Due from SPI pins. I had to use another library called EthernetENC.h to use this module with the Due.
Arduino Code:

```
#include <EthernetENC.h>
#include <EthernetUdp.h>

#define UDP_TX_PACKET_MAX_SIZE 256

// Enter a MAC address and IP address for your controller below.
// The IP address will be dependent on your local network:
byte mac[] = {
  0xA0, 0x36, 0xBC, 0x30, 0xC1, 0x16
};
IPAddress ip(192, 168, 137, 205);

unsigned int localPort = 8888;      // local port to listen on

// buffers for receiving and sending data
char packetBuffer[UDP_TX_PACKET_MAX_SIZE];  // buffer to hold incoming packet,
char ReplyBuffer[] = "acknowledged";        // a string to send back

// An EthernetUDP instance to let us send and receive packets over UDP
EthernetUDP Udp;

void setup() {
  // You can use Ethernet.init(pin) to configure the CS pin
Ethernet.init(10);  // Most Arduino shields
  //Ethernet.init(5);   // MKR ETH Shield
  //Ethernet.init(0);   // Teensy 2.0
  //Ethernet.init(20);  // Teensy++ 2.0
  //Ethernet.init(15);  // ESP8266 with Adafruit FeatherWing Ethernet
  //Ethernet.init(33);  // ESP32 with Adafruit FeatherWing Ethernet

  // start the Ethernet
  Ethernet.begin(mac, ip);

  // Open serial communications and wait for port to open:
  Serial.begin(9600);
  while (!Serial) {
    ; // wait for serial port to connect. Needed for native USB port only
  }

  // Check for Ethernet hardware present
  if (Ethernet.hardwareStatus() == EthernetNoHardware) {
    Serial.println("Ethernet shield was not found.  Sorry, can't run without hardware. :(");
    while (true) {
      delay(1); // do nothing, no point running without Ethernet hardware
    }
  }

  // start UDP
  Udp.begin(localPort);
}

void loop() {
  // if there's data available, read a packet
  int packetSize = Udp.parsePacket();
  if (packetSize) {
    Serial.print("Received packet of size ");
    Serial.println(packetSize);
    Serial.print("From ");
    IPAddress remote = Udp.remoteIP();
    for (int i=0; i < 4; i++) {
      Serial.print(remote[i], DEC);
      if (i < 3) {
        Serial.print(".");
      }
    }
    Serial.print(", port ");
    Serial.println(Udp.remotePort());

    // read the packet into packetBuffer
    Udp.read(packetBuffer, UDP_TX_PACKET_MAX_SIZE);
    Serial.println("Contents:");
    Serial.println(packetBuffer);

    // send a reply to the IP address and port that sent us the packet we received
    Udp.beginPacket(Udp.remoteIP(), Udp.remotePort());
    Udp.write(ReplyBuffer);
    Udp.endPacket();
  }
  delay(10);
}

```

Processing 3 Code:

```
 import hypermedia.net.*;

 UDP udp;  // define the UDP object

 void setup() {
 udp = new UDP( this, 6000 );  // create a new datagram connection on port 6000
 //udp.log( true );     // <-- printout the connection activity
 udp.listen( true );           // and wait for incoming message
 }

 void draw()
 {
 }

 void keyPressed() {
 String ip       = "192, 168, 137, 205";  // the remote IP address
 int port        = 8888;    // the destination port

 udp.send("Hello World", ip, port );   // the message to send

 }

 void receive( byte[] data ) {       // <-- default handler
 //void receive( byte[] data, String ip, int port ) {  // <-- extended handler

 for(int i=0; i < data.length; i++)
 print(char(data[i]));
 println();
 }

```

And this is my test setup:

After I upload the code to the Due the LinkOFF command immediately triggers and Serial.print() prints that "Ethernet cable is not connected." but this is indeed incorrect since this setup worked in other ethernet examples. But other than this message there is nothing on the Serial monitor. On the processing side, the story is even more depressing because simply nothing happens. There is just a small window opening and no matter where a click or press any key on my keyboard no string is being sent or received. I seriously don't know what to do I don't have much experience with UDP and I am trying to learn but the only responsive example in the Arduino library isn't working.

Edit: I have connected the ENC28J60 directly to my laptop ethernet port and I chose the IP from there which was IPv4 Adress = 192.168.137.1 I also remove the linkOFF() from the original example since it was just using serial monitor for no good.

# Answer
from https://github.com/JAndrassy/EthernetENC/wiki/Examples

> If the `Ethernet.linkStatus()` is invoked too soon, it may return `LinkOFF`. You can do the check in setup() this way:

```
  if (Ethernet.linkStatus() == LinkOFF) {
    delay(500);
    if (Ethernet.linkStatus() == LinkOFF) {
      Serial.println("Ethernet cable is not connected.");
    }
  }

```
> 0 votes

---
Tags: arduino-ide, arduino-due, communication, ethernet, enc28j60
---


# Question
Title: Arduino Nano R3 & Deek-Robot datalogging shield
Whilst I am much more at home programming PIC ISR's in assembler, I am building a data logger using a DS1307 to interrupt every second to write data to a USB SD card.

There does not appear to be a connection or even a pad from the DS1307 SQW for interrupts and feel I must be missing something, as this would be a remarkable designer/manufacturer oversight?

# Answer
> 1 votes
I can't find any official source for information about "Deek-Robot datalogging shield" but what I do find indicates it is the same or similar design as an Adafruit Datalogging shield. The DS1307 (or other RTC) square wave out signal is routed to a through-hole on the interior of the board indicated in this image:

It does not appear to be routed anywhere else an any of these boards. Note: the picture here is of a board (Current Adafruit logging shield apparently) that uses an NXP RTC that has the same pinout as the DS1307, but uses a different register layout. But in any case places the SQ output on a header in the same basic location. So you would need to solder a header to accept a jumper. Or solder a wire from there to one of the through holes for a digital pin, probably pin 2 or 3 if you're on an UNO (you have tagged) since those are the pins compatible with `attachInterrupt()`

---
Tags: arduino-uno
---


# Question
Title: Controll the dc motor that works with 2xAA bateries using 5v
I have a toy that has a dc motor and is runing with 2xAA bateries ( i think it is 3v motor)

So i want to run it with 5v power supply.

First question: Can 5v damage the motor

Second question: i think i need to add diode but dont know what diode to add and how to determine what i need

Third question: is there a combination that i can add series of diode so i can drop voltage to 3v

# Answer
> 0 votes
DC electric motors are usually rated to run over a range of voltages. If you are unsure of the specifications of the DC electric motors you have, consider buying new motors which are specified to operate in a rage that includes 5VDC.

Consider not running both the processor (Arduino) and any high current demanding device off the same power source. Such as solenoids or motors. This is especially true for mobile devices supplied by battery voltage. Often is the case the processor will reset (behave unexpectedly) should the supply voltage drop because of activating a solenoid or motor.

Diodes and other components are added to suppress or mitigate undesired effects of a solenoid or motor. Inductive loads such as solenoids or motors resist changes in current flow and can damage connected components if the undesired current flow is beyond the connected component's abilities. Read this stackexchange question/answer for more about this.

A silicon diode has a forward bias voltage drop of about 0.6 volts. Other diodes have different forward bias voltage drops. This wikipedia article lists a few different diodes. It may be possible to arrange enough diodes in series to drop 5 volts to 3 volts.

Consider searching for a 5VDC controllable Arduino relay module. There are plenty on the web. Such a device should include the circuitry to safely control the relay and the relay should provide more than adequate isolation from the DC motor.

For a learning experience, consider following this Arduino / Motor tutorial provided by Adafruit.

---
Tags: motor, electronics, voltage
---


# Question
Title: DS3231 with Arduino Nano for Timing precision
I am in need to synchronize two separate circuit boards working with Arduino nano. The need is to activate one relay using Arduino-1 after 45 min and another relay using Arduino-2 after 45.36 seconds. The time starts from the point of reception of input from an external switch common to both.

with ref to This question and from the advice of edgar-bonet I have used one temperature-compensated RTC for timing the Arduino s externally **(DS3231)**. I am using its 32kHz pin from the chip for counting the ticks and in the Arduino using the interrupt to count the ticks.

The program is shown below.

```

float _sec = 1;

float secTime =  _sec * 1000UL; // second->millis
uint32_t coilTime = 5 * 1000UL; // second->millis

volatile uint32_t count = 0;
/*
 * 32768 ticks in 1 sec
 * 0.032768 tick in 1 us
 */

float _multiplier = 0.032768; // 32768 Hz

uint32_t _delay = secTime * _multiplier * 1000UL ;

volatile bool onFlag = false;

ISR(INT1_vect, ISR_NOBLOCK) {
  count = count + 1UL;
  if (_delay == count) {
    PORTC |= (1 << 5);
    onFlag = true;
    EIMSK = 0;
  }
}

ISR(INT0_vect) {
  /* INTERRUPT re-initalization */
  EIMSK = 0;
  EICRA = B00001100; // INT0 - clear ; INT1 -  set
  EIFR  = 0;
  PORTB ^=  (1 << 0) | (1 << 1); // setting Green off and red on
  count = 0;
  EIMSK = B00000010; // INT0 - inactive ; INT1 - active
}

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

  /* PIN initialization */
  DDRB |= (1 << 0) | (1 << 1); // red led and green led

  pinMode(3, INPUT_PULLUP); // timer unit
  pinMode(2, INPUT); // interrupt unit

  DDRC |= (1 << 3) | (1 << 4) | (1 << 5); // relay, OUT_1, OUT_2

  /* LEDs state update */
  PORTB &=  ~(1 << 1); // red off.
  PORTB |= (1 << 0); // green on.

  PORTC &= ~(1 << 3); // A3-off

  /* INTERRUPT initalization */
  EICRA = B00000011; // INT0 - set ; INT1 - not set
  EIMSK = B00000001; // INT0 - active ; INT1 - inactive
  EIFR  = 0;
}

void loop() {

  if (onFlag) {

    PORTB |= (1 << 0); // setting green on

    delay(500);
    PORTC ^= (1 << 5);
    //    PORTB ^= (1 << 0) | (1 << 1);
    PORTB ^= (1 << 1); // setting red off
    while (true) {
      TCCR2B = 0;
      count = 0;
      PORTB ^= (1 << 0);
      delay(500);
    }
  }
}

```

when running the program The result I am expecting the accuracy of microseconds but

for input -\> Measured value 1 sec -\> 1.000387792 2 sec -\> 2.000784208 50 sec -\> 50.020926833 250 sec -\> 250.104557792

How to make the clock more precise, In the datasheet it is said that the clock is accurate to +- 2ppm.

datasheet-ds3231

# Answer
> 1 votes
This may not be a proper answer to your question. Instead of telling you how to improve the accuracy, I will show you how to measure it. The issue is that the code you posted is doing too much stuff, and it is not clear how it could be measuring the clock accuracy. So, instead I suggest you try the code below:

* connect a push button between pin 2 and GND
* connect the 32768 Hz signal to pin 5
* watch the built-in LED blink

```
const uint8_t input_pin = 5;  // 32768 Hz on digital 5 = T1
const uint8_t clear_pin = 2;  // button to clear timer

void setup() {
    pinMode(input_pin, INPUT_PULLUP);
    pinMode(clear_pin, INPUT_PULLUP);
    pinMode(LED_BUILTIN, OUTPUT);

    // Configure Timer 1 as a counter.
    TCCR1A = 0;
    TCCR1B = _BV(CS11) | _BV(CS12);  // count falling edges of T1
}

void loop() {
    // Display bit 14 of the counter on the builtin LED.
    if (TCNT1 & (1 << 14)) {
        digitalWrite(LED_BUILTIN, HIGH);
    } else {
        digitalWrite(LED_BUILTIN, LOW);
    }

    // Clear the counter on button press.
    if (digitalRead(clear_pin) == LOW) {
        TCNT1 = 0;
    }
}

```

What this sketch does is use Timer/counter 1 as a counter in order to count the falling edges of the 32768 Hz signal. Bit 14 of the counter should then toggle at 1 Hz. This bit is output on the built-in LED to let you check its frequency. You can use the push button to reset the phase of the blinks.

If you have a very accurate clock at hand, you can use the push button to synchronize the blinks with the ticks of that clock, and then see how long it takes to get visibly out of phase. You can also synchronise the blinks of two Arduinos and see for how long they stay in sync. If you have a scope, you could measure a tiny offset between the edges of the two Arduino's LEDs, then see how this offset evolves with time.

---
Tags: arduino-uno, arduino-mega, interrupt, timers, rtc
---


title: How to pass Strem object to my class

text:
# Question
Title: How to pass Strem object to my class
I'm trying to creaper class wraper to use an `Stream`object but I've an error when I try to compile. My `.h`file :

```
#include <Arduino.h>

class TestSerialListener {
public:
  TestSerialListener(Stream &serial);
  void testPrint(void);
private:
  bool _listener_start;
  Stream &_serial;

  void startListener(void);

};

```

my `cpp`file

```
#include "TestSerialListener.h"
#include <Arduino.h>

TestSerialListener::TestSerialListener(Stream &serial) : _serial(serial)
{
}

void TestSerialListener::testPrint(){
    _serial.begin(115200);      <---------- error compilation
    _serial.println("test");
}

void TestSerialListener::startListener(void)
{
    if(!_listener_start){
        _listener_start = true;
    }
}

```

And when i try to compile it I got this error : `error: 'class Stream' has no member named 'begin'`Why I can't use `begin()`in my classe ?

# Answer
> 2 votes
the `begin()` method is defined in the `HardwareSerial` class, not in `Stream`. You can look that up yourself in your Arduino installation. For me these files are placed under `~/.arduino15/packages/arduino/hardware/avr/1.8.6/cores/arduino/` and are named `Stream.h` and `HardwareSerial.h`.

And if you think about it, this is quite logical. The `Stream` class can represent any object, that can stream data. It doesn't know anything about how exactly the data is streamed on a hardware level. It just provides the convenient functions for handling the data. The `HardwareSerial` class then derives from `Stream` to get those data handling methods and adds its own methods to handle the hardware side of the problem, including setting a baudrate.

When providing a `Stream` reference to a class constructor you want to `begin()` the corresponding object outside of the class, before you start to stream any data through it. Doing it this way makes your class widely usable, since you could use any `Stream` object, even a file on an SD card.

So move the `begin()` line from your class to the `setup()` function in your main code.

---

For reference: Juraj showed the inheritance between the classes in his answer to this question. Have a look at it, since it is quite enlightening.

---
Tags: c++, class, stream
---


# Question
Title: Arduino 3.3v pro mini, most efficient use of AA batteries for power
I want to use a 3.3V pro mini that uses a BME 280 to take temp/pressure/humidity, and nRF24L01 module to transmit the data, at ?10 minute intervals. I want to use 1, 2,3 or 4 AA batteries to power it. I've read all about the techniques to reduce power consumption, by removing the power LED and using sleep functions. But I would like to know the most efficient combination of batteries to use. If I can get a year out of 1 battery and a step-up converter, I would be happiest with that. But perhaps 3 duracell or 4 (rechargeable) batteries connected directly to the Vcc pin (ie no regulator) might be better. Does anyone have first-hand experience to know what works best?

# Answer
> 1 votes
You can definitely do better with another regulator that the on-board ones, which are not energy efficient because they drop the supply voltage through a resistance, wasting the excess current as heat. An external boost regulator would waste much less current (charge, really, since we're trying to make maximum use of the battery capacity, or equivalently, trying to minimize the capacity & space needed to run your system for a year).

So you need two things:

1. The most space-efficient way (I assume...) to store a year's energy needs; and
2. A pretty good idea of what the energy requirement will be.

For (2.), you'll need an energy budget for your system:

1. How much current your system draws when it is awake;
2. How much current your system draws when it is asleep;
3. It's duty cycle (e.g.: 3% awake time, 97% sleep time), and use that to calculate the total charge in milliAmp-hours the system draws during the 1 year.

Don't forget to account for the batteries' inefficiency when they're cold, if that will be an issue, and add in a safety factor so it won't die before you arrive a year hence to change the batteries.

You'll need to consider powering down the sensor(s) and radio(s) during CPU sleep; their idle draw would make sleeping the CPU ineffective (as far as saving battery is concerned).

Once you have an energy budget, you can look at the available ways to store and deliver a year's worth - regulator type, size and efficiency; battery size and count) to see what combination will meet your needs for cost, simplicity, and space limitations.

---
Tags: battery, arduino-pro-mini
---


# Question
Title: What is the difference between ":i" and ":a" in avrdude command?
What is the difference between `:i` and `:a` after my hex file path in avrdude command.

```
avrdude -C C:\Users\santi\AppData\Local\Arduino15\packages\arduino\tools\avrdude\6.3.0-arduino17/etc/avrdude.conf -v -V -pm32u4 -c avr109 -P COM8 -b 57600 -D -U flash:w:\Users\santi\AppData\Local\Temp\arduino-sketch-35CC2EF472BAA882EB5508D7552111AD/blink_RX_Led_ProMicro.ino.hex:i

```

and

```
avrdude -C C:\Users\santi\AppData\Local\Arduino15\packages\arduino\tools\avrdude\6.3.0-arduino17/etc/avrdude.conf -v -V -pm32u4 -c avr109 -P COM15 -b 57600 -D -U flash:w:\Users\santi\AppData\Local\Temp\arduino-sketch-35CC2EF472BAA882EB5508D7552111AD/blink_RX_Led_ProMicro.ino.hex:a

```

# Answer
> 2 votes
These are Avrdude file format specifiers.

```
avrdude -C C:\Users\santi\AppData\Local\Arduino15\packages\arduino\tools\avrdude\6.3.0-arduino17/etc/avrdude.conf -v -V -pm32u4 -c avr109 -P COM15 -b 57600 -D -U flash:w:\Users\santi\AppData\Local\Temp\arduino-sketch-35CC2EF472BAA882EB5508D7552111AD/blink_RX_Led_ProMicro.ino.hex:a

```

The final `:a` in this case is a format specifier meaning "auto detect; valid for input only, and only if the input is not provided at stdin."

An `:i` in the same position means "Intel Hex"

A complete list can be found here: https://www.nongnu.org/avrdude/user-manual/avrdude\_3.html#Option-Descriptions

---
Tags: avrdude, command-line
---


# Question
Title: I don't understand what's wrong with this code
```
int ledy = 5 ;
int leds = 4 ;
int ledk = 3;
int button = 2 ;
int count = 0 ;

void setup()
{
  pinMode(ledy, OUTPUT);
  pinMode(leds, OUTPUT);
  pinMode(ledk, OUTPUT);
  pinMode(button,INPUT);
  randomSeed(analogRead(A0));
}

void loop()
{
  if(digitalRead(button)== HIGH)
  {
  count = count++ ;
  }
    if (count==1)
  {
    digitalWrite(ledk, HIGH);
    digitalWrite(leds, LOW);
    digitalWrite(ledy, LOW);

   }
    else if (count==2)
   {
    digitalWrite(ledk, LOW);
    digitalWrite(leds, HIGH);
    digitalWrite(ledy, LOW);

    }

   else if (count==3)
   {
    digitalWrite(ledk, LOW);
    digitalWrite(leds, LOW);
    digitalWrite(ledy, HIGH);
   }

     delay(1000);

}

```

I don't undertstand why it isn't working. I want it three leds to light up one by one as loop. But none of them lights up.

# Answer
One thing that jumps out to me as a possible cause of your issue here is that many push buttons require a pull-up resistor, which is provided as an internal component of most microcontrollers, but needs to be specifically requested in the `pinMode` instantiation of the button. Try changing your `setup()` function to the following:

```
void setup()
{
  pinMode(ledy, OUTPUT);
  pinMode(leds, OUTPUT);
  pinMode(ledk, OUTPUT);
  pinMode(button,INPUT_PULLUP);
  randomSeed(analogRead(A0));
}

```

however if you do this, you must also change your if statement to `if(digitalRead(button) == LOW)`, as a pullup resistor will make it so that when the button is not pressed, the pin is pulled high, and vice-versa.

Another way to troubleshoot this is to see if the LEDs light up when you remove the reliance on the button altogether by removing the

```
if(digitalRead(button)== HIGH)
  {
  count = count++ ;
  }

```

and changing it to

```
count++;
delay(1000);

```

and see if the LED changes every 1 second (delay requires a millisecond value). I agree with @StarCat that `count = count++;` possibly isn't doing what you think it is.
> 0 votes

---
Tags: led
---


# Question
Title: Unable to flash arduino pro micro from Terminal
I am trying to upload an hex file to my arduino pro micro using Avrdude . The thing is that I cannot upload any code using the Avrdude terminal commands , but when I use arduino IDE to upload any code it perfectly uploads the code to Arduino.

**The command I am using on the terminal:**

```
avrdude -C C:\Users\santi\AppData\Local\Arduino15\packages\arduino\tools\avrdude\6.3.0-arduino17/etc/avrdude.conf -v -V -patmega32u4 -cavr109 -PCOM15 -b57600 -D -U flash:w:C:\Users\santi\Documents\keyboard\corne\crkbd_rev1_layout_split_3x6_3_mine.hex:i

```

I already have avrdude on the environment variables on my windows 10 machine.

**Output**:

```
avrdude: Version 6.3-20190619
         Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
         Copyright (c) 2007-2014 Joerg Wunsch

         System wide configuration file is "C:\Users\santi\AppData\Local\Arduino15\packages\arduino\tools\avrdude\6.3.0-arduino17/etc/avrdude.conf"

         Using Port                    : COM15
         Using Programmer              : avr109
         Overriding Baud Rate          : 57600
         AVR Part                      : ATmega32U4
         Chip Erase delay              : 9000 us
         PAGEL                         : PD7
         BS2                           : PA0
         RESET disposition             : dedicated
         RETRY pulse                   : SCK
         serial program mode           : yes
         parallel program mode         : yes
         Timeout                       : 200
         StabDelay                     : 100
         CmdexeDelay                   : 25
         SyncLoops                     : 32
         ByteDelay                     : 0
         PollIndex                     : 3
         PollValue                     : 0x53
         Memory Detail                 :

                                  Block Poll               Page                       Polled
           Memory Type Mode Delay Size  Indx Paged  Size   Size #Pages MinW  MaxW   ReadBack
           ----------- ---- ----- ----- ---- ------ ------ ---- ------ ----- ----- ---------
           eeprom        65    20     4    0 no       1024    4      0  9000  9000 0x00 0x00
           flash         65     6   128    0 yes     32768  128    256  4500  4500 0x00 0x00
           lfuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
           hfuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
           efuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
           lock           0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
           calibration    0     0     0    0 no          1    0      0     0     0 0x00 0x00
           signature      0     0     0    0 no          3    0      0     0     0 0x00 0x00

         Programmer Type : butterfly
         Description     : Atmel AppNote AVR109 Boot Loader

Connecting to programmer: .avrdude: butterfly_recv(): programmer is not responding

avrdude: butterfly_recv(): programmer is not responding

```

I keep waiting but it does not upload the code.

I added a push button for RST and GND pins to enter bootloader mode, and I am pressing the reset button. I even tried resetting twice quickly, but I get the same result.

I tried using the Arduino and the code gets uploaded.

I uploaded the following code:

```
int RXLED = 17;
void setup(){
  pinMode(RXLED, OUTPUT);
}

void loop() {
  digitalWrite(RXLED, LOW);
  delay(1500);
  digitalWrite(RXLED, HIGH);
  delay(1500);
}

```

The command ran in the IDE is:

```
"C:\Users\santi\AppData\Local\Arduino15\packages\arduino\tools\avrdude\6.3.0-arduino17/bin/avrdude" "-CC:\Users\santi\AppData\Local\Arduino15\packages\arduino\tools\avrdude\6.3.0-arduino17/etc/avrdude.conf" -v -V -patmega32u4 -cavr109 -PCOM16 -b57600 -D "-Uflash:w:C:\Users\santi\AppData\Local\Temp\arduino-sketch-F0563C64AD4C1F392D3E71AA32E4F874/blink_nano.ino.hex:i"

```

Arduino IDE output:

```
avrdude: Version 6.3-20190619
         Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
         Copyright (c) 2007-2014 Joerg Wunsch

         System wide configuration file is "C:\Users\santi\AppData\Local\Arduino15\packages\arduino\tools\avrdude\6.3.0-arduino17/etc/avrdude.conf"

         Using Port                    : COM16
         Using Programmer              : avr109
         Overriding Baud Rate          : 57600
         AVR Part                      : ATmega32U4
         Chip Erase delay              : 9000 us
         PAGEL                         : PD7
         BS2                           : PA0
         RESET disposition             : dedicated
         RETRY pulse                   : SCK
         serial program mode           : yes
         parallel program mode         : yes
         Timeout                       : 200
         StabDelay                     : 100
         CmdexeDelay                   : 25
         SyncLoops                     : 32
         ByteDelay                     : 0
         PollIndex                     : 3
         PollValue                     : 0x53
         Memory Detail                 :

                                  Block Poll               Page                       Polled
           Memory Type Mode Delay Size  Indx Paged  Size   Size #Pages MinW  MaxW   ReadBack
           ----------- ---- ----- ----- ---- ------ ------ ---- ------ ----- ----- ---------
           eeprom        65    20     4    0 no       1024    4      0  9000  9000 0x00 0x00
           flash         65     6   128    0 yes     32768  128    256  4500  4500 0x00 0x00
           lfuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
           hfuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
           efuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
           lock           0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
           calibration    0     0     0    0 no          1    0      0     0     0 0x00 0x00
           signature      0     0     0    0 no          3    0      0     0     0 0x00 0x00

         Programmer Type : butterfly
         Description     : Atmel AppNote AVR109 Boot Loader

Connecting to programmer: .
Found programmer: Id = "CATERIN"; type = S
    Software Version = 1.0; No Hardware Version given.
Programmer supports auto addr increment.
Programmer supports buffered memory access with buffersize=128 bytes.

Programmer supports the following devices:
    Device code: 0x44

avrdude: devcode selected: 0x44
avrdude: AVR device initialized and ready to accept instructions

Reading | ################################################## | 100% 0.00s

avrdude: Device signature = 0x1e9587 (probably m32u4)
avrdude: reading input file "C:\Users\santi\AppData\Local\Temp\arduino-sketch-F0563C64AD4C1F392D3E71AA32E4F874/blink_nano.ino.hex"
avrdude: writing flash (3852 bytes):

Writing | ################################################## | 100% 0.29s

avrdude: 3852 bytes of flash written

avrdude done.  Thank you.

```

I tried using the same Avrdude command in the terminal.

```
"C:\Users\santi\AppData\Local\Arduino15\packages\arduino\tools\avrdude\6.3.0-arduino17/bin/avrdude" "-CC:\Users\santi\AppData\Local\Arduino15\packages\arduino\tools\avrdude\6.3.0-arduino17/etc/avrdude.conf" -v -V -patmega32u4 -cavr109 -PCOM16 -b57600 -D "-Uflash:w:C:\Users\santi\AppData\Local\Temp\arduino-sketch-F0563C64AD4C1F392D3E71AA32E4F874/blink_nano.ino.hex:i"

```

**Output:**

```
avrdude: Version 6.3-20190619
         Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
         Copyright (c) 2007-2014 Joerg Wunsch

         System wide configuration file is "C:\Users\santi\AppData\Local\Arduino15\packages\arduino\tools\avrdude\6.3.0-arduino17/etc/avrdude.conf"

         Using Port                    : COM16
         Using Programmer              : avr109
         Overriding Baud Rate          : 57600
avrdude: ser_open(): can't open device "\\.\COM16": El sistema no puede encontrar el archivo especificado.

```

I don´t know why it uses a different port. I tried changing the port in that command but I get the same result as before

```
avrdude: Version 6.3-20190619
         Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
         Copyright (c) 2007-2014 Joerg Wunsch

         System wide configuration file is "C:\Users\santi\AppData\Local\Arduino15\packages\arduino\tools\avrdude\6.3.0-arduino17/etc/avrdude.conf"

         Using Port                    : COM15
         Using Programmer              : avr109
         Overriding Baud Rate          : 57600
         AVR Part                      : ATmega32U4
         Chip Erase delay              : 9000 us
         PAGEL                         : PD7
         BS2                           : PA0
         RESET disposition             : dedicated
         RETRY pulse                   : SCK
         serial program mode           : yes
         parallel program mode         : yes
         Timeout                       : 200
         StabDelay                     : 100
         CmdexeDelay                   : 25
         SyncLoops                     : 32
         ByteDelay                     : 0
         PollIndex                     : 3
         PollValue                     : 0x53
         Memory Detail                 :

                                  Block Poll               Page                       Polled
           Memory Type Mode Delay Size  Indx Paged  Size   Size #Pages MinW  MaxW   ReadBack
           ----------- ---- ----- ----- ---- ------ ------ ---- ------ ----- ----- ---------
           eeprom        65    20     4    0 no       1024    4      0  9000  9000 0x00 0x00
           flash         65     6   128    0 yes     32768  128    256  4500  4500 0x00 0x00
           lfuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
           hfuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
           efuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
           lock           0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
           calibration    0     0     0    0 no          1    0      0     0     0 0x00 0x00
           signature      0     0     0    0 no          3    0      0     0     0 0x00 0x00

         Programmer Type : butterfly
         Description     : Atmel AppNote AVR109 Boot Loader

Connecting to programmer: .avrdude: butterfly_recv(): programmer is not responding

```

I could just use the arduino IDE to flash my device but the problem is that I only have the hex file. I am trying to flash my device with a hex file from QMK Configurator. I am trying to build a custom keyboard.

# Answer
> 2 votes
You have to reset the Arduino using a very special procedure in order for it to accept being programmed. This involves opening the port at 1200 bps, toggling some control lines, and closing the port again. You may try using this ard-reset-arduino Python script with the option `--caterina`.

By the way, this script belongs a project called “Arduino-Makefile”. You may want to take a look if you want to program your Arduino from the command line. Alternatively, you can use arduino-cli.

---
Tags: avrdude, arduino-pro-micro, atmega32u4
---


# Question
Title: Multiplexing three VFD tubes — why are the segments and the display timing incorrect?
I'm using an Arduino Nano, a UNL2803 IC, and three 2N3904 transistors to drive three seven-segment vacuum fluorescent display tubes (IV-6) in a multiplex configuration. The UNL2803 is used to drive the segments: when an Arduino pin is pulled low, 25V is sent to the corresponding segment. The 2N3904 transistors are used to drive each of the digits: when the Arduino pin is high, 25V is sent to the digit's grid, thereby activating the digit.

The problem: the tubes aren't showing the correct segments, and the displays aren't being activated with correct timing. I have checked each segment connection to make sure it is connected to the correct segment. By slowing down the time interval between digits, I can see that the second and third digits (the 10s and 1s) are being displayed sequentially with the correct interval, but the first digit (the 100s) comes on with the second digit and stays on for twice the interval time. It also appears that some of the digits are attempting to display more than one number (sequentially) while activated.

The code:

```
// Pin assignments for segments
const int SEG_A = 2;
const int SEG_B = 3;
const int SEG_C = 4;
const int SEG_D = 6;
const int SEG_E = 5;
const int SEG_F = 7;
const int SEG_G = 8;

// Pin assignments for digits
const int DIG1 = 9;
const int DIG2 = 10;
const int DIG3 = 11;

int digit = 1;
int dig_number = 0;
unsigned int number = 321;

void setup() {

  Serial.begin(9600);

  // Set segment pins as outputs
  pinMode(SEG_A, OUTPUT);
  pinMode(SEG_B, OUTPUT);
  pinMode(SEG_C, OUTPUT);
  pinMode(SEG_D, OUTPUT);
  pinMode(SEG_E, OUTPUT);
  pinMode(SEG_F, OUTPUT);
  pinMode(SEG_G, OUTPUT);

  // Set digit pins as outputs
  pinMode(DIG1, OUTPUT);
  pinMode(DIG2, OUTPUT);
  pinMode(DIG3, OUTPUT);

  // Turn off digits
  digitalWrite(DIG1, LOW);
  digitalWrite(DIG2, LOW);
  digitalWrite(DIG3, LOW);
}

void loop() {
      if (digit == 1) {
        digitalWrite(DIG1, HIGH);
        digitalWrite(DIG2, LOW);
        digitalWrite(DIG3, LOW);
        dig_number = number / 100;
        if (number < 100) {      // to disable the digit if it's not being used
          dig_number == 99;      // triggers 'default' in switch/case
          display_number(dig_number);
        } else {
          display_number(dig_number);
        }
        digit = 2;
        Serial.println("The first digit is: ");
        Serial.print(dig_number);
        delay (250);
      }

      if (digit == 2) {
        digitalWrite(DIG1, LOW);
        digitalWrite(DIG2, HIGH);
        digitalWrite(DIG3, LOW);
        dig_number = (number / 10) % 10;
        if (dig_number == 0 && number < 10) {       // to disable the digit if it's not being used
          dig_number == 99;        // triggers 'default' in switch/case
          display_number(dig_number);
        } else {
          display_number(dig_number);
        }
        digit = 3;
        Serial.println("The second digit is: ");
        Serial.print(dig_number);
        delay (250);
      }

      if (digit == 3) {
        digitalWrite(DIG1, LOW);
        digitalWrite(DIG2, LOW);
        digitalWrite(DIG3, HIGH);
        dig_number = number % 10;
        display_number(dig_number);
        digit = 1;
        Serial.println("The third digit is: ");
        Serial.print(dig_number);
        delay (250);
      }
}

void display_number(int dig_number) {

    switch (dig_number) {
        case 0:
        digitalWrite(SEG_A, LOW);
        digitalWrite(SEG_B, LOW);
        digitalWrite(SEG_C, LOW);
        digitalWrite(SEG_D, LOW);
        digitalWrite(SEG_E, LOW);
        digitalWrite(SEG_F, LOW);
        digitalWrite(SEG_G, HIGH);
        break;

    case 1:
        digitalWrite(SEG_A, HIGH);
        digitalWrite(SEG_B, LOW);
        digitalWrite(SEG_C, LOW);
        digitalWrite(SEG_D, HIGH);
        digitalWrite(SEG_E, HIGH);
        digitalWrite(SEG_F, HIGH);
        digitalWrite(SEG_G, HIGH);
        break;

    case 2:
        digitalWrite(SEG_A, LOW);
        digitalWrite(SEG_B, LOW);
        digitalWrite(SEG_C, HIGH);
        digitalWrite(SEG_D, LOW);
        digitalWrite(SEG_E, LOW);
        digitalWrite(SEG_F, HIGH);
        digitalWrite(SEG_G, LOW);
        break;

    case 3:
        digitalWrite(SEG_A, LOW);
        digitalWrite(SEG_B, LOW);
        digitalWrite(SEG_C, LOW);
        digitalWrite(SEG_D, LOW);
        digitalWrite(SEG_E, HIGH);
        digitalWrite(SEG_F, HIGH);
        digitalWrite(SEG_G, LOW);
        break;

    case 4:
        digitalWrite(SEG_A, HIGH);
        digitalWrite(SEG_B, LOW);
        digitalWrite(SEG_C, LOW);
        digitalWrite(SEG_D, HIGH);
        digitalWrite(SEG_E, HIGH);
        digitalWrite(SEG_F, LOW);
        digitalWrite(SEG_G, LOW);
        break;

    case 5:
        digitalWrite(SEG_A, LOW);
        digitalWrite(SEG_B, HIGH);
        digitalWrite(SEG_C, LOW);
        digitalWrite(SEG_D, LOW);
        digitalWrite(SEG_E, HIGH);
        digitalWrite(SEG_F, LOW);
        digitalWrite(SEG_G, LOW);
        break;

    case 6:
        digitalWrite(SEG_A, LOW);
        digitalWrite(SEG_B, HIGH);
        digitalWrite(SEG_C, LOW);
        digitalWrite(SEG_D, LOW);
        digitalWrite(SEG_E, LOW);
        digitalWrite(SEG_F, LOW);
        digitalWrite(SEG_G, LOW);
        break;

    case 7:
        digitalWrite(SEG_A, LOW);
        digitalWrite(SEG_B, LOW);
        digitalWrite(SEG_C, LOW);
        digitalWrite(SEG_D, HIGH);
        digitalWrite(SEG_E, HIGH);
        digitalWrite(SEG_F, HIGH);
        digitalWrite(SEG_G, HIGH);
        break;

    case 8:
        digitalWrite(SEG_A, LOW);
        digitalWrite(SEG_B, LOW);
        digitalWrite(SEG_C, LOW);
        digitalWrite(SEG_D, LOW);
        digitalWrite(SEG_E, LOW);
        digitalWrite(SEG_F, LOW);
        digitalWrite(SEG_G, LOW);
        break;

    case 9:
        digitalWrite(SEG_A, LOW);
        digitalWrite(SEG_B, LOW);
        digitalWrite(SEG_C, LOW);
        digitalWrite(SEG_D, LOW);
        digitalWrite(SEG_E, HIGH);
        digitalWrite(SEG_F, LOW);
        digitalWrite(SEG_G, LOW);
        break;

    default:
        digitalWrite(SEG_A, HIGH);
        digitalWrite(SEG_B, HIGH);
        digitalWrite(SEG_C, HIGH);
        digitalWrite(SEG_D, HIGH);
        digitalWrite(SEG_E, HIGH);
        digitalWrite(SEG_F, HIGH);
        digitalWrite(SEG_G, HIGH);
        break;
    }
}

```

The circuit diagram:

I have heard rumor that using delay() instead of millis() for multiplexing can be problematic. Is that what's going on here?

Many thanks in advance for considering this problem!

# Answer
Your code appears to invert the switching pattern of the digits. Instead of switching the selected digit on and the other two off, you are doing the opposite.

The grid of a VFD tube has to have a voltage applied to it to illuminate the selected segments. Those segments are also selected by having a voltage applied. The circuit you have shown, by default, powers both the grids and the segments via 10k resistors connected to the 25 volt power rail. The transistors, also in the uln2803, when switched on, pull the grids and segments to ground, thus switching those elements off. This arrangement reduces the complexity of the circuit by eliminating the need for high side switching but "wastes" power.

A simple code correction should solve the problem:

```
// Turn off digits
   digitalWrite(DIG1, HIGH);  // high turns the grid off.
   digitalWrite(DIG2, HIGH);
   digitalWrite(DIG3, HIGH);
 }

```

```
if (digit == 1) {
   digitalWrite(DIG1, LOW);  // digit one ON
   digitalWrite(DIG2, HIGH); // digit two OFF
   digitalWrite(DIG3, HIGH); // digit three OFF
}

```

Do the equivalent for digits 2 and 3.

Use resistors (say 1k) in series with the transistor bases to limit the current and protect the arduino pins. See https://learn.sparkfun.com/tutorials/transistors/applications-i-switches

You still have to confirm if the wire connecting R9, R10 and R11 goes to all the way to the +25 volt rail. This is not clear from the schematic.
> 0 votes

# Answer
I made a VFD clock using some really cool old DG10B tubes from an early calculator a year or so ago. I had a heck of a time getting it to work, until I decided try tackling one problem at a time, and then put it all together.

In my clock I used the MAX6921 VFD driver IC, a DS3231 RTC with super cap, and a XIAO for the brains. The VFD driver chip is controlled by pwm/serial (data, load, clock) and the RTC is over I2c.

Instead of trying to multiplex them, I just got them all working at once, I did a nice slow count of all digits being on and displaying the same digits. This helped me detect a couple wiring faults, and helped me figure out which segments needed to be lit for each number I wanted displayed. (the digits on my tubes are quite unique!)

once I had my "fonts" figured out and a case for each digit, I created a simple loop that counted through 0-9 on all digits with all four of them on. 4444, 5555, etc

Then I started trying to get just one digit lit at a time. (this helped me find another wiring issue) // \[pihgfedcba------1234}; //this is what the data stream looks like when sent to the driver // ...where the first 10 digits are the segments, and the last 4 are the grids for each digit from left to right 1-4. // The rest are currently unused and should be padded with zero's or 1's)

Next I made a loop that would check the time, and print out the digits. I DO use delay() in my code, in order to deliberately flicker my tubes (for the antique steampunk effect) But here's the thing, I believe my code checks the time for each individual digit. the loop says for each digits 1-4 (check time, display digit)

there was a lot more involved, and it's been a while since I worked on it so I am not sure I am being helpful here. I just wanted to suggest you follow a good troubleshooting process. (smaller problems are easier to solve)
> 2 votes

# Answer
For future searchers, I finally got this circuit going using two ULN2803 transistor arrays, instead of discrete transistors for the digit connections. Here's the final schematic:

You can check out more about the final project here. Many thanks to those who commented——your feedback was very helpful!
> 0 votes

---
Tags: arduino-nano, multiplexer
---


# Question
Title: Arduino MEGA - How to send and receive data asynchronously?
i am newbie to this so i hope i can explain my problem clearly;

Arduino MEGA connected to PC via USB port.

I am using an encoder to trigger function to send data to pc, data is a simple string "A01" or "A02" when i turn encoder to opposite direction, when arduino sends that string to serial port PC answers with another string from serial and its something like "MCPHDGxxx" and arduino does if serial available gets the string and filter it to get and show that number on my 7-segment display. (xxx is a number between 000 and 359, and that number changes on PC screen when arduino send "A01" or "A02" string to PC)

When i don't send display data from PC to arduino, encoder function works as intended, changes numbers up and down rapidly on PC screen but when i try to send that "number" data to Arduino from serial port number on the PC screen changes so slowly like 1 point up/down per 2 sec even if i turn encoder continuously. Seems like receiving data from PC blocking my send data function until it's done.

Is it possible to make it work asynchronously?

Here is my sketch:

```
#include "DigitLedDisplay.h"
 #define outputA 24
 #define outputB 25

 int aState;
 int aLastState;
 unsigned long lastButtonPress = 0;
 long finalMCPHDGLong;
 String ReceivedSerialString;

 DigitLedDisplay ld = DigitLedDisplay(21, 22, 23);

 void setup() {
   pinMode (outputA,INPUT);
   pinMode (outputB,INPUT);

   Serial.begin (115200);
   // Reads the initial state of the outputA
   aLastState = digitalRead(outputA);

     /* Set the brightness min:1, max:15 */
  ld.setBright(10);

  /* Set the digit count */
  ld.setDigitLimit(8);

 }

 void loop() {
   aState = digitalRead(outputA); // Reads the "current" state of the outputA
   // If the previous and the current state of the outputA are different, that means a Pulse has occured
   if (aState != aLastState){
     // If the outputB state is different to the outputA state, that means the encoder is rotating clockwise
     if (digitalRead(outputB) != aState) {
       if (millis() - lastButtonPress > 25) {
         Serial.println("A01");
        }

        // Remember last button press event
        lastButtonPress = millis();

     } else {
       if (millis() - lastButtonPress > 25) {
         Serial.println("A02");
        }

        // Remember last button press event
          lastButtonPress = millis();

     }

   }
   aLastState = aState;

    while (Serial.available() > 0){
      ReceivedSerialString = Serial.readString();
      if (ReceivedSerialString.substring(0,6) == "MCPHDG"){
        String value = ReceivedSerialString.substring(6,9);
          long val = value.toInt();
          finalMCPHDGLong = val;
          if((finalMCPHDGLong <= 99)){
              ld.printDigit(0,7);
            }if((finalMCPHDGLong <= 9)){
              ld.printDigit(0,6);
            }
          ld.printDigit(val, 5);
      }
    }
 }

```

# Answer
> 2 votes
> Seems like receiving data from PC blocking my send data function until it's done.

You may be saying the same thing, but I'd put it that it's waiting for more data to arrive that isn't going to.

> Is it possible to make it work asynchronously?

Depending on how you're defining "asynchronously" that may be unnecessary.

```
while (Serial.available() > 0){
  if (ReceivedSerialString.substring(0,6) == "MCPHDG"){
    String value = ReceivedSerialString.substring(6,9);

```

There's a lot that could be said about using `String` and conversion to `int` and choosing a simple message format and so forth, but I'll elide most of that. Finding a good approach to what you're doing would require understanding a lot more about what you're doing and why. But, taking your code and question as written, the **main thing is that `readString()` here is terminating based on the value of `Serial.setTimeout()`, which by default is `1000` or 1 second. So you are spending a lot of time doing nothing following receipt of your command from the PC. So during that 1 second you are not tending to the "encoder".**

You could play with `setTimeout`, but it would be better to avoid a timeout altogether by not attempting to read when there's no more command to be read. If this protocol you're using is line-oriented then you have a terminator you can use in the form of '\r' or '\n'. This can be done with `Serial.readStringUntil(whatever_your_terminator_is);` If you have both '\r' and '\n' you will need to read other part of the termination sequence and then throw it away. Either it will come in as part of the read string or it will not and you will need to do a second read to discard it. There are more sophisticated ways to go about this, but that maybe sufficient for what you're doing.

When it comes to not blocking (or significant blocking) of serial reads, you have to assure that the data is there to be read. Either because you know it's sent (and are willing to trust that it was received okay). Or you use `Serial.setTimeout` with a 0 or sufficiently small number, `.read()` indicates no data with a negative return value, or by checking `.available()`, and it all of these cases deciding what to do when you have not received everything, or everything... yet. Doing it well, manually, is a bit of a pain.

For writing/printing to serial there's a counterpart `.availableForWrite()` which you can use to determine ahead of time whether or not you're going to be stuck in waiting (in `.print()`/`.println()`/`.write()`) for the serial data to go out, in turn not tending to the encoder. Basically you can choose where and how to throttle your writing to serial so as not overly interfere checking the encoder rather than causing throttle to happen within `Serial.write`. With the way your code is currently written, with events coming in at the rate they apparently are (according to your debouncing code) this is probably not currently a problem for you. But it's worth keeping in mind if you begin handling events at a higher rate. Placing a character in the outbound serial buffer is significantly faster than waiting for space for a character to become available in the serial buffer.

# Answer
> -1 votes
Is not easy, but you can implement two modification.

The first one is handling encoder via interrupt, the second one, is change the while to an if, with the while you force the code to loop inside the while serial aviable loosing eventually encoders state change, to avoid this, you shuold take continusly the strings coming from PC and create a command queue and proces it cycle by cicle, unfortunatly arduino mega is single processor, so it can't handle different process at the same time.

You should olso to consider, and run a benckmark to test how much is the refresh rate of your display

---
Tags: serial, usb, communication, 7-segment
---


title: Error coming from specified code

text:
# Question
Title: Error coming from specified code
#### Error

```
Arduino: 1.8.19 (Windows 10), Board: "Arduino Uno"

AnalogInOutSerial:8:56: error: no matching function for call to 'PID::PID(int*, int*, double*, double&, double&, double&, int)'
 PID pid(&Rawval, &Rawval, &setpoint, kp, ki, kd, DIRECT);
                                                        ^
In file included from C:\Users\USER\AppData\Local\Temp\arduino_modified_sketch_407168\AnalogInOutSerial.ino:1:0:
C:\Users\USER\Documents\Arduino\libraries\Arduino-PID-Library-master/PID_v1.h:24:5: note: candidate: PID::PID(double*, double*, double*, double, double, double, int)
     PID(double*, double*, double*,        // * constructor.  links the PID to the Input, Output, and
     ^~~
C:\Users\USER\Documents\Arduino\libraries\Arduino-PID-Library-master/PID_v1.h:24:5: note:   no known conversion for argument 1 from 'int*' to 'double*'
C:\Users\USER\Documents\Arduino\libraries\Arduino-PID-Library-master/PID_v1.h:20:5: note: candidate: PID::PID(double*, double*, double*, double, double, double, int, int)
     PID(double*, double*, double*,        // * constructor.  links the PID to the Input, Output, and
     ^~~
C:\Users\USER\Documents\Arduino\libraries\Arduino-PID-Library-master/PID_v1.h:20:5: note:   candidate expects 8 arguments, 7 provided
C:\Users\USER\Documents\Arduino\libraries\Arduino-PID-Library-master/PID_v1.h:5:7: note: candidate: constexpr PID::PID(const PID&)
 class PID
       ^~~
C:\Users\USER\Documents\Arduino\libraries\Arduino-PID-Library-master/PID_v1.h:5:7: note:   candidate expects 1 argument, 7 provided
C:\Users\USER\Documents\Arduino\libraries\Arduino-PID-Library-master/PID_v1.h:5:7: note: candidate: constexpr PID::PID(PID&&)
C:\Users\USER\Documents\Arduino\libraries\Arduino-PID-Library-master/PID_v1.h:5:7: note:   candidate expects 1 argument, 7 provided
exit status 1
no matching function for call to 'PID::PID(int*, int*, double*, double&, double&, double&, int)'

This report would have more information with
"Show verbose output during compilation"
option enabled in File -> Preferences.

```

#### Actual Code

```
#include <PID_v1.h>

int analogPin = A3;
int Rawval ;  // variable to store the value read
double setpoint = 169; // target value for the system is set to 169
double kp = 1, ki = 0.1, kd = 0.01; // PID constants
int RELAY_pin = 10;    // Relay is connected to pin D10
PID pid(&Rawval, &Rawval, &setpoint, kp, ki, kd, DIRECT);

void setup()
{
  Serial.begin(9600);           //  setup serial
  pinMode(RELAY_pin, OUTPUT);
  pid.SetMode(AUTOMATIC);
}

void loop()
{
  Rawval = analogRead(analogPin);
  Serial.print("Rawvalue from Analog input  =");
  Serial.println(Rawval);
  pid.Compute();
  digitalWrite(RELAY_pin, Rawval < setpoint ? HIGH : LOW);
}

```

# Answer
The error message is quite clear about the problem (extracted and formatted for clarity):

> no matching function for call to
> `PID::PID(int*, int*, double*, double&, double&, double&, int)`
> *\[...\]*
> candidate:
> `PID::PID(double*, double*, double*, double, double, double, int)`
> *\[...\]*
> no known conversion for argument 1 from '`int*`' to '`double*`'
> *\[other candidates left out due to non-matching number of arguments\]*

You need to provide pointers to `double` as the first two arguments, and the candidate will match.

---

**EDIT:**

I hesitated a while to provide your this, because you learn much better by doing it yourself. Anyway, here it is.

Your original variable declaration is:

```
int Rawval ;  // variable to store the value read

```

Replace the data type `int` by `double`, as the called constructor expects:

```
double Rawval ;  // variable to store the value read

```

Now there is this line, assigning an `int` to a `double`:

```
Rawval = analogRead(analogPin);

```

And you might ask yourself, is this OK? Well, try it. You will find that the compiler implicitly converts the value. If you want to make it explicitly, change the line to:

```
Rawval = static_cast<double>(analogRead(analogPin));

```

A final point, as datenheim states: Read and learn about the `PID`. It is for sure an error to use the *same variable* for input and output.
> 2 votes

# Answer
The first two parameters need to be of type double.

```
PID pid(&Rawval, &Rawval, &setpoint, kp, ki, kd, DIRECT);
        ^^^^^^^  ^^^^^^^

```

It also makes probably no sense to have input and output both wired to &Rawval.

Take a look on this example.
> 1 votes

---
Tags: arduino-uno, pid
---


# Question
Title: Arduino + HC-05 Problem: AT Commands are not working
Device: Laptop, HC-05, Resistor 2.2k and 4.7k, Arduino Uno R3

So im trying to rename and change password of my HC-05. for full detail schematic diagram. Here(the difference is, i also used the STATE Pin from HC-05 then connected it to Pin 9 since according to Instructubles it is used for activating AT Mode):

Now for coding, i got it from Instructables.com and here: https://www.instructables.com/Modify-The-HC-05-Bluetooth-Module-Defaults-Using-A/ or

```
#include <SoftwareSerial.h>
SoftwareSerial BTSerial(10, 11);
#define Key 9
void setup()
{
  pinMode(Key, OUTPUT);  // this pin will pull the HC-05 pin 34 (key pin) HIGH to switch module to AT mode
  digitalWrite(Key, HIGH);
  Serial.begin(9600);
  Serial.println("Enter AT commands:");
  BTSerial.begin(38400);  // HC-05 default speed in AT command more
}

void loop() {
  // put your main code here, to run repeatedly:
  if(BTSerial.available()){
    Serial.write(BTSerial.read());
  }

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

```

The problem: i tried to follow the instructuble's instruction. but it didnt work. then i tried doing my own from what several tutorials i have read: for the details,

1. i set my circuit and do the necessary wiring as shown in the picture + STATE Pin -\> Arduino Pin 9.
2. I then connected my Arduino Uno to my Laptop, the HC-05 is blinking per half second, if you need the detail. Then uploaded the code...then finally, I opened the Serial Monitor(note that my HC-05 is not Paired to any devices in the first place. i "Forgot" them just incase).
3. then go to 9600 Monitor and enter simple command like **AT, AT+NAME? or AT+PSWD?** but nothing appeared in my terminal.
4. i also checked the 38400 monitor and did the same things. nothing happened.
5. then just maaaaybe it was just not showing but actually working, I tried AT+NAME=JULIE trying to rename my HC-05 to JULIE for each Terminal, going back and trying at 9600 then 38400. nothing happened at any Terminal. my HC-05 is still HC-05 name and the LED in my HC-05 are still blinking per half sec.
6. Then a bit annoyed, i then do a try-and-error. i tried to upload the code, then Paired it now, this time with my Phone. Then enter AT Commands in my Bluetooth Terminal App(from Playstore) and try to AT Command there. but still, nothing works.

My HC-05 is working as intended when i used it a simple LED on and off, and Servo using my Phone wirelessly few hours ago. But when i tried to do AT Command codes, nothing appears in my Serial Monitor such as the OK() or other AT Command replies.

so i would like to know where i did go wrong and why i cant use AT Command whether 9600, 38400 or even trying to do AT Command in my Phone's BT Terminal App? if you think i have missed an important details that i should mention, feel free to let me know.

# Answer
> 1 votes
Ok, MAYBE I solved it^^ so the thing is, i noticed that my LED is still blinking intense instead of 2 sec light off and on. which means that i am still not in AT Mode.

but the thing is if i followed Instructables and other website tutorial. I SHOULD be able to be in AT Mode. im not exactly sure why im still not in AT Mode. So tried something:

the wiring/circuit is still THE SAME. but add something: I took another wire, connect the **EN Pin of HC-05** **-\> 5V of Arduino**. since days ago i was trying to do tinker my HC-05 here and there and i remember that i tried to put EN in 5V then it start blinking differently. so i tried the same thing today. then i went back and Forget Paired Device, connect my Arduino to my Laptop, then reupload my code, then go to Serial.Monitor 9600 set **No Ending Line -\> Both NL & CR**. then i reenter the AT Commands.

**AT+NAME?** then **AT**,then **AT+PSWD?** all worked. the AT+Name shows the name of my HC-05, and the AT+PSWD shows the password. so then i decided to finally rename my HC-05. **AT+NAME=USER\_FAIZ** and **AT+PSWD=ARDUINO** individually in the Serial Monitor...and now my HC-05 has different name which is ***USER\_FAIZ*** and password which is ***ARDUINO***. i then went to my Phone, scan for bluetooth device and there it is. USER\_FAIZ and password is ARDUINO.

^^what im not really sure if it is the solution im searching for. i searched some tutorials again but none of them mention of using EN Pin and most of them use STATE Pin of HC-05.So because of that, i wont "Check" this Answer as maybe this is not the best solution out. maybe just not yet. but it did solve MY problem so it may solve other users problem too so ill add it here to inform.

---
Tags: bluetooth, hc-05
---


# Question
Title: How to create a Arduino socket server to receive messages
From linux I can send a socket message using netcat

```
echo "Hello" | nc 88.109.110.161 100

```

But I don't know how to setup the socket server for listening incoming messages using the ethernet shield.

What I have so far is one from a lot of examples I tried but still not showing anything

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

byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };

EthernetServer server(1000);

void setup() {
  Ethernet.begin(mac);
  Serial.begin(9600);
// Check for Ethernet hardware present
  if (Ethernet.hardwareStatus() == EthernetNoHardware) {
    Serial.println("Ethernet shield was not found.  Sorry, can't run without hardware. :(");
    while (true) {
      delay(1); // do nothing, no point running without Ethernet hardware
    }
  }
  if (Ethernet.linkStatus() == LinkOFF) {
    Serial.println("Ethernet cable is not connected.");
  }

  // start the server
  server.begin();
  Serial.print("server is at ");
  Serial.println(Ethernet.localIP());
}

void loop() {
  // listen for incoming clients
 EthernetClient client = server.available();
 if (client) {
   Serial.println("Client");
   // an http request ends with a blank line
   boolean currentLineIsBlank = true;
   while (client.connected()) {
     while(client.available()) {
       char c = client.read();
       // 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) {

// Here is where the POST data is.
         while(client.available())
         {
            Serial.write(client.read());
            //Serial.println(c);
         }
         Serial.println();

         Serial.println("Sending response");
         // send a standard http response header
         //client.println("HTTP/1.0 200 OK");
         //client.println("Content-Type: text/html");
         //client.println();
         client.println("OK");
         client.stop();
       }
       else 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;
       }
     }
   }
   Serial.println("Disconnected");
 }
}

```

# Answer
> -1 votes
I am learning to use the arduino library about sockets and I spent an hour detecting why your example was not working for me, I ended up noticing that you have one line wrong

```
if (c = '\n' && currentLineIsBlank) {

```

should be:

```
{ if (c != '\n' && !currentLineIsBlank) {

```

And you still have an error you are missing a return character because you are not printing it in the second loop.

Anyway thanks for your contributions.

---
Tags: arduino-uno, ethernet, networking
---


# Question
Title: How to send AT commands to the ubox modem on MKR NB 1500
I am trying to send AT commands to the modem to keep the modem always active. I tried the File \> Examples \> MKRNB \> Tools \> SerialSarapassThrough example, but that gave me a +CME ERROR: operation not supported. Here is the output for the commands I sent via serial monitor:

```
AT
OK
AT+UPSV=0
+CME ERROR: operation not supported

```

Is there a built in code or any other code which I could use to send that command?

# Answer
> -1 votes
You have to try SerialSARAPassthrough.ino from examples menu under MKRNB. If it works properly, you can start writing AT in serial monitor line. You must see answer as OK. Then you can look at the u-blox commands document that is shared above

---
Tags: mkr-gsm-1400
---


# Question
Title: Is it possible to know how long an ESP8266 was in deep sleep?
I'm working on a low power device that implements an ESP8266 MCU and uses it's deep sleep feature. The firmware uses the Arduino C++ library.

Part of the functionality requires knowing the time. To do this, I am using `configTime` to get the time (i.e. NTP). But, to reduce power consumption, I only connect to WiFi every 24 hours. The ESP8266 wakes every hour (to decide if it should do something or go back to sleep). To keep time, I record the last known unix timestamp to RTC memory and upon waking add the amount of time that the device was told to deep sleep (i.e. 1 hour).

The flaw in this design: Part of the requirement is that the user needs to be able to wake the device manually with a button press and interrupt the normal sleep pattern, but if the device is woken with the reset button, it adds an hour to the time and the time becomes completely inaccurate (because an hour was added, even though it could be seconds since deep sleep started).

Is there a way, using the ESP8266 API, to tell how long the device was *actually* in deep sleep? That way, on wake, instead of blindly adding 1 hour to the RTC-saved unix timestamp, I can add the amount of time that the MCU was in deep sleep. The datasheet seems to only mention the RTC a few times in not much detail.

If no firmware solution exists, what hardware solution could I use?

Thinking out loud: I think a compromise could be to detect if the reset button was pressed (latch/flip flop/register, maybe?). In this case I still wouldn't be able to tell how long the MCU was asleep, but at least I'd be able to tell if I should add time. I found that `system_get_rst_info` is based on how the device went to sleep (i.e. if woken from deep sleep by pressing the reset button, the reason is `REANSON_DEEP_SLEEP_AWAKE`), so I couldn't see how to make use of that in this case. I suppose I could add an external RTC, negating the need to calculate how long the MCU was in deep sleep, and just use that external IC for time keeping.

Edit: Apparently, `rtctime.dsleep()` provides time keeping across deep sleep, but it's LUA only so not useful to me. The source is written in C, but I can't see anything that would help.

> Time is kept across the deep sleep. I.e. rtctime.get() will keep working (provided time was available before the sleep).

# Answer
> 0 votes
I believe the answer is **no** (you cannot tell exactly how long an ESP8266 was asleep), given these constraints:

1. If an external RTC cannot be used.
2. If the MCU does not connect to Wi-Fi every time it wakes.
3. If the MCU can be woken arbitrarily by the user pressing the reset button.

In other words, if the ESP8266 does not connect to Wi-Fi every time it wakes, you can only estimate the time based on how long it *should* have been in deep sleep, but you can't know for sure without either going online or using an external RTC.

# Answer
> -1 votes
save timestamp in NVRAM, the time before sleep. once wakeup, simply subtract the the data saved in NVRAM from the current time.

---
Tags: esp8266, sleep
---


# Question
Title: Using SoftwareSerial along with FastLED library to control WS2812 LEDs
I am controlling WS2812 LEDs with Arduino nano using `FastLED` library. I want the LED patterns to change on receiving a command from another Arduino Nano over software serial, I don't have the option to use he hardware serial.

I have read that in order to write data to LEDs, the library disables all the interrupts. However the `SoftwareSerial` library also uses interrupts to transmit data properly. Is there any possible way to achieve this? Presently, when I am trying to do this I am getting garbage data.

# Answer
How fast do you need to update the LEDs? The nice thing about WS2812s is that if you don't update them they maintain the current settings which means you only need to drive them once you have received a serial message.

The best way to do this would be to use some form of flow control over the serial port. e.g. you send a special control code over the serial line requesting the master to stop sending data. You then wait long enough for that to be sent and any data currently in transmission to arrive (so a absolute minimum of 20/(baud rate) seconds). After that time you call the function to update the LEDs. Once the LED update is done you send a second control code indicating that the other end can resume transmission.

This is the basic structure of software flow control (or XON/XOFF as it is also called) that most serial ports support as an option. You can either use the standard implementation or use something a little simpler since you only need data and flow control in one direction.

The other option is to design the system around rules that ensure you don't miss data. The system sending you the LED updates knows that once you get the update you will need to apply it to the LEDs and that during that time you can't receive serial data. So after an update it waits and doesn't send more data until you've had time to do that.
> 1 votes

# Answer
The FastLED and NeoPixel libraries turn off interrupts for the specific timing of the WS2812. The Adafruit NeoPixel has a few extra options to be able to still handle some interrupts. The FastLED has a wiki that describes the problem with interrupts: FastLED wiki interrupts

The SoftwareSerial requires interrupts. When the SoftwareSerial is busy, the Arduino is occupied.

To me it seems impossible to make both libraries work at the same time. I think you have to change something. For example use a Arduino Micro or Pro Micro and use the spare hardware serial port. Or use a ledstrip with leds that have a clock signal and don't need specific timing.

If that is not possible, you might have to use pin 0 (RX) and pin 1 (TX), which are also used by the serial monitor and to upload a sketch.
It is possible to split RX and TX. The only thing that RX and TX have in common is the baudrate, but you can use them for seperate tasks. For example, use TX to send (debug) messages to the serial monitor, and use the RX to receive commands from another Arduino board. Disconnect that other Arduino board to upload a sketch.

\[**ADDED**\] After reading the answer by @Andrew and the FastLED wiki about interrupts, I think that my answer and @Andrew's answer are equally good answers. Perhaps the best way is to do it all: faster Arduino board, hardware serial port for commands, do one thing at a time, implement some kind of XON/XOFF in software, and if possible use other leds.
> 1 votes

# Answer
Another approach is to make the commands to change the pattern very short. Like, one letter/byte.

This assumes that the patterns are stored on your Arduino, and you just choose which one to show.

In order for that to work, the Arduino has to confirm commands it received, and return an error if it receives something it does not understand (e.g. only half of the command). This allows the host to check if the Arduino received the command or if it was animating at that time, in that case re-send the command.

This approach avoids the issue that you receive partial data (because the smallest transmission unit is used). Commands can still be lost, but then they can be re-sent.
> 0 votes

---
Tags: arduino-nano, softwareserial
---