# Question
Title: What is the right way to query an I2C device from an interrupt service routine?
The ADXL345, for example, requires that interrupts are responded to by querying the `INT_SOURCE` (interrupt source) register. In example code for the SparkFun ADXL345 Arduino Library, there is code that looks like:

```
void ADXL_ISR() {
  // getInterruptSource clears all triggered actions after returning value
  // Do not call again until you need to recheck for triggered actions
  byte interrupts = adxl.getInterruptSource();

  // Free Fall Detection
  if(adxl.triggered(interrupts, ADXL345_FREE_FALL)){

```

However, under the covers `adxl.getInterruptSource()` is sending an I2C message and receiving a response. This seems to be a bad idea in an interrupt service routine (ISR).

A possible option seems to be to turn on interrupts prior to calling `adxl.getInterruptSource()`, however there is much advice about not doing this (such as, Nick Gammon's informative post). I've managed to get it to work with something of the form:

```
void setup() {
  attachInterrupt(digitalPinToInterrupt(INT_PIN), isr, LOW);
  ...
}
void isr() {
  detachInterrupt(digitalPinToInterrupt(INT_PIN));
  interrupts();
  byte interrupts = adxl.getInterruptSource();
  ...
  attachInterrupt(digitalPinToInterrupt(INT_PIN), isr, LOW);
}

```

This seems to work but I'm worried I'm missing something. Any suggestions?

EDIT: Thanks for the answers that suggest polling, however I am using a MKR1400 and wish to minimise power consumption by putting the processor into a sleep state - only waking up to process the relatively rare "activity" or "free fall" events. As pointed out by @Majenko, a combination of sleeping and polling might be used. So this really just leaves the question of *why* is the above a bad idea.

# Answer
Just because a pin is called "interrupt" doesn't mean that you have to read it using an interrupt input. The INTx pins of the ADXL345 are simple "level" outputs. All the time there is an "interrupt" pending (a signal from the ADXL345 that something has happened) the corresponding INT pin is held LOW. It remains LOW until the interrupt has been handled by your code.

It's not something that is very brief - it's something that persists as long as you need it to.

You can just read the INTx pins with normal `digitalRead()` from within your `loop()` function (polling). Unless you *really* need to respond *right now* to an event on the ADXL345 there is no need to use an interrupt input.
> 9 votes

# Answer
Majenko's answer is useful — you can simply forego the use of interrupts for this and poll the pin directly in your main loop. Especially on AVR where the external pins are exposed as registers which can be read as fast as main memory this is a reasonable approach. But what if you really want the code to be "interrupt-fast" without writing code that might deadlock an ISR handler? Given the case of a fall or impact sensor, latency might be a genuine issue. Well, there are some things you can do.

First, structure your code so that you never go too long without polling the pin. That means that every bit of code needs to either return to the main loop within an acceptably short period of time, or else needs to take on the job of periodically polling the pin itself. Large compute tasks should have polls sprinkled into them, or be broken into subtasks that can be run by a state machine in the main loop. Long delays should be rewritten in the form

```
start = micros();
while (micros() - start < howLong) {
  // poll the ADXL interrupt
}

```

or, again, avoided entirely by queuing up work for the main loop to run later, instead of calling `delay`.

Second, consider using direct port access for the polling. A check like `if (PORTB & (1<<3))` compiles down to a bare couple of instructions, and costs 2 cycles if the interrupt isn't actually asserted (which will be the usual case). Doing `if (digitalRead(port))` does a call to a function which takes around 25 times as long. It's still only a few microseconds, but if you've taken the advice of the previous step to poll as frequently as possible to minimize latency, then you don't want all of those microseconds to add up and impact the performance of other code.

Lastly, a technique that doesn't make a lot of sense for *this* scenario, but could be applicable if you were running on a system other than an AVR-based Arduino, or if you wanted to react to some interrupt *other* than a level-triggered pin interrupt: you have an ISR that doesn't do any real work, but instead sets a global `volatile` variable to true and then immediately returns. Then in your main code, instead of polling the port directly, you check the value of that variable. If it's true, you set it to false and then run your "interrupt handler" code. The handler runs shortly after the interrupt triggers, but it's run in an interrupts-on context where it's safe to do slower operations or operations that require timer interrupts to work. This is equivalent to the old Linux concept of "bottom halves".
> 5 votes

# Answer
"What is the right way to query an I2C device from an interrupt service routine?"

The right way is to **NOT** query an I2C device from in ISR. Interrupt service routines should be **very** fast to execute. (people advise going as far as avoiding `digitalWrite()` and `digitalRead()` function calls and using port registers directly, since those functions are a little slow. Anything done on a serial line is, by definition, not fast. It takes multiple milliseconds to read or write a few characters from a serial port, which is an eternity.)

When the Arduino services an interrupt it stops doing everything else, including handling other interrupts. Your timers will stall, other sensor data will be missed, any other serial communications that are in progress when the interrupt triggers will get errors, etc.

JUST DON'T DO IT.
> 2 votes

---
Tags: i2c, interrupt, accelerometer, isr
---


# Question
Title: Can we call GPRS HTTP request asynchronously in Arduino?
Usually GPRS modules (SIM800,900, A6, etc) that used with arduino are called in synchronous way in HTTP (GET/POST) request. It takes more than 10 seconds in most times and this makes the system very slow. Is there a way to use them (libraries or the module) asynchronously (or is there any alternatives) and perform these request in background while main business is being done?

# Answer
> 1 votes
Sure there is. All you're doing is reading and writing serial data. All you have to do is learn how to do that without blocking.

Most code I see bandied around is of the form:

```
Send AT command
Delay for numerous seconds
Read and discard anything that might be there
Send another AT command
Delay for more seconds
Read and discard anything that might be there
... etc ...

```

That is completely the wrong way to do things.

Instead you should be using non-blocking reading to look for an actual OK response from the AT commands that you have sent and use that to progress through the different stages of a Finite State Machine.

Some reading resources from my blog:

---
Tags: http, threads
---


# Question
Title: how does c++ understand which function must to use?
in this code:

```
    void AdptSendReply(const char* str)
{
    string s(strlen(str) + 2);
    s = str;
    AdptSendReply(s);
}

void AdptSendReply(const string& str)
{
    string s(str.length() + 2);
    AdptSendReply(s); // use the next one
}

void AdptSendReply(string& str)
{
    if (AdapterConfig::instance()->getBoolProperty(PAR_LINEFEED)) {
        str += "\r\n";
        AdptSendString(str);
    }
    else {
        str += "\r";
        AdptSendString(str);
    }
}

```

i think c++ use of overloading ability.but how it can recognize which of the two functions "void AdptSendReply(string& str)" or "void AdptSendReply(const string& str)" must use?!

# Answer
> 1 votes
Calling overloading function triggers a process called *overload resolution*, which uses argument types to select the proper function to call

* If you supply an lvalue argument of type `string`, the compiler will call `void AdptSendReply(string& str)` version.

```
string s = "hello";
AdptSendReply(s); // calls 'string& str' version

```
* If you supply an lvalue argument of type `const string`, the compiler will call `void AdptSendReply(const string& str)` version.

```
const string s = "hello";
AdptSendReply(s); // calls 'const string& str' version

```
* If you supply an rvalue argument, the compiler will call `void AdptSendReply(const string& str)` version.

```
AdptSendReply(string("hello")); // calls 'const string& str' version

```

And so on. The full set of rules that govern overload resolution is quite extensive, especially when the context involves implicit conversions.

---

It is not clear what you mean by "must use". Normally, overloaded functions will do the same thing (functionality-wise), meaning that you are not supposed to worry about which function to use. Just call it with the argument you have available and the compiler will select the proper function to call.

Also, what is `string`? How are we supposed to know that? Without knowing it, your question make little sense.

# Answer
> 0 votes
The compiler decides which function to use based on the variable type information. Imagine you write

```
str += "test";

```

If you declare `str` as a constant, the above line will throw an error. So if you write `AdptSendReply(str)` instead, the compiler will call the const function. Likewise, if you declare `str` as a mutable variable, the above line will compile fine, and, should you call `AdptSendReply(str)`, the compiler will use the non-const function.

---
Tags: c++
---


title: Timer 1 COMPA ISR - default behaviour?

text:
# Question
Title: Timer 1 COMPA ISR - default behaviour?
I'm creating a LCD frequency generator.

When `TIMER1` reaches a set value, it's set to toggle Pin 9 (via `OC1A`).

Accidentally, I left the `TIMER1` "interrupt on compare match A" enabled, but never defined the `TIMER1_COMPA_vect` interrupt vector.

This made the Uno reset itself - but not running through the bootloader, just the program part - whenever `TIMER1_COMPA_vect` would've been called.

Once I defined the ISR, even without it having any content, it would run as expected.

**Is there a default content for ISRs, which resets the device / starts just after the bootloader? Shouldn't the compiler detect a completely missing ISR?**

# Answer
The compiler cannot detect a missing ISR since it is very difficult, in the general case, to tell whether any particular interrupt-enable bit has been set by the program.

The avr-libc library does indeed provide a “catch-all” ISR and, as stated by the manual,

> the default action is to reset the device by jumping to the reset vector.

If you don't like this behavior, you can override this catch-all with your own, as explained in the manual (search for “Catch-all interrupt vector”).
> 3 votes

---
Tags: interrupt, atmega328
---


title: Current consumption of a buzzer

text:
# Question
Title: Current consumption of a buzzer
I want to use the buzzer KPEG2000 in my Arduino application. I would like to know if a GPIO can directly drive this buzzer, without destroy the uC (a GPIO can deliver 40 mA max). In the datasheet, we can find the current consumption under 12 volts (40 mA), but if I decrease the driving voltage to 5V, will this buzzer use more or less then 40 mA ?

https://docs-emea.rs-online.com/webdocs/07a8/0900766b807a8e16.pdf

I already tried to make this buzzer work on an Arduino, and it works. But I would like to know if plugging this buzzer directly to the Arduino will not destroy it.

# Answer
> 1 votes
In the datasheet I read 14 mA @ 12V, which is below the recommended current of a GPIO pin of 20 mA.

Note that 40 mA for a GPIO pin is the max current, recommended is 20 mA. But 14 mA is way less.

To see if it changes for 5V, try connect it without an MCU (directly to a 5 V adapter/USB/breadboard power) and measure the current using a multimeter.

In case it uses more than 20 mA @ 5V, than use a transistor/mosfet to drive the buzzer.

In case you want to have the buzzer at full power, connect a VCC 5V power rail pin to a boost converter, which is controlled by a transistor/mosfet controlled by a GPIO pin.

Thus

```
Arduino VCC 5V -> Boos converter to 12 V -> Transistor/Mosfet -> Buzzer -> GND
                                                 ^
                                           Arduino GPIO pin

```

# Answer
> 0 votes
If this is a piezo buzzer they typically work over a wide range of voltages and use very little current. I've seen them with specs for an input voltage ranging from 3 to 18v.

You could likely drive a piezo buzzer directly from a GPIO line without problems.

---
Tags: arduino-uno, current, buzzer
---


title: D1 Robot... lights up but nothing

text:
# Question
Title: D1 Robot... lights up but nothing
I have the Arduino shield described here, I have run the example code compiled to the device, both v1 and 1.1 example, and it shows nothing whatsoever on the screen.

https://www.dfrobot.com/wiki/index.php/Arduino\_LCD\_KeyPad\_Shield\_(SKU:\_DFR0009)

Is there a special trick to initializing this or did I yet again get a lemon that will not display anything?

# Answer
> 0 votes
Like many cheap online shields, this one is a dud, in fact it looks like extended use would fry it if it did work - according to test code this chip is bad. https://forum.arduino.cc/index.php?topic=96747.0

# Answer
> 1 votes
I got one of the D1 Robot version 1 from AllElectronic and I had to adjust the contrast before I could see the words on the display.

---
Tags: arduino-uno, lcd
---


# Question
Title: Would it be feasible to build an arduino that takes 12v on/off signals from a vehicle diagnostic port (1984 pre-OBD)?
The vehicle is an AMC eagle, they come with a diagnostic port I have made a diagnostic tool that lights led lights when signals turn on and off, but it has to be wired in and is bulky. I am wondering if it would be possible to have an arduino plugged in and running off the 12v battery supply (with step-down to 5v) and have it catch the signals and send them over Bluetooth to a computer. Does this sound like it is within the scope of an arduino or am I asking too much? Or is there a better and easier way to do this?

# Answer
You can step down 12V to 5V with resistor dividers, or drive transistor base with 12V and let the collector pulldown an input with pullup resistor to signal an active signal (like an optocoupler, but without the slow optical part). Arduino reading the inputs and sending via bluetooth to something else is pretty straightforward, perhaps send only when a change from 0 to 1, and 1 to 0, on any input is sensed. Check Adafruit.com for bluetooth modules that are easy to use.
> 0 votes

# Answer
Yes, it is possible. The 12v signals would have to be conditioned for the Arduino to receive them (0 - 12v or maybe 0 - 12-14.5v?). Then the Bluetooth side would be the same as any other Bluetooth data transmission.

So your question comes down to: Is this a fun project that's worth the effort you put into it for the learning experience? Or is this meant to answer a need, and the most practical means to that end is the best means?

Ex: I wanted to know how long / what kind of driving would it take to get my car's oil to full temp (~100C), starting from dead-cold in the winter? I had a thermo-logger I'd built for another experiment, so I taped a sensor to my oil filter (yeah, not the greatest, but quick and dirty) and lead a cable outside the hood, through the driver's window, to the experimental PC board on my dash-board. It wasn't a *miserable* failure but nothing to be proud of, either.

The solution I settled on was a USD$12.00 OBD port sender and an iPhone app. The results were much better, and while I didn't have the built-it-myself experience, I got the data and the answers I needed.
> 1 votes

---
Tags: project
---


# Question
Title: how to apply a timer to an analogWrite command for Arduino
I have 2 sketches that control a fan using Arduino UNO, that I try to combine. The 1st is a timer, that turns a pin ON and OFF for a determined period of time. The pin signal drives a MOSFET that in turn switches a small fan ON and OFF. Since I need to control the speed of the motor, I would rather use the PWM control, however I am not sure how I can apply the timer since analogWrite command refers to a pin and value. Thanks

timer code:

```
const byte relayPin = 6; // relay module on pin 6
const byte monitorPin = 13; // builtin LED output
const unsigned long interval_1 = 1000UL * 15, interval_2 = 1000UL * 15; // ON timer + OFF timer in milliseconds
unsigned long currentMillis, previousMillis = 0;

void setup() {
  // put your setup code here, to run once:
  pinMode(relayPin, OUTPUT);
  digitalWrite(relayPin, HIGH); // relay OFF
  pinMode(monitorPin, OUTPUT);
  digitalWrite(monitorPin, LOW); // LED off
}

void loop() {
  // put your main code here, to run repeatedly:
  currentMillis = millis();
  if (currentMillis - previousMillis >= interval_1)
  {
    digitalWrite(relayPin, LOW); // relay ON
    digitalWrite(monitorPin, LOW); // LED on
  }
  if (currentMillis - previousMillis >= (interval_1 + interval_2))
  {
    digitalWrite(relayPin, HIGH); // relay OFF
    digitalWrite(monitorPin, HIGH); // LED off
    previousMillis = currentMillis; // reset
  }

```

PWM code:

```
int PWMControl= 6;
int PWM_Input = A0;

int PWM_Value = 0 ;

void setup() {
  pinMode(PWMControl, OUTPUT);
  pinMode(PWM_Input, INPUT);
}

void loop()
{
  PWM_Value = analogRead(PWM_Input);
  PWM_Value = map(PWM_Value, 0, 1023, 0, 255);
  analogWrite(PWMControl, PWM_Value);
}

```

# Answer
If I understand correctly, this is what you want to do:

1. Fan + led off for 15s
2. Fan on (speed determined by A0) + led on for 15s
3. Repeat

clearly defining your goal in english can help with coding, so I hope I guessed right.

here's my suggestion for your code

```
 const byte controlPin = 6; // MOSFET on pin 6
 const byte monitorPin = 13; // builtin LED output
 const unsigned long interval_1 = 1000UL * 15, interval_2 = 1000UL * 15; // ON timer + OFF timer in milliseconds
 unsigned long currentMillis, previousMillis = 0;
 int PWM_Input = A0;
 int PWM_Value = 0 ;

 // setting pin direction and default state
 void setup() {
   pinMode(controlPin, OUTPUT);
   digitalWrite(controlPin, HIGH); // MOSFET OFF
   pinMode(monitorPin, OUTPUT);
   digitalWrite(monitorPin, LOW); // LED off
 }

 // run fan for a while, then stop fan for a while
 void loop() {

   currentMillis = millis();

   //fan on, led on, both signals active low
   if (currentMillis - previousMillis >= interval_1){
       PWM_Value = analogRead(PWM_Input);
       PWM_Value = map(PWM_Value, 0, 1023, 0, 255);
       analogWrite(PWMControl, PWM_Value);
       digitalWrite(monitorPin, LOW);
   }

   //fan off, led off, reset timing
   if (currentMillis - previousMillis >= (interval_1 + interval_2)){
      digitalWrite(controlPin, HIGH); // MOSFET OFF
      digitalWrite(monitorPin, HIGH); // LED off
      previousMillis = currentMillis; // reset
   }
 }

```

There are still issues I can with this code:

1. You did not tell us what type of MOSFET you are using, so I can't tell if it is actually active low
2. I believe that the LED on most arduino boards (pin 13) is active high, so that's probably wrong
3. Don't forget comments. I find comments more useful for a block of code than for a single line, but you can do both if you want ;)
4. I find your code convoluted regarding millis logic, for me it would be more logical to have something along the lines of:

```
 current = millis()-previous
 if current < interval1
    fan off
 elseif current < inteval1+interval2
    fan on
 else
    previous = millis()

```

It would be more readable for a human, the result on the arduino would be similar.
> 1 votes

# Answer
Don't think of what you have as a "timer". That's not what it really is. What you have is a loop function that repeats itself thousands of times per second and an if statement that asks "is it time to do this yet". So if you want to use analogWrite instead of digitalWrite when it is time to do that thing then use analogWrite instead. It doesn't change your timing setup one bit. Just replace the digitalWrite calls with analogWrite calls. If you want to read your pot at the same time then put that in there as well. Basically everything inside the block of code controlled by that if statement is going to happen every time that interval passes no matter what it is that you put there. If you want something to print every interval then you could put a print statement in there. If you want it to call some custom function every interval then call that function in there. There's nothing special about that way of timing that only works with digitalWrite.
> 0 votes

---
Tags: programming-sequence
---


# Question
Title: If I try to pause my loop function my output screen starts printing trash
I am working of on a Wemos R1 D2 board with VL53L0X Laser Sensor. I need to stop my program after calculating an average of 50 readings but as soon as I try while(1) { } or any other method my output produces garbage.

```
void loop()
{
  float initial=0,inside=0,outside=0,sum=0,x;
  for (int i = 0; i < 10; i++) {
    x = sensor.readRangeSingleMillimeters();
    if (sensor.timeoutOccurred()) { Serial.print(" TIMEOUT"); }
    sum = sum + x;
    Serial.print("Initial Reading: ");
    Serial.println(sum);
  }
  while(1) {};
  Serial.flush();
}

```

# Answer
> 3 votes
ESP8266 based boards do not like being tied up for too long without being able to service any WiFi based tasks.

Having a while(1){} effectively ties up the processor indefinitely. This causes a watchdog reset, and the serial port will print garbage (actually it's the chip's boot message). You don't show your Serial setup.

The ESP8266 can service its WiFi tasks at the end of loop(), during a delay() or if the yield() function is called.

I would suggest adding a delay() or yield() to your while block will fix the problem.

# Answer
> 0 votes
There is nothing immediately obviously wrong with your program, but what happens if you do it a bit more "normally"?

By normally, just do nothing after the 10th (or 50th) time through, instead of the infinite loop you are currently executing.

```
int cntr = 0;
float initial=0,inside=0,outside=0,sum=0,x;

void loop()
{
  if (cntr < 10 /* or 50 */) {
    cntr++;
    x=sensor.readRangeSingleMillimeters();
    if (sensor.timeoutOccurred()) {
      Serial.print(" TIMEOUT");
    }
    sum=sum+x;
    Serial.print("Initial Reading: ");
    Serial.println(sum);
  }
}

```

My reason for suggesting this is that when I tried an ESP board, there was an enourmous amount of bloatware included in the generated code. There may well be other stuff that needs to happen in the background between calls to the loop method. But you are preventing that from happening with your infinite loop.

However, clearly something is happening in the background because your infinite loop is somehow generating, as you put it, "garbage".

You did not publish the details of sensor library or its methods. Could there be any side affects there? What pins does the sensor connect to?

---
Tags: arduino-ide
---


# Question
Title: XBee using Serial rather than SoftwareSerial--how to fix
So I have a couple of XBee S2Cs, and I have configured them properly--they can in fact communicate with each other. I am using them with Arduino Unos and this shield: https://store.arduino.cc/usa/shield-xbee-without-rf. I am attempting to interface with the XBees with SoftwareSerial, but for whatever reason, they are instead using just regular Serial. Anything I put on the SoftwareSerial appears to be ignored entirely, while anything I put on Serial appears in my serial monitor and also is transmitted to the other XBee. I have this code for transmitting:

```
#include <SoftwareSerial.h>
SoftwareSerial xbee (2, 3);
void setup() {
    Serial.begin(9600);
    xbee.begin(9600);
}

void loop() {
    xbee.println("hello");
    Serial.println("world");
    delay(5000);
}

```

And this code for receiving:

```
#include <SoftwareSerial.h>

SoftwareSerial xbee(2, 3);

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

void loop() {
    if (xbee.available() > 0) {
        Serial.println("xbee: " + xbee.readString());
    }
    else {
        Serial.println("no xbee data");
    }

    if (Serial.available() > 0) {
        Serial.println("serial: " + Serial.readString());
    }
    else {
        Serial.println("no serial data");
    }
    delay(5000);
}

```

Every 5 seconds, I get this output through the serial monitor on the transmitting side:

```
world

```

and this on the receiving side:

```
no xbee data
serial: world

```

I also get the string `world` when I connect a third XBee to my XCTU console.

So I have a couple of questions:

First off--how is this happening? I'm no Arduino expert, but as far as I can tell from what I've read, if the XBee is capturing my serial output, then I shouldn't also be able to see it in the serial monitor.

Second off--how can I get the SoftwareSerial to work? I could theoretically just use Serial forever, but that would make debugging way more trouble, and would probably create a code-maintenance headache later. If I had to guess, I might need to use different pins for my shield, but I have no idea how to find out what pins are the right ones to use.

Update: Based on what I've seen and read, it looks like the particular combination of the Uno with this shield leaves me with no options but to use the hardware serial. A different shield or Arduino board would grant me options to separate my serial output from my xbee output, but that does not appear to be an option here.

# Answer
> 1 votes
To debug the sketch with SoftwareSerial, remove the jumpers from JP2 and JP3 and wire (with jumper wires) the middle pin of JP2 and JP3 to SoftwareSerial pins of your choice.

Middle pin of JP2 is TX of the Xbee so wire it to RX of SoftwareSerial. Middle pin of JP3 is RX of XBee.

On that particular board, JP2 is the jumper closer to the middle of the board, while JP3 is closer to the edge.

shield's schematics

# Answer
> 1 votes
You will need an xbee breakout board Xbee breakout board or this one from Sparkfun to do that...

Make sure you check if the board comes with headers as they are **not always included**. Note also that the xbee socket is not a standard size - which is why you need the breakout board - it converts the XBee pin to a standard size. Here are the 2mm headers required for xbee and regular 0.1" headers required for connection to a breadboard or jumper wires etc.

*Actually*, I used leonardo for the very reason that you asked about in your question. Leonardo has two serial ports, one is for the usb connection you are familiar with on Uno, **but** it is not connected to pins 0 and 1.

The other is a completely independent serial port that is wired to pins 0 and 1 on leonardo.

So on Leonardo, you can do `Serial.println("Debug msgs");` and `Serial1.println("xbee messages");` (note the digit 1 in Serial**1**). Of course other platforms such as Mega also can be used in the same way.

I am assuming you already have some sort of an XBee shield that allows you to plug the XBee directly into your Uno. The beauty of the Leonardo is that you can continue to use that sheild. The XBee will "automatically" be connected to Serial1.

FWIW, i had all sorts of trouble with s/w serial. I couldn't get it to work with my XBees at all. I could never work out why it did not seem to work.

As soon as i moved to leonardo, it worked like a charm.

---
Tags: arduino-uno, xbee
---


# Question
Title: Serial communication between PC and Arduino using C
I'm trying to send some data to my arduino mega 2560 using serial communication.

I'm using the exemple that I found here without success.

Every site I read say that I can send data to the arduino board like writing to any file on ubuntu.

But I alway get `Segmentation fault`

**Here is my code**

```
#include <stdio.h>
#include <string.h>

char arduinoPort[] = "/dev/ttyACM0";

int main() {

  char buffer[] = {'1'};

  FILE *usb_port;

  usb_port = fopen(arduinoPort, "rwb");

  fwrite(buffer, sizeof(char), sizeof(buffer), usb_port);

  fclose(usb_port);

  return 0;
}

```

# Answer
Your program works flawlessly on my Ubuntu 18.04. I would guess that you have a problem with your setup (flaky USB port, permission problems...) rather than the program itself. Still, I would recommend you add some error checking: right after the `fopen()` call,

```
if (!usb_port) {
    perror(arduinoPort);
    return 1;
}

```

I would expect you see something like

```
/dev/ttyACM0: No such file or directory

```

or

```
/dev/ttyACM0: Permission denied

```

that could help you pin down the real problem.
> 1 votes

---
Tags: serial, arduino-mega, c, ubuntu
---


title: Calculate statistic in EEPROM

text:
# Question
Title: Calculate statistic in EEPROM
I've search on how to do statistic calculation in EEPROM, but non related. The data that I stored in EEPROM is body temperature. Currently I stored the data using float.

Below is my code for data store in eeprom. I'm stuck at the void function named "printTemp". I know how to calculate average in array using for loop statement, but not EEPROM. From average/mean, I can find standard deviation.

Does anyone have an idea on how can we do calculation using data from EEPROM?

```
#define LM35 A1
#define READSAMPLES 100

float bt;
int buttonPin1 = D5;     // the number of the pushbutton pin 1 MEASURE
int buttonPin2 = D6;     // the number of the pushbutton pin 2 RESET CYCLE
int buttonState = 0;         // variable for reading the pushbutton status
int ButtonState = 0;         // variable for reading the pushbutton status
int address = 0;      //EEPROM address counter
int count, counT;
int sample[READSAMPLES];

void setup() {

    int contCount = EEPROM.get(5, count) / 10;

}

void loop() {

  buttonState = digitalRead(buttonPin1);
  ButtonState = digitalRead(buttonPin2);

  // check if the pushbutton is pressed.
  // if it is, the buttonState is HIGH:
  if (buttonState == LOW) {
        Serial.println("Measuring your Body Temperature:");

        count = counting();
        counT = count / 10;
        Serial.print("Data count entering: ");
        Serial.println(counT);

        writeTemp();
  }

  if (ButtonState == LOW) {

        Serial.println("Update New Cycle of body temp...");
        printTemp();
        clearEEPROM();
        Particle.publish("DONE new Cycle");

  }

}

void printTemp()
{
  for (int i = 0 ; i < EEPROM.length() ; i++) {
    float cel = EEPROM.read(i);                //read EEPROM data at address i
    //How to find MEAN of all data?
  }
}

void clearEEPROM()
{
  for (int i = 0 ; i < EEPROM.length() ; i++) {
    if(EEPROM.read(i) != 0)                     //skip already "empty" addresses
    {
      EEPROM.write(i, 0);                       //write 0 to address i
    }
  }
  Serial.println("EEPROM erased");
  address = 0;                                  //reset address counter
}

void writeTemp()
{
  //getting the voltage reading from the temperature sensor
  int j;
  float average;
  for (j = 0; j < READSAMPLES; j++)
  {
    sample[j] = analogRead(LM35);        //read sensor value
    delay(50);
  }

  average = 0;
  for (j = 0; j < READSAMPLES; j++)
  {
    average += sample[j];
  }
  average /= READSAMPLES;

  //float mv = ( average / 4096.0) * 3300;
  //float cel = ( mv / 10 ) - 55.01;
  float mv = ( average / 1024.0) * 5000;
  float cel = ( mv / 10 );

  EEPROM.write(address, cel);         //write value to current address counter address

  Serial.print("Sensor value stored at address ");
  Serial.println(address);

  address++;                      //increment address counter
  if(address == EEPROM.length())  //check if address counter has reached the end of EEPROM
  {
    address = 0;              //if yes: reset address counter
  }
}

float counting()
{
  count = count + 10;   // plus 10 is because to give a space for data entering the eeprom for LATER CODE. Just live it here.
    Particle.publish("Start Count =", String(count));
  return count;
}

```

What I can share from my problem findings are, to do the calculation of statistic from EEPROM data;

1. we need to know how to read back all the data in EEPROM. As in my code I know how to read the data, but the data cannot be hold because in FOR loop the the process will running until the end of 'i'.
2. we need to know how many data are there in EEPROM that have entered. To solve this, I'm using count; in order to count the entering data.

I need suggestion links or maybe any idea on how to do statistics in EEPROM.

Thanks.

# Answer
Doing that calculation from EEPROM is exactly the same as doing it from any other source. You have a count so you know where the EEPROM data ends. You know where the EEPROM data starts. You know how to read a number out of EEPROM. What is stopping you from creating a for loop to read the i'th address from EEPROM and add all those numbers together just like you would for an array?

```
for (int i = EEPROM_START; i < EEPROM_END; i++){
   sum = sum + EEPROM.read(i);
}
average = sum / count;

```

where EEPROM\_START and EEPROM\_END are supplied by you by knowing what address you started and ended writing at.
> 0 votes

# Answer
There are quite a few issues with your program. Averaging is just one of them.

You wrote:

> Currently I stored the data using float.

No, you didn't. You stored 8-bit unsigned integers (aka `uint8_t`).

```
int contCount = EEPROM.get(5, count) / 10;

```

Assuming you are using an 8-bit Arduino, this is reading the EEPROM cells at addresses 5 and 6, combining these two readings into a single signed 16-bit number, and storing it in `count`. Given that these EEPROM cells are also used to store temperature readings, this operation makes no sense at all. BTW, the line above also stores a copy of the newly updated `count` into a fresh local variable that gets immediately discarded. This also makes no sense.

Later you wrote:

```
for (int i = 0 ; i < EEPROM.length() ; i++) {
  if(EEPROM.read(i) != 0)  //skip already "empty" addresses
  {
    EEPROM.write(i, 0);    //write 0 to address i
  }
}

```

There is an `EEPROM.update()` method meant to do this in a simpler way:

```
for (int i = 0 ; i < EEPROM.length() ; i++) {
  EEPROM.update(i, 0);  //write 0 to address i unless it is already 0
}

```

Later:

```
for (j = 0; j < READSAMPLES; j++)
{
  sample[j] = analogRead(LM35);        //read sensor value
  delay(50);
}

```

There is no point in storing all the readings in RAM just to compute the average. You can get rid of the `sample` array and instead:

```
float average = 0;
for (int j = 0; j < READSAMPLES; j++)
{
  average += analogRead(LM35);  //read sensor value
  delay(50);
}
average /= READSAMPLES;

```

Later:

```
float cel = ( mv / 10 );
EEPROM.write(address, cel);
[...]
address++;

```

This is probably your biggest issue. You may believe you are storing floats, yet `EEPROM.write()` can *only* write bytes. Thus the value `cel`, which is a voltage in centivolts, is implicitly casted to a `uint8_t`. This means it is rounded down to the nearest integer below it, then wrapped modulo 256. This is quite likely *not* what you want.

If you really want to store floats, you should replace the last two lines of code above by

```
EEPROM.put(address, cel);
address += sizeof cel;

```

but then beware that when reading the EEPROM you should also increment the address in steps of `sizeof(float)`.
> 0 votes

---
Tags: analogread, eeprom
---


# Question
Title: Can the Arduino (Nano) bootloader be updated via itself and the Arduino IDE or is an ISP required?
I ran into the following error with a recent Arduino IDE version (1.8.9) when trying to upload to an "Arduino Nano" clone (ATmega328P):

```
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x18
...
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 10 of 10: not in sync: resp=0x18
Problem uploading to board.  See http://www.arduino.cc/en/Guide/Troubleshooting#upload for suggestions.

```

The problem could be resolved by choosing "ATmega328P (Old Bootloader)" as *Processor* in the *Tool* menu - as now suggested to me and solved in Arduino Nano uploading gives error: avrdude: stk500\_recv(): programmer is not responding.

The change was made in August 2018 with the release of Arduino IDE 1.8.6: https://github.com/arduino/Arduino/releases/tag/1.8.6

Details about the different bootloaders are described in Arduino Nano ATmega328P bootloader difference.

It seems the fuses have to be changed in order to make full use of the newer, smaller bootloader, so an ISP will have to be used anyway.

But is the bootloader able to update itself (via *Tools \> Burn bootloader*) or is there an intermediate "bootloader update sketch" available?

# Answer
On ATmega328p and similar ATmega MCUs with bootloader support, the application is not allowed to write to flash. Only code running in bootloader area of the flash memory is allowed to write to flash. Bootloader area is at the end of the flash and the beginning is set with the BOOTSZ fuses.

The write to flash page is done in two steps. First step is deleting the contents of the flash page, second step is write the new data to the flash page. In bootloader area\* it is allowed to first prepare the data to temporary buffer page, then delete the flash and write the data in one step. So in theory the bootloader could overwrite itself with a function running in the last flash page. But I don't know about bootloader which would do it.

**To write a bootloader an ISP programmer is necessary. Or other Arduino with the "Arduino as ISP" sketch.**

\*note: the read-while-write area at the end of flash has the size of the largest bootloader area possible and is not determined by BOOTSZ.
> 2 votes

---
Tags: arduino-ide, arduino-nano, bootloader, uploading, fuses
---


# Question
Title: Two libraries collide. Ambiguous functions/variables?
I get several errors once I try to include these two libraries:

> error: expected unqualified-id before '{' token #define DEBUG\_PRINTLN(...) {}

```
#include <DHT.h>
#include <DGS.h>

void setup() {
}

void loop() {
}

```

Apparently `DEBUG_PRINTLN` is causing the problems, because it is defined as a private function in DGS.h and as a constant (#define) in DHT.h.

Including DGS.h before DHT.h does not throw errors. But is this a safe workaround or might I run into errors later? How can I deal with that, without modifying the libraries?

DGS.h:

```
/*
  DGS_25SEP17.h - Library for reading KWJ Engineering with SPEC Sensors on Digital SDK with firmware date 25SEP17.
  Created by David E. Peaslee, Mar 29, 2018.
*/

#ifndef _DGS_h
#define _DGS_h

#if defined(ARDUINO) && ARDUINO >= 100
#include "Arduino.h"
#elif defined(SPARK)
//#include "application.h"
#else
#include "WProgram.h"
#endif

#include "Stream.h"

class DGS
{
  private:
    Stream *_mySerial;
    long dataArray[11]; //Multipurpose array
    //void unlock(void);
    void DEBUG_PRINTLN(long x);
    void DEBUG_PRINTLN(float x);
    void DEBUG_PRINTLN(String x);
    void DEBUG_PRINT(long x);
    void DEBUG_PRINT(float x);
    void DEBUG_PRINT(String x);

  public:
    DGS(Stream &mySerial); //Class that represents DULP with Stream as class for Serial
    DGS(Stream *mySerial); //Class that represents DULP with Stream as class for Serial

    bool DEBUG;

    int setToff(float offset);  //Sets a temperature offset
    int setBC(String BC);  //Initializes DGS with all information from barcode, only way to set Span
    String getFW(void); //Returns the Firmware Date

    int getLMP(void); //Loads LMP[3] with register values from LMP91000
    int LMP[3];  //LMP Registers, needs to be loaded with getLMP
    int setLMP(int R1, int R2, int R3); //Sets new LMP registers and reintializes LMP

    int zero(void); //Zeros to current reading, Zero only in a clean air environment
    int setXSpan(float); //ReCalibrates device, only should be used after zero, and using a calibrated gas

    int getData(char c); //Gets the data and loads into variables
    long getConc(char x = 'p');  //Reads concentration from current data array 'p' ppb or 'c' counts
    long getTemp(char t = 'C');  //Reads temperature from current data array 'C' for Celsius or 'F' for Fahrenheit
    long getRh(char r = 'r'); //Reads Rh from current data array 'r' for Rh and 'c' for counts

    void getEEPROM(void); //Loads variables into EEPROM E[5] and e[14] arrays, outputs EEPROM if DEBUG is true
    String eepromStr[5]; //Stores the character based EEPROM data
    long eepromInt[13];  //Stores the integer based EEPROM data
    float Sensitivity_Code;  //Stores the sensitivity coefficient in nA/PPM
};

#endif

```

DHT.h:

```
/* DHT library

MIT license
written by Adafruit Industries
*/
#ifndef DHT_H
#define DHT_H

#if ARDUINO >= 100
 #include "Arduino.h"
#else
 #include "WProgram.h"
#endif

// Uncomment to enable printing out nice debug messages.
//#define DHT_DEBUG

// Define where debug output will be printed.
#define DEBUG_PRINTER Serial

// Setup debug printing macros.
#ifdef DHT_DEBUG
  #define DEBUG_PRINT(...) { DEBUG_PRINTER.print(__VA_ARGS__); }
  #define DEBUG_PRINTLN(...) { DEBUG_PRINTER.println(__VA_ARGS__); }
#else
  #define DEBUG_PRINT(...) {}
  #define DEBUG_PRINTLN(...) {}
#endif

// Define types of sensors.
#define DHT11 11
#define DHT12 12
#define DHT22 22
#define DHT21 21
#define AM2301 21

class DHT {
  public:
   DHT(uint8_t pin, uint8_t type, uint8_t count=6);
   void begin(uint8_t usec=55);
   float readTemperature(bool S=false, bool force=false);
   float convertCtoF(float);
   float convertFtoC(float);
   float computeHeatIndex(bool isFahrenheit=true);
   float computeHeatIndex(float temperature, float percentHumidity, bool isFahrenheit=true);
   float readHumidity(bool force=false);
   bool read(bool force=false);

 private:
  uint8_t data[5];
  uint8_t _pin, _type;
  #ifdef __AVR
    // Use direct GPIO access on an 8-bit AVR so keep track of the port and bitmask
    // for the digital pin connected to the DHT.  Other platforms will use digitalRead.
    uint8_t _bit, _port;
  #endif
  uint32_t _lastreadtime, _maxcycles;
  bool _lastresult;
  uint8_t pullTime; // Time (in usec) to pull up data line before reading

  uint32_t expectPulse(bool level);

};

class InterruptLock {
  public:
   InterruptLock() {
#if !defined(ARDUINO_ARCH_NRF52)
    noInterrupts();
#endif
   }
   ~InterruptLock() {
#if !defined(ARDUINO_ARCH_NRF52)
    interrupts();
#endif
   }
};

#endif

```

# Answer
> 3 votes
The DEBUG\_ functions in the DGS class are private and used only in DGS.cpp. They will not collide with the macros from DHT.h

If DHT.h is included before DGS.h, the preprocessor replaces the DEBUG\_ function names with the content of the macros from DHT.h and the result doesn't make sense for the compiler.

You could do `#undef DEBUG_PRINT` and `#undef DEBUG_PRINTLN` after DHT.h to undefine the macros for the rest of the sketch. DHT.cpp includes DHT.h and will have the macros defined.

---
Tags: library, compilation-errors
---


# Question
Title: measure +3V and -3V through resistor divider and switch on/off by digital pins
I've seen that resistor dividers can be used to read negative voltages, but I'ld like if there is a way to accomplish this with less components and having a way to turn this off.

I was thinking if there would be an extreme option of changing from pinMode INPUT to INPUT\_PULLUP or INPUT\_PULLDOWN to power the circuit and use the 20k pullups to make part of the divider, together with another resistances on the input. Alternatively, switching from INPUT to OUTPUT would be fine.

What I want to measure is an external +3V/GND/-3V power supply (battery pack) that shares the GND with the arduino SAMD21 (3.3V), measuring both +3V and -3V, and avoiding drain when not measuring (hence the pin mode changes)

Currently I'm using this schema to measure the voltage of +5V supply battery (connected through VIN, thus using the internal regulator), by dividing with 2 1Mohm resistances, ground to digital pin and measurement by internal adc. I don't need so much precision, so this is enough here. So I'm looking for the same or better alternatives, but for the -3V I don't know how to properly calculate the 3 resistor divider.

# Answer
> 3 votes
When measuring a voltage that is higher than the maximum rating, the voltage of interest is tied to ground with a voltage divider. When measuring a negative voltage, you instead have to tie the voltage of interest to the positive supply voltage (study the answers to this question).

In theory you can use the internal pullup to spare one resistor, but I would consider this a bad practice and recommend using an external pullup for the following reasons:

* a uC's internal pullups/-downs are not accurate and sometimes not specified
* especially when measuring negative voltage, chances are that harmful voltage is applied to the adc (consider the default state of a gpio)
* a pullup/-down is an uncritical component concerning its value and precision. Therefore they are very cheap

# Answer
> -1 votes
Two 1M resistors for a voltage divider is high. You could add a capacitor (1nF or 10nF) to GND and the analog input.

Could you try to find what the leakage current or the self-discharge current of the battery itself is? Then take a percentage of that, for example 20%, then calculate what resistor value the voltage divider should be.

It does not have to be 20%, it can be any current that you are willing to give up to be able to measure the voltage.

For example, when the battery has a self-discharge current of 10µA, then 20% is 2µA, which is two resistors of 825kΩ. That happens to be close to the 1M resistors that you already use.

---
Tags: pins, resistor, voltage
---


title: Order of Evaluation for #define Macros

text:
# Question
Title: Order of Evaluation for #define Macros
EDIT: I think this fits better in the C++ Stack Overflow, so I'm going to re-post this there.

I am working on a menu system with `#define` macros (inspired by the Marlin firmware on my 3D printer) I am attempting to generalize each menu item with the macro `#define MENU_ITEM_EDIT()`. The full code is really long, so I am leaving out chunks of code of compactness. However, you can find the full code here: https://pastebin.com/h24itG9y

```
void draw_row(int row, char* value) { /* Stuff here*/ } // Draws row
char* uiToStr(int x) { /* Stuff here*/ } // Converts unsigned int to a string

#define disp_array(display, value)  display[value]
#define disp_func(display, value)   display(value)
#define disp_char(display, value)   display

#define MENU_ITEM_EDIT(min, max, rate, display, displayType, width, label, value) \
    // A bunch of stuff
    draw_row(rowNum, disp_ ## displayType(display, value)); \
    // More stuff

```

Using the code macro would look like:

```
// Values
const char item1[] = "Item 1", item2[] = "Item 2", item3[] = "Item 3";
const char* const itemList[] = {item1, item2, item3};
int currentItem = 0;
uint8_t item1Val = 10;

void menu1()
{
   START_MENU();
       MENU_ITEM_EDIT(0, 3, 1, itemList, array, 6, "Item:", currentItem);
       MENU_ITEM_EDIT(0, 255, 1, uiToStr, func, 3, "Item 1 Value:", item1Val);
   END_MENU();
}

```

Which displays as:

```
Item:     Item 1
Item 1 Value: 10

```

For convenience in the declarations of my menus, I am trying to use common menu types, such as an `uint8_t` that ranges from 0 to 255. Then, in the menu, I would use `__u255_t` instead of the first 6 arguments.

```
#define __u255_t 0, 255, 1, uiToStr, func, 3

void menu2()
{
    int item2Val = 10;

    START_MENU();
        MENU_ITEM_EDIT(__u255_t, "Item 2 Value", item2Val);
    END_MENU();
}

```

Previously, I had it set up such that every time I wanted a different type of menu, even if I would only use it once, I had to define a type for it and how it should evaluate in the macro. This way, I can use 1 argument instead of 6 for commonly recurring types in rows. However, I still want the ability to use the 6 argument option when I have a row that has a unique set of arguments, such as a different range or list of display strings.

However, in this example, the program won't compile because it places `__u255_t` into `min` in the `MENU_ITEM_EDIT()` macro, rather than expanding `__u255_t` into its 6 values and placing them into the first 6 arguments of `MENU_ITEM_EDIT()`. The macro evaluates as:

```
MENU_ITEM_EDIT(__u255_t, "Item 2 Value", item2Val);
// Evaluates as:
MENU_ITEM_EDIT( (0, 255, 1, uiToStr, func, 3), "Item 2 Value", item2val, , , , , );

```

Note: I put an extra set of parentheses to make it more clear to understand.

But I want:

```
MENU_ITEM_EDIT(__u255_t, "Item 2 Value", item2Val);
// Evaluates as:
MENU_ITEM_EDIT(0, 255, 1, uiToStr, func, 3, "Item 2 Value", item2Val);

```

I thought about using a `struct`, however I'm not sure that I can because depending on the row, the `value` string in `draw_row()` could be a function or an array. Does anyone have any advice on how to solve this problem?

Also, please let me know if I need to add any more code to make my problem more clear.

# Answer
You need to turn your macro itself into a macro. Sounds odd, I know. But take the following example:

```
#define foo bar, baz
#define foobar(X, Y, Z) something(X, Y, Z);
#define boofar(...) foobar(__VA_ARGS__)

boofar(foo, 4)

```

`boofar` is a macro that takes a variable argument list. That expands out into a call for your actual macro call, expanding `foo` in the process. Then your actual macro gets expanded out with the real arguments already in here. The point here is that `foo` is expanded *before* being passed to the macro that needs the multiple arguments that are inside `foo`.

So the expansion chain is actually:

```
boofar(foo, 4) ->
foobar(bar, baz, 4) ->
something(bar, baz, 4);

```

Running it through `cpp` and you get:

```
# 1 "t.c"
# 1 "<built-in>"
# 1 "<command-line>"
# 31 "<command-line>"
# 1 "/usr/include/stdc-predef.h" 1 3 4
# 32 "<command-line>" 2
# 1 "t.c"

something(bar, baz, 4);

```
> 1 votes

---
Tags: c++
---


# Question
Title: How to fix when i shorted 5v to gnd accidentally (Arduino Nano)
I connected 5V to GND accidentally (connect directly, no LED, no motor). Now the LED on the board doesn't light up and power LED lights up but it is not bright. The 5V output pin is only around 1.98V. I'm using clone version from Alibaba. I ordered two, one is still working but the shorted one doesn't work. May I know how to fix them?

# Answer
I would say that to repair an Arduino Nano clone yourself, if ICs/SMD parts are damaged, is not worth the effort, if you could do it at all (first having to find out which parts need to be replaced, carefully de-soldering the delicate SMD parts, then putting new parts in place, etc.).
> 3 votes

---
Tags: arduino-nano
---


# Question
Title: light detection system: Response different from power bank and computer system
Hello friends

I'm working on a light detection system for the higher secondary summer term project, for which I'm using a simple Arduino board, Adafruit 16-Bit ADC, an LDR with some resisters, a 5V USB power source either the computer USB 2.0 port or a mobile power bank 5V-500mA/1A/2.1A, a USB mobile charging cable (not the data cable) and a Bluetooth module to communicate with Arduino system, an android or a computer (different from Arduino power source) to record the data.

The difference in maximum and minimum response is very poor when replacing the power source from the computer USB to power bank USB. With the same environmental and experimental conditions, the response goes from 50000 to 45000 counts (the changes in response are 5000 counts) with the power bank. For the same situations, the response goes from 50000 to 5000 counts (the changes are 45000) with the computer power source which is more suitable but it's better to use a small power supply.

How can I get the better and stable response? Kindly help me to solve out this issue. Thank you.

# Answer
> 1 votes
Based on limited knowledge of the design and limited knowledge of the requirements here are 3 possible reasons. More may exist.

1. The USB 2.0 definition stats such a port provide 0.5A of current. Some devices limit the current as a precaution. Therefor the battery may provide more current then the USB source. The type of USB source was not specified and no voltage measurement data was provided.
2. How fast does the device need to react to a change in light level? A light-dependent resistor or LDR can have a latency of as much as a second with respect to light level changes.
3. With regards to the 16 bit ADC. What precautions have been made with regards to precisely controlling the ADC's voltage reference? Any fluctuation can cause large errors. What precautions have been made with regards to filtering out the ADC's random noise? For example, many ADCs only have a fraction of their resolution if averaging is not used.

---
Tags: arduino-uno
---


title: Why does this take more byte?

text:
# Question
Title: Why does this take more byte?
I am only replacing a portion of my code where I want to use the first method but as you can see it is making my sketch size little bigger

```
//if(iBPM >= 40 || iBPM <= 170 )
      {
      char iBPMwav[50];
      String thisString = String(iBPM);
      String stringThree =  "n" + thisString;
      stringThree =  stringThree + ".wav";
      stringThree.toCharArray(iBPMwav, 50);
      tmrpcm.play(iBPMwav);
      }

```

**`Sketch uses 29678 bytes (100%)`**

This is simple but at the end, I want to go from the number 40 up to 170, and this is why I want to use the first method.

```
//if(iBPM >= 40 || iBPM <= 170 )
  {
      if(iBPM == 71)
tmrpcm.play("n71.wav");
  else if(iBPM == 72)
tmrpcm.play("n72.wav");
  else if(iBPM == 73)
tmrpcm.play("n73.wav");
  else if(iBPM == 74)
tmrpcm.play("n74.wav");
  else if(iBPM == 75)
tmrpcm.play("n75.wav");
  else if(iBPM == 76)
tmrpcm.play("n76.wav");
  else if(iBPM == 77)
tmrpcm.play("n77.wav");
  else if(iBPM == 78)
tmrpcm.play("n78.wav");
  else if(iBPM == 79)
tmrpcm.play("n79.wav");
  else if(iBPM == 80)
tmrpcm.play("n80.wav");
  else if(iBPM == 81)
tmrpcm.play("n81.wav");
  else if(iBPM == 82)
tmrpcm.play("n82.wav");
  else if(iBPM == 83)
tmrpcm.play("n83.wav");
  else if(iBPM == 84)
tmrpcm.play("n84.wav");
  else if(iBPM == 85)
tmrpcm.play("n85.wav");
  else if(iBPM == 86)
tmrpcm.play("n86.wav");
  else if(iBPM == 87)
tmrpcm.play("n87.wav");
  else if(iBPM == 89)
tmrpcm.play("n89.wav");
  else if(iBPM == 90)
tmrpcm.play("n90.wav");
  else if(iBPM == 91)
tmrpcm.play("n91.wav");
  else if(iBPM == 92)
tmrpcm.play("n92.wav");
  else if(iBPM == 93)
tmrpcm.play("n93.wav");
  else if(iBPM == 94)
tmrpcm.play("n94.wav");
  else if(iBPM == 95)
tmrpcm.play("n95.wav");
  else if(iBPM == 96)
tmrpcm.play("n96.wav");
  else if(iBPM == 97)
tmrpcm.play("n97.wav");
  else if(iBPM == 98)
tmrpcm.play("n98.wav");
  else if(iBPM == 99)
tmrpcm.play("n99.wav");
  else if(iBPM == 100)
tmrpcm.play("n100.wav");
  else if(iBPM == 101)
tmrpcm.play("n101.wav");
  else if(iBPM == 102)
tmrpcm.play("n102.wav");
else
 tmrpcm.play("n170.wav");
}

```

**`Sketch uses 29024 bytes (101%)`**

# Answer
I suggest having simpler file names (same size, always 3 digit numbers)

```
/// Return a text "n000.wav" ... "n255.wav"
/// depending on the parameter
char* makeFileName(byte i) {
  static char name[9] = "nxxx.wav";
  byte digit = i/100;
  name[1] = '0' + digit;
  i -= digit*100;
  digit = i/10;
  name[2] = '0' + digit;
  i -= digit*10;
  name[3] = '0' + i;

  return name;
}

```
> 2 votes

# Answer
While the Strings class makes a C/C++ program easy to understand and maintain, as stated in the comments, using the Strings class is a memory intensive option which should be should be avoided when memory is in short supply. Such as on the embedded processors used in most Arduino platforms.

Here are 2 examples where Stings is used and not used. Note the reduction from 2326 bytes to 734 bytes of program memory necessary to store the sketch in the embedded processor.

```
void setup()
{
}

void loop()
{
  uint8_t iBPM;
  uint8_t pointer;
  for(iBPM = 40; iBPM <= 170; iBPM++)
  {
    char iBPMwav[50];
    String thisString = String(iBPM);
    String stringThree =  "n" + thisString;
    stringThree =  stringThree + ".wav";
    stringThree.toCharArray(iBPMwav, 50);
//  tmrpcm.play(iBPMwav);
  }
}

```

Sketch uses 2326 bytes (7%) of program storage space. Maximum is 32256 bytes. Global variables use 27 bytes (1%) of dynamic memory...

```
void setup()
{
}

void loop()
{
  uint8_t iBPM;
  uint8_t pointer;
  for(iBPM = 40; iBPM <= 170; iBPM++)
  {
    char iBPMwav[50];
    pointer = 0;
    char temp_str[10];
//  String thisString = String(iBPM);
//  String stringThree =  "n" + thisString;
//  stringThree =  stringThree + ".wav";
//  stringThree.toCharArray(iBPMwav, 50);
    itoa(iBPM, temp_str, 10);
    if(iBPM < 100)
    {
      strncpy(&iBPMwav[pointer],"n0",2);
      pointer += 2;
      strncpy(&iBPMwav[pointer],temp_str,2);
      pointer += 2;
    }
    else
    {
      strncpy(&iBPMwav[pointer],"n",1);
      pointer += 1;
      strncpy(&iBPMwav[pointer],temp_str,3);
      pointer += 3;
    }
    strncpy(&iBPMwav[pointer],".wav",4);
//  tmrpcm.play(iBPMwav);
  }
}

```

Sketch uses 734 bytes (2%) of program storage space. Maximum is 32256 bytes. Global variables use 15 bytes (0%) of dynamic memory...
> 1 votes

---
Tags: sketch
---


# Question
Title: How can I adapt this code for the ATTiny85?
So I set up an Arduino circuit that while a button was pressed, a sound effect would play and an LED would activate until I stopped pressing the button. Since I didn't use a micro sd card module, I had to use wav2c to convert the audio to numeric values that I then used the code here to implement the audio. The numeric values for the audio were placed in a header file that was referenced in the code. The code and my circuit work but I want to see if I can use one of my new ATTiny85's to run the code and perform the same operations as the Arduino did. I have set up my Arduino Mega 2560 to program the ATTiny85. I have tested it with Blink and it works. However, after I had moved the pins of the speaker, LED, and button to those of the ATTin85 and edited the appropriate code, it will not upload to the ATTiny85. It gives error messages that certain variables have not been declared in this scope. One such is "TCCR1B" and when I comment it out, it claims another variable has not been declared in this scope. Any idea how I can overcome this and if it's even possible to use the ATTiny in this capacity?

The Code I tried uploading to the ATTiny85

```
#include <stdint.h>
#include <avr/interrupt.h>
#include <avr/io.h>
#include <avr/pgmspace.h>

#define SAMPLE_RATE 20000
#include "Test.h"

int ledPin = 0;
int speakerPin = 1; // Can be either 3 or 11, two PWM outputs connected to Timer 2
const byte pinSwitch1 = 2;
volatile uint16_t sample;
byte lastSample;
int buttonState = 0;
const byte interruptPin = 2;
volatile byte state = LOW;

void stopPlayback()
{
    digitalWrite(ledPin, LOW);
    // Disable playback per-sample interrupt.
    TIMSK1 &= ~_BV(OCIE1A);

    // Disable the per-sample timer completely.
    TCCR1B &= ~_BV(CS10);

    // Disable the PWM timer.
    TCCR2B &= ~_BV(CS10);

    digitalWrite(speakerPin, LOW);
}

// This is called at 8000 Hz to load the next sample.
ISR(TIMER1_COMPA_vect) {
    if (sample >= sounddata_length) {
        if (sample == sounddata_length + lastSample) {
            stopPlayback();
        }
        else {
            if(speakerPin==11){
                // Ramp down to zero to reduce the click at the end of playback.
                OCR2A = sounddata_length + lastSample - sample;
            } else {
                OCR2B = sounddata_length + lastSample - sample;
            }
        }
    }
    else {
        if(speakerPin==11){
            OCR2A = pgm_read_byte(&sounddata_data[sample]);
        } else {
            OCR2B = pgm_read_byte(&sounddata_data[sample]);
        }
    }

    ++sample;
}

void startPlayback()
{
    digitalWrite(ledPin, HIGH);
    pinMode(speakerPin, OUTPUT);

    // Set up Timer 2 to do pulse width modulation on the speaker
    // pin.

    // Use internal clock (datasheet p.160)
    ASSR &= ~(_BV(EXCLK) | _BV(AS2));

    // Set fast PWM mode  (p.157)
    TCCR2A |= _BV(WGM21) | _BV(WGM20);
    TCCR2B &= ~_BV(WGM22);

    if(speakerPin==11){
        // Do non-inverting PWM on pin OC2A (p.155)
        // On the Arduino this is pin 11.
        TCCR2A = (TCCR2A | _BV(COM2A1)) & ~_BV(COM2A0);
        TCCR2A &= ~(_BV(COM2B1) | _BV(COM2B0));
        // No prescaler (p.158)
        TCCR2B = (TCCR2B & ~(_BV(CS12) | _BV(CS11))) | _BV(CS10);

        // Set initial pulse width to the first sample.
        OCR2A = pgm_read_byte(&sounddata_data[0]);
    } else {
        // Do non-inverting PWM on pin OC2B (p.155)
        // On the Arduino this is pin 3.
        TCCR2A = (TCCR2A | _BV(COM2B1)) & ~_BV(COM2B0);
        TCCR2A &= ~(_BV(COM2A1) | _BV(COM2A0));
        // No prescaler (p.158)
        TCCR2B = (TCCR2B & ~(_BV(CS12) | _BV(CS11))) | _BV(CS10);

        // Set initial pulse width to the first sample.
        OCR2B = pgm_read_byte(&sounddata_data[0]);
    }

    // Set up Timer 1 to send a sample every interrupt.

    cli();

    // Set CTC mode (Clear Timer on Compare Match) (p.133)
    // Have to set OCR1A *after*, otherwise it gets reset to 0!
    TCCR1B = (TCCR1B & ~_BV(WGM13)) | _BV(WGM12);
    TCCR1A = TCCR1A & ~(_BV(WGM11) | _BV(WGM10));

    // No prescaler (p.134)
    TCCR1B = (TCCR1B & ~(_BV(CS12) | _BV(CS11))) | _BV(CS10);

    // Set the compare register (OCR1A).
    // OCR1A is a 16-bit register, so we have to do this with
    // interrupts disabled to be safe.
    OCR1A = F_CPU / SAMPLE_RATE;    // 16e6 / 8000 = 2000

    // Enable interrupt when TCNT1 == OCR1A (p.136)
    TIMSK1 |= _BV(OCIE1A);

    lastSample = pgm_read_byte(&sounddata_data[sounddata_length-1]);
    sample = 0;
    sei();
        //digitalWrite(ledPin, HIGH);
        //delay(1000);
        //digitalWrite(ledPin, LOW);
}

void setup()
{
    pinMode( pinSwitch1, INPUT );
    pinMode(ledPin, OUTPUT);
    pinMode(interruptPin, INPUT_PULLUP);
    attachInterrupt(digitalPinToInterrupt(interruptPin), stopPlayback, CHANGE);

}

void loop()
{
//startPlayback();
//delay(5000);
//stopPlayback();
buttonState = digitalRead(pinSwitch1);

stopPlayback();

if (buttonState == LOW) {
    startPlayback();
    delay(1150);

}

}

```

The header file with the audio

```
#ifndef _HEADERFILE_H    // Put these two lines at the top of your file.
#define _HEADERFILE_H    // (Use a suitable name, usually based on the file name.)

const int sounddata_length=32000;
//const int sounddata_sampleRate=20000;

const unsigned char sounddata_data[] PROGMEM = {
  15,1,49,0,150,0,138,0,219,255,133,0,176,0,15,1,210,

//There are a lot more numbers in here to generate the audio but I cut most out to save space

};

#endif // _HEADERFILE_H    // Put this line at the end of your file.

```

# Answer
> 1 votes
As @delta\_G pointed out, this code is written specifically to access the timer hardware on the chip, and the ATTINY85 has different timer hardware.

It would not be hard to change this code to work with your just need to output the next step in the list of audio values 8000 timer per second.

There are two ways you could do this...

1. You could figure out the corresponding settings for the ATTINY85 timer hardware and use those instead. The timer registers are documented in the ATTINY85 datasheets and you can google lots of info on how to set those registers, but it is complicated.
2. You can bit-bang the audio data out though a digital pin. Bing banging means you write code that manually sets the pin high or low at the appropriate times.

Since it does not look like you need to do anything else while the sound is playing, I think bit banging is the simpler approach here.

Do do bit banging, you get rid of the start and end playback functions and instal have a playSound() function that looks something like this...

```
void playSound() {
    pinMode(speakerPin, OUTPUT);  // This really belongs in setup()
    for(unsigned sample=0; sample<sounddata_length; sample++) {      // step though the audio samples
        sample_value=pgm_read_byte(&sounddata_data[sample])/2;    // grab next value from array in flash

        // Note that we divide the value by 2. This is because our target rate is
        // 8000 samples per second, which is 125us per sample. Each sample value is 0-255, so /2 gives us
        // a value 0-127. If we spend about 127us on each sample then we are in the right ballpark
        // for playback speed (ok, a bit slow).

        digitalWrite( speakerPin , 1);     // poor man's single cycle bitbang PWM
        _delay_us( sample_value );
        digitalWrite( speakerPin , 0);
        _delay_us( 127-sample_value );

     }

    }
}

```

This is just pseudo code and I have not checked to see if this even compiles, but you should get the idea.

This is also a hack, so it does not take into account how long the digitalWrite() takes or the overhead of the loop. It also explicitly stretches the sample time from 125us to 127us for math simplicity and speed (dividing the 0-255 by 2 is very fast). All these will likely make the playback sound slow and low, but i'm not sure how much.

I also do not take into account that the playback can get interrupted which would cause audio glitches. You can fix this by putting cli()/sei() around the playSound() code.

Finally, each sample only gets a single PWM cycle so I don't expect audio to be CD quality, but maybe good enough. If you need more PWM cycles then there are ways to do this, but then probably better to use the hardware timer.

LMK if you can get this working (post a video!) or have any questions!

---
Tags: arduino-mega, attiny, audio
---


title: Arduino Voice recognition

text:
# Question
Title: Arduino Voice recognition
Is it possible to use only arduino to do voice recognition? or maybe with esp32 no internet.

I found speech recognition chip but that's not what i want I got esp32 esp8266 and arduino board. I would like to know if somebody could do it

# Answer
> 3 votes
No. It's as simple as that. No. Voice Recognition is a very very complex task. To do it fast and well in a "general" way takes a neural network, or a very powerful PC (note: all common ones now use online resources to do all the work).

A voice recognition chip generally is pre-programmed to respond to specific words.

# Answer
> 1 votes
A simple speech (word) recognition can be done. I made one in 1998. Chip was atmega16. Now there are ready to use sound detectors and you just use digital out. https://s.click.aliexpress.com/e/cn6IwDhI From that digital signal you get frequencies, durations and delays. First output results to serial and then get key features, ranges of voice command or a word. Put those boundaries to table and there you have it. It works like a charm with few words but then you have to make indexed database or something to keep it reasonable fast. I had only 8 commands and recognition was about 85% There were only 2 times when it "hear" some other word as a listed word. Language was finnish. I assume that it might lower those false positive occurrencies. As you see this is nothing compared to real systems but can be easily used in non critical solutions. ESP32 can do so much more that I think this might be interesting.. You may also want to look -\> https://github.com/MhageGH/esp32\_CloudSpeech

# Answer
> 1 votes
Yes it is possible - see here for ESP32 example:

https://github.com/espressif/esp-adf/tree/master/examples/speech\_recognition/asr

---
Tags: arduino-uno, esp32
---


# Question
Title: Logging data to SD card from software serial
I have an Arduino Uno and an Adafruit data logging shield and I have connected a digital pressure sensor that uses serial communication. The sensor requires a character to start transmitting data. I have managed to read the data using this code:

```
#include <SoftwareSerial.h>
SoftwareSerial mySerial(8,9);

int depth;

void setup() {

    Serial.begin(9600);
    mySerial.begin(9600);
    mySerial.print("C");

}

void loop()
{

 if (mySerial.available()) {

   depth = mySerial.read();

 }

}

```

This returns the following:

> C1000
> C1000
> C1000

where 1000 is the value.

I have written another code that logs data to the shield and tested with other sensors but I cannot log data from this sensor by modifying the above code and cannot find any relevant examples. If I add something like this it does not return the same value.

```
logfile.println(depth);

```

Complete newbie in so any suggestions are welcome.

UPDATE

# Answer
> 1 votes
use the C as the line start indicator. if received char is 'C' then do a `file.println();` example with output to Serial

```
#include <SoftwareSerial.h>
SoftwareSerial mySerial(8,9);

void setup() {
    Serial.begin(9600);
    mySerial.begin(9600);
    mySerial.print("C");
}

void loop() {
 if (mySerial.available()) {
   char c = mySerial.read();
   if (c == 'C') {
     Serial.println();
   }
   Serial.write(c);
 }
}

```

---
Tags: arduino-uno, sd-card, adafruit
---


title: RDTSC alternative for Arduino

text:
# Question
Title: RDTSC alternative for Arduino
To calculate an operation execution time, I was saving the `millis()` result before and after the operation to calculate the interval time. Is there an alternative on the Arduino Uno like the RDTSC found on x86 architectures?

# Answer
> 0 votes
There are several alternatives. The best choice for you depends on the time resolution you need and the maximum duration you may want to measure:

1. `millis()` is good for slow things. It has a resolution of 2 ms (it increments by steps of 1 ms most of the time, but 2 ms occasionally) and can measure durations as long as 49.7 days.
2. `micros()` is the easy choice for when you want more resolution for faster things. It increments in steps of 4 µs and is limited to about 71.6 minutes.
3. For very fast things, you can get single-cycle resolution if you configure Timer 1 to count at the full CPU speed, assuming you don't need the timer for something else. But beware the timer will roll over roughly every 4.1 milliseconds.
4. You could also use Timer 1 with the prescaler set at ÷8 in order to expand the measurable range to 32.8 ms, at the cost of a degraded resolution.

Here is a table summing up the available methods, sorted by resolution:

```
method        data type  resolution  max. duration
--------------------------------------------------
millis()       uint32_t        2 ms     49.7 days
micros()       uint32_t        4 µs     71.6 min
Timer 1 (÷8)   uint16_t      0.5 µs     32.8 ms
Timer 1 (÷1)   uint16_t     62.5 ns      4.1 ms

```

---
Tags: arduino-uno, timers, time
---


title: A confusing condition statements

text:
# Question
Title: A confusing condition statements
I am working on a project in making a timer socket using Arduino and a current sensor. For the code I decided to modify a code that was meant to be a kitchen timer.

In that code I found a statement

`currentMode = currentMode == MODE_IDLE ? MODE_RUNNING : MODE_IDLE;`

I assumed this works in a way that it chose whether the timer is in the current mode or the idle mode but I don’t understand the mechanism behind it. What does this statement mean?

# Answer
> 1 votes
Assuming you understand how the ternary operator works, the statement is simply toggling the currentmode between its two possible settings.

if you do not understand ternary operators, it can be re-written as:

```
if (currentMode == MODE_IDLE) {
  currentMode = MODE_RUNNING;
} else {
  currentMode = MODE_IDLE;
}

```

You should read up on the `ternary` operator. It appears in several languages in various formats and can come in handy in a variety of situations.

In general terms the ternary operator is of the following form (as used in an assignment):

```
result = (booleanExpression) ? (value if true) : (value if false);

```

but you can use it in other contexts for example in a function call:

```
someFn(booleanExpression ? trueValue : falseValue);

```

---
Tags: arduino-uno, code-review
---


# Question
Title: Phase and frequency correct PWM mode Arduino Mega 2560
I wrote a code to generate 1kHz Phase and frequency correct PWM signal from Arduino mega 2560 using timer 4. When I try the code with fast PWM mode it works perfectly. But phase correct mode didn't provide the expected outcome. What is wrong with my code?

```
unsigned int b=7999;
void setup() {
pinMode(6,OUTPUT);
pinMode(7,OUTPUT);

TCCR4A=0;
TCCR4B=0;
//Timer 1 1kHz mode 8: phase and frequency correct pwm oc1a non inverting

TCCR4A=(1<<COM4A1)|(0<<COM4A0)|(0<<WGM41) ;//| (0<<WGM40)
TCCR4B=(1<<WGM43)|(0<<WGM42);//
ICR4=b;
OCR4A=int(b*1/5);
TCCR4B|=(1<<CS10);
TIMSK4 |=(1<<OCIE4A);
}

void loop() {
  }

ISR(TIMER_COMPA_vect){

  }

```

The output of the code for different duty cycles are as below **Duty cycle:0.2 (OCR4A=b/5)**

**Duty cycle:0.2 (OCR4A=b/2)**

# Answer
> 2 votes
You wrote:

> `TIMSK4 |= (1<<OCIE4A);`

and then never defined `ISR(TIMER4_COMPA_vect)`. As soon as you get a compare match, you get a bad interrupt, which defaults to resetting your program and restarting again from reset vector.

---
Tags: arduino-mega, pwm
---


# Question
Title: Using case statement with IR emitter reciever
I am trying to use two "infrared obstacle avoidance modules" to work with the following sketch. From all my research, I believe, a case statement is my best option because, (I understand) the sketch will not continue until the case is satisfied, however, I'm getting a weird outcome. When using two sensors with sketch below, the leds blink in an alternating pattern without any near the ir sensors.

If I use only one module the led will light until the sensor sees something, then the led turns off for the programmed delay then turns back on.

The outcome I'm looking for is eventually three modules, that will randomly light, when one lights it waits until something breaks the beam, then another will light and wait... Does anyone have any ideas how to make this work?

```
int ledselect;
int led1 = 2;
int led2 = 3;
int ir1 = 4;
int ir2 = 5;
int s1 = A0;
int s2 = A1;

void setup() {
  Serial.begin(9600);
  pinMode(led1, OUTPUT);
  pinMode(led2, OUTPUT);
  pinMode(ir1, OUTPUT);
  pinMode(ir2, OUTPUT);
  pinMode(s1, INPUT);
  pinMode(s2, INPUT);

}
void loop() {
  ledselect = random(2);
  switch (ledselect) {

    case 0:
      digitalWrite(led1, HIGH);
      digitalWrite(ir1, HIGH);
      delay(50);
      while (analogRead(s1) >= 100)
      {
        delay(50);
        digitalWrite(led1, LOW);
        digitalWrite(ir1, LOW);
      }
      break;

    case 1:
      digitalWrite(led2, HIGH);
      digitalWrite(ir2, HIGH);
      delay(50);
      while (analogRead(s2) >= 100)
      {
        delay(50);
        digitalWrite(led2, LOW);
        digitalWrite(ir2, LOW);
      }
      break;
  }
}

```

# Answer
> 0 votes
What happens is:

1. A random number is selected
2. A light goes on
3. It goes off when nothing is near (assuming a low value of an analog sensor means nothing near?)
4. The same light or another light goes on (depending on the random led)
5. Continue with 3.

Some reasons why this might fail:

* Check the value (should it be higher or lower than 100?)
* Maybe the sensor is not so accurate and sometimes give 0 or max values which are incorrect. To change this, read multiple times the sensor and take the average, or remove the lowest and highest few (to remove spikes) and take the average.

**UPDATE**

The body of the `case` statements are almost equal, make it a function called from both `case` statements:

Your code will look like:

```
void loop() {
  ledselect = random(2);
  switch (ledselect) {
    case 0:
      process(led1, ir1, s1);
      break;

    case 1:
      process(led2, ir2, s2);
      break;
  }
}

void process(int led, int sw, int ir)
{
  digitalWrite(led, HIGH);
  digitalWrite(ir, HIGH);
  delay(50);
  while (analogRead(sw) >= 100)
  {
    delay(50);
    digitalWrite(led, LOW);
    digitalWrite(ir, LOW);
  }
}

```

If you use the ternary operator ( x ? y : z, meaning if x than y else z), than your `loop` function will be:

```
void loop() {
  ledselect = random(2);
  process(ledselect == 0 ? led1 : led2,
          ledselect == 0 ?  ir1 :  ir2,
          ledselect == 0 ?   s1 :   s2);
}

```

An even more elegant way, is to use an array for the parts (not sure what better name can be), instead of all variables naming 0 and 1, put them in arrays, and you get the following code below. If you make more parts, you just have the change the beginning of the code.

```
int ledselect;

const int NrOfParts = 2;

int leds     [NrOfParts] = {  2 , 3 };
int irs      [NrOfParts] = {  4,  5 };
int switches [NrOfParts] = { A0, A1 };

void setup() {
  Serial.begin(9600);
  for (int part = 0; part < NrOfParts; part++)
  {
    pinMode(leds    [part], OUTPUT);
    pinMode(irs     [part], OUTPUT);
    pinMode(switches[part],  INPUT);
  }
}

void loop()
{
  ledselect = random(2);
  process(leds[ledselect], irs[ledselect], switches[ledselect]);
}

void process(int led, int sw, int ir)
{
  digitalWrite(led, HIGH);
  digitalWrite(ir, HIGH);
  delay(50);
  while (analogRead(sw) >= 100)
  {
    delay(50);
    digitalWrite(led, LOW);
    digitalWrite(ir, LOW);
  }
}

```

**Update 2**

An even better way is to create a structure (so you keep all information of one 'part' together).

This solution uses the & (dereference) operator, meaning it is like a variable pointing to a part.

```
int ledselect;

const int NrOfParts = 2;

struct Part
{
  int led;
  int ir;
  int sw;
};

Part _parts[NrOfParts] =
{
  { 2, 4, A0 },
  { 3, 5, A1 }
};

void setup() {
  Serial.begin(9600);
  for (int partNumber = 0; partNumber < NrOfParts; partNumber++)
  {
    Part& part = _parts[partNumber];
    pinMode(part.led, OUTPUT);
    pinMode(part.ir , OUTPUT);
    pinMode(part.sw ,  INPUT);
  }
}

void loop()
{
  process(_parts[random(2)]);
}

void process(Part& part)
{
  digitalWrite(part.led, HIGH);
  digitalWrite(part.ir, HIGH);
  delay(50);
  while (analogRead(part.sw) >= 100)
  {
    delay(50);
    digitalWrite(part.led, LOW);
    digitalWrite(part.ir, LOW);
  }
}

```

---
Tags: programming, analogread
---


title: Execute code only once

text:
# Question
Title: Execute code only once
I am trying to create an if statement that only runs once, the very first time the void loop is started and switches to another code after that. But the following only executes stepper1a(). Any help would be great. Thx !

```
int var;
int var2;
bool executed = false;

const int M1dirpin = 4; //Stepper Dir Pin
const int M1steppin = 5; //Stepper Step Pin

void setup() {

pinMode(A2,INPUT);
pinMode(M1dirpin,OUTPUT);
pinMode(M1steppin,OUTPUT);
Serial.begin(9600);

}

void stepper1() {
  int j;
    delayMicroseconds(10);
    digitalWrite(M1dirpin,HIGH);
  for(j=0;j<=200;j++){
    digitalWrite(M1steppin,LOW);
    delayMicroseconds(10);
    digitalWrite(M1steppin,HIGH);
    delay(2);
  }
}

void stepper1a() {
  int j;
    delayMicroseconds(10);
    digitalWrite(M1dirpin,HIGH);
  for(j=0;j<=1600;j++){
    digitalWrite(M1steppin,LOW);
    delayMicroseconds(10);
    digitalWrite(M1steppin,HIGH);
    delay(2);
  }
}

void loop() {

if (executed == false) {
var = analogRead(A2);
delay(10);
if (var > 500) {
  stepper1a();
  delay(2000);
  executed = true;
  Serial.println("turned 1600");
  Serial.println(executed);
  }
else if (executed == true) {
 var2 = analogRead(A2);
delay(10);
if (var > 500) {
  stepper1();
  delay(2000);
  Serial.println("turned 200");
}
}
}
}

```

Updated void loop:

```
void loop() {

    static bool yes_we_did_the_one_time_job = false;

    if (yes_we_did_the_one_time_job) {
        var = analogRead(A2);
        delay(10);
        if (var > 500) {
            stepper2();
            delay(2000);
            Serial.println("turned 1600");
        }
    }
    else {
        var2 = analogRead(A2);
        delay(10);
        if (var > 500) {
            stepper1();
            delay(2000);
            Serial.println("turned 200");
            yes_we_did_the_one_time_job = true;
        }
    }
}

```

This works now, thx !!!:

```
void loop() {
  static bool yeswedid = false;

  if(yeswedid) {
    if(analogRead(A2) > 500) {
    stepper1();
    stepper2();
    }
  }
  else {
    if(analogRead(A2) > 500) {
    stepper1();
    yeswedid = true;
  }

  }
}

```

# Answer
> 1 votes
Generic solution:

```
void loop() {
    static bool yes_we_did_the_one_time_job = false;
    if (yes_we_did_the_one_time_job) {
        do_the_other_jobs();
    } else {
        do_the_one_time_job();
        yes_we_did_the_one_time_job = true;
    }
}

```

# Answer
> 2 votes
If you have any code you want to run only once at the beggining of your program you can use the `setup()` method. It can actually do much more than just setting up pins and default values.

The code of main function of Arduino (main.cpp) looks like this:

```
int main(void)
{
    //(...) I cut some stuff from here

    setup();

    for (;;) {
        loop();
        if (serialEventRun) serialEventRun();
    }

    return 0;
}

```

As you can see `setup()` is just a method and it can do almost exactly the same things as `loop()`.

The `setup()` method can actually contain a `for(;;)` loop that will stop the program from running the `loop()` method. From inside it you can check the sensor value and `break` from it when condition is met.

```
void setup()
{
  for (;;)
  {
    var = analogRead(A2);
    delay(10);
    if (var > 500) {
      stepper1();
      delay(2000);
      Serial.println("turned 200");
      break;
    }
  }
}

```

in this case the `loop()` is very simple:

```
void loop()
{
  var = analogRead(A2);
  delay(10);
  if (var > 500)
  {
    stepper2();
    delay(2000);
    Serial.println("turned 1600");
  }
}

```

---
Tags: stepper
---


# Question
Title: How to keep the regulator cool while battery powering the arduino and accessories?
I'm trying to build a battery operated hand lantern. It has the Arduino, an MPU6050 accelerometer, and 4 APA106 (WS2812B-like) LEDs.

If everything's powered through the Arduino's 5V pins, that's 80mA for the Arduino, 240mA for the 4 LEDs, and let's round up to 5 mA for the MPU6050.

If I'm using 5x AA batteries for 7.5V (at full charge) that should be 2.5V * 325mA of power wasted or just under a watt that'll be heating up the regulator? I'm not sure if that's huge or tiny or in between or what.
What's the most sane way to power this device for an absolute newbie?

# Answer
> 1 votes
Use en external voltage regulator (go switch-mode if you care about battery life) that is adequately cooled.

# Answer
> 1 votes
1W is near the limit of what a small LDO can handle. It will get considerably hot.

I would use 4 batteries instead of 5, and a 3.3V Arduino clone instead of the UNO, and power the LEDs directly from the batteries. You could also use your original UNO, feeding it with 6V on a 5V pin through a simple diode, which would drop it to something like 5.4..5.3V.

# Answer
> 1 votes
I suggest using a DC-DC buck/boost voltage regulator. Those can take a wide range of input voltages and put out an adjustable output voltage

This one on Amazon, for example, can take an input of 3-40V and provide an output of 1.5-35V(Adjustable). It is a switching power supply, so it should not produce much waste heat. That one is rated at 2A, or 3A if you add a heat-sink.

You could feed the regulated 5V into the USB connector on your Arduino, and to your other components as well. (Just take a USB cable, cut it, and tie the red and black wires to ground and +5V, respectively.

You might need a filtering capacitor to protect the Arduino from voltage variations as the load on the power supply changes.

---
Tags: arduino-uno, power, led, battery
---


# Question
Title: Losing top brightness when using tip120 and PWM with 70w LED panel
I have been experimenting with pwm dimming using TIP120 on various high powered LED's, and have noticed a marked drop in the top level brightness compared to original connection without the tip 120 in line. For instance a 70w panel connected with heavier gauge cable (not using jumper cables) no longer reaches full brightness with pwm set too full. im using tasmota on a nodemc8266. Is there something inherent the hardware set up causing the loss that I am missing or is there a software limitation with PWM? curious

thanks

# Answer
Replace the TIP120 with a Low Rds N-channel MOSFET. Look at AOD508 or AOD514 for example, very low Rds, so it will develop very little voltage drop as the current increases.
> 0 votes

---
Tags: led, pwm
---


title: Arduino HID keyboard does not work

text:
# Question
Title: Arduino HID keyboard does not work
I'm using a ItsyBitsy 32u4, Adafruit says it can act as a USB HID keyboard. The mc is based on the 32u4 which the Keyboard docs say are supported.

I have a simple sketch that prints "A" every second and should press "A". When I upload the sketch and connect to the serial port I see the print output but I don't get any key presses.

Any ideas? I'm on linux, I suspect that the controller doesn't register as a HID device, maybe I need UDEV rules or drivers?

EDIT: the keyboard works on a different computer.

```
#include <Keyboard.h>
void setup() {
  Serial.begin(9600);
  Keyboard.begin();
  Serial.println("Start");
}

void loop() {
  Serial.println("a");
  Keyboard.write('a');
  delay(1000);
}

```

# Answer
> 0 votes
There was some issue with my laptop, not controller or the sketch.

I tried the my board with another computer and it worked. I tried a commercial keyboard on my first computer it also didn't work.

Both keyboards work after a reboot.

# Answer
> 2 votes
Keyboard.press() expects a character, but you are passing a character array. Also Keyboard.press() only presses but does not release the key. Keyboard.releaseAll() can be used to release all keys.

I would try:

```
Keyboard.press('A') ;  //note the ' instead of "
Keyboard.releaseAll();

```

or preferably:

```
Keyboard.write('A');   //handles press and release of basic keys

```

---
Tags: keyboard
---


# Question
Title: How to acheive fast and reliable communication between NodeMCUs?
I have two NodeMCU which have to send data to a server (also a NodeMCU). I want to acheive speed of atleast 10Hz because the sensor sends it at that rate. I have tried websockets and couldn't get transfer rate of more than 1Hz and the data was being put in the buffer.

Any ideas how could I can acheive speed of 10Hz via WiFi?

Thanks for any help.

# Answer
WiFiClient object wraps a TCP socket. A normal TCP socket is connected to IP address and port. WiFiServer starts a listening socket on a port. If server on listening socket is contacted by a remote client socket, it creates a local socket connected with the remote client socket on a free port and returns a WiFiClient object wrapping the socket. Everything you write or print to a WiFiClient is send to that one remote socket.

If one of your client boards creates a WiFiClient and connects it to IP address and port of the WiFiServer on your 'server' board, then you get there a WiFiClient from server.available() and this two WiFiClient objects are connected. What you write/print on one side you read from the WiFiClient object on the other side.

client socket

```
if (client.connect(serverIP, PORT)) {
  client.print("request\n");
  String response = client.readStringUntil('\n');
  Serial.println(response);
  client.stop();
}

```

server side

```
WiFiClient client = server.available();
if (client && client.connected()) {
  String request = client.readStringUntil('\n');
  Serial.println(request);
  client.print("response\n");
  client.stop();
}

```
> 2 votes

---
Tags: wifi, nodemcu
---


# Question
Title: Why the SoftwareSerial is not working properly on Arduino Pro Mini 3v3?
I uploaded regular pass through code for Serial and SoftwareSerial to communicate with my AT command based module.

Writing to SoftwareSerial seems to be working but reading not. As I write "AT", the module returns me "-5" which should be "OK".

As I write "asdad" the module returns something similar ot "invalid syntax" but very messy.

```
#include <SoftwareSerial.h>
SoftwareSerial ss(rx, tx);

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

void loop() {
  while (Serial.available()) ss.write(Serial.read());
  while (ss.available()) Serial.write(ss.read());
}

```

# Answer
> 0 votes
With SoftwareSerial 9600 baud is about the maximum rate you can reliably run at when using a 5V 16MHz Arduino. You are using an 8MHz one at 3.3V, so you can expect that speed cap to be halved.

Don't use SoftwareSerial. Ever. Full stop. There is no call to ever use it. If you don't have enough real UART ports on your board then you are using the wrong board. Don't just use a board because it's the one that everyone uses. Look at what you want to do and then pick a suitable board that fits your needs. There are many many 3.3V boards available with multiple (or even one single spare) UARTs - for example the Fubarino Mini, the Teensy 3.x, Any number of ESP32 based boards - all with a similar footprint to the Pro Mini, and with a huge amount more power to boot.

# Answer
> 0 votes
You may get better results if you do not nest the read and write function calls as you did. That is, read everything then write everything.

The reason for this is that softwareserial.read() returns 1 character. If you immediately turn around and pass that character to softwareserial.write() you will devote the resources of the processor to sending that character. In the meantime if another character is sent to the processor the processor will not see it or will only see part of it.

That said, you will likely get better results if you use a better embedded processor with dedicated serial port hardware for each port your project requires. Such as the Mega 2560 processor on the Arduino Mega.

Moving away from a cheap processor to one with enough hardware is a valid solution. Because, with another hardware serial port, the processor is only needed to read & write a character to & from the hardware using one command for each of these operations, not waste time reading & waiting each bit of a charater. A hardware serial port or UART can cut the effort of receiving & sending a character by the processor by more than an order of magnitude.

---
Tags: serial, atmega328, softwareserial, arduino-pro-mini
---


title: How to connect IRLZ44N to Arduino?

text:
# Question
Title: How to connect IRLZ44N to Arduino?
simulate this circuit – Schematic created using CircuitLab

In above schematic;

1. what value should R1 have? is it even needed?
2. do we need that pull down resistor(R2)? if yes, 10K is enough or we need higher value like 100K resistor there?

IRLZ44N DATASHEET

# Answer
> 2 votes
1. It's better with resistor so output driver isn't stressed to its maximum limits. Gate has its capacitance so it's better to limit charge/discharge current for such weak source
2. As the gate is basically capacitor, it has really big input impedance. Without pull down resistor it'll be catching all kinds of EMI (electro-magnetic interferences). So 10k is fine. The 100k might be less unreliable if the mcu output is not active (boot/reset)

---
Tags: mosfet
---


title: Insane heat development with ESP8266

text:
# Question
Title: Insane heat development with ESP8266
I have a ESP8266 on a Wemos D1 mini board. Simple "Rainbow with FastLED" animation. Shouldn't do much but the board gets so hot I can't touch it and it drains a 2500mAh battery in less than an hour.

Any idea what I'm doing wrong? Especially as a comparable micropython implementation just doesn't get that hot and the same battery keeps for about 5 hrs...

Here's the code

```
#define FASTLED_ALLOW_INTERRUPTS 0
#include "FastLED.h"
#include <EEPROM.h>

// How many leds in your strip?
#define NUM_LEDS 60
#define DATA_PIN 13
#define CLOCK_PIN 14
#define COLOR_ORDER RGB
int starthue = 0;
int incrementer = 255/NUM_LEDS;
CRGB leds[NUM_LEDS*2];
int address = 0;
int max_modes = 4;
int colormode;

void setup() {
  Serial.begin(9600);
  // put your setup code here, to run once:
  FastLED.addLeds<APA102, DATA_PIN, CLOCK_PIN, RGB>(leds, NUM_LEDS*2);
    EEPROM.begin(512);
  colormode = EEPROM.read(address);
  Serial.println(colormode);
  int new_mode = (colormode == max_modes) ? 1 : ++colormode;
  Serial.println(new_mode);
  new_mode = (colormode == 0) ? 1: new_mode;
  Serial.println(new_mode);
  EEPROM.write(address, new_mode);
  EEPROM.commit();
  EEPROM.end();
}

void rainbow_mid(int howfast) {
  while (true) {
    fill_rainbow(leds, NUM_LEDS, starthue, incrementer);
    for (int i =0; i< NUM_LEDS; i++) {
      leds[NUM_LEDS-i-1] = leds[i];
      leds[NUM_LEDS*2-i-1] = leds[i];
    }
    FastLED.show();
    delay(howfast);
    starthue++;
  }
}

void rainbow(int howfast) {
  while (true) {
    fill_rainbow(leds, NUM_LEDS, starthue, incrementer);
    //addGlitter(80);
    for (int i =0; i< NUM_LEDS; i++) {
      //leds[NUM_LEDS-i-1] = leds[i];
      leds[NUM_LEDS*2-i-1] = leds[i];
    }
    FastLED.show();
    delay(howfast);
    starthue++;
  }

}

void loop() {
  switch(colormode) {
    case 1: rainbow_mid(10); break;
    case 2: rainbow_mid(50); break;
    case 3: rainbow(10); break;
    case 4: rainbow(50); break;
  }

}

```

# Answer
> 1 votes
the heat is from the supply lines of board.

it's not the chip itself, as if it gets hot like that the chip should be destroyed. it seems you have connected 60 LEDs strip to the board and you provide it's supply from the board's supply line. so the lines get hot, and the board gets hot too. so the heat is not from the chip. its from power supply tracks on the PCB.

use another power source for the LED strip.

---
Tags: esp8266, led, eeprom
---


title: From Strings to int problem

text:
# Question
Title: From Strings to int problem
I create applications for a computer that is to be used to control the robot arm. I wanted to make the first attempt to run the application not on the motor, but on the diode and check if it will change its brightness depending on the position of the slider. I wrote an application in Qt that sends thongs to Arduino, and Arduino I read and converts to int. The problem is that although the slider is set to 0, the Arduino does not show it, often the figures do not agree too often (often too small), also when I suddenly move the number slider all the time count towards the front instead of back.

Arduino code:

```
String br;

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

void loop()
{
   while (Serial.available()>0)
 {
    br = Serial.readString();
    analogWrite(9, br.toInt());
    Serial.println(br.toInt());
 }
}

```

Qt code:

```
void MainWindow::on_horizontalSliderGrip_sliderMoved(int position)
{
   this->sendMessageToDevice(QString::number(position) + "n");
   qDebug() << "Grip: " << QString::number(position);
}

void MainWindow::sendMessageToDevice(QString message)
{
   if(this->device->isOpen() && this->device->isWritable())
   {
       //this->addToLogs("Sending information to the device " + message);
       this->device->write(message.toStdString().c_str());
   }
   else
   {
       this->addToLogs("I can not send a message. The port is not open!");
   }
}

```

# Answer
> 1 votes
As Majenko wrote in his comment, your problem lies with `Serial.readString()`. It is generally not a good way to handle Serial data. It reads data from the Serial interface, until the timeout (default 1s) occurs. So it will try to read until 1 second after your last change of the slider and return the whole data as one string. `String.toInt()` will then start to read the string from the first character and convert them to an integer, until it reads a non-digit character (meaning the `n`, that you send). It stops there and returns the already converted value.

This means, that out of all the data, that was send to the Arduino, only the first value will be used. The rest get's thrown away.

Better you should use a non-blocking code, that handles the messages (numbers in your case) correctly. This is done by reading the incoming serial data byte by byte, adding them into a buffer, until a special delimiter character get's received. Then the message get's processed as a whole. After that, the next message can be read and processed. This way you don't miss any of the send values.

The special delimiter character is arbitrary; you can use any character, that does not occur in the valid data. So using the character `n` is ok here. But mostly the newline character `\n` is used, so that you can also send messages with alphanumeric characters. Most likely you already meant to use `\n`.

As an example of this serial code, you can take the `readline()` function from Majenko's blog post:

```
char buf[80];

int readline(int readch, char *buffer, int len) {
    static int pos = 0;
    int rpos;

    if (readch > 0) {
        switch (readch) {
            case '\r': // Ignore CR
                break;
            case '\n': // Return on new-line
                rpos = pos;
                pos = 0;  // Reset position index ready for next time
                return rpos;
            default:
                if (pos < len-1) {
                    buffer[pos++] = readch;
                    buffer[pos] = 0;
                }
        }
    }
    return 0;
}

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

void loop() {
    if (readline(Serial.read(), buf, 80) > 0) {
        Serial.print("You entered: >");
        Serial.print(buf);
        Serial.println("<");
    }
}

```

You can convert the character buffer to an int with `atoi()` in the if statement in `void loop()` and use it for ´analogWrite()\`.

---
Tags: arduino-uno, serial, softwareserial, string
---


title: Stepper Motor Code. Delay or Millis

text:
# Question
Title: Stepper Motor Code. Delay or Millis
i will be designing a robot with multiple stepper motor. is it advisable to use millis instead of delay here or not? right now im testing if Millis() would work but still having a hard time programming this.

# Answer
Arduino function delay() which pauses the program for an amount of milliseconds specified as parameter.

millis(), on the other hand, is a function that returns the amount of milliseconds that have passed since program start.

Just like delay() has a microsecond-version called delayMicroseconds(), millis() has micros(). If you need better resolution, micros() may be the way to go.

However, be aware that micros() will overflow after approximately 70 minutes, compared to millis()‘s 50 days. This means that the functions’ return values will start all over from zero.
> 1 votes

---
Tags: stepper-motor
---