# Question
Title: What would be a good way to identify items spending as little as possible?
I'm a software developer for quite some time and now I'm going to start developing for Arduino. My question is related to technology I can use. It's also my first time posting here, so if this site is not the proper place for this questions would you tell me which one I could use to get this answer?

My problem:

I need to identify items within a certain range (~3ft). So I thought about a RFID tag on each item and a reader. The problem with that approach is currently the price. The lowest price I found for RFID tags are about US$0.09 per unit. Which is way too much for this project. up to US$0.01 per unit would be acceptable.

Is there any other way I could identify these items, based on range, not being directed to the reader's laser, that would be cheaper?

I though also about something like stores do with their products to prevent theft. Adding a plastic thingy on their clothes and those totems alert if an item with that plastic thingy passed through.

I appreciate any help :)

Thanks

**EDIT**

Imagine a bag and products being thrown inside this bag. In my mind I'd have a mechanism in which there would be like a rim around this bag that reads the products information. That rim would be a RFID (just for illustration's sake) reader.

Items would be thrown inside this bag, sometimes plenty of items at once. And they all need to be identified.

Something like this:

I'm not actually going to implement this solution on a bag, but I think it perfecly illustrates my point.

I hope I was able to clarify the problem now :)

# Answer
Seems like you're stuck in "requirements hell". In my theorie this means that your requirements are too strict, and you or your client won't let go of these requirements.

It can help to do a research, set up some "research questions". And if possible with some sub questions, like:

"How can we measure multiple objects at a price of only 0.01$ per object. Withouth having direct line of sight to all sides of the packaging."

With sub questions:

1. What techniques are available to identify objects.
2. In what environment will this system work?
3. How do other companies detect Products?
4. What techniques fit these requirements and environment.

And if none fit at question 4

5. How can we change the requirements or environment to have one technique fit.

---

The idea is, that after the research, you probably have a valid answer. But also that you can convince your Boss/client (or yourself), bases on your research, what solution is acceptable, even if it means altering the requirements.

You may also want to check how other companies do this, since it's a pretty common thing to identify objects etc.

---

For us, it is extremely difficult to say whatever will fit your needs. And you'll most likely have to adapt something.

To start off, you will either need some kind of vision or RF. But any RF tag is most likely to be too costly.

So you're either stuck with vision or increasing the price limit.

With vision, usually you either require some kind of barcode or qr code. Or you'll have to detect the object itself.

Another wat could be to differentiate on the objects' variables. Like check the weight, color, conductivity or even shape. This could be tricky, but not unlikely.

Mind that it also depends on what items you want to detect.
> 1 votes

---
Tags: project, project-critique
---


# Question
Title: Using an Arduino for a Diorama Controller
Kind of new to the whole DIY electronics scene.

I'm building a diorama for my son. It will include a length of track, a station, some other buildings, and scenery. It will be HO scale. The buildings came with these cool little LED lights and I've bought additional ones as well. I want it to be of the period of the late 1800s to early 1900s. So the additional LEDs I bought give off a more "yellow" light to simulate candle/lantern light. The track is not a circuit and is not powered. It is just "static" to sit a train so it appears to be at the station.

I have the following questions:

1. Could I hook up the LEDs to a Arduino and have the different buildings (or floors within a building) be controlled separately?
2. Could I make the LEDs "flicker" to simulate candle/lantern light?
3. Could I maybe hook up a little speaker inside the train station to give off train noises, whistles, conductor calls, etc?
4. Could this setup (Arduino with LEDs/speaker) be run off of batter power (not a custom battery, just off the shelf AAs, AAAs, or Cs, etc.)?
5. Is an Arduino instead the appropriate controller for this kind of project?

I think this is a great opportunity to teach my kids not only modeling but also electronics (myself as well on the electronics).

Thanks in advance for any help/suggestions.

**EDIT:**

A little more about the setup. The LEDs are made specifically for this type of application (model buildings/railroads). Hence, they already have an 1800 ohm resistor attached to the input side of the LED. There will indeed be multiple LEDs per building (even per floor). I would like to at least isolate the circuits by building and even better if I could isolate them by floor. I think it would be cool to have the software cycle the buildings/floors on and off at different times.

A smaller form factor for the Arduino would be ideal as it will have to fit into one of the scale buildings. I've never really worked with the Arduino so I don't know all my options. I've done a little with the Raspberry Pi and originally posted this question there and was told the Raspberry Pi would be overkill for this type of application.

# Answer
First, since you didn't mention any kind of Arduino, my answer is based on using Arduino Uno/Nano (I think its the most common)
1. Yes you can. You use 1 transistor per building as switch (if there are many LEDs in the building) to gives optimal current and prevent your Arduino pin. The value of R2 -- Rx is depend the LED colour. You can control each group with one Arduino pin.

simulate this circuit – Schematic created using CircuitLab

2. Yes you can, one in my mind is using PWM feature, like this project
3. Yes you can. But maybe the generated sound is not up to your expectation. Here is one of the simple example and this maybe a bit challenging.
4. The battery is up to your setup. More output (such as led and speaker) requires power source that can provide greater current. Arduino Uno voltage limit is 6v-20v
5. In my opinion, yes.

As for the form factor, I think Arduino Nano is small enough to hide in the building, while Arduino Uno size is just slightly less than a Raspberry Pi.

Good luck for your project :)
> 1 votes

---
Tags: led, battery, audio, speaker
---


title: IDE avoiding math operation

text:
# Question
Title: IDE avoiding math operation
I have no idea why this has been happening:

```
byte potenciometro = 0;int redpin=9;

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

void loop() {
int valor=analogRead(potenciometro);  delay(50);
Serial.println();
Serial.print(valor, DEC);

analogWrite(redpin,valor);   }

```

This code above has been working just fine. However, i understand the LEDs will work properly with intensities that range from 1 to 255, so i replaced this line

```
Serial.print(valor, DEC);

```

for this Serial.print((valor/700)\*255, DEC);

and all that the IDE has been returning since then is 0 as console output.

i tried also just

```
Serial.print(valor/700, DEC);

```

and i get nothing but 0s

anyone?

my arduino is the UNO version.

# Answer
> 2 votes
In the C family of programming languages, the division operator (`/`), when used with integer arguments, provides an *integer division*. You get the integer quotient, and you can use `%` to get the remainder.

If you want a floating point division, then at least one of the arguments should be a floating point number. E.g.:

```
Serial.print(valor / 700.0 * 255);

```

(the `DEC` argument is redundant). The final result is then truncated to an integer before being passed to `Serial.print()`.

A better option, which is outlined in dhimaspw's answer, is to do the multiplication before the division. This way you avoid costly floating point operations. If you do that, however, you should be careful about overflows: `valor*255` can be as big as 1023 × 255 = 260865, which is larger than the maximum value an `int` can store (215−1 = 32767). You should then write

```
Serial.print(valor * 255L / 700);

```

where the `L` suffix forces the operation to be carried using long integers.

The simplest solution, however, is to use the Arduino function `map()`, which does essentially the same as above:

```
Serial.print(map(valor, 0, 700, 0, 255));

```

# Answer
> 2 votes
Using `Serial.print (xx,DEC)` will give you a number on decimal base (round number). That's why your first code works

To solve this, you just simply change to

```
Serial.print((valor*255/700),4) //4 digits behind comma

```

---
Tags: arduino-uno, led, variables
---


# Question
Title: Getting different results from function. How to retrieve values correctly?
Trying to implement PI controller in function. Already worked for one controller. However, for more than one controller, the results are shifting. Suppose to get same values in the following code. Any help I appreciate it.

```
float r_in_1 = 10.00;
float y_out_1 = 5.00;

float r_in_2 = 10.00;
float y_out_2 = 5.00;

float r_o_1;
float y_o_1;

float r_o_2;
float y_o_2;

float vi_1 = 0;
float vi_2 = 0;

void setup() {

 Serial.begin(9600);

  // put your setup code here, to run once:

}

void loop() {
  // put your main code here, to run repeatedly:

r_o_1 = pow_2(r_in_1);

r_o_2 = pow_2(r_in_2);

y_o_1 = pow_2(y_out_1);

y_o_2 = pow_2(y_out_2);

vi_1 = PI_1(r_o_1, y_o_1);
vi_2 = PI_1(r_o_2, y_o_2);

Serial.print(vi_1);
Serial.print(',');
Serial.println(vi_2);
delay(1000);

}

float pow_2(float x){

float z;

z = x*x;

return z;

}

float PI_1(float r, float y){

float e;
static float sum_e=0;
float vi;
float kp=2.00;
float ki=10.00;

e = r - y;
sum_e =  sum_e + e;
vi = kp * e + ki * sum_e;

return vi;
}

```

# Answer
The problem is you declare `static float sum_e` in PI\_1 function. The value of will increase everytime PI\_1 function is called. In 1 loop, you call PI\_1 two times, resulting first call always smaller than second call because of the value of `sum_e`. Sum of error should be declared as global variable, and each controller has its own "sum" variable.
**Declare as global :**

```
float sum_e[100]; //for 100 controller.

```

**Your function**

```
float PI_1(float r, float y,int number){

float e;
float vi;
float kp=2.00;
float ki=10.00;

e = r - y;
sum_e[number] =  sum_e[number] + e;    //integrator for controller number
vi = kp * e + ki * sum_e[number];

return vi;
    }

```

**function call**

```
vi_1 = PI_1(r_o_1, y_o_1,1);
vi_2 = PI_1(r_o_2, y_o_2,2);

```

Here is the rough example. There are lot more efficient ways than this, but this should gives you some idea. You can reduce the code yourself since the values should be correct already.
> 1 votes

# Answer
A PI controller has “state”: it has to remember the sum of all the previous errors. If you want several controllers you have to independently store the state of each one.

The traditional solution used by C programmers is to write a controller function that takes an extra parameter which is a pointer to the state. In C++ you can use a reference instead:

```
// PI controller.
float PIController(float &sum, float r, float y)
{
    const float kp = 2.00;
    const float ki = 10.00;

    float e = r - y;  // error
    sum += e;         // integral of error
    return kp * e + ki * sum;
}

```

You would use it like this:

```
void loop()
{
    static float sum_1, sum_2;  // State of the controllers.
    // ...
    vi_1 = PIController(sum_1, r_o_1, y_o_1);
    vi_2 = PIController(sum_2, r_o_1, y_o_1);
}

```

The C++ language provides a nicer way of writing the same thing: you can use a class to wrap the state and the controlling method together under the same name:

```
// PI controller.
class PIController {
public:
    PIController() : sum(0) {}
    float operator()(float r, float y);
private:
    float sum;
};

float PIController::operator()(float r, float y)
{
    const float kp = 2.00;
    const float ki = 10.00;

    float e = r - y;  // error
    sum += e;         // integral of error
    return kp * e + ki * sum;
}

```

Which you would use like this:

```
void loop()
{
    static PIController pi_1, pi_2;  // Controller instances.
    // ...
    vi_1 = pi_1(r_o_1, y_o_1);
    vi_2 = pi_2(r_o_1, y_o_1);
}

```

The generated assembly should not be much different. Note that in both cases the static variables of `loop()` could be globals if you prefer.
> 1 votes

---
Tags: arduino-uno, programming
---


title: Converting char array to int

text:
# Question
Title: Converting char array to int
I'm trying to use nRF24L01 module to send a messages between 2 arduinos

Transmiter code:

```
  const char text[] = "Hello World";
  radio.write(&text, sizeof(text));

  delay(1000);

```

Reciver code:

```
char text[32] = {0};
radio.read(&text, sizeof(text));

Serial.println(text);

```

How I can put into char array an int value? I tried doing it in this way

For example: int a = 60; const char text\[\] = String(a); radio.write(&text, sizeof(text));

```
  delay(1000);

```

# Answer
> 0 votes
Are you just looking for a way to get an arbitrary number expressed as a string? If so, you'll likely want to use some existing functions to help you along.

I recommend using sprintf

```
sprintf(char * str, char * format, args)

```

Where str is the string you're storing results in, format is the string you're inserting your values into for, you guessed it, formatting, and args are all the args, separated by commas, that you'll be passing into the format string to be inserted into the str string. An example might be:

```
char[x] result;    //x is the number of elements in your array, atleast one for every letter and one for the end character, ex: "hello" needs 6.
int number = 24;
sprintf(result, "My number is %d", number);
sendSomewhere(result);   //sends "My number is 24"

```

# Answer
> 0 votes
You can not have 'const' prefixed the 'text' variable as it then become 'read-only'.

```
    char text[32];
    int a = 60;
    sprintf(text, "Number %d", a);
    radio.write(&text, sizeof(text));

```

# Answer
> 0 votes
The simplest method is to send the integer in binary format (skipping the conversion to text).

```
int a = 60;
radio.write((char*) &a, sizeof(a));

```

Cheers!

---
Tags: arduino-uno, wifi, arduino-leonardo, nrf24l01+, wireless
---


# Question
Title: How do I read data from Parallel port DB25 over my Arduino?
I am using this program. However, I am getting garbage values only. Do revert as to how can I get proper values over my arduino.

```
/*****************************************************************************/
* PrinterCapturePoll.ino
* ------------------
* Monitor a parallel port printer output and capture each character. Output the
* character on the USB serial port so it can be captured in a terminal program.
*
* By............: Paul Jewell
* Date..........: 29th January 2015
* Version.......: 0.1a
*-------------------------------------------------------------------------- -     ----
* Wiring Layout
* ------------ -
*
* Parallel Port Output               Arduino Input
* --------------------               ------------ -
* Name      Dir.   Pin                Name    Pin
* ----             -- -                ----    -- -
* nSTROBE    >       1..........................2
* DATA BYTE  >     2 - 9.......................3 - 10
* nACK       <      10.........................11
* BUSY       <      11.........................12
* OutofPaper <      12................GND
* Selected   <      13.................5v
* GND        <>  18 - 25................GND
*------------------------------------------------------------------------------ -
******************************************************************************** /

int nStrobe = 2;
int Data0   = 3;
int Data1   = 4;
int Data2   = 5;
int Data3   = 6;
int Data4   = 7;
int Data5   = 8;
int Data6   = 9;
int Data7   = 10;
int nAck    = 11;
int Busy    = 12;
int led     = 13; // use as status led

void setup() {
  // Configure pins
  pinMode(nStrobe, INPUT_PULLUP);
  for (int n = Data0; n < (Data7 + 1); n++)
    pinMode(n, INPUT_PULLUP);
  pinMode(nAck, OUTPUT);
  pinMode(Busy, OUTPUT);
  pinMode(led, OUTPUT);
  Serial.begin(9600);
  while (!Serial) {
    Serial.println("Waiting to Initialise");
  }
  //State = READY;
  delay(1000);
  Serial.println("Initialised");
  delay(1000);
}

void loop() {
  while (digitalRead(nStrobe) == HIGH) {
    digitalWrite(Busy, LOW);
    digitalWrite(nAck, HIGH);
    digitalWrite(led, HIGH);
    ProcessChar();
  }
  digitalWrite(Busy, HIGH);
  digitalWrite(led, LOW);
  digitalWrite(nAck, LOW);
  delay(5); //milliseconds. Specification minimum = 5 us
}

void ProcessChar() {
  byte Char;
  Char = digitalRead(Data0) +
         (digitalRead(Data1) << 1) +
         (digitalRead(Data2) << 2) +
         (digitalRead(Data3) << 3) +
         (digitalRead(Data4) << 4) +
         (digitalRead(Data5) << 5) +
         (digitalRead(Data6) << 6) +
         (digitalRead(Data7) << 7);
  Serial.print(char(Char));
}

```

# Answer
I think I can see the problem - although I have no way to test it.

According to Wikipedia:

> When the data was ready, the host pulled the STROBE pin low, to 0 V. The printer responded by pulling the BUSY line high, printing the character, and then returning BUSY to low again.

That's not what you're doing - you are repeatedly reading while the strobe is HIGH.

Here's my attempt at your loop() which I hope will at least get you started:

```
void loop()
{
    // Wait for strobe to go LOW, indicating a character is ready
    while (digitalRead(nStrobe) == LOW) {
        delay(1)
    };

    // Strobe is now LOW - a character is ready.
    // Pull BUSY to high
    // (NB: I don't know what you're doing with nAct and led)
    digitalWrite(Busy, HIGH);
    digitalWrite(led, LOW);
    digitalWrite(nAck,LOW);

    // Print the character
    ProcessChar();

    // Return BUSY to low again
    // (NB: I don't know what you're doing with nAct and led)
    digitalWrite(Busy, LOW);
    digitalWrite(led, HIGH);
    digitalWrite(nAck,HIGH);

    // Wait for the strobe to go HIGH again
    while (digitalRead(nStrobe) == LOW) {
        delay(1)
    };
}

```

You should also probably consider setting the initial values of your outputs (BUSY and nAck) rather than relying on them defaulting to some particular state. I don't know what (n)Ack is for in this case -- Wikipedia doesn't mention it.
> 1 votes

# Answer
Do you know the printer is working properly?

You are trying to fix more than one thing at once and that's never a good idea. What I suggest you do is get a breadboard and make your own printer simulator. You need to connect and LED up to every output pin and a button to every input pin.

Then you can simulate data from the printer, i.e. just pressing the button for pin 3 and you should see 1 coming out on the serial monitor. OK I agree this "simulator" is rubbish, but you probably have the bits to knock it up now.

If you are still seeing 'junk' values then have a look and see if there is a pattern to the data. This would be helped by printing the values in hex.

Of course if the Arduino side works then the issue is that the printer is sending data that you are not expecting. It might help stick LEDs on every pin, both directions, it will help you see what is being sent.

Its possible that you are expecting 1 to indicate the bit is set and the printer is using 0.
> 0 votes

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


# Question
Title: Arduino DUE deadlock problem, watchdog not working
I am using Arduino DUE in my project. The project is massive (about 7000 lines of code in total, with massive schematic), so I decided not to post the whole code and schematic, except explain the hardware and configuration I am working with:

* **Arduino DUE;**
* **12V switching power supply**;
* **LTC1660 DAC** (used withstandard SPI library);
* **Nextion HMI** (Used with standard library `#include Nextion.h //INCLUDE NEXTION LIBRARY)`;
* **DS3231 RTC module** on I2C bus (Library used: Wire `#include <DS3231.h>`)
* **24LC256 EEPROM** on same I2C bus (Library used: Ext EEPROM `#include <extEEPROM.h>`)

The base line, is that on power-on the controller just freezes besides, it can't be the problem with power as I get this problem using both 12 V from switching PSU and 5 V USB cable. I can not really analyse the problem, as the deadlock occurs even before the program start to execute content of `void setup()`. My best guess is that the deadlock occurs due to infinite loops in the Arduino's `twi.cpp` where infinite loop can occur if the controller receives no acknowledge bit. But then again I can not be sure here. However when I push restart button on the Arduino or enable Serial monitor in Arduino IDE when the circuit is powered on , it starts to work, and it works just as expected.

After reading the datasheet for the DUE's μC, I've found that it have the watchdog option embedded:

> After a Processor Reset, the value of WDV is `0xFFF`, corresponding to the maximum value of the counter with the external reset generation enabled (field `WDRSTEN` at 1 after a Backup Reset). This means that a default Watchdog is running at reset, i.e., at power-up. The user must either disable it (by setting the `WDDIS` bit in `WDT_MR`) if he does not expect to use it or must reprogram it to meet the maximum Watchdog period the application requires. The Watchdog Mode Register (`WDT_MR`) can be written only once. Only a processor reset resets it. Writing the `WDT_MR` register reloads the timer with the newly programmed mode parameters.

I've started to explore it, and as I got it, the watchdog is ON by default, and its timer period is 16 seconds by default, so as it is not normally used in DUE, I assumed, that somewhere it is just disabled, and in `main.cpp` I found the following:

```
int main( void )
{
   // Initialize watchdog
   watchdogSetup();
   init();
   initVariant();

```

where `watchdogSetup()` led to:

```
void watchdogDisable(void)
{
   WDT_Disable (WDT);
}
void watchdogReset(void)
{
   WDT_Restart (WDT);
}
extern "C"
void _watchdogDefaultSetup (void)
{
   WDT_Disable (WDT);
}
void watchdogSetup (void) __attribute__ ((weak, alias("_watchdogDefaultSetup")));

```

As I got it, due to this, the watchdog was disabled for DUE by default, and commenting out `watchdogSetup();` in `int main()` would allow the watchdog to work (as watchdog is on at power on by default, according to datasheet).

I've also added the `WDT_Restart (WDT);` to `void loop()` of the program in order to kick watchdog every program cycle.

Well, for some reason, that did not help me, and I'm still receiving the deadlock when I power on the controller, even through the watchdog is technically not disabled, after 16 seconds it still do not restart the system. And, pressing the reset button or the Serial monitor in Arduino IDE makes the system run as expected. Am I missing something out? Your help and suggestions are appreciated, shall any additional info be needed, just let me know, I need to get this project running so badly.

By the way, my `void setup()` function is quite long, and if I set the watchdog to 1 second, using `void watchdogEnable (uint32_t timeout)` instead of commenting out `watchdogSetup()` in `main.cpp`, and use reset button after power on, I can see the watchdog working as it can't get to `void loop()` in time in order to reset watchdog (as `void setup()` takes about 3 seconds due to delays).

# Answer
> 0 votes
Found people suffering with the same problem on Arduino's official forum. It turned out that the problem arises from the schematic of Arduino Due, that fails to hold 'reset' pin high for long enough period of time on power-on.

There are multiple solutions involving adding some capacitance between reset pin and ground pin, but this might damage circuit in long run (at power-off), so I managed to find other way around it: **there is an ATmega16U2 used as USE-to-TLL serial chip that have access to reset pin of AT91SAM3X8E.**

The ATmega16u2 can be reprogrammed so that on power-on it provide short "HIGH" period to AT91SAM3X8E reset pin. The program for ATmega16U2 can be found here: https://forum.arduino.cc/index.php?action=dlattach;topic=167492.0;attach=52901

The updating precision is given here: https://www.arduino.cc/en/Hacking/Upgrading16U2Due

**I've performed the given precision using Arduino UNO as programmer and can confirm that it worked properly.The problem's gone now.**

---
Tags: arduino-due
---


title: Update custom library

text:
# Question
Title: Update custom library
I've recently made a custom library. Then, I've imported the library into the IDE via the `add .zip library`. Once I tried to compile the code, I've realised that I made a small typo. Once I changed the error and then retried to compile the code, the error still appeirs and I'm **quite** sure that I've changed it.

So my guess is that the library is not updating. I've tried to go to manage library and then seeing if there is an other version of the library. There wasn't any.

So is there an easy fix to this solution that doesn't involve updating or downgrading the IDE?

# Answer
I actually found this answer on Stack Overflow.

> In the Arduino GUI on windows, if I click on Sketch --\> Import Library, at the bottom of the menu there is a section called "Contributed".
>
> Unfortunately, I had misclicked and added a library I did not want to that list.
>
> **How can I remove it from that list?**
>
> The help page only mentions that "If a sketch no longer needs a library, simply delete its #include statements from the top of your code" but it does not mention how to remove the library from the list of contributed libraries.

By : @merlin2011 from *Stack Overflow*.
> 0 votes

# Answer
Text from here says this:

> In Arduino v16 and earlier, libraries were stored in the ArduinoInstallDirectory/hardware/libraries folder, which also contained all the built-in libraries (like Wire and Serial).
>
> In v17 and up, the user libraries are now stored in the ArduinoSketchDirectory/libraries folder.

Check your version of the Arduino SDK and then look in the appropriate directory for your library source code. Then change it there.

The Arduino SDK is fairly simple and often compiles everything to avoid problems like this. The installing from a zip file feature (unless it has changed) is more for convenience when downloading a single zip file. I have often developed & edited custom library source code where the SDK expects to find it.
> 1 votes

---
Tags: library, ide
---


# Question
Title: Mega 2560 & smoking/burning 5v requlator, probable cause?
Problem: board seriously fried. Desired outcome: measures to take in future.

Background: This project has been running for about a week on the 2560, and previously for a few weeks on an UNO clone. Board switch a result of program size/expansion. It sits on a shelf with others of the same ilk. Nothing is touched unless I need to plug in USB cable for update. The Arduino is a clone, connected to DS3231, LCD1602 via I2C Serial Interface board, LCD2004 also via 12C SIB, SD card adapter, HC-12 wireless, 5 leds \[normally off, used to flag specific conditions, each in series with 470 ohm resistor. The unit receives data from another Arduino and logs to the SD, updating the two LCD displays.

Steps leading to failure: Plugged in USB cable \[no other physical changes, nothing else touched, power jack remained connected\]. went to Arduino s/w to make minor changes, would not upload to Arduino. While scratching my head, smelled something burning, then saw smoke coming from the shelf.

Post failure: Board seriously scorched around 5v regulator, can provide photo, but seems unnecessary. Visual wiring inspection revealed no obvious problems. Input to power jack measured at 10.06v. Replaced with new Arduino 2560 clone, matching connection for connection, connected USB but not power port \[just in case of ?, seen ancedotal posts of possible conflict; a clone after all\]. Uploaded my modified program, and all works fine. Disconnected USB, reconnected power jack and all still fine, 16 hours in. Also searched internet for possible problems related to such a failure, but found nothing to suggest probable cause.

Seeking: Words of wisdom from others far more knowledgeable and experienced than I. Could the dual connection of USB and power jack, be the root cause? Never experienced this with UNO clones.

I do not want to put more boards at risk in the future.

# Answer
> 2 votes
They are using the same SOT223 LDO as every other product. These have a very low limit of output current when run from an input voltage such as 12V. If you replace the LDO with a switching regulator, you can eliminate the waste heat regardless of the output current (Except for the 5V to 3.3V secondary LDO which is a constant). The PDF linked below shows a comparison between the LDO and drop in switcher. Not that the switcher performance at 1900mA is equivalent to the LDO at 250mA... at 250mA the switcher temperature rise would only be 8.5C.

https://www.sugarsync.com/pf/D3258881\_07979653\_7526812

---
Tags: arduino-mega, power, voltage-protection
---


title: Arduino USB Host Shield with joystick

text:
# Question
Title: Arduino USB Host Shield with joystick
I'm building my own quadcopter and going to use an Arduino for this. An Arduino Micro for the quadcopter and an Arduino UNO for the controller. I want to use an USB host shield with a Logitech Extreme 3D Pro to control the quadcopter.

I have the joystick already working with de example from the USB host shield example, but I can't get the values to my `void loop()`. There is not much information on the internet about this.

The link to the library and example I'm using: https://github.com/felis/USB\_Host\_Shield\_2.0/tree/master/examples/HID/le3dp

.INO file:

```
/* Simplified Logitech Extreme 3D Pro Joystick Report Parser */

#include <hid.h>
#include <hiduniversal.h>
#include <usbhub.h>

#include "le3dp_rptparser.h"

// Satisfy the IDE, which needs to see the include statment in the ino too.
#ifdef dobogusinclude
#include <spi4teensy3.h>
#include <SPI.h>
#endif

USB                                             Usb;
USBHub                                          Hub(&Usb);
HIDUniversal                                    Hid(&Usb);
JoystickEvents                                  JoyEvents;
JoystickReportParser                            Joy(&JoyEvents);

void setup()
{
  Serial.begin( 115200 );
#if !defined(__MIPSEL__)
  while (!Serial); // Wait for serial port to connect - used on Leonardo, Teensy and other boards with built-in USB CDC serial connection
#endif
  Serial.println("Start");

  if (Usb.Init() == -1)
      Serial.println("OSC did not start.");

  delay( 200 );

  if (!Hid.SetReportParser(0, &Joy))
      ErrorMessage<uint8_t>(PSTR("SetReportParser"), 1  );
}

void loop()
{
    Usb.Task();
}

```

.cpp file:

```
#include "le3dp_rptparser.h"

JoystickReportParser::JoystickReportParser(JoystickEvents *evt) :
    joyEvents(evt)
{}

void JoystickReportParser::Parse(HID *hid, bool is_rpt_id, uint8_t len, uint8_t *buf)
{
    bool match = true;

    // Checking if there are changes in report since the method was last called
    for (uint8_t i=0; i<RPT_GAMEPAD_LEN; i++) {
        if( buf[i] != oldPad[i] ) {
            match = false;
            break;
        }
  }
    // Calling Game Pad event handler
    if (!match && joyEvents) {
        joyEvents->OnGamePadChanged((const GamePadEventData*)buf);

        for (uint8_t i=0; i<RPT_GAMEPAD_LEN; i++) oldPad[i] = buf[i];
    }
}

void JoystickEvents::OnGamePadChanged(const GamePadEventData *evt)
{
    Serial.print("X: ");
    PrintHex<uint16_t>(evt->x, 0x80);
    Serial.print(" Y: ");
    PrintHex<uint16_t>(evt->y, 0x80);
    Serial.print(" Hat Switch: ");
    PrintHex<uint8_t>(evt->hat, 0x80);
    Serial.print(" Twist: ");
    PrintHex<uint8_t>(evt->twist, 0x80);
    Serial.print(" Slider: ");
    PrintHex<uint8_t>(evt->slider, 0x80);
    Serial.print(" Buttons A: ");
    PrintHex<uint8_t>(evt->buttons_a, 0x80);
    Serial.print(" Buttons B: ");
    PrintHex<uint8_t>(evt->buttons_b, 0x80);
    Serial.println("");
}

```

.h file:

```
#if !defined(__HIDJOYSTICKRPTPARSER_H__)
#define __HIDJOYSTICKRPTPARSER_H__

#include <hid.h>

struct GamePadEventData
{
  union { //axes and hut switch
    uint32_t axes;
    struct {
      uint32_t x : 10;
      uint32_t y : 10;
      uint32_t hat : 4;
      uint32_t twist : 8;
    };
  };
  uint8_t buttons_a;
  uint8_t slider;
  uint8_t buttons_b;
};

class JoystickEvents
{
public:
    virtual void OnGamePadChanged(const GamePadEventData *evt);
};

#define RPT_GAMEPAD_LEN sizeof(GamePadEventData)/sizeof(uint8_t)

class JoystickReportParser : public HIDReportParser
{
    JoystickEvents      *joyEvents;

  uint8_t oldPad[RPT_GAMEPAD_LEN];

public:
    JoystickReportParser(JoystickEvents *evt);

    virtual void Parse(HID *hid, bool is_rpt_id, uint8_t len, uint8_t *buf);
};

#endif // __HIDJOYSTICKRPTPARSER_H__

```

So I hope that someone can give me a solution how I can get the value out of the code below (I changed the code a bit, so that I get decimal values) into the void loop().

```
void JoystickEvents::OnGamePadChanged(const GamePadEventData *evt)
{
    Serial.print("X: ");
    Serial.print(evt->x);
    Serial.print("\t Y: ");
    Serial.print(evt->y);
    Serial.print("\t Hat Switch: ");
    Serial.print(evt->hat);
    Serial.print("\t Twist: ");
    Serial.print(evt->twist);
    Serial.print("\t Slider: ");
    Serial.print(evt->slider);
    Serial.print("\t Buttons A: ");
    Serial.print(evt->buttons_a);
    Serial.print("\t Buttons B: ");
    Serial.print(evt->buttons_b);
    Serial.println("");
}

```

I've some experience with Arduino programming but not much.

Please ask me if you need more information.

# Answer
> 1 votes
The following assumes you are seeing `OnGamePadChanged` being called.

One way you could get the values you want (`GamePadEventData *evt`) into the `loop()` would be to add a member variable to the `JoystickEvents` class, so that class would become something like

```
class JoystickEvents
{
public:
    virtual void OnGamePadChanged(const GamePadEventData *evt);
    static GamePadEventData mostRecentEvent;
};

```

In `OnGamePadChanged`, make a copy of `evt`:

```
GamePadEventData JoystickEvents::mostRecentEvent;
void JoystickEvents::OnGamePadChanged(const GamePadEventData *evt)
{
    mostReventEvent = *evt;
}

```

Now you can read it from `loop()` using something like

```
Serial.print("X: ");
Serial.print(JoystickEvents::mostReventEvent.x);

```

A significant limitation of this method is that it will only keep the most recent event. Maybe that's OK for your purpose.

It's probably not quite what the author of that code had in mind: he probably expected you to do the work in `OnGamePadChanged`: his implementation of that method looks like an example so you can see how it works.

# Answer
> 0 votes
After trying some other things I came up with the following idea:

I moved this piece of code from the .cpp file to the .INO file:

```
void JoystickEvents::OnGamePadChanged(const GamePadEventData *evt)
{
    Serial.print("X: ");
    PrintHex<uint16_t>(evt->x, 0x80);
    Serial.print(" Y: ");
    PrintHex<uint16_t>(evt->y, 0x80);
    Serial.print(" Hat Switch: ");
    PrintHex<uint8_t>(evt->hat, 0x80);
    Serial.print(" Twist: ");
    PrintHex<uint8_t>(evt->twist, 0x80);
    Serial.print(" Slider: ");
    PrintHex<uint8_t>(evt->slider, 0x80);
    Serial.print(" Buttons A: ");
    PrintHex<uint8_t>(evt->buttons_a, 0x80);
    Serial.print(" Buttons B: ");
    PrintHex<uint8_t>(evt->buttons_b, 0x80);
    Serial.println("");
}

```

After I changed some of the code in the .INO file the code looks like this:

```
/* Simplified Logitech Extreme 3D Pro Joystick Report Parser */

#include <hid.h>
#include <hiduniversal.h>
#include <usbhub.h>

#include "le3dp_rptparser.h"

int joyX = 512;       // min: 0 | max: 1023 | center: 512
int joyY = 512;       // min: 0 | max: 1023 | center: 512
int joyHat = 8;       // up: 0 | right-up: 1 | right: 2 | right-down: 3 | down: 4 | left-down: 5 | left: 6 | left-up: 7 | center: 8
int joyTwist = 128;   // min: 0 | max: 255 | center: 128
int joySlider = 0;    // min: 0 | max: 255
int joyButtonsA = 0;
int joyButtonsB = 0;

// Satisfy the IDE, which needs to see the include statment in the ino too.
#ifdef dobogusinclude
#include <spi4teensy3.h>
#include <SPI.h>
#endif

USB                                             Usb;
USBHub                                          Hub(&Usb);
HIDUniversal                                    Hid(&Usb);
JoystickEvents                                  JoyEvents;
JoystickReportParser                            Joy(&JoyEvents);

void setup()
{
  Serial.begin( 115200 );
#if !defined(__MIPSEL__)
  while (!Serial); // Wait for serial port to connect - used on Leonardo, Teensy and other boards with built-in USB CDC serial connection
#endif
  Serial.println("Start");

  if (Usb.Init() == -1)
      Serial.println("OSC did not start.");

  delay( 200 );

  if (!Hid.SetReportParser(0, &Joy))
      ErrorMessage<uint8_t>(PSTR("SetReportParser"), 1  );
}

void loop()
{
    //Print all the values into the serial monitor:
    Usb.Task();
    Serial.print("X: ");
    Serial.print(joyX);
    Serial.print("\t Y: ");
    Serial.print(joyY);
    Serial.print("\t Hat: ");
    Serial.print(joyHat);
    Serial.print("\t Twist: ");
    Serial.print(joyTwist);
    Serial.print("\t Slider: ");
    Serial.print(joySlider);
    Serial.print("\t Buttons A: ");
    Serial.print(joyButtonsA);
    Serial.print("\t Buttons B: ");
    Serial.println(joyButtonsB);
}

void JoystickEvents::OnGamePadChanged(const GamePadEventData *evt)
{
  //Put the values from the joystick in another variable:
  joyX = evt->x;
  joyY = evt->y;
  joyHat = evt->hat;
  joyTwist = evt->twist;
  joySlider = evt->slider;
  joyButtonsA = evt->buttons_a;
  joyButtonsB = evt->buttons_b;
}

```

It works very good for me and I'm now able to send the values to another Arduino with the nRF24L01+.

---
Tags: arduino-uno, usb, shields, joystick
---


# Question
Title: Arduino Uno: how to increase distance of serial communication to PC
Does Arduino Uno's serial communication to PC has the same distance as USB communication? (if I'm not mistaken 5m) If it is, what are the options for me to be able to communicate from Arduino Uno to PC with a longer distance? Thank you for any help!

# Answer
> 1 votes
There are many options of varying complexities, pros, cons and prices.

The simplest method is to use powered USB hubs to extend the range. It's 5m per run of cable between powered hubs, so if you have access to power at 5m intervals (or can provide power at 5m intervals) you can chain hubs together to increase your distance. That rapidly becomes unwieldy and expensive though.

Assuming you want to keep the ability to directly program your Arduino from the PC without having to mess with swapping cables around, etc, other options include:

* USB over CAT5 adapters (up to 100m length)
* Bypass the USB altogether and use RS-232 (MAX-232 chips, about 15m length)

There are also some bluetooth adaptors that allow programming of the Arduino, but that gets a bit tricky.

If you're not too worried about programming there are far more options:

* Radio options, such as using XBees, nRF24L01 modules, etc.
* Networking - connect to an Ethernet or WiFi network
* GSM modem
* RS-485 / RS-422 - similar to RS-232 but longer distance, and without the signals needed for rebooting the Arduino for programming

The "distance" of the fully networked options is, literally, global. Once on a network you have the option of arranging access from anywhere on the globe with an internet connection

It all depends, really, on what you want to be able to do over the connection.

<sub>(I am sure there are many more options I have forgotten - feel free to suggest them in comments, or even go ahead and edit this answer to add them if you like.)</sub>

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


# Question
Title: How to use potentiometer data from slave to master Arduino?
I'm trying to make a game where i can use one Arduino as a controller (the controller is a potentiometer) and the other Arduino sending the signals to the computer. Im trying to figure out communication with two Arduino's so i would like to use two instead of one although using one would be logical and easier. Ive tried looking into I2C but cant seem to figure it out.

# Answer
Start by reading the potentiometer. Add a Wire request service function and that makes the Slave:

```
#include <Wire.h>

const uint8_t controllerAddress = 8;
const int controllerPin = A0;
volatile int controllerValue = 0;

void setup() {
  Wire.begin(controllerAddress);
  Wire.onRequest(requestEvent);
}

void loop() {
  int value = analogRead(controllerPin);
  noInterrupts();
    controllerValue = value;
  interrupts();
}

void requestEvent() {
  Wire.write((const uint8_t*) &controllerValue, sizeof(controllerValue));
}

```

This is minor update of the Arduino Wire Master Reader tutorial. The sketch for the Master is left as an exercise.

Cheers!
> 1 votes

---
Tags: arduino-uno, i2c
---


# Question
Title: How to interpret accelerometer data to get decimals from -255 to 255
I'm using gy-521 module and I'm wondering how can i get useful readings from it so that i could work with the data that I'm receiving.

I want for AcX and AcY variable values to be from -255 to 255. How to make this work.

sample data that I'm getting right now

```
X = 16380 Y = -64
X = 8116 Y = 3520
X = 12564 Y = 8728
X = -12652 Y = 1296
X = -17732 Y = -2420
X = -14576 Y = -2264

```

;

```
#include<Wire.h>
const int MPU_addr=0x68;
int16_t AcX,AcY;
void setup(){
  Wire.begin();
  Wire.beginTransmission(MPU_addr);
  Wire.write(0x6B);
  Wire.write(0);
  Wire.endTransmission(true);
  Serial.begin(9600);
}

void loop(){
  Wire.beginTransmission(MPU_addr);
  Wire.write(0x3B);  // starting with register 0x3B (ACCEL_XOUT_H)
  Wire.endTransmission(false);
  Wire.requestFrom(MPU_addr,14,true);
  AcX=Wire.read()<<8|Wire.read();
  AcY=Wire.read()<<8|Wire.read();

  Serial.print("X = "); Serial.print(AcX);
  Serial.print(" Y = "); Serial.println(AcY);

  delay(333);
}

```

# Answer
Use this code:

```
AcX = map(AcX, -32768, 32767, -255, 255);
AcY = map(AcY, -32768, 32767, -255, 255);

```

Of course, you won't be able to store the resulting value in `int8_t` since its range is from -128 to 127.

Here you can read more about Arduino `map()` function.
> 0 votes

---
Tags: arduino-ide
---


# Question
Title: RF24 communication between Leonardo and Micro not responding
I have Arduino Leonardo and Micro. I can't manage them to communicate via nRF24L01. I made a receiver and sender sketch to test it and can't see any respond. I tested the same code on two arduino nano and they work fine.

I connected the pins correctly using the ICSP pins in Leonardo and corresponding pins (not ICSP) dedicated for SPI in Micro.

Please could someone tell me what am I missing in porting sketch from nano-nano to leonardo-micro?

Here are the sketches:

PS some additional channels are left to see what I expected from working sketch.

Receiver module:

```
//NRF24
#include <SPI.h>
#include "nRF24L01.h"
#include "RF24.h"
RF24 radio(9, 10);
byte addresses[][6] = {"1Node", "2Node", "3Node", "4Node"};

int channel = 1;

void setup() {
  // put your setup code here, to run once:
  Serial.begin(115200);
  radio.begin();
  radio.setAutoAck(1);
  radio.setRetries(15, 15);
  radio.openReadingPipe(1, addresses[0]);
  radio.openReadingPipe(2, addresses[1]);
  radio.openReadingPipe(3, addresses[2]);
  radio.openReadingPipe(4, addresses[3]);
  radio.startListening();
}

void loop() {
  // put your main code here, to run repeatedly:
  while (radio.available()) {
    char theMessage[13];
     radio.read(&theMessage, 13);
     Serial.println(theMessage);
     if(theMessage == "testingsend"){
       //this is removed in nano
      digitalWrite(13,HIGH);
      delay(50);
      digitalWrite(13,LOW);
     }
  }
}

```

And the sender:

```
//NRF24
#include <SPI.h>
#include "nRF24L01.h"
#include "RF24.h"
RF24 radio(9, 10);
byte addresses[][6] = {"1Node", "2Node", "3Node", "4Node"};

int channel = 1;

void setup() {
  // put your setup code here, to run once:
  radio.begin();
  radio.setAutoAck(1);
  radio.setRetries(15, 15);
  radio.openWritingPipe(addresses[channel]);
}

void loop() {
  // put your main code here, to run repeatedly:
  char theMessage[13] = "testingsend";
  radio.write(theMessage, sizeof(theMessage));
  memset(theMessage,0,sizeof(theMessage));
  delay(300);
}

```

# Answer
Ok I solved the issue, somehow I had to use 10 uF capacitor instead of 4.7 uF
> 0 votes

---
Tags: communication, arduino-leonardo, nrf24l01+
---


title: Hold a random number

text:
# Question
Title: Hold a random number
I am trying to create a code that has at least 6 servos attached and two buttons for a two player game. I want to be able to roll a random number and have it hold that value then when it is that players turn. The program should also take that previous number and add it to the next. It would eventually be adding up all the values of the rolls. This is what I have so far. Any advice would be helpful. Thanks!

```
#include <Servo.h>

Servo myservo;

int pos = 0;    // variable to store the servo position
int x;
int button = 8;
int BUTTON;
int randomNumber;
int xPrevious;

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

void loop() {
  for (x = 2; x <= 7; x += 1) {
    myservo.attach(x);

    for (pos = 0; pos <= 180; pos += 1) { // goes from 0 degrees to 180 degrees
      // in steps of 1 degree
      myservo.write(pos);              // tell servo to go to position in variable 'pos'
      delay(15);                       // waits 15ms for the servo to reach the position
    }
    for (pos = 180; pos >= 0; pos -= 1) { // goes from 180 degrees to 0 degrees
      myservo.write(pos);              // tell servo to go to position in variable 'pos'
      delay(15);                       // waits 15ms for the servo to reach the position

      BUTTON = digitalRead(button);
      if(BUTTON == LOW){
        randomNumber = random(1,7);
        delay(350);
        Serial.println(randomNumber);
      }
    }
    randomNumber += xPrevious;
  }
}

```

# Answer
You are redefining the random number wrongly each time with

```
randomNumber += xPrevious;

```

this is an error. You need another new variable (initialised at 0) to keep the running totals of all the random "rolls". You should be able to fix your program now you know this. Maybe something like

```
TotalofTherandomNumbers += xPrevious;

```

to start off with.

You may also want to add in the after the line

```
 randomNumber = random(1,7);

```

a new function, of yours, that takes random value randomNumber do the action in the game, what ever that is, depending on if its the first or second player.
> 1 votes

# Answer
Your xPrevious is declared but never given any value.

Is this what you're looking for?

```
    randomNumber += random(1,7);

```

Another thing is that you should not assume that randomNumber is initialized to 0. Better assign it a starting value.

```
    int randomNumber = 0;   // or whatever you want

```

Lastly, an Arduino int is a 2 bytes signed number. If the game goes on for a long time the variable will roll over at 32,767. Consider making it a unsigned long instead.
> 0 votes

---
Tags: servo, button
---


# Question
Title: delete or free on object causes Arduino to hand or reboot
I've read a lot about dynamic allocation for strings or buffers, but that's not my case.

I plan to implement much blinkers types as classes, all inheriting from a base `Action` class.

I declare an array of 10 pointers because I want to limit to 10 blinkers simultaneously at most :

```
Action** actions = new Action*[10];

```

In the code, I will do something like :

```
int i = GetFreeActionID();
actions[i] = new ActionLightBlinkerMono(myPin, onDuration, offDuration);

```

Then the loop will call a method of the object and it works fine.

When it comes to stop the blinking, I would just destroy the object and set the pointer to zero, so the loop will not try to call the method of the object anymore :

```
if (actions[i]->Do() != 0)
{
  delete(actions[i]);
  actions[i] == 0;
}

```

Howerver, I see in the serial console that when it comes to the `delete` instruction, the Arduino just reboots itself ...

Tryed also `free` instead of `delete` with same result.

How could I safely free the object when it's not used anymore ?

It's an evidence I don't know what will be used at compile time, the blinkers will be started by the user (via I2C instructions) at runtime, hence instanciating different classes.

# Answer
> ```
>   actions[i] == 0;
>
> ```

That statement has no useful effect. Perhaps you mean:

```
actions[i] = 0;

```
> 0 votes

---
Tags: c++, memory-usage, memory
---


# Question
Title: How to use this Arduino code to control multiple different LEDs?
I am making an Android-controlled LED system over Bluetooth but I need to use 4 LEDs. I have done Android app but I am not able to figure out this Arduino code. Can some please help me get this done?

```
char command;
String string;
boolean ledon = false;
#define led 5

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

void loop() {
  if (Serial.available() > 0) {
    string = "";
  }

  while(Serial.available() > 0) {
    command = ((byte)Serial.read());
    if(command == ':') {
      break;
    } else {
      string += command;
    }
    delay(1);
  }

  if(string == "TO") {
    ledOn();
    ledon = true;
  }

  if(string =="TF") {
    ledOff();
    ledon = false;
    Serial.println(string);
  }

  if ((string.toInt()>=0)&&(string.toInt()<=255)) {
    if (ledon==true) {
      analogWrite(led, string.toInt());
      Serial.println(string);
      delay(10);
    }
  }
}

void ledOn() {
  analogWrite(led, 255);
  delay(10);
}

void ledOff() {
  analogWrite(led, 0);
  delay(10);
}

```

# Answer
> 1 votes
Its better if you use SoftwareSerial for Bluetooth, so the native serial port can be used to debugging. But in case you doesn't need them:

```
uint8_t led[4] = {5,6,7,8}; // pin for LED 1,2,3,4
char command1,command2;
String string;
  void setup()
  {
    Serial.begin(9600);
    for (int i=0; i<4; i++)
        pinMode(led[i], OUTPUT); //set all LED pin as OUTPUT
  }

  void loop()
  {
    if (Serial.available() > 1) //run if 1 bit or more data received
    {
    string = "";
        command1 = Serial.read();
        command2 = Serial.read();
        switchled(command1-'0',command2-'0');
    string = command1+command2;
    }
    delay(1);
  }
void switchled(char pinLED,char statusLED)
{
    if (statusLED == 0 || statusLED == 1)
    digitalWrite(led[pinLED-1],statusLED);
    else
    digitalWrite(led[pinLED-1],!digitalRead(led[pinLED-1]));

    Serial.print("LED ");
    Serial.print(pinLED);
    Serial.print(" = ");
    Serial.print(digitalRead(pinLED));
}

```

The code reads 2 byte of data, so if your phone sent "11" the 1st led will turned on, and "10" will turn the 1st led off. The first digit is the LED index (1/2/3/4) and the second digit is the LED state (0/1), other than that, the LED on selected index will be toggled;

---
Tags: arduino-uno, programming, led
---


title: What is the principle of scanner

text:
# Question
Title: What is the principle of scanner
I find a 2.4GHz scanner in this web . I want to do same thing in 433 Mhz with SI4463. But I fail to understand it's principle. Who can explain it ? Thanks.

>

# Answer
> I find a 2.4GHz scanner in this web . I want to do same thing in 433 Mhz with SI4463. But I fail to understand it's principle. Who can explain it ?

The scanner you found loops through the channels looking for activity. The channels are defined by the NRF24L01. And activity is received signal within the channel above threshold (RSSI). For this device this is a single bit.

Other devices define RSSI as the signal quality/level for the latest received package. This is the case for the SI4463.

Cheers!
> 2 votes

---
Tags: nrf24l01+, wireless, rf
---


# Question
Title: How to run 50 IR LEDs off an Arduino UNO?
Hi I have 50 camera devices I want to program. Luckily the camera devices have a param.xml file I can import. I have already loaded the param.xml file on each of the camera devices however, now I need to import the param.xml file.

The devices work on IR waves, Usually I would have to import the params on each individual device with a remote but I decided to try and create a neat project where I would attempt to program all of the devices at once using an Arduino.

I would like to buy 50 IR LEDs, make small booster circuits for each LED and then point each one too the receiving module on the camera devices. All the Signal wires would be connected to Arduino pin 3.

I am mostly concerned about all the signal wires connected to Arduino pin 3. is there perhaps some kind of circuit I can use on pin 3 to ensure that this project will work perhaps someone Knows of a better way or has some advice?

Any suggestions will be appreciated.

I am not worried about power because I will connect the IR LEDs + & - to an external Power supply with adjustable current and voltage.

Booster Circuit:

Link To IR Led Datasheet

Link To Transister Datasheet

simulate this circuit – Schematic created using CircuitLab

This is the code I am using with an Arduino Uno and I have tested it with the IR booster circuit and it does work.

```
#include <IRremote.h>

IRsend irsend;

void setup()
{
}

void loop() {
    for (int i = 0; i < 3; i++) {
        irsend.sendNEC(0x1067E21D, 32); // Login
        delay(1000);
        irsend.sendNEC(0x106722DD, 32); // Password Digit 1
        delay(1000);
        irsend.sendNEC(0x106722DD, 32); // Password Digit 2
        delay(1000);
        irsend.sendNEC(0x106722DD, 32); // Password Digit 3
        delay(1000);
        irsend.sendNEC(0x106722DD, 32); // Password Digit 4
        delay(1000);
        irsend.sendNEC(0x106722DD, 32); // Password Digit 5
        delay(1000);
        irsend.sendNEC(0x106722DD, 32); // Password Digit 6
        delay(1000);
        irsend.sendNEC(0x10676897, 32); // Down Arrow
        delay(1000);
        irsend.sendNEC(0x10676897, 32); // Down Arrow
        delay(1000);
        irsend.sendNEC(0x10676897, 32); // Down Arrow
        delay(1000);
        irsend.sendNEC(0x10676897, 32); // Down Arrow
        delay(1000);
        irsend.sendNEC(0x10676897, 32); // Down Arrow
        delay(1000);
        irsend.sendNEC(0x10676897, 32); // Down Arrow
        delay(1000);
        irsend.sendNEC(0x10678877, 32); // Right Arrow
        delay(1000);
        irsend.sendNEC(0x10676897, 32); // Down Arrow
        delay(1000);
        irsend.sendNEC(0x1067A857, 32); // Enter
        delay(1000);
        irsend.sendNEC(0x1067A857, 32); // Enter
        delay(1000);
        irsend.sendNEC(0x10678877, 32); // Right Arrow
        delay(1000);
        irsend.sendNEC(0x1067A857, 32); // Enter
        delay(1000);
    }
    delay(5000); //5 second delay between each signal burst
}

```

# Answer
You should put a current-limiting resistor in series with *each* LED. You could then try to drive all of those LEDs from a beefy transistor, like a power MOSFET or a Darlington. Alternatively, you can use a small transistor for each LED, and then drive all of them from a PNP transistor, like this:

simulate this circuit – Schematic created using CircuitLab

This way, if you want to drive some of the LEDs independently, you can just connect an Arduino pin to its R2.

Beware that the PNP reverses the logic: pin `LOW` turns the LEDs ON.
> 5 votes

---
Tags: arduino-uno, led, ir
---


# Question
Title: ESP8266 Nodemcu create custom PWM with 1.25us resolution
I am trying to control some SMD LEDs WS2812B with the ESP8266-Nodemcu. I am using Arduino environment for coding. Actually I am trying to accomplish a PWM that is precisely able to:

* Go High for 850ns and then
* Go Low for 400ns

According to the Spec this, this High Low change is considered as a bit with value 1.

I have tried to delay between the lows and highs, without an effort (delays only work for microseconds and above i suggest).

Do you have any idea how to accomplish that?

# Answer
According to §1.7 (Pulse-Width Modulation) of espressif.com's ESP8266 technical reference document, “PWM frequency range is adjustable from 1000 μs to 10000 μs, i.e., between 100Hz and 1 kHz.” That range is shown in other sections of that reference, and in other ESP8266 documents as well. I don't know whether that range reflects any hardware limitations, or whether the PWM APIs enforce such limits or can be operated outside them.

Depending on what your intent is, you might instead consider use of UART capabilities. For example, if you set the UART data rate to 2.5 MHz and transmit a 110110110... binary pattern synchronously, you will have 800 ns high alternating with 400 ns low. \[I've seen references to use of USARTs on ESP8266's but don't know with certainty whether synchronous protocol actually is supported.\]

The I2S subsystem mentioned in §1.5 and described in §10 of the technical reference document also may be able to generate a bit stream as desired. As noted in §10.2.1.5 one six-bit field selects an input clock prescale factor, and another six-bit field is used as the frequency divider of the communication clock signal.

*Edit 1:* As noted in cranphin's comments, cnlohr's esp8266ws2812i2s github page provides code that uses the I²S subsystem and DMA to drive WS2812 LED units. Using DMA (direct memory access, *ie* transfer of memory data under control of a subsystem other than the CPU) means that once the CPU has set up a data buffer for a new display, it can turn actual transmission of the buffered data over to I²S / DMA and then go on with unrelated tasks while transmission occurs. Note, cnlohr's page links to a youtube video that illustrates and briefly explains the process.
> 3 votes

---
Tags: arduino-ide, esp8266, nodemcu
---


# Question
Title: How do I run multiple vibration motors from an Arduino Mini with PWM?
I'm building a project for my Physical Computing class that involves 4 vibration motors for varied haptic feedback based on serial input via analogRead. I have each coming out of their own pin and assigned to conditionals.

I'm wondering:

* how do i control the PWM of each individual motor?
* assuming I need an external power source for the motors, do I need to have a diode and transistor in between each motor and the ground?

Thanks in advance - I'm still learning but definitely looking forward to taking Part II next semester!

# Answer
> 3 votes
1. You can control motor PWM by using AnalogWrite() feature. Arduino Mini is equipped with 6 PWM pin, so you can use 1 PWM pin for each of you motor. Check here about more information on AnalogWrite, and here about Arduino Mini
2. This is the circuit if you want to use external power source. Normally, I use 1k ohm resistor, I'm sure there are someone out there that knows the exact formula.

simulate this circuit – Schematic created using CircuitLab

---
Tags: motor, pwm, arduino-pro-mini
---


# Question
Title: How to read RPS for fast rotation with status change method in Arduino?
I'm trying to calculate the coming RPS from rotary encoder. I am trying to get it by checking the status with `digitalRead`. However, I can not get more than 6 RPS. Any solution? I will be obliged for your help. Following is the code.

```
float rps;

void setup() {
  Serial.begin(9600);
  DDRC &= ~_BV (1); // pinMode (A1, INPUT);
}

void loop() {
  static int lastReedState;
  static unsigned long lastTransition;
  int reedState = (PINC & _BV (1)) == 0; // digitalRead (A1);
  // On a rising transition of the reed switch:
  if (reedState == LOW && lastReedState == HIGH) {
    // HIGH LOW measuring the low period
    // Compute time since last valid transition.
    unsigned long now = micros();
    unsigned long revolutionTime = now - lastTransition;
    // measuring the High period
    // Compute the RPS
    rps = 1.00 / (12.00*revolutionTime) *1000000.00;
    // 12 is rotary encoders resolution
    // Remember this transition.
    lastTransition = now;
  }
  // Remember last state.
  lastReedState = reedState;
  Serial.println(rps);
}

```

# Answer
> 1 votes
Consider using code similar to that shown in answers to the following questions: *Reading from a KY-040 rotary encoder with Digispark*; and *Read RC receiver channels using Interrupt instead of PulseIn*; and *Can external interrupts be OR'd together on the '328 (Uno)?*.

The first answer illustrates a fast-operating state machine to handle quadrature-encoded signals, ie rotary-encoder inputs.

The second answer illustrates handling of multiple encoders via a single interrupt routine, using a pair of two pin-change-interrupt (PCI) pins per encoder. The method assumes pins of a pair are in the same port. Most Arduino IO pins are PCI capable; some are not; on some models of Arduinos, some PCI pins aren't brought out to headers, or aren't recognized as PCI by the IDE, as noted in the question *Why PJ0 and PJ1 are not reporting as PCINT pins*.

The third answer includes code from the first two, and also has a sketch that displays a table of PCI vectors and masks. This table assists in planning pin layouts to reduce ISR overhead. For example, if you have half a dozen encoders, you might attach three of them to six pins on one port (and one vector), and the other three to six pins on another port (and another vector). Or you might put two encoders on each of three ports. The latter method might run, on average, a little faster (eg a microsecond or so per ISR invocation).

# Answer
> 0 votes
For one channel I'd use Input Capture capability on `Timer/Counter 1`. Without debouncing it'll be pretty easy.

If you want to read 8 inputs simultaneously, you can use Pin Change interrupts and `Timer/Counter 1` as a timebase. If you don't use Serial communication, you can use whole `PORTD`, otherwise you can use for example 4 channels on `PORTC` and 4 channels on `PORTD`. But again, debouncing will be little bit challenging.

---
Tags: arduino-uno
---


# Question
Title: Timer for how long button is not pressed
I would like to timer for how long a button is not pressed. So actually if(buttonState == LOW 'for two seconds') than execute the code that comes after it. But the problem is while the user is still pressing the button the timer already starts.

Code:

```
int ledPin[] = {7,8,9,10};
int ledPin11 = 11;
long randNumber;
const int buttonPin = 2;
int buttonPushCounter = 0;
int buttonState = 0;
int lastButtonState = 0;
unsigned long previousMillis = 0;
const long interval = 2000;

void setup() {
 Serial.begin(9600);
 pinMode(LED_BUILTIN, OUTPUT);
 randomSeed(analogRead(0));
 randNumber = random(1, 16);
 Serial.println(randNumber);
 for (int i = 0; i < 4; i++) {
   pinMode(ledPin[i], OUTPUT);
 }
  pinMode(buttonPin, INPUT);
 }

 void loop() {
  displayBinary(randNumber); //functie 'display binary'
  unsigned long currentMillis = millis();
  if(currentMillis - previousMillis >= interval){
    previousMillis = currentMillis;
    if(buttonState == LOW){
    antwoord(buttonPushCounter,randNumber);
    delay(5000);
    displayBinary(randNumber);
  }
 }
 buttonState = digitalRead(buttonPin);
 if (buttonState != lastButtonState) { // als de button word ingedrukt krijgt buttonPushCounter + 1
 if (buttonState == HIGH) {
  buttonPushCounter++;
  Serial.print("Nummer hoe vaak is gedrukt");
  Serial.println(buttonPushCounter);
 } else {
  Serial.println("off");
}
delay(250);
 }
}

void antwoord(int teller, int antwoord) {
 if (teller == antwoord) {
  for (int i = 0; i < 4; i++) {
  pinMode(ledPin[i], LOW);
 }
 digitalWrite(LED_BUILTIN, HIGH);
 delay(250);
 digitalWrite(LED_BUILTIN, LOW);
 delay(250);
 digitalWrite(LED_BUILTIN, HIGH);
 delay(250);
 } else if (teller > antwoord || teller < antwoord) {
   for (int i = 0; i < 4; i++) {
    pinMode(ledPin[i], LOW);
  }
    digitalWrite(LED_BUILTIN, HIGH);
  }
}

void displayBinary(byte numToShow) //van byte naar decimaal
  {
   for (int i = 0; i < 4; i++) {
    if (bitRead(numToShow, i) == 1) {
    digitalWrite(ledPin[i], HIGH);
    } else {
      digitalWrite(ledPin[i], LOW);
    }
   }
  }

```

# Answer
I would start a timer when the button changes state. Then you timeout if the button is released **and** it hasn't changed state for too long:

```
void loop()
{
    static int lastButtonState;
    static unsigned long buttonChangeTime;
    int buttonState = digitalRead(buttonPin);
    unsigned long now = millis();

    // Record time when button changes state.
    if (buttonState != lastButtonState)
        buttonChangeTime = now;

    // Timeout if button is not pushed for too long.
    if (buttonState == LOW && now - buttonChangeTime >= interval)
        Serial.println("Timeout.");

    lastButtonState = buttonState;
}

```

Don't forget to update `lastButtonState` on each iteration.
> 2 votes

# Answer
Your question is not clear enough.

I hope I get what you want.

Do while loop about the pressing...

```
if (button == LOW)
     while(!digitalread(button)){};

```
> 0 votes

---
Tags: arduino-uno, c
---


# Question
Title: Use of struct and sizeof in C for Arduino
I am a newbie in C and I can not understand the point of using a structure in C. Could someone explain to me what is the point of defining a structure in C programming?

For example, this code(written in C for Arduino)

```
struct books
{
  char name[30];
  char author[30];
  int ID;
} Mybook, Yourbook;

void setup()
{
  Serial.begin(9600);
  // put your setup code here, to run once:
  strcpy(Mybook.name, "Girl in the train");

  strcpy(Yourbook.name, "Gone");

  Serial.print("Name of the book is:");
  Serial.println(Mybook.name);
  Serial.println((long)&(Mybook.name));
  Serial.println((long)&(Mybook));
  Serial.println((long)&Mybook);
  Serial.println(sizeof(Mybook));

  Serial.print("Name of the book is:");
  Serial.println(Yourbook.name);
  Serial.println((long)&Yourbook);
  Serial.println(sizeof(Yourbook));
}

```

Would use the same amount of memory as defining

```
char Mybookname[30];
char Yourbookname[30];

```

And you should type the same amount of lines.
So what is the point?

I have another question:

Why I get 62 for the `sizeof(Mybook)`? I have not defined it anywhere. Is it set automatically?

# Answer
Consider the following:

```
void printBook(const books &theBook)
{
    Serial.println("Name of the book is: ");
    Serial.println(theBook.name);
    Serial.println("author is: ");
    Serial.println(theBook.author);
    Serial.println("ID is: ");
    Serial.println(theBook.ID);
}

void loop()
{
    printBook(MyBook);
    printBook(YourBook);
}

```

You should appreciate this avoids the code duplication you have in your example.

> Why I get 62 for the sizeof(Mybook)?

* 30 bytes for `name[30]` (each char is one byte)
* 30 bytes for `author[30]`
* 2 bytes for `ID` (the AVRs have 16-bit ints)

No padding between the members because this architecture has no alignment constraints.
> 2 votes

# Answer
Using Arrays-of-Parts (AoP) to represent a single item or "record" means that record's information is scattered among the AoP. When you need to do more than storing and listing 'N' records, that can get cumbersome and error-prone (as in: you miss one of the AoP when writing one of your routines). It also limits how you can allocate memory for the set of records.

Using an Array-of-Structs (AoS) only requires you to manipulate the one struct as a unit. If you move a record, all of its parts go with it. If you delete it, all of its parts get deleted. When you need more space, you only need to re-declare one array instead each of the individual parts arrays.

And one step up from an AoS is a Linked List of Structs (LLoS). Each record will contains one or more pointers (links) to some other record(s). Sorting then requires nothing more than writing some record's address into this record's link, and you've established a precedence. LLoS really shine when the records get large; writing a couple of pointers is way faster than copying 100 or more bytes. Same with deleting a record (call it "me"): change my predecessor's link-to-me to instead link to my successor, and Bang, done! I'm out of the list, there's no hole left as there would be with AoS or AoP, and my memory can be de-allocated, or I can be linked onto a different list.

Bottom line, arrays can get cumbersome when the data-set is large and and the records are complex. Structs gather a whole record together and allow more flexible manipulation.
> 1 votes

---
Tags: c, struct
---


# Question
Title: Writing new functions into progmem after main program is burned
I've been experimenting with writing very basic operating system-like programs on the Arduino, and so far I have been running user-defined programs on a small virtual machine I wrote. This has been an interesting experience, but the VM runs on an assembly-like language and not C.

I want to be able to do something more. I would like to be able to write a core OS, and then install new programs, written in C. The core OS would get user input for which program to run, and then jump to that program.

Now, I know that I can do this trivially by writing the OS along with all of the programs into a single sketch. The programs are then just functions, and the OS just calls those functions. However, I want to do this with functions I've written *after* I've burned the main OS.

From what I can tell, this is just a bootloader with additional user functionality. However, I don't think that's quite right for two reasons:

First, I keep hearing that you can't write to progmem at runtime. But isn't that what a bootloader does? Which is correct?

Second, once a user program ends, I should return to the OS. As far as I understand it, on the ATMega, once the main function terminates it jumps into a no-operation function and that's that. I'd need it to jump back to the bootloader and continue the bootloader's operation. Is that even possible?

# Answer
> 2 votes
> First, I keep hearing that you can't write to progmem at runtime. But isn't that what a bootloader does?

Indeed. My understanding is that *non-bootloader code* cannot write to the Flash, except on the smallest AVRs. You may need to check the datasheet of your target MCU.

> Second, once a user program ends, I should return to the OS.

You could require for the user programs to be linked against a library you provide. Just implement `void exit(int status)` in that library and it will automatically override the version from avr-libc.

---
Tags: bootloader
---


title: MAC address arduino

text:
# Question
Title: MAC address arduino
The MAC address is hardwired onto the NIC card when a device is manufactured. How is it that, we get to set a 48 bit MAC address of our choice while programming the arduino ?

# Answer
> 2 votes
MAC address is not *hardwired* in the modern network interface cards; it is set during programming of the configuration of the card, which is loaded on the card's start/configuration.

Modern NICs usually have option for user to set custom MAC address.

If you talk about shield device based on network chip like W5100 - there's no initial configuration within this network card for Arduino; thus by "programming the arduino" you set this initial configuration of the "card". You act like a manufacturer of the NIC.

# Answer
> 2 votes
Your initial premise is incorrect. The MAC address is NOT "hardwired". In many cases it is held in a very small non-volatile memory chip. But when the Ethernet driver is initialized you can feed it whatever MAC address you want. For most people they just accept "defaulting" it to the address programmed into the tiny memory.

Remember that the MAC address must be unique. At least within your LAN. If you start diddling the MAC addresses and you end up with a duplicate, at best you will kill connectivity for your node plus the other node with the same MAC address. Not a good thing to do. That is why people generally just accept the manufacturer's MAC address which is designed to be unique.

---
Tags: networking
---


title: Very strange power supply problem

text:
# Question
Title: Very strange power supply problem
So, I've put together my Christmas tree lights - a string of WS2811s driven by my Uno board. They are 12 volt WS2811s, so I have rigged a 12 volt supply to them and just using the Uno for the data channel, powered, initially by the USB port of the PC. So far, so good.

Then I take the whole arrangement to the tree and try to power the Uno from a USB charger - but that's where it all goes wrong! The LEDS start to flash madly, nothing like the pattern that I've programmed.

I've tried various USB chargers and various USB cables to no avail, I've tried powering with 6 volts to the DC in socket - same thing. When I go back to the PC and pick up the Uno power from the USB cable, all is good! I have no idea what can be causing this, please help!

# Answer
> 2 votes
\[Turning my comment and other peoples replies into an answer to make it easier to read\]

You are using two different power supplies? (PC + 12V or USB Charger + 12V) Have you connected the grounds from the two power supplies?

I have a limited understanding of why, but I know that unless the two power supplies have a common ground level the values for 0V and 5V may not be the same across the two feeds and you get odd and unpredictable behaviour.

Gerban explained that the reason it works on your PC is that most PC Power supplies reference Gnd from the Earth. If you 12V supply is an ex-PC PSU, or similar, that will be doing the same which is why that setup works, they share a common ground via the mains earth. The 5V phone charge probably has a plastic earth pin, which means it doesn't do this and therefore the Gnds are not tied to each other.

Majenko's blog will provide a more detailed, less hand wavey explanation: https://hackingmajenkoblog.wordpress.com/2016/12/06/the-importance-of-sharing-grounds/

# Answer
> 1 votes
The Arduino Uno barrel jack input connects to a linear 5 volt regulator. These types of regulators require a several volt difference between the input and output. So you need to supply 5 volts + several more volts or at least 7 volts at the barrel jack.

From the Arduino Uno web page:

> The board can operate on an external supply from 6 to 20 volts. If supplied with less than 7V, however, the 5V pin may supply less than five volts and the board may become unstable. If using more than 12V, the voltage regulator may overheat and damage the board. The recommended range is 7 to 12 volts.

---
Tags: power, led, usb
---


# Question
Title: Problem with combination of Bluetooth and RF 434MHz with Arduino Mega
I want to receive text from Bluetooth from an android phone to Arduino Mega. Then I want to send that text to other Arduino UNO through RF 434MHz.
Here is my code for Transmitter.

```
#include <VirtualWire.h>
void setup()
{
  Serial.begin(9600);
  vw_setup(2000);
}

void loop()
{
  String voice;
  digitalWrite(8,HIGH);
  while (Serial.available())
  {                 //Check if there is an available byte to read
    delay(10); //Delay added to make thing stable
    char c = Serial.read(); //Conduct a serial read
    if (c == '#') {break;} //Exit the loop when the # is detected after the word
    voice += c; //Shorthand for voice = voice + c
  }
  if (voice.length() > 0)
  {
    Serial.println(voice);
  }
  send(voice);
  delay(1000);
}

void send (char *message)
{
  vw_send((uint8_t *)message, strlen(message));
  vw_wait_tx(); // Wait until the whole message is gone
}

```

after compiling, I am getting an error as

> exit status 1
> cannot convert 'String' to 'char\*' for argument '1' to 'void send(char\*)'

Please anyone tell me a way for solving this.
Problem is at transmitter part only. So I posted only about it.

# Answer
> 1 votes
\[This should be a comment, but its too long\]

> •exit status 1 invalid conversion from 'const char\*' to 'char\*' \[-fpermissive\]

This means that the function you are calling wants a char\* as a parameter, but you are passing it a char\* that can't be modified. The chances are that the send function doesn't modify the value in the parameter, so you *might* be OK just casting it, but you might get a runtime error if send does modify the value (a segmentation fault most likely, or just an ugly crash). If you do you will need to allocate a temporary buffer that is big enough (str.length() + 1) and then copy it into that buffer and pass that to send.

So, try this first:

```
send((char*)voice.c_str());

```

If that fails then try this:

```
char* tempBuffer = malloc(sizeof(char) * (voice.length() + 1));
if (tempBuffer)
{
    strncpy(tempBuffer, voice.c_str(), (voice.length() + 1));
    send(tempBuffer);
    free(tempBuffer);
    tempBuffer = 0;
}

```

Of course if the data is always a fixed length then you can allocate an array on the stack instead of mallocing a buffer onto the heap.

# Answer
> 0 votes
> exit status 1 cannot convert 'String' to 'char\*' for argument '1' to 'void send(char\*)'

The compiler is telling you about the issue. You can access the `String` as a character vector (C string) with the member function `c_str()`, e.g. `send(voice.c_str());`

You might need to check that it is not too long for the payload in the VirtualWire library.

Cheers!

---
Tags: arduino-mega, bluetooth, rf
---


# Question
Title: How to I press a button once to display text and again to remove it?
My code is displaying voltage and I want to have a button that when pressed it displays a text and when I pressed it again it would turn off the text. I put the word "YES" just for a test

```
float vPow = 4.7;
float r1 = 1000000;
float r2 = 100000;
const int buttonPin = 8;
int buttonState = 0;
#include <LiquidCrystal.h>
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);

void setup() {
  lcd.begin(16, 2);
  pinMode(buttonPin, INPUT);
  Serial.begin(100);
}

void loop() {
  float v = (analogRead(0) * vPow) / 1024.0;
  float v2 = (v / (r2 / (r1 + r2)))/.48;
  lcd.setCursor(0,0);
  lcd.print("V:");Serial.println(v2); lcd.print(v2); lcd.print("%");delay(100);
  buttonState = digitalRead(buttonPin);
  if (buttonState == HIGH) {
    lcd.setCursor(0,1); lcd.print("YES");
  } else {
    lcd.setCursor(0,1); lcd.print("");
  }
}

```

# Answer
You can try to use a variable which is used to save the last condition. (whether it displaying or removing in the last button-press event)

```
bool state=false;
bool pressed = false;

void loop() {
  float v = (analogRead(0) * vPow) / 1024.0;
  float v2 = (v / (r2 / (r1 + r2)))/.48;
  lcd.setCursor(0,0);
  lcd.print("V:");Serial.println(v2); lcd.print(v2); lcd.print("%");delay(100);

  pressed = false;
  while (digitalRead(buttonPin)) pressed = true; //wait the button to unpressed

  if (pressed)
    {
    state=!state;
    if (state) {lcd.setCursor(0,1); lcd.print("YES");}else
               {lcd.setCursor(0,1); lcd.print("   ");} //3 spaces. To erase 3 characters ("YES")
    }
}

```
> 1 votes

# Answer
You need to somehow debounce the button. Using a long delay in the loop (your `delay(100)`) can do the trick, but it's probably not the best way, as it will slow down anything that you may later add to your program.

Better would be to write your own debounce function, or to use one of the libraries that already implement that. For example, with Bounce2, you would write something like:

```
#include <Bounce2.h>

const int buttonPin = 8;
Bounce button;       // debounced button
bool textDisplayed;  // whether the text is displayed or not

void setup()
{
    button.attach(buttonPin, INPUT);

    // etc...
}

void loop()
{
    // Read and display the analog value, then...

    // Update the state of the debounced button.
    button.update();

    // Toggle display on rising edges of the button.
    if (button.rose()) {
        lcd.setCursor(0,1);
        if (textDisplayed) {
            lcd.print("   ");
            textDisplayed = false;
        } else {
            lcd.print("YES");
            textDisplayed = true;
        }
    }
}

```
> 1 votes

---
Tags: arduino-uno, lcd, analogread, button
---


# Question
Title: How to unify all RPS reading in one function?
Want to unify rps reading in one function. However, it shows incorrect values. when it is reading for one it works fine. Following is the code. Appreciate for your help.

```
float rps[4] = {0.00, 0.00, 0.00, 0.00};
long int PRINT_PERIOD = 1000;
long int lastTimePrinted = 0;

void setup() {
    Serial.begin(9600);
    DDRD &= ~_BV(7); // pinMode(7, INPUT);     // rps_1
    DDRB &= ~_BV(0); // pinMode(8, INPUT);     // rps_2
    DDRC &= ~_BV(1); // pinMode(A1, INPUT);    // rps_3
    DDRD &= ~_BV(2); // pinMode(2, INPUT);     // rps_4
}

float rps_out(int k) {
    static int lastReedState;
    static unsigned long lastTransition;
    static float rps_result;
    int reedState;
    unsigned long now;
    unsigned long revolutionTime;

    if (k == 1)    reedState = (PIND & _BV (7)) == 0; // digitalRead(7);
    else if (k==2) reedState = (PINB & _BV (0)) == 0; // digitalRead(8);
    else if (k==3) reedState = (PINC & _BV (1)) == 0; // digitalRead(A1);
    else if (k==4) reedState = (PIND & _BV (2)) == 0; // digitalRead(2);

    // HIGH LOW measuring the low period
    // LOW HIGH measuring the high period
    // On a rising transition of the reed switch:
    if (reedState == HIGH && lastReedState == LOW) {

        // Compute time since last valid transition.
        now = micros();
        revolutionTime = now - lastTransition;    // measuring the High period
         rps_result = 1.00 / (12.00*revolutionTime) *1000000.00;  // 12 is rotary encoders resolution
        // Remember this transition.
        lastTransition = now;
    }

    // Remember last state.
    lastReedState = reedState;

    return rps_result;
}

void loop() {
    rps[0] = rps_out(1);
    rps[1] = rps_out(2);
    rps[2] = rps_out(3);
    rps[3] = rps_out(4);

    if (millis() - lastTimePrinted >= PRINT_PERIOD) {
        Serial.println(rps[0]);
        Serial.print(',');
        Serial.println(rps[1]);
        Serial.print(',');
        Serial.print(rps[2]);
        Serial.print(',');
        Serial.println(rps[3]);
        lastTimePrinted = millis();
    }
}

```

worked code except for rps\[3\] at the beginning. it shows rps\[3\] = 672.04

```
float rps[4];
long int PRINT_PERIOD = 100;
long int lastTimePrinted = 0;
int lastReedState[4];
unsigned long lastTransition[4];
int reedState[4];
unsigned long now[4];
float rps_result[4];
unsigned long revolutionTime[4];

void setup(){

 Serial.begin(9600);

 DDRD &= ~_BV (7); // pinMode (7, INPUT);       // rps_1
 DDRB &= ~_BV (0); // pinMode (8, INPUT);       // rps_2
 DDRC &= ~_BV (1); // pinMode (A1, INPUT);      //  rps_3
 DDRD &= ~_BV (2); // pinMode (2, INPUT);       //  rps_4

}

float rps_out(int k){

    //static int lastReedState;
    //static unsigned long lastTransition;
    //static float rps_result;
    //float rps_result;
    //int reedState;
    //unsigned long now;
    //unsigned long revolutionTime;

   if ( k == 0 )     reedState[0] = (PIND & _BV (7)) == 0; // digitalRead (7);
   else if ( k==1 )  reedState[1] = (PINB & _BV (0)) == 0; // digitalRead (8);
   else if ( k==2 )  reedState[2] = (PINC & _BV (1)) == 0; // digitalRead (A1);
   else if ( k==3 )  reedState[3] = (PIND & _BV (2)) == 0; // digitalRead (2);

    // On a rising transition of the reed switch:
    if (reedState[k] == HIGH && lastReedState[k] == LOW) {                   // HIGH  LOW   measuring the low period    // LOW HIGH measuring the high period
        // Compute time since last valid transition.
        //unsigned long now = micros();
        //unsigned long revolutionTime = now - lastTransition;       // measuring the High period
         now[k] = micros();
         revolutionTime[k] = now[k] - lastTransition[k];       // measuring the High period
        // Compute the rps

        if(revolutionTime[k] == 0 ) rps_result[k] = 0.00;     // avoid deviding by zero

        else rps_result[k] = 1.00 / (12.00*revolutionTime[k]) *1000000.00;  // 12 is rotary encoders resolution

        // Remember this transition.
        lastTransition[k] = now[k];

    }

    // Remember last state.
    lastReedState[k] = reedState[k];

    return rps_result[k];

}

void loop() {

   rps[0] = rps_out(0);
   rps[1] = rps_out(1);
   rps[2] = rps_out(2);
   rps[3] = rps_out(3);

    if (millis() - lastTimePrinted >= PRINT_PERIOD) {

     Serial.print(rps[0]);
     Serial.print(',');
     Serial.print(rps[1]);
     Serial.print(',');
     Serial.print(rps[2]);
     Serial.print(',');
     Serial.println(rps[3]);

      lastTimePrinted = millis();

     }

}

```

# Answer
> 1 votes
Your problem is that you have one set of (static) state information that you are trying to use for all your inputs. That's never going to work. You need separate state information for each and every input.

There's numerous ways of doing that:

1. The traditional C library "re-entrant" style. This involves passing pointers to any state variables into your function. The caller is responsible for creating and managing these variables and passing the pointers when the function is called. This is messy but pretty much completely portable across systems since it doesn't rely on any C++ facilities.
2. Similar to option 1 but grouping your different state variables into a `struct` to make things cleaner.
3. Global arrays - have a global array (maybe of structs as in option 2) to store the state information and pass the slice number to your function.
4. The OOP (C++) way - create a class with all the state variables and functions within it then instantiate a new object for each input. This is by far the cleanest and most self contained way but does require knowledge of creating and using classes.

Of the four options I would most likely choose option 4:

```
class RPS {
    private:
        uint8_t _pin;
        uint8_t _lastReedState;
        uint32_t _lastTransitionTime;
        uint32_t _rps;

    public:
        RPS(uint8_t pin) : _pin(pin) {}
        void begin() {
            pinMode(_pin, INPUT);
            _lastReedState = digitalRead(_pin);
            _lastTransitionTime = millis();
            _rps = 0;
        }
        void calc() {
            uint8_t reedState = digitalRead(_pin);
            if (reedState != _lastReedState) {
                uint32_t now = millis();
                _lastReedState = reedState;
                if (reedState == HIGH) {
                    uint32_t diff = now - _lastTransitionTime;
                    if (diff == 0) {
                        _rps = 0; // Avoid divide by zero
                    } else {
                        _rps = 1000 / diff;
                    }
                }
                _lastTransitionTime = now;
            }
        }
        uint32_t get() {
            return _rps;
        }
};

RPS rps1(1);
RPS rps2(2);

#define PRINT_PERIOD 1000

void setup() {
    rps1.begin();
    rps2.begin();
}
void loop() {
    static uint32_t lastTimePrinted = 0;

    rps1.calc();
    rps2.calc();

    if (millis() - lastTimePrinted >= PRINT_PERIOD) {
        lastTimePrinted = millis();
        Serial.print("RPS 1: ");
        Serial.println(rps1.get());
        Serial.print("RPS 2: ");
        Serial.println(rps2.get());
    }
}

```

*(note: Untested. It may not even compile)*

---
Tags: arduino-uno
---


# Question
Title: Understanding Nikon modified version of SPI
I am trying to use this library to connect a Nikon lens to an Arduino. https://lainy.github.io/NikonLens/classlain\_1\_1t\_nikon\_lens.html

I'm finding it very hard to understand the correct wiring.

> Connections are as follows (with Arduino Uno pin numbers):
>
> SS (10) is unused.
>
> SCK (13) is connected directly to lens SCLK.
>
> MISO (12) is connected to the lens Data line, which must be pulled high.
>
> MOSI (11) drives the lens Data line through a transistor, open-collector. So: MOSI -\> Base, Data -\> Collector, GND -\> Emitter
>
> handshakePin\_In is connected directly to lens H/S
>
> handshakePin\_Out drives lens H/S through a transistor, open-collector.

I would like help to understand this.

> drives the lens Data line through a transistor, open-collector. So: MOSI -\> Base, Data -\> Collector, GND -\> Emitter

It uses a variant of SPI interface. I'm just finding it hard to wrap my mind around it.

# Answer
It is simply a way of splitting a single-pin read/write function between two pins. It's easier to visualise with schematics:

simulate this circuit – Schematic created using CircuitLab

Under idle conditions the resistor pulls the data signal high. When the lens wants to transmit the open-collector output (represented by a transistor here) either pulls the data line low (for a 0) or releases it to be pulled up by the resistor (for a 1).

The Arduino reads that data in through the data in pin.

When the Arduino wants to transmit it does the same thing, but the "open collector" is external in the form of the transistor. It drives the transistor using the data output pin to get it to pull the data line low for a 0, or release it to be pulled up by the resistor for a 1.

This is exactly the same way (on an electrical level) that I2C works and studying that protocol can help you to understand what is going on here.
> 1 votes

---
Tags: spi
---


title: Best way to detect tilt using MPU 6050

text:
# Question
Title: Best way to detect tilt using MPU 6050
I want to make a gesture controlled car using this IMU.. What is the simplest way to detect tilts? I've seen many programs on the Internet that calculate the angles but is this really necessary? Why can't we just get components of acceleration in the x, y plane and then detect tilts..Pls tell me how to do this!

# Answer
> 2 votes
Well suppose you have a starting position, let's say 0 degrees, then once you detect and angle change, let's say 10 degrees, you know that there is a tilt of 10 degrees on one of the 3 axies.

The MPU6050 is a 6DOF, meaning 6 Degrees Of Freedom. This means that it can detect acceleration on axis: x, y, and z and it can detect gyro angles on axis: yaw, pitch, and roll.

For the best accuracy, use a mix of both acceleration and the gyroscope. This is the best way to calculate position. Heck, the Apollo space program used a gyro and accelerometer to navigate from planet Earth to the Moon.

---
Tags: arduino-uno, accelerometer, mpu6050
---


# Question
Title: How do I see the command line equivalent of clicking Verify?
I am using the ESP8266 board manager. I want to see how Arduino IDE compiles my code once I click Verify.

### Why do I want to do this?

I am trying to integrate a C library for which there is now Arduino library package available. So I have to integrate it from source. I want to be able to specify custom `-I`, `-L` and `-l` flags when I compile my code.

# Answer
> 1 votes
In the Arduino IDE switch on `File`\>`Preferences`\>`Upload erbose` and `Compile Verbose`

When you build you will see all the compiler commands

The verify is often a `-v` param in the command

You will find the esp8266 platform.txt in a location such as `c:\users\[name]\appdata\local\arduino15\packages\esp8266...`

The `platform.txt` contains all the compiler switches, the `boards.txt` in the same location can also contain board specific switches.

You can not specify different switches for different files in a compilation but you could compile your code into an archive then force it into the build process. Not sure if that is practical or not.

---
Tags: esp8266, library, compile, command-line
---


# Question
Title: Modbus Communication protocol for Arduino as Slave
I have an Arduino Uno board, with these components:

In addition I have a level sensor which reads either 1 when it is above water, and 0 when it is below.

I need to be able to give the value of this sensor to a modbus master over rs485.

Cooking Hacks Tutorial

This page has a description of how to use the ModbusMaster485 library, but I can not find any information about the slave library.

I can not find any documentation for this library, and would really appreciate any pointers.

# Answer
> 2 votes
It's not very well documented for the slave but maybe that is because it only has two methods...

It looks like the slave library is contained in the same library as the master but with name `ModbusSlave485.h`

You can see in the .h it only has two public methods. One is `connfigure()` and the other is `update()`. see below an extract from the .h which explains what each method does.

```
#include "ModbusSlave485.h"

mySlave = ModbusSlave485();

void setup()
{
  mySlave.configure(slave, baud, parity, txenpin);
}

void loop()
{
  //check for update from master
  mySlave.update(regs, regs_size)
}

```

extract from .h

```
/*
 * configure(slave, baud, parity, txenpin)
 *
 * sets the communication parameters for of the serial line.
 *
 * slave: identification number of the slave in the Modbus network (1 to 127)
 * baud: baudrate in bps (typical values 9600, 19200... 115200)
 * parity: a single character sets the parity mode (character frame format):
 *         'n' no parity (8N1); 'e' even parity (8E1), 'o' for odd parity (8O1).
 * txenpin: arduino pin number that controls transmision/reception
 *        of an external half-duplex device (e.g. a RS485 interface chip).
 *        0 or 1 disables this function (for a two-device network)
 *        >2 for point-to-multipoint topology (e.g. several arduinos)
 */
  void configure(unsigned char slave, long baud);

/*
 * update(regs, regs_size)
 *
 * checks if there is any valid request from the modbus master. If there is,
 * performs the requested action
 *
 * regs: an array with the holding registers. They start at address 1 (master point of view)
 * regs_size: total number of holding registers, i.e. the size of the array regs.
 * returns: 0 if no request from master,
 *  NO_REPLY (-1) if no reply is sent to the master
 *  an exception code (1 to 4) in case of a modbus exceptions
 *  the number of bytes sent as reply ( > 4) if OK.
 */
  int update(int *regs, unsigned int regs_size);

  // constructor
  ModbusSlave485()
  {
    myDevice = RS485();
  }

```

---
Tags: arduino-uno, modbus, rs485
---


# Question
Title: Ping IP address using ESP8266 connected to Arduino
I want to make a system using NeoPixels, an Arduino and an ESP8266 module to ping IP addresses on my network to determine if certain people are on our Wi-Fi (I'll be pinging mobile phones).

I'm finding it hard to find any help as to how to ping IP addresses from an Arduino using the ESP8266 module. I did find the ICMP Ping library, but it uses the Ethernet shield, and I'm quite new to Arduino so I don't even know if I could modify the library in any way.

If anyone could help me on my way, that'd be great!

# Answer
> 2 votes
From what I could find, it seems theres a command for pinging a server. It returns the number of milliseconds taken for the server to respond. The command is: `AT+PING="web site"` or `AT+PING=<ip addr>`, from 2 separate sources. You'll have to test them to see which (if not both) is correct.

# Answer
> 2 votes
This answer does not answer your question, but it implements the device you are describing. Unfortunately I don't have enough reputation to comment, so I will post it as an answer.

As people said before, ping is not a reliable option to scan the network. On Linux you can use dedicated (software) tools to scan the network, but even they struggle to reliably detect (some) mobile devices. So I wanted my router to do the work for me (at least it should reliably know which devices are logged into the Wi-Fi, right?).

Fortunately I have a Fritz!Box that provides an API to communicate with. Based on that API and an ESP8266 I build such a device you described in your question: \[15min\] Weasley Clock / Who is Home Indicator - based on TR-064 (beta).

To do that I wrote a library for Arduino to uses that API: Aypac/Arduino-TR-064-SOAP-Library.

# Answer
> 1 votes
Not all devices (including) phones respond to ICMP Ping. This may differ for each (mobile) OS and version and phone make and model. But assuming your phone does respond to ping...

If you use the ESP with just the default firmware (a waste of a perfectly capable microcontroller), then indeed use the AT+PING command from the other answers.

If you use the ESP directly, you may be out of luck. Both the nocemcu lua firmware and the arduino api for esp seem to lack icmp ping functionality.

---
Tags: esp8266, arduino-mini
---


# Question
Title: 4.7v as HIGH on digital output instead of 5v
I'm new to Arduino, just got my starter kit, and I noticed that digital outputs 3 & 4 have 5v as HIGH level while 5 to 13 have 4.7v as HIGH level. Is it as it suppose to be?

# Answer
Also depends on what your driving via this output. Standard TTL is:

But CMOS will be a bit different:
> 2 votes

# Answer
Yes, that's perfectly fine.

According to the datasheet, at 5V, the minimum voltage you can expect on a HIGH output (AKA VOH) is 4.2V. 4.7V is above that, so it's fine.
> 1 votes

# Answer
Some of the answers here suggest that a reading of 4.7V is in spec (which it is). As Majenko says, 4.2V is the minimum output high voltage, at an ambient temperature of 85°C, with a load of 20 mA, and Vcc = 5V.

*However* with no load, and at room temperature, I measured 4.99V on all of those pins, when set to `OUTPUT` and `HIGH` on *my* Uno. Test code:

```
void setup()
{
for (int i = 3; i <= 13; i++)
  pinMode (i, OUTPUT);
}
void loop()
{
for (int i = 3; i <= 13; i++)
  digitalWrite (i, HIGH);
}

```

> That was weird for me, because 1 hour ago it was showing 5v to me.

Right. What were you doing an hour ago? Did you have LEDs connected to those pins? If so, what value resistor did you have in series with them? Or were you driving a motor from the pins perhaps?
> 1 votes

---
Tags: arduino-uno
---