# Question
Title: Is there a way to replace an Arduino core function without modifying the Arduino code?
(Let's just skip the suggestions that it's the wrong idea and interrupts for a while...).

Is there a way to replace the `digitalWrite()` method (for example) so I can add something more to happen in there? But the following rules must be obeyed:

* A call to `digitalWrite(pin, value)` must invoke the new method.
* A call to `digitalWrite(pin, value)` from **a different library** included in my code (SD.h for example) must invoke the new method.
* None of the Arduino files can be modified (I don't want to do it on every Arduino version upgrade).
* Everything must be done in a header file that I can include to use the new function.

I have tried this and it works, but only in my code, not in external libraries that I include after this header:

```
#include <Arduino.h>

class PinsHook {
  public:
    static void digitalWriteHook(uint8_t pin, uint8_t value) {
      digitalWrite(pin, value);
      if (pin == 8) {
        Serial.print("Pin ");
        Serial.print(pin);
        Serial.print(" changed to ");
        Serial.println(value);
      }
    }
};

#define digitalWrite(pin, value) PinsHook::digitalWriteHook(pin, value)

```

# Answer
Not sure about the Arduino IDE (I don't have it installed right now) but using UECIDE it's as simple as defining a new `digitalWrite` function in your code. When the whole shebang gets linked together the function in your code overrides the function in the libraries.

```
void setup() {
    pinMode(13, OUTPUT);
}

void loop() {
    digitalWrite(13, HIGH);
    delay(100);
    digitalWrite(13, LOW);
    delay(800);
}

void digitalWrite(int pin, int level) {
    // Not gonna do anything!
}

```

Comment out the digitalWrite function and the LED blinks. Uncomment it and it doesn't blink any more.
> 4 votes

# Answer
Did you try with a C macro?

```
#define digitalWrite(a, b) \
(pre(), digitalWrite(a, b), post())

```

this evaluates to the retval of `post()`

you can omit either the `pre()` or the `post()` functions/macros.

This needs to be placed somewhere that is included whenever the header for digitalWrite is included, so that it can override it.

The only other alternative is to become creative with the library binary.

Or, just be reasonable and modify the source code. It's specifically available so that people can modify it.

Wrt not repeating the modification every time there is a new Arduino release, that should be avoidable. If you build the environment from the git sources, you can maintain your patch by merging/rebasing onto the master branch.
> 2 votes

# Answer
Arduino uses the avr compiler to compile its standard library into a `core.a` file. Due to the way the avr-gcc linker works and the order in which Arduino specifies the link order, you're able to "override" the behavior of core functions by copying the file that contains the method you want to alter into your project.

> The compiler compiles a single high-level language file (C language, for example) into a single object module file. The linker (ld) can only work with object modules to link them together. Object modules are the smallest unit that the linker works with.
>
> Typically, on the linker command line, you will specify a set of object modules (that has been previously compiled) and then a list of libraries, including the Standard C Library. The linker takes the set of object modules that you specify on the command line and links them together. Afterwards there will probably be a set of "undefined references". A reference is essentially a function call. An undefined reference is a function call, with no defined function to match the call.
>
> The linker will then go through the libraries, in order, to match the undefined references with function definitions that are found in the libraries. If it finds the function that matches the call, the linker will then link in the object module in which the function is located. This part is important: the linker links in THE ENTIRE OBJECT MODULE in which the function is located. Remember, the linker knows nothing about the functions internal to an object module, other than symbol names (such as function names). The smallest unit the linker works with is object modules.
>
> When there are no more undefined references, the linker has linked everything and is done and outputs the final application.
>
> ....
>
> The linker will search libraries in the order that they appear on the command line. Whichever function is found first that matches the undefined reference, it will be linked in.

Arduino's linking occurs in this order:

* Project Files
* Libraries
* core.a (Arduino std lib)

So, copying the file from the Arduino installation location (`C:\Program Files (x86)\Arduino\hardware\arduino\avr\cores\arduino`) into your project and modifying it will result in it using your modified implementation.

This will certainly over-ride it for any files in your project, and *I believe* it will also override it in any libraries you're using as well, so be careful with this approach.
> 1 votes

# Answer
~~Just throwing an idea. No time to test now.~~

**Edit**: I tested the solution below, and it works as expected, provided both the `__wrap_` and `__real_digitalWrite()` are declared `extern "C"`.

If you can convince the IDE to add extra options to the compile command line, you could:

1. name `__wrap_digitalWrite()` your implementation of `digitalWrite()`
2. inside it, call `__real_digitalWrite()` when you want to get the implementation from Arduino core
3. add `-Wl,--wrap=digitalWrite` to the compile command of the final link step

Example wrapper:

```
extern "C" {
    void __wrap_digitalWrite(uint8_t, uint8_t);
    void __real_digitalWrite(uint8_t, uint8_t);
}

// Calls to digitalWrite() are diverted to this.
void __wrap_digitalWrite(uint8_t pin, uint8_t value)
{
    __real_digitalWrite(pin, value);  // call implementation from Arduino core
    if (pin == 8) {
        Serial.print(F("Pin 8 changed to "));
        Serial.println(value);
    }
}

```

Trying to put this inside a class won't help.

C.f. the man page of gnu ld.
> 1 votes

# Answer
In your code module, define your own wrapper function, and use the global scope operator to reference the Arduino function:

```
void pinMode(int pin, int pinmode)
{
  /*use my custom function?*/
  if(pin >= MY_OWN_PIN_CODES_BASE)
  {
    /*todo : my own custom pin access*/
    example_pinmode(pin, pinmode);
  }
  else /*use regular Arduino function*/
  {
    /*use global scope operator :: to call Arduino library version*/
    ::pinMode(pin, pinmode);
  }
}

```

Remember, the linker has rules for which one it references. The global scope operator forces the linker to choose the globally available one, while the custom wrapper function is seen privately by the module.
> 0 votes

# Answer
"Maybe" using the c++ "functions overriding" feature can help

```
void digitalWrite(uint8_t P, int8_t V, bool _wrap)
{
  Serial.print("wrap digitalwrite");
  digitalWrite(P,V);
}

```

Thus, if you call in you main application:

```
digitalWrite(pin_button, 1, 0);

```

The wrapped version will be called

and if you used this:

```
digitalWrite(pin_button, 1);

```

The original one will be called

---

You may also use this definition:

```
void digitalWrite(double P, int8_t V)
{
  Serial.print("wrap digitalwrite");
  //digitalWrite(P,V); Calling it even with (int) P will cause a recursive loop
}

```

But in-order to use it you need to define a variable with double type:

```
double pin;
pin = 13;
digitalWrite(13,1);

```
> 0 votes

# Answer
The information from Rubber Duck is correct but incomplete.

I need a huge amount of digital PWM output for hobby train control.

So I connected 4 x 74HC595 to my At Mega which must be fed with a 2 kHz bit pattern through 0,5 ms. interrupts.

My serial shift function that shifts 32 bits into the registers takes 562 us per cycle. Impossible.

I made an optimized version of digitalWrite and Read, which takes 328 us. Now it is possible to PWM with 2 kHz. The trick is that my optimized function remembers the last 2 Pins including its bitmasks and outports; and I skip the Timer check. It is thread safe. For a single digitalWrite this takes a tiny bit more time. With repeating writing to datapin and clockpin it improves the standard Arduino digitalWrite with about 42%.

By the way: With the digitalWriteFast library the result is 45,8 µs, a really enormous improvement. But this library handles only writes, if the pin number is known (and thus fixed!) at compile time. That is not the case with my LiquidCrystal library, where either 4 or 8 bits parallel are written to the shield via 4 sequential pins.

I got my optimized digitalWrite only working for my application including the LiquidDisplay when I copied the C:\Users\Dell\Downloads\arduino-1.8.5\hardware\arduino\avr\cores\arduino library to a subfolder in the folder of my application, called

C:\Users\Dell\Google Drive\ …\…..**\AppFolder\libraries**.

When I replaced in both folders the **wiring\_digital.c** with my optimized version, it worked.

I could not get it at work, when I only replaced the wiring\_digital.c in the Arduino library (the LiquidCrystal took the standard function somewhere else).

Adding only wiring\_digital.c in de subfolder of my application generated a mass of linking errors.

Thus I copied the whole Arduino folder (which is not that large) to my subfolder in the application and it compiles without any problem. Not a very elegant solution, because there is a replication of the whole library; but it works.

Conclusion to override a core Arduino function:

• Put your changed function(s) (.c and/or .h) in the Arduino library, and copy this library entirely to the subfolder "libraries" in your application folder. Then all other libraries will also use your own changed function.

Conclusion performance digitalWrite in a real 32 bit serial shift :

• An optimized generic digitalWrite and Read easily outperforms the standard one with 42% if 2 pins are used in repetition. • digitalWriteFast (with determined pins at compile time) outperforms the standard digitalWrite in a real 32 bit shift application with 92% (is 12,2 times faster).

Hope this helps other Arduino users…..

```
//**********************
void digitalWrite(uint8_t pin, uint8_t val)
//**********************
{
uint8_t
  timer,
  bit,
  port;

volatile uint8_t *out; // volatile because bitmask may be changed by (higher) interrupt

uint8_t oldSREG;

static uint8_t pin1 = 0,
               pin2 = 0;

static bool    p1   = true; // boolean toggle memory

static uint8_t // Store 2 sets of port/out adresses static

//          timer1, //now exclued. Safety threat?
          bit1,
          *out1,
//          timer2,
          bit2,
          *out2;

  oldSREG = SREG;  // CLI for thread proof function
  cli();
  if ( (pin == pin1) || (pin == pin2) )
  {
    if (pin == pin1)   //Compiler optimizes this excellent (see ASM listing)
    {
      if (val == LOW)
      {
        *out1 &= ~bit1;
      } else
      {
        *out1 |= bit1;
      }
    }
    else
    if (pin == pin2)
    {
      if (val == LOW)
      {
        *out2 &= ~bit2;
      } else
      {
        *out2 |= bit2;
      }
    }

    SREG = oldSREG;
  }
  else  //normal clumsy digitalWrite operation
  {
    SREG = oldSREG;   //Enable interrupts again
    timer = digitalPinToTimer(pin);
    bit = digitalPinToBitMask(pin);
    port = digitalPinToPort(pin);
    if (port == NOT_A_PIN) return;

    // If the pin that support PWM output, we need to turn it off
    // before doing a digital write.
//    if (timer != NOT_ON_TIMER) turnOffPWM(timer);

    out = portOutputRegister(port);

    oldSREG = SREG;
    cli();

    if (val == LOW) {
      *out &= ~bit;
    } else {
      *out |= bit;
    }

    if (p1)        // Save this port, bit and out, also atomic
    {
      pin1  = pin;
      bit1  = bit;
      out1  = out;  // save the pointer, not the value
    }
    else
    {
      pin2  = pin;
      bit2  = bit;
      out2  = out;  // save the pointer, not the value
    }
    p1 = !p1;
    SREG = oldSREG; //enable interrupts
  }
}

//**********************
int digitalRead(uint8_t pin)
//**********************
{

uint8_t
  oldSREG,
  timer,
  bit,
  port;

static uint8_t pin1 = 0;

bool           readBit;

static uint8_t // Store 2 sets of port/out adresses static

//          timer1, //now exclued. Safety threat?
              port1,
              bit1;

  oldSREG = SREG;
  cli();
  if (pin == pin1)
  {
    readBit = (*portInputRegister(port1) & bit1);
    SREG = oldSREG;
    return readBit;
  }
  else
  {
    SREG = oldSREG;
    timer = digitalPinToTimer(pin);
    bit = digitalPinToBitMask(pin);
    port = digitalPinToPort(pin);

    if (port == NOT_A_PIN) return LOW;

    // If the pin that support PWM output, we need to turn it off
    // before getting a digital reading.
  //  if (timer != NOT_ON_TIMER) turnOffPWM(timer);

    oldSREG = SREG;
    cli();
    pin1 = pin;       //Atomic operation pin - bit combi must be correct
    bit1 = bit;
    port1 = port;
    SREG = oldSREG;

    if (*portInputRegister(port) & bit) return HIGH;
    return LOW;
  }
}

```
> 0 votes

---
Tags: c++, library, core-libraries
---


# Question
Title: How to recover an I2C bus when SDA is stuck low? Edit: SDA line stuck high
See edit at the end of the message.

I have an Arduino in master mode connected via I2c to a slave, with 2k pull-up resistors on SDA and SCL. Sometimes the SDA line is stuck low, which causes my program to hang indefinitely.

How to recover from such a scenario?

Edit1: Since the SDA line is tied low the problem probably comes from the master. My guess is that the slave waits for the rest of the clock pulses that never come.

I'm not using the Wire library. I wrote my own implementation based on the AMmega328P datasheet.

```
void TWIInit() {
  TWSR = 0x00;
  TWBR = 0x48; // SCL = 100khz
  TWCR = (1 << TWEN);
}

void TWIStart() {
  TWCR = (1 << TWINT) | (1 << TWSTA) | (1 << TWEN);
  while ((TWCR & (1 << TWINT)) == 0);
}

void TWIStop() {
  TWCR = (1 << TWINT) | (1 << TWSTO) | (1 << TWEN);
  while (TWCR & (1 << TWSTO));
}

void TWIWrite(uint8_t data) {
  TWDR = uint8_data;
  TWCR = (1 << TWINT) | (1 << TWEN);
  while ((TWCR & (1 << TWINT)) == 0);
}
unsigned int TWIReadACK() {
  TWCR = (1 << TWINT) | (1 << TWEN) | (1 << TWEA);
  while ((TWCR & (1 << TWINT)) == 0);
  return TWDR;
}

unsigned int TWIReadNACK() {
  TWCR = (1 << TWINT) | (1 << TWEN);
  while ((TWCR & (1 << TWINT)) == 0);
  return TWDR;
}

unsigned int TWIGetStatus() {
  unsigned int statusOfRegister;
  statusOfRegister = TWSR & 0xF8;
  return statusOfRegister;
}

int TWISendBytes(uint8_t slaveAddr, uint8_t regAddr, uint8_t buf[], int numbBytes) {
  TWIStart();
  if (TWIGetStatus() != 0x08) {
    TWIStop();
    return 1;
  }
  // send address and Write bit
  TWIWrite(slaveAddr & 0xFE);
  if (TWIGetStatus() != 0x18) {
    TWIStop();
    return 1;
  }
  // send the register address
  TWIWrite(regAddr);
  if (TWIGetStatus() != 0x28) {
    TWIStop();
    return 1;
  }
  // send bytes
  for (int i = 0; i < numbBytes; i++) {
    TWIWrite(buf[i]);
    if (TWIGetStatus() != 0x28) {
      TWIStop();
      return 1;
    }
  }
  TWIStop();
  return 0;
}

int TWIGetBytes(uint8_t slaveAddr, uint8_t regAddr, uint8_t buf[], int numbBytes) {
  TWIStart();
  if (TWIGetStatus() != 0x08) {
    TWIStop();
    return 1;
  }
  // send address and Write bit
  TWIWrite(slaveAddr & 0xFE);
  if (TWIGetStatus() != 0x18) {
    TWIStop();
    return 1;
  }
  // send the register address
  TWIWrite(regAddr);
  if (TWIGetStatus() != 0x28) {
    TWIStop();
    return 1;
  }
  // repeated start
  TWIStart();
  if (TWIGetStatus() != 0x10) {
    TWIStop();
    return 1;
  }
  // send address and Read bit
  TWIWrite(slaveAddr | 0x01);
  if (TWIGetStatus() != 0x40) {
    TWIStop();
    return 1;
  }
  // get bytes
  for (int i = 0; i < numbBytes; i++) {
    if (i == (numbBytes - 1)) {
      buf[i] = TWIReadNACK();
      if (TWIGetStatus() != 0x58) {
        TWIStop();
        return 1;
      }
    } else {
      buf[i] = TWIReadACK();
      if (TWIGetStatus() != 0x50) {
        TWIStop();
        return 1;
      }
    }
  }
  TWIStop();
  return 0;
}

```

Edit2: The SDA line, and SCL, is held high not low as I first incorrectly assumed (I probably did something wrong when I measured it and thought it was low but anyway.) The problem was that the resistors I was using as pull-up resistors were in fact 1k not 2k. I changed them for 2k resistors and the problem disappeared.

# Answer
I solved the problem by replacing the pull-up resistors with 2k Ohm resistors. I thought I connected 2k Ohm resistors when in fact their value was 1k. So sometimes the SDA line couldn't be driven low due to the too strong pull-up resistors and that caused the hanging.
> 2 votes

---
Tags: i2c
---


# Question
Title: ESP8266 on WiFi without password, possible?
Is it possible to connect to an SSID that does not require a password? My project using ESP8266-01 modules will sometimes be used in non-password protected guest networks.

# Answer
Yes, it works! You can use:

```
WiFi.begin(ssid, NULL)

```

or even leave the passphrase empty, because it is optional:

```
WiFi.begin(ssid)

```

Reference: https://www.arduino.cc/en/Reference/WiFiBegin
> 7 votes

---
Tags: esp8266, wifi
---


title: Arduino Voltage Divider

text:
# Question
Title: Arduino Voltage Divider
So am doing a project which involves the reading of voltage and current generated by Solar Panel. Now I learnt that Arduino cant Read Voltage directly above 5V. To read above that you need to add a voltage divider circuit in between. But that's the great solution for a solar panel around 20W. Now what if i want to read voltages of n number of solar panels which are in a farm in which each solar panel generated around 300-400 W . 1)Will adding voltage divider help? 2) What is the limit of Arduino of Voltage Divider? 3) What registers i would have to use for such big voltage divider?

# Answer
> 0 votes
> 1)Will adding voltage divider help?

You will need *n* voltage dividers, one for each solar panel.

> 2) What is the limit of Arduino of Voltage Divider?

There is a limit on the equivalent Thévenin resistance of the voltage source connected to the Arduino analog inputs. It should be no larger that 10 kΩ, otherwise you risk cross-talk between the channels.

If the solar panels have a low output resistance, then the equivalent Thévenin resistance is the resistance resulting from setting the two resistors of the divider *in parallel*. Setting the smallest resistance to 10 kΩ will ensure you meet the condition while at the same time keeping the consumed current quite low.

There is also a limit on the number of solar panels that you can independently monitor: 16, which is the number of analog inputs on the Mega.

> \[...\] each solar panel generate\[s\] around 300-400 W

The power generated is irrelevant: only the voltage is a concern. Your dividers must output no more than 5 V.

# Answer
> 0 votes
> 1) Will adding voltage divider help?

Yes.

> 2) What is the limit of Arduino of Voltage Divider?

The Arduino has no relevance here. You can build voltage dividers to convert thousands or millions of volts down to 5V if you need to.

> 3) What registers i would have to use for such big voltage divider?

I guess you mean "resistors" here, not "registers"...

Resistors that give no more than 5V out at the peak voltage of the solar panels, and have a high enough voltage tolerance for the maximum voltage across any one resistor.

---
Tags: arduino-mega, analogread, voltage-level, current, solar
---


# Question
Title: #include<ESP8266WiFi.h> showing error message
i was trying to send some data to a webpage via esp8266wifi module connected to arduino uno. My sketch contains a header file .After searching online I could get the library Arduino-master.zip from github. I extracted the files and put it in inside the directory arduino-\>hardware-\>arduino-\>avr-\>libraries.but even then it was showing me the error message like this:

fatal error: ESP8266WiFi.h: No such file or directory #include ^ compilation terminated. exit status 1 Error compiling for board Arduino/Genuino Uno.

How can I remove this error. please refrain from technical words as i am new to this language. Thank you.

**EDIT**: After adding esp8266WiFi.h in the library i got out from that error message .But it showed me a new one

C:\Program Files (x86)\Arduino\libraries\ESP8266WiFi\src/ESP8266WiFiType.h:26:19: fatal error: queue.h: No such file or directory #include ^ compilation terminated. exit status 1 Error compiling for board Arduino/Genuino Uno.

I dont know how to come out of this error. somewebsites give a solution but it didn't worked for me.

# Answer
That library is part of the ESP8266 core. It's not for the Arduino, but for programming the ESP8266 as a standalone unit without an Arduino connected to it.
> 1 votes

# Answer
ESP8266WiFi part of the project Arduino Core here: https://github.com/esp8266/Arduino Arduino Core provides support for the ESP8266 to be used with Arduino IDE through the boards manager facility. So its libraries are for the ESP8266 not the Uno.

If you are interested in communicating with the ESP8266 over serial using its AT+ command firmware then you just send them as strings over serial.

```
Serial1.println("AT+GMR");
while(Serial1.available() == 0) {
  delay(1);
}
while(Serial1.available() > 0) {
  Serial.write(Serial1.read());
}

```
> 0 votes

---
Tags: esp8266
---


# Question
Title: Is there any way for one Arduino board to communicate with multiple sensors?
Say a home IoT application to monitor water levels in basement at 4 or 5 different places and transmit that data back to a single Arduino board to be then interfaced with a GUI to do home monitoring?

# Answer
> 0 votes
Yes this could be done using SPI (with separate slave select wires), i2c or daisy chained UART providing a wired solution.

# Answer
> 0 votes
Yes you can ... however, how you transmit the sensor data? If wireless, you need some RF communication, and possibly a microcontroller like Arduino (or ESP) within each sensor module.

With nRF24L01 (2.4GHz) you can use 6 'slaves' (sensor modules in your case) to send data to the master (monitoring module).

Do things one by one:

* First make one sensor module
* Than make the master to receive data
* Than make the GUI screen
* Than make the other five sensor modules

---
Tags: arduino-uno, sensors, iot
---


title: Is output pin set to LOW grounded

text:
# Question
Title: Is output pin set to LOW grounded
If I do following:

```
pinMode(MYPIN, OUTPUT)
digitalWrite(MYPIN, LOW)

```

What will happen? Will this effectively ground *MYPIN* or output some low voltage?

# Answer
> 5 votes
This will effectively connect the pin to ground. Note that the connection is made by a transistor that has a finite resistance. This output resistance is not really specified, but from the curves on the “typical characteristics” section of the datasheet you can infer that the *typical* value is about 26 Ω.

The only hard specification states that the `OUTPUT` `LOW` voltage should be no larger than 0.9 V, as long as the pin is not sinking more than 20 mA. C.f. the table “DC characteristics” of the ATmega2560 datasheet.

---
Tags: arduino-mega, c
---


# Question
Title: Problem with Arduino and INA226 power meter module
I am new to the use of Arduino in general, and to the INA226 Module for power metering.

I first got everything set up WITHOUT anything plugged to the INA226 module metering pins (V+, ISens+, Isens-, V- not connected to any power source) and running a sample code that gets data being read by the INA226, of course, all values return 0, but at least I know the program runs and the arduino can connect to the INA226. Now, the problem comes when I try to get some reading such as 5V or even 3.3V from the Arduino pins.

I connected the circuit as follows:

simulate this circuit – Schematic created using CircuitLab

(I noticed that I wrote A6 instead of A4, sorry about that)

But when I do this, there is no reading at all from the serial console. I tried connecting the V+ and Isens+ directly to the 5V pin leaving everything else as shown in the diagram, but the Arduino board doesn't even turn on.

I tried referencing other sources, but their tests use external power supplies or other equipment I don't have.

I would be really thankful if someone could lend me a hand here or help me understand why am I having this problem and how can I make it read something basic such as 5V or 3.3V directly from the Arduino board.

Thanks!

# Answer
> 1 votes
There is a discrepancy in pin terminology between your schematic & what TI uses in their datasheets. I don't see anything in their datasheets using I+ or I-. I only see V+ & V-. These 2 pins perform all your voltage & current measurements depending on the "mode" you tell the IC to use.

As near as I can tell based on your schematic, you should be seeing the voltage reading based on what is applied between V+ & V- (In your case, 3.3vdc) if you've told the chip to read the bus voltage channel.

You should also be getting a current reading between the V+ & V- pins if you've told the chip to read the shunt voltage channel. Since the part is designed for a full scale voltage differential of 36v between the V+ & V- pins, I suspect a reading of about 10% of max (based on a 3.3v differential).

I confess to not knowing the board or its operation but having looked it up on the TI website, it does appear to have a few jumper settings & a calibration routine to follow. There's a user guide on TI's website as well as the usual technical data pages. Perhaps those will assist in setting the jumpers correctly. ina226 data sheet & eval board user guide bc

# Answer
> 1 votes
If this is the usual Arduino-style module with a shunt resistor already in it, then with your schematic, you have \[nearly\] shorted your supply rail. Your schematic should have the load wired in series to the `Isense+` and `Isense-` terminals, and the `V+` and `V-` terminals should be connected in parallel across the voltage powering the load.

The current must "pass through" the `Isense` terminals, and the module has to measure the voltage across the load in order to be able to get both I and V to compute power consumption.

---
Tags: arduino-uno, power
---


title: http request in time intervals

text:
# Question
Title: http request in time intervals
I'm doing a program that receives data from a web page every so often, but only receives the data once and then receives everything blank. I need help to receive the data every time indefinitely. I am using arduino uno with arduino etherner shield

My code:

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

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

IPAddress ip(192, 168, 0, 177);
EthernetClient client;

int REDLed= 2;
int GREENLed= 3;
int BLUELed= 4;

void setup()
{
  pinMode(REDLed, OUTPUT);
  pinMode(GREENLed, OUTPUT);
  pinMode(GREENLed, OUTPUT);
  Ethernet.begin(mac, ip);
  Serial.begin(9600);
  Serial.println("power up" );
  delay(3000);
}

void loop()
{
  Serial.println("SubmitHttpRequest - started" );
  SubmitHttpRequest();
  Serial.println("SubmitHttpRequest - finished" );
  delay(10000);
}

void SubmitHttpRequest()
{
  if (client.connect(server, 80))
  {
    Serial.println("connected");
    client.println("GET /arduino/getstate.php?color=All HTTP/1.1");
    client.println("Host: cybertodo.mx");
    client.println("Connection: close");
    client.println();
  }
  else
  {
    Serial.println("connection failed");
  }
  delay(100);
  changeLed();
}

void changeLed()
{
  String content = "";
  Serial.println(client.available());
  while(client.available()!=0)
  {
    content = content + String(char (client.read()));
  }
  Serial.println(content);
  if(content.substring(30,31)== "1")
  {
    digitalWrite(REDLed, HIGH);
  }
  else if (content.substring(30,31)== "0")
  {
    digitalWrite(REDLed, LOW);
  }

  if(content.substring(31,32)== "1")
  {
    digitalWrite(GREENLed, HIGH);
  }
  else if (content.substring(31,32)== "0")
  {
    digitalWrite(GREENLed, LOW);
  }

  if(content.substring(32,33)== "1")
  {
    digitalWrite(BLUELed, HIGH);
  }
  else if (content.substring(32,33)== "0")
  {
    digitalWrite(BLUELed, LOW);
  }
  content = "";
}

```

# Answer
Immediately after making the request when reading client.available() will be 0 since no data was received yet so:

```
  while(client.available()!=0)
  {
    content = content + String(char (client.read()));
  }

```

Will never actually run. Try something like:

```
unsigned long last = millis();
String content = "";

while(client.connected()) {
  int len = client.available();
  if(len > 0) {
    last = millis();

    char buff[len];
    for(int i = 0; i < len; i++) {
      buff[i] = client.read();
    }
    content += String(buff);

  } else {
    if(millis() - last > 2000) {
      client.stop();
      return;
    }
    delay(1);
  }
}

```

Also note if you use Connection: close on the client then you must close the connection. This example doesn't do that until 2 seconds have passed. To do this properly you'd need to also add header parsing to your client and close the connection once the amount specified in Content-Length is received.
> 1 votes

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


# Question
Title: Problems recycling c++ lib with templated class for Arduino
I have a header & cpp file located in Arduino\libraries\Parentfolder\Header&Cpp. Arduino IDE recognizes my lib (the class is color coded & Sketch-\>include library-\>MyLibrary shows in the dropdown menu and #includes properly).

Problem: Arduino IDE gives `undefined reference to MyClass . . .` error in my sketch for every reference of the class including function calls. The function fully in other IDEs as header/cpps so I don't think pasting the cody is necessary -- what could I be missing? I've read a million Stack Exchange posts with similar error/watched a million YouTube guides on writing Arduino libs and I can't seem to find the differentiating factors that would make my code *not* work for Arduino IDE.

tl;dr what are the reasons that a working c++ library (self-made) would not work with Arduino IDE?

/e

```
Queue.h
#ifndef Queue_h
#define Queue_h

#include "Arduino.h"

template <typename T>
class Queue
{
  public:
    typedef struct node
    {
      T data;
      node * next = nullptr;
    } * nodePtr;

    nodePtr head; // = nullptr;
    nodePtr tail; // = nullptr;
    nodePtr curr; // = nullptr;
    nodePtr temp; // = nullptr;

    unsigned int counter;

    Queue();
    void push(T);
    T& peek();
    T pop();
    int size();
    bool isEmpty();
    void clear();
};

#endif

```

Queue.cpp

```
#include "Arduino.h"
#include "Queue.h"

template <typename T>
Queue<T>::Queue()
{
    nodePtr head = nullptr;
    nodePtr tail = nullptr;
    nodePtr curr = nullptr;
    nodePtr temp = nullptr;

    counter = 0;
}

template <typename T>
void Queue<T>::push(T data)
{
  if (head == nullptr)
  {
    head = new node;
    head->data = data;
    tail = head;
  }
  else
  {
    temp = head;
    head = new node;
    head->data = data;
    head->next = temp;
  }
  counter ++;
}

template <typename T>
T& Queue<T>::peek()
{
  if (head == nullptr)
  {
    return 0;
  }
  return head->data;

}

template <typename T>
T Queue<T>::pop()
{
  // Empty
  if (head == nullptr)
  {
    return 0;
  }

  // Head = tail
  if (head == tail)
  {
    T data = head->data;
    delete head;
    return data;
  }

  // Size > 1
  curr = head;
  while (curr->next != tail)
  {
    curr = curr->next;
  }
  T data = curr->next->data;
  tail = curr;
  curr = curr->next;
  delete curr;
  counter --;
  return data;
}

template <typename T>
int Queue<T>::size()
{
  return counter;
}

template <typename T>
bool Queue<T>::isEmpty()
{
  if (counter ==0)
  {
    return true;
  }
  return false;
}

template <typename T>
void Queue<T>::clear()
{
  while (head->data != nullptr)
  {
    temp = head->next;
    delete head;
    head = temp;
  }
  if (head == nullptr)
  {
    return;
  }
  delete head;
  return;
}

```

.ino

```
. . .
Queue<float> avgQueue;
. . .

```

error

```
. . . In function `__static_initialization_and_destruction_0':
. . . undefined reference to `Queue<float>::Queue()'

```

***SOLVED:***

Combining the .cpp contents in the .h and removing the .cpp worked.

# Answer
***SOLVED:***

Putting the .cpp contents in the .h and removing the .cpp from the lib folder entirely worked.
> -1 votes

---
Tags: arduino-uno, arduino-ide, library
---


# Question
Title: FastLED + structs + PROGMEM strange behavior
I'm afraid I have to post a lengthy bit of code, because I can't pinpoint what's causing my issues – in short, it appears **repeatedly** adding `float position + float speed` in a struct ends up borking the whole thing.

The purpose of the code is to animate at most `MAX_PARTICLES` particles ("pixels") traveling at random speeds across the LED stripe.

The array named `particles` stores the current list of particles being managed. Each particle in the array is stored as a struct, as defined at the beginning of the code. Particles are added to the array using function `addParticle()` at the very end of the code. Particles which reach the end of the stripe are killed in the second part of the `loop()` function (after `FastLED.show()`).

Here's the code:

```
#define FASTLED_INTERNAL // Eliminates a compiler warning
#include <FastLED.h>
#include <colorutils.h>
#define NUM_LEDS 149
#define DATA_PIN 6
#define MAX_PARTICLES 5 // This uses up the memory, mostly
CRGB leds[NUM_LEDS];

struct particle {
  float position;
  CRGB color;
  float speed;
  int id;
};
typedef struct particle Particle;
Particle particles[MAX_PARTICLES];
int numParticles = 0;
int maxId = 0;

// Gramma correction tables (Defalt Gamma = 2.8)
const uint8_t PROGMEM gammaR[] = {
    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,
    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  1,  1,  1,
    1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  2,  2,  2,  2,  2,
    2,  2,  2,  3,  3,  3,  3,  3,  3,  3,  4,  4,  4,  4,  4,  5,
    5,  5,  5,  5,  6,  6,  6,  6,  7,  7,  7,  7,  8,  8,  8,  9,
    9,  9, 10, 10, 10, 11, 11, 11, 12, 12, 12, 13, 13, 14, 14, 14,
   15, 15, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22,
   23, 24, 24, 25, 25, 26, 27, 27, 28, 29, 29, 30, 31, 31, 32, 33,
   33, 34, 35, 36, 36, 37, 38, 39, 40, 40, 41, 42, 43, 44, 45, 46,
   46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61,
   62, 63, 65, 66, 67, 68, 69, 70, 71, 73, 74, 75, 76, 78, 79, 80,
   81, 83, 84, 85, 87, 88, 89, 91, 92, 94, 95, 97, 98, 99,101,102,
  104,105,107,109,110,112,113,115,116,118,120,121,123,125,127,128,
  130,132,134,135,137,139,141,143,145,146,148,150,152,154,156,158,
  160,162,164,166,168,170,172,174,177,179,181,183,185,187,190,192,
  194,196,199,201,203,206,208,210,213,215,218,220,223,225,227,230 };

const uint8_t PROGMEM gammaG[] = {
    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,
    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  1,  1,  1,  1,
    1,  1,  1,  1,  1,  1,  1,  1,  1,  2,  2,  2,  2,  2,  2,  2,
    2,  3,  3,  3,  3,  3,  3,  3,  4,  4,  4,  4,  4,  5,  5,  5,
    5,  6,  6,  6,  6,  7,  7,  7,  7,  8,  8,  8,  9,  9,  9, 10,
   10, 10, 11, 11, 11, 12, 12, 13, 13, 13, 14, 14, 15, 15, 16, 16,
   17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22, 23, 24, 24, 25,
   25, 26, 27, 27, 28, 29, 29, 30, 31, 32, 32, 33, 34, 35, 35, 36,
   37, 38, 39, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 50,
   51, 52, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 66, 67, 68,
   69, 70, 72, 73, 74, 75, 77, 78, 79, 81, 82, 83, 85, 86, 87, 89,
   90, 92, 93, 95, 96, 98, 99,101,102,104,105,107,109,110,112,114,
  115,117,119,120,122,124,126,127,129,131,133,135,137,138,140,142,
  144,146,148,150,152,154,156,158,160,162,164,167,169,171,173,175,
  177,180,182,184,186,189,191,193,196,198,200,203,205,208,210,213,
  215,218,220,223,225,228,231,233,236,239,241,244,247,249,252,255 };

const uint8_t PROGMEM gammaB[] = {
    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,
    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  1,
    1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  2,  2,  2,
    2,  2,  2,  2,  2,  2,  3,  3,  3,  3,  3,  3,  3,  4,  4,  4,
    4,  4,  5,  5,  5,  5,  5,  6,  6,  6,  6,  6,  7,  7,  7,  8,
    8,  8,  8,  9,  9,  9, 10, 10, 10, 10, 11, 11, 12, 12, 12, 13,
   13, 13, 14, 14, 15, 15, 15, 16, 16, 17, 17, 18, 18, 19, 19, 19,
   20, 20, 21, 22, 22, 23, 23, 24, 24, 25, 25, 26, 27, 27, 28, 28,
   29, 30, 30, 31, 32, 32, 33, 34, 34, 35, 36, 37, 37, 38, 39, 40,
   40, 41, 42, 43, 44, 44, 45, 46, 47, 48, 49, 50, 51, 51, 52, 53,
   54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 69, 70,
   71, 72, 73, 74, 75, 77, 78, 79, 80, 81, 83, 84, 85, 86, 88, 89,
   90, 92, 93, 94, 96, 97, 98,100,101,103,104,106,107,109,110,112,
  113,115,116,118,119,121,122,124,126,127,129,131,132,134,136,137,
  139,141,143,144,146,148,150,152,153,155,157,159,161,163,165,167,
  169,171,173,175,177,179,181,183,185,187,189,191,193,196,198,200 };

void setup() {
  FastLED.addLeds<WS2812B, DATA_PIN, BGR>(leds, NUM_LEDS);
  randomSeed(analogRead(0));
  Serial.begin(115200);
}

void loop() {
  if (numParticles < MAX_PARTICLES && random(10)>8) {
    addParticle();
  }

  for (int i=0; i<numParticles; i++) {
    // Antialiasing
    int basePosition = floor(particles[i].position);
    byte percentOnePos = round(255 * (particles[i].position-basePosition));
    byte percentBasePos = 255 - percentOnePos;
    CRGB color0 = particles[i].color % percentOnePos;
    CRGB color1 = particles[i].color % percentBasePos;

    leds[basePosition] += color0;
    leds[basePosition+1] += color1;
  }

  // Apply gamma correction
  for (int i=0; i<NUM_LEDS; i++) {
    //leds[i] = applyGamma_video(leds[i], 2.2);
    // *** applyGamma_video(2.2) pros and cons:
    // PROs: smoother color transitions
    // CONs: much slower; much worse color calibration
    // TODO: pre-render custom, color calibrated gamma tables

    leds[i].red = pgm_read_byte(&gammaR[leds[i].red]);
    leds[i].green = pgm_read_byte(&gammaG[leds[i].green]);
    leds[i].blue = pgm_read_byte(&gammaB[leds[i].blue]);
  }

  FastLED.show();

  for (int i=0; i<numParticles; i++) {
    int basePosition = floor(particles[i].position);
    leds[basePosition] = CRGB::Black;
    leds[basePosition+1] = CRGB::Black;
    particles[i].position += particles[i].speed;
    if (particles[i].position > (NUM_LEDS+1)) { // We want to render it fading out
      for (int j = i; j<numParticles-1; j++) {
        particles[j] = particles[j+1];
      }
      numParticles--;
      i--; // We want the for() cycle to process the particle we shifted down
    }
  }
  debugParticles();
}

void debugParticles()
{
  for (int i = 0; i<MAX_PARTICLES; i++) {
    if (i>0) {
      Serial.print(", ");
    }

    Serial.print(i);
    Serial.print(",");
    Serial.print(particles[i].id);
    Serial.print(",");
    Serial.print(particles[i].position);
  }
  Serial.println("");
}

void addParticle()
{
  particles[numParticles].color = CHSV(random8(),255,150);
  particles[numParticles].position = 0;
  particles[numParticles].speed = (0.0+random(10))/100+0.01;
  particles[numParticles].id = maxId++;
  numParticles++;
}

```

For debugging purposes, each unique particle ever created has a unique ID. The debugging output contains the following fields:

* \[0\] the array index for the first entry in the array (always 0)
* \[1\] the unique ID of the particle stored in the first record of the array
* \[2\] the position of the particle stored in the first record of the array
* \[3\] the array index for the second entry in the array (always 1)
* \[4\] the unique ID of the particle stored in the second record of the array
* \[5\] the position of the particle stored in the second record of the array
* (and so on – three fields for each record in the particles array)

Finally, here's an interesting excerpt from the output, after ~1,500 records:

```
0   0   30.36   1   1   30.28   2   2   147.70  3   3   59.04   4   4   73.15
0   0   30.38   1   1   30.30   2   2   147.80  3   3   59.08   4   4   73.20
0   0   30.40   1   1   30.32   2   2   147.90  3   3   59.12   4   4   73.25
0   0   30.42   1   1   30.34   2   2   148.00  3   3   59.16   4   4   73.30
0   0   30.44   1   1   30.36   2   2   148.10  3   3   59.20   4   4   73.35
0   0   8.00    1   1   30.38   2   2   148.20  3   3   59.24   4   4   73.40
0   0   8.00    1   1   30.40   2   2   148.30  3   3   59.28   4   4   73.45
0   0   8.00    1   1   30.42   2   2   148.40  3   3   59.32   4   4   73.50
0   0   8.00    1   1   30.44   2   2   148.50  3   3   59.36   4   4   73.55
0   0   8.00    1   1   30.46   2   2   148.60  3   3   59.40   4   4   73.60
0   0   8.00    1   1   30.48   2   2   148.70  3   3   59.44   4   4   73.65
0   0   8.00    1   1   30.50   2   2   148.80  3   3   59.48   4   4   73.70
0   0   8.00    1   1   30.52   2   2   148.90  3   3   59.52   4   4   73.75
0   0   8.00    1   1   30.54   2   2   149.00  3   3   59.56   4   4   73.80
0   0   8.00    1   1   30.56   2   2   149.10  3   3   59.60   4   4   73.85
0   1   0.00    1   2   149.20  2   3   59.64   3   4   73.90   4   4   73.85
0   1   0.00    1   2   149.30  2   3   59.68   3   4   73.95   4   4   73.85
0   1   0.00    1   2   149.40  2   3   59.72   3   4   74.00   4   4   73.85

```

Notice how in all but the last three lines, the array index and the particle ID are still in sync (0=\>0, 1=\>1, 2=\>2, 3=\>3, 4=\>4), which means no particles have died yet (new particles would have larger IDs). I'm trying to say that no particle re-assignment magic has happened yet – for now, we're just running the boring code which moves particles along the strip.

And yet, on the sixth line in the output, the first particle's position becomes mangled – notice how on the first five lines the first particle's position has steadily increased by 0.02 (presumably that particle's speed) up to 30.44, whereas on the sixth line it inexplicably becomes 8.00 (other times I experimented, it becomes 32.00). Not only that, but that 8.00 (the particle's position) never increases again, and three lines from the bottom the code also decides to kill the first particle altogether (notice that the second column becomes 1, which means the first record in the particles array now stores the particle with unique ID 1, instead of unique ID 0).

I have no idea what I'm doing wrong – I've been experimenting with this over and over, killing off all the bugs and warnings I could find, and still no luck.

# Answer
> 1 votes
As you are keeping the particles over the position 149 (because of fading), I'd expect overwritting the memory after the space allocated for the `leds` variable.

According to the log it started somewhere around position 148, which is earlier, but in your code is this:

```
int basePosition = floor(particles[i].position);
leds[basePosition] += color0;
leds[basePosition+1] += color1;

```

So if you have position 148, you are already changing something after the array. It might add zero values in the color1 (for `148.0` and `148.1`) so it didn't changed anything but later the value gets nonzero and changes a wrong memory.

---
Tags: neopixel, float, progmem, struct
---


title: DAC to play audio samples

text:
# Question
Title: DAC to play audio samples
I have a buffer which contains *16000 PCM* samples of *8Khz 8-bit mono*. I am trying to play it using *12 bit MCP4725 DAC*. I have tried using `micros()` to control the write interval for the DAC. Here's my code:

```
uint8_t soundData[16000] = { 234,206,79,255,249,....,210,222 }; // 8Khz 8-bit mono
long previousMicros = 0; // Sorry for missing this out!!

void setup() {

Serial.begin(115200);
Wire.begin(D2, D1);
delay(100); // delay 100 ms
Serial.flush();
delay(1000);

}

void value_write(uint16_t temp){

  Wire.beginTransmission(0x62);
  Wire.write(64);
  Wire.write(temp >> 4);        // the 8 most significant bits...
  Wire.write((temp & 15) << 4); // the 4 least significant bits...
  Wire.endTransmission();

}

void loop() {

  unsigned long currentMicros = micros();

// 125 uS sampling for 8KHz signal
if(currentMicros - previousMicros > 125) {
  Serial.print("Index: ");
  Serial.println(indx);
  uint16_t temp = map(soundData[indx++], 0, 255, 0, 4095);

  value_write(temp);
}

}

```

The write should logically be completed within *2 seconds* but takes way more time. Any help regarding successfully writing the *PCM values to the DAC* at *8000Hz* is greatly appreciated.

# Answer
In your code, you never set or update `previousMicros` value.
> 1 votes

# Answer
One sample takes 38 I2C clock cycles to write. That's:

```
1 START
7 Address
1 R/W
1 ACK
8 Byte
1 ACK
8 Byte
1 ACK
8 Byte
1 ACK
1 STOP

```

At the default 100kHz clock speed that's 100,000/38 = 2631.58 samples per second *absolute maximum*.

You can increase the clock speed to 400kHz, which would allow you 400,000 / 38 = 10526 samples per second *absolute maximum*. That would just about be do-able.

I am unsure what the ESP8266 can support, but the DAC also supports "High Speed" mode - 3.4MHz I2C. If the ESP8266 supports that you can then run at 3,400,000 / 38 = 89474 samples per second, which is better still.

There's also the matter of the `map()` function which is just nasty in this situation. You can just bit-shift.

So besides just removing the Serial commands (which will slow things down massively) you should also:

1. Change the I2C clock to *at least* 400kHz
2. Change `map()` to `soundData[indx++] << 4`
3. Consider using a timer to trigger the sending of the samples

But, with all that said. an I2C DAC is really not suited to audio playback. I2C is just too slow and clunky for audio. You'd be better off with an SPI DAC which can run much much faster than I2C. Better still you should investigate I2S on the ESP8266. This is designed specifically for audio, although it's much harder to set up owing to the increased number of special clocks you need to provide ("master" clock, "bit" clock and "l/r" clock). Also the DACs (also known as CODECs) tend to be at least 16 bit or even higher, and capable of proper audio sampling frequencies, like 44100ksps and above.
> 4 votes

---
Tags: esp8266, c, audio
---


# Question
Title: Battery life calculation using Nano, NRF24L01+ and window magnetic reed switch
I'm trying to make my own home wireless security system. I will be using probably 3 AA batteries to power these devices. My problem is that I need to know if the batteries will be enough to power the devices for at least 6 months. Below are the details of all the devices I will be using:

1. Mini Nano V3.0 ATmega328P Microcontroller Board w/USB Cable For Arduino
2. Makerfire Arduino NRF24L01+ 2.4GHz Wireless RF Transceiver Module
3. uxcell MC 38 Mount Wired Door Window Sensor Magnetic Reed Switch Recessed

Below are some project requirements that might be useful:

1. For the Nano, I want to put it to sleep using delay(2000) in the loop() function. The Nano will be the one checking the window sensor.
2. I will be using a project enclosure of about 4X4 inches.

If this will not be possible maybe someone knows of other devices that use less power that will be more suitable for this project? I would prefer something easy to use like Arduino Nano with USB so I can easily program it.

EDIT: sorry but I just like to add that from the main HUB component, I would like to check the status of the window sensor if it is open/closed. This will be useful if there is an open window/door around the house when going to sleep. Probably the Nano will broadcast its current window sensor status to the main HUB program. Thanks.

# Answer
> 1 votes
You should use interrupts for the reed switch and then put the microcontrolller into sleep for a keep alive interval. Your master device should check that the sensor is still active and set off the alarm if its not. You would also want to allow for a battery low condition that might disable the alarm for convince. This still should keep the power consumption low.

The nano is roughly 1mA @ 3.3v while the CPU is running and 72uA when its in sleep. Discounting power consumption in the alarm condition triggered by the interrupt using an interval of 9 seconds using delay or interrupt timers then average consumption then about a second to wake up and send a keep alive over the RF. (0.000072 * 9 + 0.001 * 1) / 10 = 0.0001648 amps. (average over 10 second duty cycle)

My guesstimate of your RF power consumption without knowing what kind of protocol would be somewhere around 128 bytes per transmission taking about 90ms. (0.0001 * 9910 + 0.015 * 90) / 10,000 = 0.0002341 amps.

Total of their averages is: 0.0003989 or 398.9uA.

Alkaline AA cells vary widely. So instead based on some Ni-MH with 2400mAh per cell and 1.2v

3 cells would be 3.6v so you'll "get" most of the mAhs out of the batteries.

2400mAh = 2400000uAh

2400000uAh / 398.9uA ~= 6016.54 hours or 250 days or 8 months.

Power consumption were intentional overestimates. You should be able to make it last a lot longer.

https://www.avrprogrammers.com/howto/atmega328-power http://harizanov.com/2013/05/nrf24l01-power-consumption-footprint/

# Answer
> 0 votes
It only seems to do one thing: activate an alarm if the reed switch changes. Power the system *through* the reed switch. It will have zero standby current and the battery will last the shelf life. That said, you might be able to use an RF module w/o even a MCU, though not that particular one...

# Answer
> 0 votes
You should use a reed switch that is both NC and NO. Then power only the disconnected part of the switch and listen to pin changes and put everything into sleep. This can improve your power consumption. See the answers postet here: Low Power Pin Change Detection

---
Tags: power, arduino-nano, electronics
---


# Question
Title: Code for determining beats per min when timing a wooden clock
I'm new to Arduino and coding but I build wooden clocks. The biggest problem is timing the clock to the correct beats per min when adjusting pendulum length. I'm thinking Arduino and an IR sensor?? to detect when the pendulum breaks the beam, then displaying the beats per min real time would be possible. If not real time then just beats in a variable time period, ie 1 min or 2 or 5 or 10 min. I've looked for this type of code and circuit but haven't been able to find one. Any help would sincerely be appreciated.

# Answer
If the accuracy you require is about 1%, that should be doable with any Arduino. Much higher accuracies would be hard to achieve because most Arduinos are clocked off a ceramic resonator, and these have a frequency tolerance of about 0.5%.

Given that your signal is very slow, the simplest approach may be to poll the pin connected to the sensor and record the time (using `micros()`) of the low → high transition. Then you can compute the beat frequency as the inverse of the time between consecutive transitions.

There is, however, the possibility that the sensor is not exactly in the middle of the swing. Then, for better accuracy, I would measure the time taken by *two* beats, i.e. a full swing. This way the pssible asymmetry will not affect the accuracy.
> 1 votes

# Answer
I'd suggest to have the Arduino send a message to the PC when a 'tick' occurs. Then have the PC do the calculations over a larger number of ticks. You can even have the PC measure it's drift using NTP (PC clocks also aren't extremely accurate, but better that the crystal on the Arduino).

The procedure that I used, I found at https://www.logre.eu/wiki/Horloge\_analogique\_24h/en#Quartz\_calibration I ran it for a few hours. Which might also be useful in your case to see if the swing is consistent.

I used this to calibrate my Arduino clock to within a few seconds per year,
> 0 votes

---
Tags: arduino-mega
---


# Question
Title: Arduino/ESP8266 to put PC to sleep and wake it up
I have a Wemos D1 mini that's connected to a pc with usb, I want to be able to sleep the pc and wake it up programmatically.

Is there a way to do this? Like sending a simulated sleep keyboard button press?

Maybe I can send a wake up on lan command from the Wemos since they both are connected to the same router, but I'm still more interested in sending a sleep command.

I found this but it's old and it looks like they don't really have a way to do it.

# Answer
The hardware interface would be the easiest like others were saying. Here is a project someone else shared that does that.

https://www.hackster.io/zvonko-bockaj/wemos-esp8266-remote-pc-switch-062c7a

The wake-on-lan part is easy and here is some code for that.

https://github.com/koen-github/WakeOnLan-ESP8266

I'm also interested in sending some kind of RPC call to a system (linux/windows/mac) via wifi to initiate a shutdown. If I find a solution I will post it here.

UPDATE: I found a Sleep-On-Lan project that should work. You can use the same code above for the ESP8266 but just reverse the MAC Address of the system you want to shutdown.

https://github.com/SR-G/sleep-on-lan

You will need to run this as a service on the system you intend to put to sleep. There is a windows and linux version. They didn't mention mac but I bet it will compile and run on a mac too. :)

I hope this helps. I will probably use this myself in the future.
> 2 votes

# Answer
**Sleep**

If this is a Windows PC and you can write a WIN32 C++ program then you can look at the `WH_KEYBOARD_LL()` function and use that to inject the "sleep key", but I'm not sure the "sleep key" isn't an OEM key which might make things difficult.

You could also look at sending a remote command (shutdown) over the network, but you'd have some hefty protocols to implement. Unless you had a service on your PC that listened to the serial connection and waited for the device to send a sleep command to it over that and converted it into a system call. The same will work with a Linux Daemon.

**Wake Up**

You can get Windows (don't know about Linux) to let a USB device wake it up, but I don't know if you could get a Arduino/ESP to send the correct signals.

Like The great Majenko says WoLAN is an option, but difficult to achieve.

My preferred option would be to splice a wire into the power button of the PC in parallel (so you can still use the button) and control that with a relay. That should give you a Wifi enabled power switch, but you need to check how the switch works and mimic it properly. I would try it with an old, almost dead, worthless PC first if I was you.
> 1 votes

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


title: Arduino connection with Arduino

text:
# Question
Title: Arduino connection with Arduino
I have 3 Arduino boards, let's call them be A, B, C. I'm connecting A with a bluetooth module and I'm getting the input from the bluetooth module. Now I want to send output from A using the digital pins and I want the output of A to be the inputs of B and C. The output sent from A will be based on voice input from the bluetooth module. The inputs of B and C will provide output signals to L293D and L298N motor drives. I have only one bluetooth module. Is this possible? Please let me know, it's urgent. I'm working on a project.

# Answer
> 0 votes
If you can connect ABC with wires, then it is easy - I use Wire library to send a lot of messages to net of many Arduinos.

Also other protocols are avaiable, like SPI, software serial, ... or if the communication is extremely easy (like just On/Off), then digitalWrite()/digitalRead() would work really easy.

I see the voice input to be more difficult in Arduino-size computers (voice recognition is not easy), but maybe you can process the voice before sending BT (on PC/tablet/phone/...) and then the BT would transfer only simple commands and it would be no problem at all.

If there is something I missed, you may write more, where you see the main problem.

---
Tags: arduino-uno, hc-06, l298n, l293d
---


title: L298 module - unusual power specs

text:
# Question
Title: L298 module - unusual power specs
I would like to purchase this dual H-bridge module. I plan on connecting it to an Arduino Uno. In the products datasheet the specified power supply (Vd) is 6.5-12V, and the voltage for the motor control pins is 2.3V HIGH and -0.3V LOW.

**My question** is whether this product is compatible with the standard 5V of Arduino Uno for both the power supply and logic; i.e. can I connect the Vd to the 5V terminal of the Arduino and the control pins to the digital terminals?

If not, what modifications do I need in order to use this H-bridge with an Arduino?

*Note:* Originally I bought this cheap module and connected the motor control pins to the Arduino, but each output returned a different output voltage!

# Answer
That's a very poor datasheet. I think it's using equals signs where it means less-or-equal, so:

> High level: 2.3V = Vin = Vss

Intends to say that Vin between 2.3 and Vss will be considered high, and

> Low:-0.3V = Vin = 1.5V

Intends to say that Vin between -0.3 and 1.5V will be considered low.

"Vss" in the high level definition is confusing, because in the rest of the datasheet, "VD" is used for the logic voltage and "VS" is used for the motor; you'd expect the upper limit to be the logic voltage.

**The diagram at the end of the datasheet shows how it can be used with an Arduino.** A 7.5V source is going into the Vin pin (instead of the barrel jack, which is unusual). There's a protection diode on the power input which incurs a ~1V voltage drop, so the Arduino Vin pin should be outputting 6.5V, which drives the board. The digital outs from the Arduino, when driven high, are at 5V, well above the 2.3V threshold given on the datasheet.

I'd recommend powering the Arduino through the barrel jack with a 7.5V or 9V supply to drive the logic side of the board. (Powering through the USB port will put 5V or less on the Vin pin.)

You'll want a more robust supply for the motor side, because the Arduino can't deliver very much current.
> 1 votes

---
Tags: arduino-uno, motor, l298n
---


# Question
Title: Undefined reference to stdlib (strtof) while compiling
I'm trying to run the AzureIoTProtocol\_MQTT/esp8266 example, but I get linker errors:

> Archiving built core (caching) in: /var/folders/fj/y3vtrz597kv4885q1b\_5qypr0000gn/T/arduino\_cache\_934614/core/core\_esp8266\_esp8266\_d1\_mini\_CpuFrequency\_80,UploadSpeed\_921600,FlashSize\_4M3M\_e1e103f2055a19e071ac9522162e1787.a libraries/AzureIoTHub/sdk/agenttypesystem.c.o: In function `sscanfd':
>  /Users/jonas/Documents/Arduino/libraries/AzureIoTHub/src/sdk/agenttypesystem.c:2826:
>  undefined reference to`strtoull' libraries/AzureIoTHub/sdk/agenttypesystem.c.o: In function `sscanfllu':
>  /Users/jonas/Documents/Arduino/libraries/AzureIoTHub/src/sdk/agenttypesystem.c:2826:
>  undefined reference to`strtoull' libraries/AzureIoTHub/sdk/agenttypesystem.c.o:(.text.CreateAgentDataType\_From\_String+0xac): undefined reference to `strtof'
>  libraries/AzureIoTHub/sdk/agenttypesystem.c.o: In function` CreateAgentDataType\_From\_String': /Users/jonas/Documents/Arduino/libraries/AzureIoTHub/src/sdk/agenttypesystem.c:3571: undefined reference to \`strtof' collect2: error: ld returned 1 exit status

The issue can be broken down to the call to `strtof` function call. I get the same error with only this very simple code snippet:

```
#include <stdlib.h>

void setup() {
  char szOrbits[] = "686.97";
  float f;
  f = strtof (szOrbits, NULL);
}

void loop() {
}

```

Tested environment: Mac OS X 10.13.2 with Arduino 1.8.3 AND Windows 10 with Arduino 1.8.5.

# Answer
> 1 votes
Its because the "strtof" function resides in "stdlib.h", "Stdio.h" deals with i/o tasks.

Since you din't include you get that undefined reference error. Correct that and compile again. Hopefully the error shall be resolved, else reply in the comments.

> ## Update1:
>
> After digging around standard gcc stdlib definitions and avr-gcc definitions found out that the above solution works for a gcc and not avr-gcc especially the 8-bit ones which the arduino IDE compiles for uno and the works as expected for 32bit processors like of Due.
>
> Cite:
>
> 1. https://www.arduino.cc/reference/en/language/variables/data-types/double/
> 2. https://www.arduino.cc/reference/en/language/variables/data-types/float/

## Reason:

The size of the double and float is the same, ie: 4 bytes and even if you use double its actually the float itself and wont gain any precision advantage.

## Solution:

Since the size of the double and the float is same there is not point in having two function definition doing the same job. so

1. **Use "strtod" instead of "strtof"** or
2. Define a macro **#define strtof(A, B) strtod(A, B)** in the begning of your sketch so that the "strtod" handles the functioning of the "strtof".

# Answer
> 0 votes
Its because you haven't added the core of esp8266 to the arduino IDE. you are defaulting it to the "UNO" board and compiling it. so you get that error for which i have explanation

here: https://arduino.stackexchange.com/a/48719/3557

solution for your problem is simple added the esp8266 core and select the right board and compile again.

Cite: https://learn.sparkfun.com/tutorials/esp8266-thing-hookup-guide/installing-the-esp8266-arduino-addon

Follow above link and install the esp8266 core.

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


# Question
Title: Lifecycle hook in Arduino to know if Arduino is reset or powered down
I am new to Arduino programming and I'm really fascinated with its working. Is there a way to know if an Arduino is getting switched off or being reset? Like a function would be called before the Arduino gets switched off.

I want to detect this event *to preserve a value*, where a user resets his Arduino, or switches it off. Is it possible?

# Answer
> EEPROM has a limit of 100,000 write/erase cycles, so we cant do more than that

You have 1k bytes of EEPROM and they survive a minimum of 100,000 writes. So that's 102,400,000 writes you could potentially do, if you are saving one byte. Even at one write a second that would be around 3 years.

However the EEPROM page size is 4 bytes, so that is actually 25,600,000 writes you could get away with (of 4 bytes at a time). Still, that is quite a lot of writes.

A while back I tested one of my chip's EEPROM and found that it greatly exceeded the 100,000 writes specified before it starting misreading the data back.

Also, if you refrain from writing if the value hasn't changed (hopefully that's a lot of the time?) then you could probably extend the life to 100 years.

---

> Like a function would be called before the Arduino gets switched off.

No, that's impossible. How would it possibly know it is about to be switched off? Once it is switched off, functions are hardly going to be able to run.

---

> Is there a way to know if an Arduino is getting switched off or being reset?

Once you hit Reset the processor starts again. It doesn't run any functions "just before" or "just after" being reset (using the original variables). That would mean that the reset doesn't actually reset it.

---

If you are designing some gadget that lets you configure it (eg. with a volume control) then simply save the new setting to EEPROM when it is changed. This is hardly going to happen 24 hours a day.
> 1 votes

# Answer
You can read the `MCUSR` status register to determine the source of the reset.

Sources can be the Watchdog timer, brownout (too low a voltage), reset (button), or power-cycle.
> 0 votes

---
Tags: arduino-uno, atmega328
---


title: Use of array in case statement

text:
# Question
Title: Use of array in case statement
I want to know how I can use case statement for each array.

Below is my code:

```
int incomingByte = 0;

void setup()
{
  Serial.begin(115200);
  for (int thisPin = 2; thisPin < 6; thisPin++)
  {
    pinMode(thisPin, OUTPUT);
  }
}

void loop()
{
  int button1[] = {0xFF, 0x04, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x05};
  int button2[] = {0xFF, 0x04, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x06};
  int button3[] = {0xFF, 0x04, 0x04, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x08};
  int button4[] = {0xFF, 0x04, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0C};

  if (Serial.available() > 0)
  {
    incomingByte = Serial.read();
  }

  switch (incomingByte)
  {
    case button1:
      digitalWrite(2, HIGH);
      break;
    case button2:
      digitalWrite(3, HIGH);
      break;
    case button3:
      digitalWrite(4, HIGH);
      break;
    case button4:
      digitalWrite(5, HIGH);
      break;
    default:
      for (int thisPin = 2; thisPin < 6; thisPin++)
      {
        digitalWrite(thisPin, LOW);
      }
  }
}

```

# Answer
Not checked/compiled, just to give an idea.

```
/* One button message is 12 bytes, it is assumed that all received messages are 12 bytes. If note, you have to check later differently. */
#define MSG_SIZE 11
byte incomingBytes[MSG_SIZE]; /* Storage for 11 bytes */
byte index = 0; /* Current byte to set within incomingBytes */

void setup()
{
  Serial.begin(115200);
  for (int thisPin = 2; thisPin < 6; thisPin++)
  {
    pinMode(thisPin, OUTPUT);
  }
}

void loop()
{
  if (Serial.available() > 0)
  {
    /* Store the next incoming byte. Assume 0xFF is the start of a message. */
    byte incoming_byte = Serial.read();
    if (incoming_byte == 0xFF)
    {
      index = 0;
    }

    incomingBytes[index] = incoming_byte;
    index++;
    if (index >= MSG_SIZE)
    {
       check_message();
       index = 0;
    }
  }
}

/* Checks which button is pressed and performs an action based on the
pressed button. */
void check_message()
{
  case check_button_pressed())
  {
    case 1:
      digitalWrite(2, HIGH);
      break;
    case 2:
      digitalWrite(3, HIGH);
      break;
    case 3:
      digitalWrite(4, HIGH);
      break;
    case 4:
      digitalWrite(5, HIGH);
      break;
    default:
      for (int thisPin = 2; thisPin < 6; thisPin++)
      {
        digitalWrite(thisPin, LOW);
      }
  }
}

/* Checks which button is pressed by comparing 11 incoming bytes to the
four buttons to be checked. Returns -1 for an illegal message/unsupported
button and 1, 2, 3 or 4 for the pressed button. */
int check_button_pressed()
{
  int button_pressed = -1;
  if ((incomingBytes[0] == 0xFF) &&
      (incomingBytes[1] == 0x04) &&
      (incomingBytes[3] == 0x00) &&
      (incomingBytes[4] == 0x00) &&
      (incomingBytes[5] == 0x00) &&
      (incomingBytes[6] == 0x00) &&
      (incomingBytes[7] == 0x00) &&
      (incomingBytes[8] == 0x00) &&
      (incomingBytes[9] == 0x00))
  {
    if ((incomingBytes[2] == 0x01) && (incomingBytes[10] == 0x05))
    {
      button_pressed = 1;
    }
    else if ((incomingBytes[2] == 0x02) && (incomingBytes[10] == 0x06))
    {
      button_pressed = 2;
    }
    else if ((incomingBytes[2] == 0x04) && (incomingBytes[10] == 0x08))
    {
      button_pressed = 3;
    }
    else if ((incomingBytes[2] == 0x08) && (incomingBytes[10] == 0x0C))
    {
      button_pressed = 4;
    }
  }
  return button_pressed;
}

```
> 0 votes

# Answer
`case` doesn't work like that; it can only switch on a single integer. Are you trying to pattern-match those sequences of bytes? You'll have to use some sort of state machine instead, keeping track of what bytes you've received and where in the expected pattern you are.
> 0 votes

---
Tags: arduino-uno, array, switch
---


# Question
Title: Using malloc() and free() for a stack/linkedlist
I know this question has been asked before, however it was asked two years ago and I have some other constraints to add.

(Previous question here) : Is using malloc() and free() a really bad idea on Arduino?

I understand that dynamically allocating and freeing memory can cause fragmentation, and without an operating system to manage the memory, this fragmentation can reach a point where no memory can be allocated because the current memory is a mess.

That being said, the only memory allocation I plan to do is for a linked list that I am using as a stack. This means that I will only even be adding or removing from one end of the linked list. In the case that the arduino `malloc()` implementation is 'next fit', is it safe to assume that I can use this linked list safely, since the only element I'll be removing is the next one that fit, and everything else will stay where it is?

tl;dr the two questions I'm asking:

Is the arduino `malloc` implementation 'next fit'? Where can I read up on this in detail?

AND

A single stack running in a 'next fit' environment will never cause fragmentation, correct?

# Answer
> 3 votes
On my answer to the question you are referencing, I state that “*If you use the heap like a stack (last in is first out), then it will behave like a stack and not fragment.*” This seems to be exactly your usage pattern, thus you should not fear fragmentation. Of course, the caveat written in Michel Keijzers’ answer applies: you should make sure that no other part of your code, including libraries, is using `malloc()` and `free()`.

Just to give some evidence, the avr-lic documentation provides some implementation details about malloc:

> When allocating memory \[...\] If nothing could be found on the freelist, heap extension is attempted. \[...\] When deallocating the topmost chunk of memory, the size of the heap is reduced.

All this can be seen in action in the source code of malloc() and free(), which is abundantly commented and quite readable.

---

**Edit 1**: From the same section of the avr-libc documentation, we learn about how `realloc()` grows a memory chunk:

> If \[...\] the old chunk is at the top of heap, and the above freelist walk did not reveal a large enough chunk on the freelist to satisfy the new request, an attempt is made to quickly extend this topmost chunk (and thus the heap), so no need arises to copy over the existing data.

Based on this, I would suggest you use an array, rather than a linked list, and use `realloc()` to adjust the size of the array. A linked list of *n* objects of size *m* has a memory cost *n* × (*m*+4): each objects has an overhead of 2 bytes for the linking pointer, plus 2 bytes for `malloc()`'s internal bookkeeping. The cost of an array would be only (*n* × *m*)+2.

In this case, however, it is essential that no other part of your code uses `malloc()`, otherwise `realloc()` could end up allocating a whole new array, which would be very costly.

---

**Edit 2**: I wrote a small test program that randomly grows and shrinks a memory buffer. Running the test on an Uno shows that the allocated memory chunk never changes address even though its size varies wildly.

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

void loop()
{
    static void *p;
    static size_t sz;
    sz = random(max(sz, 22) - 20, min(sz + 20, 1536) + 1);
    p = realloc(p, sz);
    Serial.print((uintptr_t) p);
    Serial.print("  ");
    Serial.println(sz);
}

```

# Answer
> 1 votes
Probably it will not be a problem, since when you free memory, those memory sizes will be equal than the memory size you malloc. E.g. suppose one element of a linked list is 24 bytes, if this is freed, the next time when 24 bytes are requested by malloc, it will use that space.

So my assumption it works when you never use free or malloc, EXCEPT when using it for one single linked list with elements that are always equal size.

However, you have to make sure:

* You do not free memory elsewhere (with different size)
* You do not malloc memory elsewhere (with different size)
* All libraries you use do not call a malloc/free under water.

Also, you can do an easy check by malloc/free and fill one item a lot of times one element (thus adding and removing it), and checking the memory usage is similar (or it does not crash to have a very simple test).

Btw, afaik Arduino pointers use 2 bytes, so this can cause quite some memory. If you use max. 256 elements, consider using indices, but in this case you have to write your own 'linked list' library (e.g. when removing, you have to move all subsequent indices).

# Answer
> 0 votes
There are many implementations of malloc() and AFAIK, none is specified in the standard. So, while you could get lucky and and find that your preferred environment uses a malloc() algorithm compatible with your intended use, your code will not be known portable to another, unspecified, environment, and even a compiler or library revision to your preferred environment could break you code.

You'd be better off to write an allocator that works as you need it to work. Whether you need a linked-list or an array of fixed size blocks to accomplish your stack structure, using a `getStackFrame()`, `freeStackFrame()` pair of functions, written and controlled by you, will avoid some potential nasty surprises.

---
Tags: memory
---


# Question
Title: VisualMicro Can't compile in debug ('Serial' was not declared in this scope) for attiny84a
I was working on a project build initialy from the Arduino IDE to program an attiny84a (without a bootloader) using the board from https://github.com/damellis/attiny

I got an atmel-ice recently and I was trying to debug the arduino sketch using it.

I installed AtmelStudio (because I know it has an GUI debugger) and found VisualMicro that should help me to compile arduino sketch. Unfortunatly as soon as a set the project to debug I got a compilation error :

```
'Serial' was not declared in this scope

```

(I don't have this error in Release mode).

My code doesn't use any serial (because I don't have any pin left), so this was wierd. I still tried to add the SoftwareSerial.h include (just in case) without success.

So I created an empty (I mean with only an empty setup() and loop() methods) and it throw the same error.

I tried to setup different versions of arduino IDE into VisualMicro (1.6.13, 1.8.1, 1.8.5 and 1.9 build 34) without success.

Then after a couple of hours I found the .cpp source generated by VisualMicro and it try to use the member "Serial" for some debugging reason.

I would like an easy way to integrate with arduino (all those library and easy to install library) and to be able to debug as well, what can I look for or do?

Thank

# Answer
> 1 votes
I found how to disable the vMicro debugging, in AtmelStudio open the "vMicro" menu then click the "Debugger" item and make sure the option "Atmel Studio Debugger" is checked.

1) Change the optimization flag to a usefull state (-Og or -O0) in order to NOT have "Unknown identifier" or "Optimized away" when looking at variable.

I tried:

* Put -Og in the project property "Extra flags" (vMicro)
* Before my code I added

```
#pragma GCC push_options
#pragma GCC optimize ("Og")

```

then at the end of my code

#pragma GCC pop\_option

**ANSWER:** I probably fuckup in the rebuild because only the line below is enough (in the .cpp file):

```
    #pragma GCC optimize ("Og")

```
* Replaced -Os in playform.txt (in this case it didn't work at all)

I saw a size changes in my binary (except for the last point), but when running the simulator I still couldn't see any value.

2) Couldn't start a debugging session (When I try to change the debugging device it always crash AtmelStudio, I think it is because the target IC is force to ATSAM3X8E by the vMicro plugin which isn't supported on my computer, and because it isn't supported I can't change the target IC to attiny84a...)

**ANSWER:** When creating the project vMicro read the current board selected (yes before you even can select it) to detect if it has to create a 32 bits or 8 bits project

Also you **MUST** create a project with an .ino (even if it is empty) as the same name as the project in order to be able to compile.

# Answer
> 0 votes
```
'Serial' was not declared in this scope

```

This error is not surprising when compiling for ATtiny84 because in Arduino `Serial` refers to the hardware serial port and ATtiny84 doesn't have one.

But you didn't use `Serial` in your sketch so why should you get this error? The answer is this magical debug feature of Visual Micro that you desire. It turns out that on AVR microcontrollers such as your ATtiny84 all this actually consists of is Visual Micro automatically inserting various Serial.print() statements into your code, just as we always do manually to debug our code in the good old Arduino IDE:

http://www.visualmicro.com/page/User-Guide.aspx?doc=Debugging-Explained.html

So in fact your sketch is attempting to use `Serial` without your knowledge or being able to see it! If you turn off debugging you should no longer get that error.

Visual Micro does allow you to change the debugging output to software serial:

http://www.visualmicro.com/page/User-Guide.aspx?doc=Debugging-With-Different-Ports.html

but since you say you have no pins available that may not be any help.

---
Tags: debugging, atmel-studio
---


# Question
Title: Is it possible to receive a 9 bit protocol on the Arduino Uno with Arduino?
I want send and receive a 9 bit async-serial protocol with 4800 baud on my Arduino Uno, i have read on the specification from the ATmega328P that the uart can do that. My aim is that when my Uart receive the 9th bit as a 1 he must throw a interrupt. On this interrupt i can recognize that this byte was an adress byte. When he receive a zero he sould do nothing spezial, only transmit it as hex-byte over usb to the pc.

My Problem now, i can´t initialize the Uart right because the command Serial.begin(4800, config) is not enough, i must throw the interrupt and translate the data to hex-bytes. My Question can i modify the Serial.begin() source code respectively where can i find the source code for the Serial.begin function?

When there is no possibility to change the code has someone a other option for me to send and receive the 9 bit protocol with an Arduino Uno?

# Answer
If you want to set the UART to 9-bit mode, you will have to set the UCSZ02 bit of the `_ucsrb` register to 1 in `HardwareSerial::begin()`. For example:

```
void HardwareSerial::begin(unsigned long baud, byte config)
{
  // Mostly unchanged... but by the end:
  sbi(*_ucsrb, RXCIE0);
  cbi(*_ucsrb, UDRIE0);
  sbi(*_ucsrb, UCSZ02);  // set 9-bit data mode
}

```

Notice that you do not need to modify the Arduino core library for this: you could set that bit in your `setup()`, right after calling `Serial.begin()`.

Then, in the `HardwareSerial::_rx_complete_irq()` interrupt handler, you will have to read the 9th bit as the RXB80 bit in UCSR0B, **before** reading the low byte from `_udr` (emphasis in the datasheet). For example, you could replace the line `unsigned char c = *_udr;` by:

```
bool is_address = UCSR0B & _BV(RXB80);  // read 9th bit first
unsigned char c = *_udr;                // then the other bits
if (is_address) {
  do_something_with_address(c);
  return;
}

```

where `do_something_with_address()` is the stuff you wanted to do in another interrupt (no need for that, you are already in interrupt context).

It is worth noting that, with an Arduino Uno, you will not be able to do all this while sending data to the PC. This is because the communication with the PC uses the only UART of the ATmega328P.
> 5 votes

# Answer
It sounds like you want some device with a 9-bit protocol to send data to an Arduino, and then the Arduino to forward that data (perhaps in a slightly different format) to a PC.

People who want to connect their Arduino to two serial devices at the same time (and the PC counts as one) generally either:

## Change the hardware to accept multiple serial devices

While the Arduino Uno has only one hardware serial port, the following (and probably many others) have 2 or more hardware serial ports:

("Sending and Receiving 9-bit Frames with Arduino" uses the hardware approach).

## Change the software to accept multiple serial devices

In principle, it's possible to tweak SoftwareSerial to handle 9-bit data. Several people have talked about it
> 1 votes

# Answer
The Max3140 is a very capable USART with built-in full/half-duplex RS-485 drivers that interfaces to a uController via SPI. They are a bit pricey and you would have to make a board, solder, etc..

Another solution would be to dedicate a simple and inexpensive minimal Arduino-compliant board (like a Pro-Mini) to interface with the "main" Arduino via I2C or SPI, and program the Pro-Mini for 9-bit addressing mode and add the RS-485 driver. Pro-Mini or Nano clones are dirt cheap, but it is not even that expensive to use an authentic Arduino product and support their great contributions ;-).
> 1 votes

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


title: Portal gun sound effects and lights

text:
# Question
Title: Portal gun sound effects and lights
I'm building a portal gun from the game Portal and I'm struggling with the wiring for the lights and sound. I've the lights working using the first image from Instructables and adding more LEDs shouldn't be a problem. I'm trying to add the SD card and speaker so when you flick the switch, as well as the lights changing, the firing sound is played. Image 2. everything is wired quite nicely the only change is I'm using pin 10 not 4 on the memory card.

This is my code and it all compiles fine and seems to make sense to me but I'm new to programming.

The lights work but none of the sounds play. I've formatted the SD card and also made sure the .wav files are the right format: mono 8 bit 16000 Hz. I can't work out what's wrong and why I can't get it to play the sounds.

I also have an Adafruit amp just in case it isn't loud enough but not a clue how to wire it in.

```
#include <pcmRF.h>
#include <TMRpcm.h>
#include <SD.h>                       // need to include the SD library
#define SD_ChipSelectPin 10            // using digital pin 10 on arduino uno 328, can use other pins
#include <SPI.h>

void setup()
{
  // put your setup code here, to run once:
  TMRpcm tmrpcm;
  tmrpcm.speakerPin = 9;          //5,6,11 or 46 on Mega, 9 on Uno, Nano, etc

  Serial.begin(9600);
  if (!SD.begin(SD_ChipSelectPin))
  {
    Serial.println("SD fail");
    return;
  }
  tmrpcm.setVolume(6);
  tmrpcm.play("1.wav");
  tmrpcm.play("2.wav");

  //set the switch input, pin 8, as an
  pinMode(8, INPUT);

  //set both the LED pins, pin 5 and 6 as OUTPUTs
  pinMode (5, OUTPUT);
  pinMode (6, OUTPUT);
}

void loop()
{
  TMRpcm tmrpcm;
  int switchValue = digitalRead(8);
  if (switchValue == 1)
  {
    digitalWrite(5, HIGH);
    digitalWrite(6, LOW);
    tmrpcm.setVolume(6);
    tmrpcm.play("4.wav");
  }
  else
  {
    digitalWrite(6, HIGH);
    digitalWrite(5, LOW);
    tmrpcm.setVolume(6);
    tmrpcm.play("5.wav");
  }
}

```

# Answer
At a guess I would say your main problem is you are defining your TMRpcm objects within the setup and loop functions, which means that as soon as that function exits the TMRpcm objects will be disposed of. I.e., it won't work. It may *start* playing a sound in `setup()`, but it will stop (and maybe even crash completely) before you even have a chance to hear it.

Your `TMRpcm` object *must* be declared globally for you to have any hope of making it work.

```
TMRpcm tmrpcm;

void setup() {
    // ....
    tmrpcm.speakerPin=9;
    tmrpcm.setVolume(6);
    tmrpcm.play("1.wav");
}

```

etc.

Another thing to note is that `TMRpcm` plays the sounds *asynchronously*. That is, it doesn't wait while it plays the sound, so if you play one sound and then another sound the second sound will start before the first one has even begun playing, so you'll never hear the first one. Instead, if you want to play sounds sequentially, you should for the first sample to finish using something like:

```
while (tmrpcm.isPlaying()) {
    delay(1);
}

```

which will stop your sketch running until the last sound has finished. Including the `delay(1)` is a good idea since it allows `yield()` to execute allowing anything that needs it to run (not really a problem on an Uno, but on things like an ESP8266 it's absolutely critical or you get a watchdog timeout).
> 2 votes

---
Tags: led, sd-card, wires, speaker
---


# Question
Title: This logic level converter does not want to work
I got this logic level converter to be able to use my lcd but I can't figure out how to get it to work, the problem is that the current is not passing through. This is the model: TXS0108E

Any help is appreciated.

\[EDIT\]

A few Combinations that I have tried:

And I tried to swap the voltages, same wiring as in the pictures but 3.3v instead of 5v and vice versa.

# Answer
> 5 votes
The TSX0108 doesn't magically provide you with a regulated voltage. You have to provide the voltage, the TSX0108 merely switches it.

As you can see from the datasheet, the basic wiring is:

In the circuit above the 1.8V connection is your 3.3V connection, and the 3.3V is your 5V connection.

**You must provide both the 3.3V and 5V power sources.**

---
Tags: arduino-uno, voltage-level
---


# Question
Title: Meaning of part number suffix on top of atmega2560 chip
I have been working on creating a stand alone atmega2560 arduino. When trying to program it with a serial adapter using the rx and tx pins nothing was happening. After a lot of debugging I found the problem was with the chip.

I found that the ones that worked said atmega2560 16AU 0721, the ones that did not work said Atmega2560 16AU 1241. When looking on eBay, i noted that the Atmega2560 16AU comes with many different versions of those last four numerals, does anyone know what the last four digits on top of the atmega2560 16AU mean?

# Answer
> 0 votes
The last four digits are a date code - the date of manufacture.

It's in the form `YYWW` where `YY` is the last two digits of the year, and `WW` is the week number.

So `0721` is the 21st week of 2007, and `1241` is the 41st week of 2012.

# Answer
> 1 votes
The data sheet (or supplemental product-line documentation) will specify the formal package marking codes, but for an ATmega, the `16AU` is part of the variant specification but the following would appear to be date or lot codes.

These are probably not your problem.

More likely, the chip you are trying to interact with via the serial port

* **does not have a bootloader flashed (normally they are sold blank)**
* has a bootloader which requires a different baud rate
* is fused for a clock source you are not providing
* has the brownout detector set lower than the supply you are providing
* is improperly or incompletely soldered
* is damaged

While there was the infamous case of Sparkfun being sold a reel of power supply chips falsely marked as ATmega328's, this is still a relatively unlikely possibility compared to the more likely ones above, especially the simple lack of a bootloader. And a date code is no proof of authenticity - though if you ended up co-mingly inventory from various sources/purchases, it might help you with preliminary sorting them.

---
Tags: serial, arduino-mega, atmega2560
---


# Question
Title: "Soft WDT reset" stack error: RFID-RC522 with NodeMCU
I have been all over the internet to try and find a solution to this, but after one solid week of intense Google searching I have come up with nothing.

**What I'm trying to accomplish:**

I am simply trying to use the RFID-RC522 NFC reader on an NodeMCU development board (built in ESP8266) with the mfrc522 library.

**Problem:**

Upon initiating the mfrc522 library, reaching the line `mfrc522.PCD_Init();` the Serial outputs the following "error":

```
Soft WDT reset

ctx: cont
sp: 3ffefa10 end: 3ffefc40 offset: 01b0

>>>stack>>>
3ffefbc0:  00241001 00000001 3ffeec20 40106895
3ffefbd0:  00000002 3ffee9d8 3ffee9f4 40202794
3ffefbe0:  402010b2 00000001 00000032 402010a7
3ffefbf0:  3fffdad0 00000010 3ffee9d8 4020290d
3ffefc00:  402010b2 3ffee9d8 3ffee9d8 40202a01
3ffefc10:  feefeffe 00000000 3ffeebec 40202080
3ffefc20:  feefeffe 00000000 3ffeec08 40203e08
3ffefc30:  feefeffe feefeffe 3ffeec20 40100108
<<<stack<<<
R+⸮⸮⸮

```

I found a tool that can translate the error EspExceptionDecoder, translated error:

```
Decoding 10 results
0x40106895: __digitalWrite at C:\Users\my_user\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.4.0\cores\esp8266/core_esp8266_wiring_digital.c line 84
0x40202794: MFRC522::PCD_ReadRegister(MFRC522::PCD_Register) at C:\Users\my_user\Documents\Arduino\libraries\MFRC522\src/MFRC522.cpp line 1141
0x402010b2: delay at C:\Users\my_user\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.4.0\cores\esp8266/core_esp8266_wiring.c line 54
0x402010a7: delay at C:\Users\my_user\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.4.0\cores\esp8266/core_esp8266_wiring.c line 51
0x4020290d: MFRC522::PCD_Reset() at C:\Users\my_user\Documents\Arduino\libraries\MFRC522\src/MFRC522.cpp line 1141
0x402010b2: delay at C:\Users\my_user\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.4.0\cores\esp8266/core_esp8266_wiring.c line 54
0x40202a01: MFRC522::PCD_Init() at C:\Users\my_user\Documents\Arduino\libraries\MFRC522\src/MFRC522.cpp line 1141
0x40202080: setup at C:\Users\my_user\OneDrive\Arduino\projekter\RFID_DumpInfo_test/RFID_DumpInfo_test.ino line 53
0x40203e08: loop_wrapper at C:\Users\my_user\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.4.0\cores\esp8266/core_esp8266_main.cpp line 57
0x40100108: cont_norm at C:\Users\my_user\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.4.0\cores\esp8266/cont.S line 109

```

When the `mfrc522.PCD_init();` line is commented out the stack-error does *not* appear. Reading the NFC tags has worked before on the NodeMCU unit, and I sometimes stubmled upon this error when adding *one* simple line like `var1 = var2;` somewhere in the loop, but now the error is there constantly, even with code that once worked - however I *did* change the pin-loadout, and I suspect that this is the problem.

**What I have tried:**

* With the configurable pins I have tried most combinations I could think of, trying both the SS and the RST in every available pin.
* this Github example suggets
* this instructables tutorial.
* 3 different RFID-RC522 modules (same model)
* 2 different NodeMCU units (same model)

**Pin layout:**

My pin layout for the RFID-RC522 module is as follows;

* **SDA (SS)**: D4
* **RST**: D3
* **SCK**: D5
* **MOSI**: D7
* **MISO**: D6
* **GND**: GND
* **3v3**: 3v3

**Arduino project info:**

* Arduino IDE 1.8.5
* Latest MFRC522 from the Library Manager
* **Board:** NodeMCU 1.0 (ESP-12E Module)

**Code:**

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

#define SS_PIN          D4
#define RST_PIN         D3

MFRC522 mfrc522(SS_PIN, RST_PIN);

void setup() {
    Serial.begin(9600);
    delay(100);
    SPI.begin();
  delay(100);
    mfrc522.PCD_Init();
    mfrc522.PCD_DumpVersionToSerial();
    Serial.println(F("Scan PICC to see UID, SAK, type, and data blocks..."));
}

```

I've been on this issue for days now, and my Google searches tell me that I'm not the only one who has had this problem before. Any input is very welcome.

# Answer
I have come to the conclusion that using RFID with NodeMCU is not going to work - I can't confirm this, but I'm pretty sure the two libraries (ESP8266 and mfrc522) have some complications caused by one another.

A good workaround is using the TX and RX pins to communicate from an Arduino Nano which has the RFID reader to a NodeMCU board - this way you can send the NFC data to your WiFi board without complications.
> 1 votes

# Answer
can you also try to increase the serial boud rate to fe. 115200 instead of 9600? In some cases I had some issues with 9600, because some buffers were not cleared fast enough and forces some WDT resets.

Cheers, Jorgen
> 3 votes

---
Tags: arduino-ide, rfid, nodemcu
---


title: Arduino Nano wih mfrc522 warning error

text:
# Question
Title: Arduino Nano wih mfrc522 warning error
**UPDATE**

I have managed to get rid of the `WARNING: Communication failure, is the MFRC522 properly connected?`. Unfortunately, that did not fix the firmware error it now says `0x80`. I have now also tried using different IDEs from arduino in the hopes of fixing this, still nothing. The connection error between the reader and the arduino has come back as well.

Furthermore...

```
*****************************
MFRC522 Digital self test
*****************************
Firmware Version: 0x92 = v2.0
-----------------------------
Only known versions supported
-----------------------------
Performing test...
-----------------------------
Result: DEFECT or UNKNOWN

```

would this now mean that my device is a defect?

Also, that version has gone back to showing `unknown` and the other hexadecimal codes.

I have just bought the parts. The arduino nano v3 and the MFRC522 based RFID reader. I have followed the typical pin layout after downloading the library from arduino. When I go to test one of the examples I get a warning within the arduino serial monitor :

```
Firmware Version: 0xFF = (unknown)
WARNING: Communication failure, is the MFRC522 properly connected?
Scan PICC to see UID, SAK, type, and data blocks...

```

I try to scan one of the existing cards but nothing happens. It either stats that it is version `0xFF` or `0x0`. I am new with this and this is my first 'project'. the pins are defined.

I have 3.3V on the reader to 3v3 on the arduino I have RST on the reader to D9 on the arduion I have GND on the reader to GND on the arduino (on the same side as the 3v3 is ) I have MISO on the reader to D12 on the arduino I have MOSI on the reader to D11 on the arduino I have SCK on the reader to D13 (on the same side as the 3v3 is) I have SDA on the reader to D10 on the arduino

The code I am using is from the arduino library manager:

```
  /*
  * --------------------------------------------------------------------------------------------------------------------
  * Example sketch/program to test your firmware.
  * --------------------------------------------------------------------------------------------------------------------
  * This is a MFRC522 library example; for further details and other examples see: https://github.com/miguelbalboa/rfid
  *
  * This example test the firmware of your MFRC522 reader module, only known version can be checked. If the test passed
  * it do not mean that your module is faultless! Some modules have bad or broken antennas or the PICC is broken.
  * NOTE: for more informations read the README.rst
  *
  * @author Rotzbua
  * @license Released into the public domain.
  *
  * Typical pin layout used:
  * -----------------------------------------------------------------------------------------
  *             MFRC522      Arduino       Arduino   Arduino    Arduino          Arduino
  *             Reader/PCD   Uno/101       Mega      Nano v3    Leonardo/Micro   Pro Micro
  * Signal      Pin          Pin           Pin       Pin        Pin              Pin
  * -----------------------------------------------------------------------------------------
  * RST/Reset   RST          9             5         D9         RESET/ICSP-5     RST
  * SPI SS      SDA(SS)      10            53        D10        10               10
  * SPI MOSI    MOSI         11 / ICSP-4   51        D11        ICSP-4           16
  * SPI MISO    MISO         12 / ICSP-1   50        D12        ICSP-1           14
  * SPI SCK     SCK          13 / ICSP-3   52        D13        ICSP-3              15
  */

 #include <SPI.h>
 #include <MFRC522.h>

 constexpr uint8_t RST_PIN = 9;     // Configurable, see typical pin layout    above
 constexpr uint8_t SS_PIN = 10;     // Configurable, see typical pin layout    above

 MFRC522 mfrc522(SS_PIN, RST_PIN);  // Create MFRC522 instance

 /**
  * Check firmware only once at startup
  */
 void setup() {
   Serial.begin(9600);   // Initialize serial communications with the PC
   while (!Serial);      // Do nothing if no serial port is opened (added for    Arduinos based on ATMEGA32U4)
   SPI.begin();          // Init SPI bus
   mfrc522.PCD_Init();   // Init MFRC522 module

Serial.println(F("*****************************"));
Serial.println(F("MFRC522 Digital self test"));
Serial.println(F("*****************************"));
mfrc522.PCD_DumpVersionToSerial();  // Show version of PCD - MFRC522 Card Reader
Serial.println(F("-----------------------------"));
Serial.println(F("Only known versions supported"));
Serial.println(F("-----------------------------"));
Serial.println(F("Performing test..."));
bool result = mfrc522.PCD_PerformSelfTest(); // perform the test
Serial.println(F("-----------------------------"));
Serial.print(F("Result: "));
if (result)
  Serial.println(F("OK"));
else
  Serial.println(F("DEFECT or UNKNOWN"));
Serial.println();
 }

 void loop() {} // nothing to do

```

# Answer
You are using SPI comm. The code is fine too. Usually this "communication failure" happens due to wrong pin connections. Say for eg. If MOSI and MISO are interchanged. Check all connections, ground and VCC connections once more. I have also seen that soldering the pins of MFRC522, instead of simply connecting by wire has solved this issue most of the time. Another work around is repeatedly calling PCD\_init() function even after failing result inside loop() . And see whether its working. If none of these worked, hard luck. I think its firmware issue or defective board.
> 4 votes

---
Tags: rfid
---