title: How to multiplex multiple displays?

text:
# Question
Title: How to multiplex multiple displays?
I want to use 2 "displays" with 4 digits. The displays are common cathodes with cathode transistors connected to the digits, as the figure:  The segments of both displays are connected together on the digital pins. The problem is that I tried to use some libraries for 7 segment displays and they worked with only one 4 digit display, but when I connected the second display, did not display the numbers correctly. The numbers that will be written are integers and I'm using mega 2560 R3.

Here are my attempts:

```
#include "SevSeg.h"
byte digitPins_1[] = {29, 30, 31, 33};//Digits pins
byte digitPins_2[] = {25, 26, 27, 28};
byte segmentPins[] = {38, 39, 40, 41, 42, 43, 44, 46}; //segment pins
SevSeg disp1;
SevSeg disp2;

void setup() {
disp1.begin(P_TRANSISTORS, 4, digitPins_1, segmentPins);
disp2.begin(P_TRANSISTORS, 4, digitPins_2, segmentPins);
disp1.setBrightness(20);
disp2.setBrightness(20);
}

void loop() {
disp1.setNumber(8888, 0);
disp1.refreshDisplay();
disp2.setNumber(1111, 0);
disp2.refreshDisplay();
}

```

or using another lib:

```
#include <SevenSeg.h>
SevenSeg disp1(38,39,40,41,42,43,44);//segment pins
SevenSeg disp2(38,39,40,41,42,43,44);
int digitPins1[4]={29,30,31,33};//digitpins
int digitPins2[4]={25,26,27,28};

void setup() {
disp1.setDigitPins(4,digitPins1);
disp2.setDigitPins(4,digitPins2);
disp1.setDigitDelay(1600);//time delay
disp2.setDigitDelay(1600);
disp2.setActivePinState(HIGH,HIGH);//seg active HIGH, digit active HIGH
disp1.setActivePinState(HIGH,HIGH);
}

void loop() {
disp1.write(8888);
disp1.clearDisp();
disp2.write(1111);
disp2.clearDisp();
}

```

# Answer
> 2 votes
The code instantiates two instances of the SevSeg class. This may or may not work. Really depends on if the class uses any resources are not meant to be shared between multiple instances of that class. For instance, it is unlikely that one hardware timer can be used for more than one purpose at a time.

But the code continues on to use the same (anode) pin resources for both instances of the class. This is likely not going to work.

Apologies for being vague using qualifier like "unlikely" instead of simply stating that it will not work. Truth is, one might be able to write a class that can deal with multiple instances of its self. But it would be very difficult and a far more complex programming task than to simply use one instance for all 8 digits.

In case there is a question as to the maximum number of digits supported for one instance of the SevSeg class, this line is in the one of the SevSeg header files:

```
#define MAXNUMDIGITS 8 // Can be increased, but the max number is 2^31

```

# Answer
> 1 votes
Why do you feel you need to multiplex two displays? What is wrong with just having one display of 8 digits? They don't have to be physically together, and it's entirely up to you what you display on each character of the display.

# Answer
> 1 votes
As the answers suggested, it is better to make a single display with 8 digits. But if anyone needs 2, here is my solution:

As suggested, I checked if the library supported, and the solution was to only increase the delay on each digit.

```
#include <SevenSeg.h>
SevenSeg disp1(38,39,40,41,42,43,44);//segment pins
SevenSeg disp2(38,39,40,41,42,43,44);
int digitPins1[4]={29,30,31,33};//digitpins
int digitPins2[4]={25,26,27,28};

void setup() {
disp1.setDigitPins(4,digitPins1);
disp2.setDigitPins(4,digitPins2);
disp1.setDigitDelay(4000);//time delay
disp2.setDigitDelay(4000);
disp1.setDutyCycle(10);//decrease the duty cycle
disp2.setDutyCycle(10);
disp2.setActivePinState(HIGH,HIGH);//seg active HIGH, digit active HIGH
disp1.setActivePinState(HIGH,HIGH);
}

void loop() {
disp1.write(8888);
disp1.clearDisp();
delay(1);// don't need
disp2.write(1111);
disp2.clearDisp();
}

```

---
Tags: arduino-mega, multiplexer, 7-segment
---


# Question
Title: Intermittent LOW reading from input pin set to INPUT_PULLUP
i have an output pin connected to a magnetic reed switch. The pin mode is INPUT\_PULLUP. When the switch is closed, it connects the pin to GND and drags the pin to a LOW reading. I check the state of the pin in the loop function. Occasionally the pin reads LOW when it shouldn't (the switch is not closed) - e.g. around once per second. What could cause this? The wire from the pin to the switch is about 1m long - could this be long enough to intermittently drag it down to a LOW? Also, it seems to happen much more when the air temperature is hotter.

Circuit summary: Pin (INPUT\_PULLUP) -\> Magnetic reed switch -\> GND

# Answer
My guess would be that you're getting noise interference on the line and it's too much for the Arduino's little internal pullup. Try adding an external pullup resistor - say 5k-10k (exact value is not critical).
> 3 votes

---
Tags: input, switch
---


# Question
Title: Use server.arg results as a function parameter?
I've got an ESP8266 (NodeMCU) and I am trying to understand the ESP8266WebServer library, as how to use the results across functions.

In my setup function, I have the following:

```
   server.on("/marquee", []() {
      varOne = server.arg("baseColor");
      varTwo = server.arg("marqueeColor");
      server.send(200, "text/html", webPage);
      Serial.println("Marquee  activated");
      state = true;
      ledMode = "marquee";
    });

```

In my loop, I detect the ledMode and if it is set to marquee then it runs the following FastLED function, amongst others:

```
fill_solid(leds, NUM_LEDS, 0xFF0000);

```

What I am trying to figure out is how I go from taking a hex color code of say `FF0000` from the URL parameter, and use that in my `fill_solid` function.

server.arg stores get the parameter as a string, so I am not sure what needs to be done. Also, using a variable name in place of the Hex code in the `fill_solid` function results in an error due to not expecting the variable

# Answer
> 1 votes
> server.arg stores get the parameter as a string, so I am not sure what needs to be done.

The parameter needs to be converted to an uint32\_t (and then to a CRGB or CHSV struct). The simplest way is to use the C library function strtoul

```
uint32_t color = strtoul(arg, NULL, 16);

```

This can be improved so that it checks that a number was scanned, etc.

Cheers!

---
Tags: esp8266
---


# Question
Title: Turn on a LED when an other LED turn off
I'm a beginner on arduino.

I have an arduino mega with two LED (like the image with only 2 less and without the buzzer). A red LED and a green LED. When the arduino receive the code 200 I want the red LED turn on and the green LED turn off. But when I test that but any led turn off or turn on..

```
void setup()
{
  pinMode(LR, OUTPUT);
  pinMode(LV, OUTPUT);
  Serial.begin(9600);
}

void readSerial(){
  while(Serial.available() > 0){
    car = Serial.read();

    if(car != '+'){
      buff[i] = car;
      buff[i+1] = '\0';
      i++;
    }
    else{
      sscanf(buff, "%d", &received_code);
    }
  }
}

void loop()
{
  readSerial();
  if (received_code == 200){
    LRstate = HIGH;
    digitalWrite(LR, LRstate); // turn the LED on (HIGH is the voltage level)
    digitalWrite(LR,LOW);
    delay(100);
    digitalWrite(LV,LOW);
  }
}

```

How can I solve my problem?

Thanks a lot.

# Answer
> 1 votes
First, make sure the LEDs are connected correctly: I presume the red LED is connected to whichever pin `LR` is, and the green LED to `LV`.

According to your diagram, your LEDs will be on if the output is `HIGH`, and off if the output is `LOW`. Your code sets `LR` to high, but then immediately to `LOW` again.

Here's a fixed (I hope) verson of your `loop()`:

```
void loop()
{
  readSerial();
  if (received_code == 200){
    // Turn the red LED on
    digitalWrite(LR,HIGH);

    // Turn the green LED off
    digitalWrite(LV,LOW);
  }
}

```

---

Unrelated to the problem you're having, but worth a mention anyway:

There's nothing in your code to stop you overrunning `buf` if you get a longer input than you're expecting. If this happens you'll get unpredictable results as you trash over whatever happens to be in that part of memory.

# Answer
> 0 votes
In addition to the code changes noted by @MarkSmith, the LEDs are not connected properly. The straight LED pin on the Fritzing diagram is its cathode and must be connected to grounded, and the bent pin is its anode and must be at +V (+5v, in this case), for the LED to light. To turn the LED on, the anode must be at +V and the cathode at ground. To turn the LED off bring both pins to the same voltage, usually by grounding the anode (logic 0 on its connected pin).

To identify the cathode on a real LED, look inside its plastic blob (that's a technical term :) and you'll see two bits of metal, each on a wire, like two flags. The larger flag is the cathode. Usually, the cathode also has a shorter external lead and the plastic blob has a flat edge on that side, but the larger flag is definitively the cathode:

---
Tags: arduino-mega, programming, led
---


# Question
Title: How can I adjust my code so that the value that I print with my BLE device does not get chopped up when I receive it on an app?
I am using a BLE device (https://www.adafruit.com/product/1697) that I use to print data to an app. I can successfully connect the BLE to the app and receive the data but the result however gets chopped up.

What I am sending is a lat, lng value (that I gather with a library called TinyGPS++ http://arduiniana.org/libraries/tinygpsplus/) and the code looks like this:

```
BTLEserial.Print::print(gps.location.lat(), 8);
BTLEserial.print (", ");
BTLEserial.Print::print(gps.location.lng(), 8);

```

So for example if the latitude is: `32.12345678`, it comes like this to the app: `3`, new row, `2`, new row etc.

So my question is, how can I adjust my code to make sure it does not send the result chopped up but instead sends it's complete value?

# Answer
> 0 votes
> how can I adjust my code to make sure it does not send the result chopped up but instead sends it's complete value?

The BLE device uses a package approach and the print member functions only support strings (char vectors and Arduino String). Construct the message as a String:

```
double lat = gps.location.lat();
double lng = gps.location.lng();
String msg = String(lat, 8) + String(", ") + String(lng, 8);
BTLEserial.print(msg);

```

Cheers!

---
Tags: arduino-uno
---


# Question
Title: Control RGB led using microphones, getting the right components
Sorry if this is too basic, but I am very new to arduino and electronics. I come from programming, I am trying to start a project where I can control an RGB led strip, I want to be able to control the light intensity and color of the light strip (something like this), using a microphone.

My goal is for frequency to control de color of the rgb light and the dB (Volume) to control the light intensity. I have found several microphones such as this ones. Can I get both frequency and dB input from this microphones?

Would I need some extra controllers for this project? Again I am very new with this, sorry by the basic questions.

# Answer
It would be worth checking out the ColorChord project. It runs on an ESP8266, not an Arduino, but it ought to get you going.
> 1 votes

---
Tags: arduino-uno, rgb-led, audio
---


# Question
Title: How can I make this code read a page every 10 seconds?
I got problems with the code and I have used most of today, trying to find a solution and it's starting to drive my crazy. I hope one of you guys will be able to help me out.

I need the code to check a specific page every 10 seconds, single character.

This is what I have now, working code: Where should I start?

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

byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
byte ip[] = { 192, 168, 1, 104 };
char server[] = "billigefittings.dk";

EthernetClient client;

void setup()
{
  Ethernet.begin(mac, ip);
  Serial.begin(9600);

  delay(1000);

  Serial.println(Ethernet.localIP());
  Serial.println();

  Serial.println("connecting ...");

  if (client.connect(server, 80)) {
    Serial.println("connected");
    client.println("GET /lan.php");
    client.println();
  } else {
    Serial.println("connection failed");
  }
}

void loop()
{
  if(client.available() > 0) {

    char c = client.read();

    Serial.print("page value:");
    Serial.println(c);

    if(c == '1') {
        digitalWrite(8, HIGH);
        Serial.println("8 HIGH ...");
        delay(5000);
        digitalWrite(8, LOW);
        Serial.println("8 LOW ...");
    }else{
        Serial.println("page value does not match '1' !");
    }

    // The code above should run even 10 seconds

  }

  if(!client.connected()) {
    Serial.println();
    Serial.println("disconnecting.");
    client.stop();
    for(;;);
  }

}

```

Update: Edit the loop like the example below does not work either, it stops after the first loop (8 LOW):

```
void loop()
{
  if(client.available() > 0) {

    char c = client.read();

    Serial.print("page value:");
    Serial.println(c);

    if(c == '1') {
        digitalWrite(8, HIGH);
        Serial.println("8 HIGH ...");
        delay(5000);
        digitalWrite(8, LOW);
        Serial.println("8 LOW ...");
    }else{
        Serial.println("page value does not match '1' !");
    }

    delay(5000);

    // The code above should run even 10 seconds

  }

}

```

# Answer
As discussed in the comments, you need to connect to the client *each time*, not just once.

Here's my modified version of your code, which I hope will work -- I'm not set up to test it.

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

byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
byte ip[] = { 192, 168, 1, 104 };
char server[] = "billigefittings.dk";

void setup()
{
  Ethernet.begin(mac, ip);
  Serial.begin(9600);

  delay(1000);

  Serial.println(Ethernet.localIP());
  Serial.println();
}

void loop()
{
  // Connect to the server
  Serial.println("connecting ...");

  EthernetClient client;
  if (client.connect(server, 80)) {
    Serial.println("connected");
    client.println("GET /lan.php");
    client.println();
  } else {
    Serial.println("connection failed");
  }

  // Wait a moment for data to arrive
  // Note: This is NOT a reliable way of doing it!
  delay(1000);

  if(client.available() > 0) {
    char c = client.read();

    Serial.print("page value:");
    Serial.println(c);

    if(c == '1') {
        digitalWrite(8, HIGH);
        Serial.println("8 HIGH ...");
        delay(5000);
        digitalWrite(8, LOW);
        Serial.println("8 LOW ...");
    }else{
        Serial.println("page value does not match '1' !");
    }
  }

  // Disconnect the client
  if(client.connected()) {
    Serial.println();
    Serial.println("disconnecting.");
    client.stop();
  }

  // Wait another 9s, which will give us a delay of roughly 10s
  delay(9000);
}

```
> 1 votes

---
Tags: serial, ethernet, lan
---


# Question
Title: ESP8266 Serial Communication with ATMega328P
I am isolating the ATMega328P from the Arduino Uno. I have used it for many other projects, so it does work as intended. Also, I have used my ESP8266-01 for other projects and works great (including serial communication).

I am trying to get the ESP8266-01 to make the ATMega328P pin 13 blink an LED. That is all.

When the ESP8266 is hooked to the TX/RX of the arduino board, the program works exactly as intended. I hook it up the exact same way to the ATMega328P and it doesn't work.

I am using baud rate of 9600 for the communication and using a 16MHz crystal for the ATMega328P.

simulate this circuit – Schematic created using CircuitLab

The controller is getting 3.3v from the supply as well. And pin 13 is supposed to turn on/off depending on the serial value. Below is the code for the ESP8266:

```
#include <ESP8266WiFi.h>

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

void loop() {
  delay(10000);
  Serial.write("LED ON");
  delay(10000);
  Serial.write("LED OFF");
}

```

And below is the code for the ATMega328P:

```
#include <SoftwareSerial.h>

SoftwareSerial esp8266(2,3);

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

void loop()
{
  if(esp8266.available())
  {
    String command = "";
    while(esp8266.available())
    {
      command += (char)esp8266.read();
    }

    if(command == "LED ON") {
      digitalWrite(13, HIGH);
    }

    if(command == "LED OFF") {
      digitalWrite(13, LOW);
    }
  }

  delay(500);
}

```

As stated, they work great separately, but when I try serial communication with them together, it doesn't work.

P.S. I usually set my ESP8266 baud rate to 115200, but the ATMega328P, I believe, needs to run at 9600 because of the 16MHz clock frequency. Not sure about this part, though.

EDIT:

simulate this circuit

# Answer
Generally, try to debug the problem. Evidently either you're not getting data from your `esp8266.available()` and/or `esp8266.read()`, or it's not the right data. Put traces (`Serial.println(...)`) in, print things out, and find out what's going wrong.

---

Specifically, I suspect the issue here is that you are relying on all the data being available *immediately*: you check `esp8266.available()` which will tell you whether one or more bytes is available. Then you `esp8266.read()` until there are no more bytes available. What if there's a 1ms delay between bytes arriving? You'll get,perhaps `LED O`, `esp8266.available()` will tell you there's no more data (there's not, *yet*!) and you stop reading.

You could probably get it working by putting a small `delay()` in:

```
while(esp8266.available())
{
  command += (char)esp8266.read();
  delay(100);
}

```

That's a solution (probably) but not a *good* one. A better solution would be to make your commands `LED_ON\n` and `LED_OFF\n` \- and read until you get a `\n`.
> 0 votes

---
Tags: arduino-uno, serial, esp8266, atmega328
---


# Question
Title: Digital read on voltages between 1 and 31 volts?
Hello Arduino comunity!

I am working on a circuit that uses an Arduino Mini to read values from certain points of a boost/buck converter circuit to determine things like input state, output state, overheat and so on. The circuit is working all right, and the only part left to do is to connect the digital pins of the Arduino to the different points in the boost/buck regulator.

The problem is however that I need to read from a range of voltages between 1 and 31 volts with the Arduino, which isn't possible, because not only will it damage the controller if the voltage exceeds 5V, but values below 3V will be regarded as false.

I thought of putting some potential dividers, which would obviously not do the trick, and I also thought of using a WS78L05 voltage regulator per input pin (because each pin might have a different voltage from the rest) but that isn't dealing with voltages \<=5V and 31V exceeds its rating as well.

Lastly I thought of using transistors, which seemed like a good idea, but I would require 2 transistors per input wired as follows:

simulate this circuit – Schematic created using CircuitLab

But it is impractical to do for 4 inputs and there is limited space available on the PCB too :(

Is there any IC that encapsulates the circuit above, or is there any other way to achieve what I want to do?

Thanks very much :)

# Answer
Using a simple voltage divider (51K / 10K as you have worked out already) fed directly into an ADC input will give you a reading of 32 on the ADC at 1V input. That should be enough to give a reliable threshold detection.

If you want to have higher sensitivity at lower voltages you can increase the output of your voltage divider to more than 5V and then clip it with a zenner diode. For instance if you reduce the 51K to 33K you get 7.2V out of the voltage divider. A 5V zenner diode can then clip it to 5V. Your 1V input (which would be 0.233V on the output of the divider) would now read 47 on the ADC. Anything over 21V would then read 1023.

simulate this circuit – Schematic created using CircuitLab

Theoretically you could get away with not having the voltage divider at all and just using the zenner and one resistor to clip the incoming voltage to 5.1V. That would give you the greatest sensitivity, but also the greatest current flow through the zenner.

simulate this circuit

Size R1 to limit the current at your maximum voltage to within the rating of the zenner.
> 0 votes

# Answer
Use two quad lm339 voltage comparator chips to make an analog to digital convertor-you will need 2 to read 31 volts accurately. Its a standard ADC circuit, with this common lm339 is, so a search will find circuit-it may need a simple modification to combine the two circuit.
> 0 votes

# Answer
The junction of a 51KΩ, 10KΩ voltage divider will feed an Arduino ADC input 5.08 V at 31 V input, and 0.16 V at 1 V input. With a 5 V reference, I think the first of those will give 1023 counts, and the latter, 33 counts. This is from 1023\*(1/5)\*10/(10+51) ≃ 33.54. That may be enough counts for reliable detection, depending on how noisy the environment is.

For more sensitivity at lower voltages, if the first reading is less than 225 counts, one can switch to the 1.1 V internal ADC reference and take another reading. (1023\*1.1/5 ≃ 225.06.) With a 1.1 V reference, a 1 V input to the divider produces 152 counts, and a 6.7 V input produces about 1023 counts. (1023\*(1/1.1)\*10/(10+51) ≃ 152.46 and 1.1/(10/61) ≃ 6.7.)

To change the ADC reference voltage, say `analogReference(DEFAULT)` for Vcc reference, or `analogReference(INTERNAL)` for 1.1 V reference.
> 0 votes

---
Tags: atmega328, digital-in
---


# Question
Title: How to store a string in an object and retrieve it safely later?
I'm writing a program where I will be able to toggle between multiple banks, and each bank has 4 presets on it. Right now, I'm trying to give each preset a name that is assigned on creation.

I have an object I called `StoredDataManager`, which will handle all the banks. In its constructor, I do this:

```
for (byte i = 0; i < NUMBER_OF_BANKS; i++) {
  Bank bank;
  _banks[i] = &bank;
}

```

`_banks` is declared like this: `Bank* _banks[NUMBER_OF_BANKS];` in the `.h`file of `StoredDataManager`.

A bank has 4 presets, like this:

```
Preset* _A;
Preset* _B;
Preset* _C;
Preset* _D;

```

Which I initialize as this:

```
Preset preset(presetName, presetData);
...
_A = &preset; ...

```

Where `presetName` is `"CHR"`, and `presetData` doesn't matter, because I'm just trying to get the name to work.

In the preset, the name is saved like this: `char _presetName[4];`. It is returned like this:

```
char* Preset::getPresetName() {
  return _presetName;
}

```

I try to print a preset's name like this:

```
Serial.println(_banks[0]->getPreset('A')->getPresetName());

```

But, right now it simply returns .

Why is that? I suspect it has to do with the memory being erased or overwritten.

EDIT: Here is the code of `getPreset`:

```
Preset* Bank::getPreset(char presetLocation) {
  switch (presetLocation) {
    case PRESET_LOCATION_1:
      return _A;
    case PRESET_LOCATION_2:
      return _B;
    case PRESET_LOCATION_3:
      return _C;
    case PRESET_LOCATION_4:
      return _D;
    default:
      return NULL;
  }
}

```

I think now that I'll turn this into 4 separate functions, like `getA`, `getB` and so on, but this what it is the moment. `PRESET_LOCATION_1` is just a `#define PRESET_LOCATION_1 'A'`.

EDIT 2: I start in the main arduino `.ino` file with this:

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

```

This triggers this constructor:

```
StoredDataManager::StoredDataManager() {
  for (byte i = 0; i < NUMBER_OF_BANKS; i++) {
    Bank bank;
    _banks[i] = &bank;
  }
  _currentBankIndex = 0;
  Serial.println(_banks[0]->getPreset('A')->getPresetName());
}

```

This is `_banks`: `Bank* _banks[NUMBER_OF_BANKS];`. The initializing of the `bank` object runs this constructor: (PRESET\_LOCATION\_1, 2, 3, and 4 just being `'A', 'B', 'C', 'D'`)

```
Bank::Bank() {
  addPreset("CHR", "Some data", PRESET_LOCATION_1);
  addPreset("CHR", "Some data", PRESET_LOCATION_2);
  addPreset("CHR", "Some data", PRESET_LOCATION_3);
  addPreset("CHR", "Some data", PRESET_LOCATION_4);
}

```

Which calls this function:

```
void Bank::addPreset(const char* presetName, String presetData, char presetLocaton) {
  Preset preset(presetName, presetData);
  switch (presetLocaton) {
    case PRESET_LOCATION_1:
      _A = &preset; break;
    case PRESET_LOCATION_2:
      _B = &preset; break;
    case PRESET_LOCATION_3:
      _C = &preset; break;
    case PRESET_LOCATION_4:
      _D = &preset; break;
  }
}

```

Then, above in the `StoredDataManage`s constructor, this line is hit:

```
Serial.println(_banks[0]->getPreset('A')->getPresetName());

```

And that's where I try to log out the preset name.

# Answer
```
void Bank::addPreset(const char* presetName, String presetData, char presetLocaton)
{
  Preset preset(presetName, presetData);

  switch (presetLocaton)
  {
    case PRESET_LOCATION_1:
      _A = &preset; break;
    case PRESET_LOCATION_2:
      _B = &preset; break;
    case PRESET_LOCATION_3:
      _C = &preset; break;
    case PRESET_LOCATION_4:
      _D = &preset; break;
  }
}

```

I can't see how this is going to work because you are storing somewhere outside a function a pointer to a local variable *inside* the function. As soon as `addPreset` exits the variable `preset` will go out of scope, and a pointer to it will be undefined.

---

You should probably do a `new` to make a new instance of `Preset` which it is then valid to store outside the scope of the function.
> 1 votes

---
Tags: programming, c++, string, memory
---


# Question
Title: How to fix compilation error for tone() using same timer as other function
I am trying to integrate tone() with the open source program for the Amped heart rate monitor. The error:

> Tone.cpp.o (symbol from plugin): In function \`timer0\_pin\_port':
>
> (.text+0x0): multiple definition of \`\__vector\_7'
>
> sketch\PulseSensorAmped\_Arduino\_1dot4.ino.cpp.o (symbol from plugin):(.text+0x0): first defined here

The program comes in three files. PulseSensorAmped\_Arduino\_1dot4.cpp I don't think references any timers but references a function in another file with this code:

```
  // Initializes Timer2 to throw an interrupt every 2mS.
  TCCR2A = 0x02;     // DISABLE PWM ON DIGITAL PINS 3 AND 11, AND GO INTO CTC MODE
  TCCR2B = 0x06;     // DON'T FORCE COMPARE, 256 PRESCALER
  OCR2A = 0X7C;      // SET THE TOP OF THE COUNT TO 124 FOR 500Hz SAMPLE RATE
  TIMSK2 = 0x02;     // ENABLE INTERRUPT ON MATCH BETWEEN TIMER2 AND OCR2A
  sei();             // MAKE SURE GLOBAL INTERRUPTS ARE ENABLED

```

This uses timer 2; but isn't the error for timer 1? The tone() reference page says that tone interferes with pins 3 and 11. Is there any way to fix this?

references:

https://www.arduino.cc/en/Reference/Tone

https://github.com/WorldFamousElectronics/PulseSensor\_Amped\_Arduino

# Answer
> 4 votes
It looks like the Tone library uses Timer 2, and it looks like your other code also uses Timer 2, hence the error message. Vector 7 would be the TIMER2\_COMPA\_vect (Timer 2 compare "a").

Pins 3 and 11 are from Timer 2.

I wrote a small library that generates tones using the hardware PWM and not interrupts. You can read about it here.

Example code:

```
#include <TonePlayer.h>

TonePlayer tone1 (TCCR1A, TCCR1B, OCR1AH, OCR1AL, TCNT1H, TCNT1L);  // pin D9 (Uno), D11 (Mega)

void setup()
  {
  pinMode (9, OUTPUT);  // output pin is fixed (OC1A)

  tone1.tone (220);  // 220 Hz
  delay (500);
  tone1.noTone ();

  tone1.tone (440);
  delay (500);
  tone1.noTone ();

  tone1.tone (880);
  delay (500);
  tone1.noTone ();
  }

void loop() { }

```

Library can be downloaded from http://www.gammon.com.au/Arduino/TonePlayer.zip

This uses Timer 1 (so that won't interfere with Timer 2) and no interrupts.

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


# Question
Title: Volatile variable not updating from timer ISR
I know this is a problem that has come up many times but I can't seem to get this code fragment to update the count variable on an ATMEGA328P. I am using an Arduino Uno as a development board, with the LED on pin 13 set to flash for debugging. I have confirmed the timer and LED part work by toggling port B pin 5 in the ISR routine.

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

volatile uint8_t count;

void init_100us_tick(void) {
    TCCR0A = _BV(WGM01) | _BV(WGM00);       // WGM mode 7 with OCRA as top
    TCCR0B = _BV(WGM02) | _BV(CS01);        // CLK / 8 prescaler
    TIMSK0 = _BV(OCIE0B) | _BV(TOIE0);      // Interrupt enabled on OCR0A
    OCR0A = 200;                            // 16 MHz / 8 / 200 = 100 us
    sei();                                  // Enable interrupts
}

ISR(TIMER0_COMPB_vect) {
    count++;
}

int main(void) {
    DDRB |= _BV(DDB5);                      // PB5 output
    init_100us_tick();                      // Initialise 100 us tick
    count = 0;                              // In case of micro reset

    for (;;) {
        if (count >= 100) {                 // Every 10 ms
            count = 0;
            PORTB ^= _BV(DDB5);             // Toggle PB5
        }
   }
   return 0;
}

```

This is being compiled and burned to an Arduino Uno with the following:

```
avr-gcc -Os -DF_CPU=16000000UL -mmcu=atmega328p -c -o test.o test.c
avr-gcc -mmcu=atmega328p test.o -o test
avr-objcopy -O ihex -R .eeprom test test.hex
avrdude -F -V -c arduino -p ATMEGA328P -P /dev/ttyUSB0 -b 115200 -U flash:w:test.hex

```

I have tried disabling the optimisation with no effect. AVR-GCC is version 4.9.2

# Answer
You want CTC mode for that to work. As in:

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

volatile uint8_t count;

void init_100us_tick(void) {
    TCCR0A = _BV(WGM01);       // CTC mode 2 with OCRA as top
    TCCR0B = _BV(CS01);        // CLK / 8 prescaler
    TIMSK0 = _BV(OCIE0B) | _BV(TOIE0);      // Interrupt enabled on OCR0B
    OCR0A = 200;                            // 16 MHz / 8 / 200 = 100 us
    sei();                                  // Enable interrupts
}

ISR(TIMER0_COMPB_vect) {
    count++;
}

int main(void) {
    DDRB |= _BV(DDB5);                      // PB5 output
    init_100us_tick();                      // Initialise 100 us tick
    count = 0;                              // In case of micro reset

    for (;;) {
        if (count >= 100) {                 // Every 10 ms
            count = 0;
            PORTB ^= _BV(PORTB5);             // Toggle PB5
        }
   }
   return 0;
}

```

That toggles every 10 ms.

---

**(Edited to add)**

The PWM mode you chose will work providing you enable the correct interrupt. This also outputs 10 ms pulses:

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

volatile uint8_t count;

void init_100us_tick(void) {
    TCCR0A = _BV(WGM01) | _BV(WGM00);       // Fast PWM mode 7 with OCRA as top
    TCCR0B = _BV(WGM02) | _BV(CS01);        // CLK / 8 prescaler
    TIMSK0 = _BV(OCIE0A);                   // Interrupt enabled on OCR0A  ***
    OCR0A = 200;                            // 16 MHz / 8 / 200 = 100 us
    sei();                                  // Enable interrupts
}

ISR(TIMER0_COMPA_vect) {                    // Compare A vector ***
    count++;
}

int main(void) {
    DDRB |= _BV(DDB5);                      // PB5 output
    init_100us_tick();                      // Initialise 100 us tick
    count = 0;                              // In case of micro reset

    for (;;) {
        if (count >= 100) {                 // Every 10 ms
            count = 0;
            PORTB ^= _BV(PORTB5);           // Toggle PB5  ***
        }
   }
   return 0;
}

```

Changed lines indicated by `***`

Note that you should **not** have enabled `_BV(TOIE0)` because you have no interrupt handler for Timer 0 overflow. Without an interrupt handler the compiler probably generated code to jump to the reset vector.

The interrupt occurs when the timer matches the **Compare A** amount (not Compare B) so you need an interrupt on the A side.
> 2 votes

---
Tags: arduino-uno, atmega328, timers, isr, avr-gcc
---


title: Reading Infrared raw data

text:
# Question
Title: Reading Infrared raw data
I'm trying to understand a few things about this code.

1. Why is `digitalRead()` slower than `IRpin_PIN & (1 << IRpin)`?
2. What does `IRpin_PIN & (1 << IRpin)` mean? I translated it to numbers and I figured out it's actually `PIND & (0b100)`. What does PIND translate to and why is bitwise-and with `0b100` performed on it?
3. Why is the 20-microsecond delay (`RESOLUTION`) necessary?
4. What does `_BV` in `while (! (IRpin_PIN & _BV(IRpin)))` mean?

---

```
/* Raw IR decoder sketch!

 This sketch/program uses the Arduno and a PNA4602 to
 decode IR received. This can be used to make a IR receiver
 (by looking for a particular code)
 or transmitter (by pulsing an IR LED at ~38KHz for the
 durations detected

 Code is public domain, check out www.ladyada.net and adafruit.com
 for more tutorials!
 */

// We need to use the 'raw' pin reading methods
// because timing is very important here and the digitalRead()
// procedure is slower!
//uint8_t IRpin = 2;
// Digital pin #2 is the same as Pin D2 see
// http://arduino.cc/en/Hacking/PinMapping168 for the 'raw' pin mapping
#define IRpin_PIN      PIND
#define IRpin          2

// the maximum pulse we'll listen for - 65 milliseconds is a long time
#define MAXPULSE 65000

// what our timing resolution should be, larger is better
// as its more 'precise' - but too large and you wont get
// accurate timing
#define RESOLUTION 20

// we will store up to 100 pulse pairs (this is -a lot-)
uint16_t pulses[100][2];  // pair is high and low pulse
uint8_t currentpulse = 0; // index for pulses we're storing

void setup(void) {
  Serial.begin(9600);
  Serial.println("Ready to decode IR!");
}

void loop(void) {
  uint16_t highpulse, lowpulse;  // temporary storage timing
  highpulse = lowpulse = 0; // start out with no pulse length
//  while (digitalRead(IRpin)) { // this is too slow!
    while (IRpin_PIN & (1 << IRpin)) {
     // pin is still HIGH
     // count off another few microseconds
     highpulse++;
     delayMicroseconds(RESOLUTION);
     // If the pulse is too long, we 'timed out' - either nothing
     // was received or the code is finished, so print what
     // we've grabbed so far, and then reset
     if ((highpulse >= MAXPULSE) && (currentpulse != 0)) {
       printpulses();
       currentpulse=0;
       return;
     }
  }
  // we didn't time out so let's stash the reading
  pulses[currentpulse][0] = highpulse;
  // same as above
  while (! (IRpin_PIN & _BV(IRpin))) {
     // pin is still LOW
     lowpulse++;
     delayMicroseconds(RESOLUTION);
     if ((lowpulse >= MAXPULSE)  && (currentpulse != 0)) {
       printpulses();
       currentpulse=0;
       return;
     }
  }
  pulses[currentpulse][1] = lowpulse;
  // we read one high-low pulse successfully, continue!
  currentpulse++;
}

void printpulses(void) {
  Serial.println("\n\r\n\rReceived: \n\rOFF \tON");
  for (uint8_t i = 0; i < currentpulse; i++) {
    Serial.print(pulses[i][0] * RESOLUTION, DEC);
    Serial.print(" usec, ");
    Serial.print(pulses[i][1] * RESOLUTION, DEC);
    Serial.println(" usec");
  }
  // print it in a 'array' format
  Serial.println("int IRsignal[] = {");
  Serial.println("// ON, OFF ");
  for (uint8_t i = 0; i < currentpulse-1; i++) {
    //Serial.print("\t"); // tab
    Serial.print("pulseIR(");
    Serial.print(pulses[i][1] * RESOLUTION , DEC);
    Serial.print(");");
    Serial.println("");
    //Serial.print("\t");
    Serial.print("delayMicroseconds(");
    Serial.print(pulses[i+1][0] * RESOLUTION , DEC);
    Serial.println(");");
  }
  //Serial.print("\t"); // tab
  Serial.print("pulseIR(");
  Serial.print(pulses[currentpulse-1][1] * RESOLUTION, DEC);
  Serial.print(");");
}

```

# Answer
> 1 votes
```
int digitalRead(uint8_t pin)
{
    uint8_t timer = digitalPinToTimer(pin);
    uint8_t bit = digitalPinToBitMask(pin);
    uint8_t port = digitalPinToPort(pin);

    if (port == NOT_A_PIN) return LOW;

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

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

```

1) so it

* calls function `digitalRead()` (puts value on stack, jumps, prepare function frame - each cost some time)
* calls 3 other functions (with all the same problems)
* check for sanity of value
* check for PWN (and eventually calls another function)
* does the `PIND & (0b100)`
* returns from function (so read stack, clear the frame, jumps, set the result)

just to obtain the same functionality

* typical for library functions, that each call makes sure the environment is sane and expected each and every time it is called - in close loop you can check it onece before and then just do not broke it
* translates parameter from `nice arduino numbers` to `real addresses and bits` each and every time again

2) it access the PORT D (see AVR (the processor) internal construction) and reads value of its 3. bit (which maps to the relevant pin of the chip/Arduino board

3) see following comment - it is expected length of the pulse (maybe with some safety limit)

4) \_BV is for BitValue - shift 1 to position given by arg (that is macro doind 1 \<\< IRpin) maybe more nice/readable version, compiles to the same. (the `!` is ofcourse negaition)

---
Tags: infrared
---


# Question
Title: Arduino due - SAM-BA bootloader is it there even if you replace the original chip
On this page http://playground.arduino.cc/Bootloader/DueBootloaderExplained it mentions the sam-ba bootloader is permanently burned into the rom of the chip.

Does this mean even if I buy a new chip from Farnell, it will still have the bootloader in or is just ones that are specifically made for the arduino due?

That is different from say the mega328, with the mega328 I have to burn the bootloader on manually using isp programmer/ buy it preprogrammed.

# Answer
> 2 votes
## Yes, for the Due, but No, for a Zero or Adafruit Feather M0.

The Due uses the Atmel SAM3X8E featuring:

> 16 Kbytes ROM with embedded bootloader routines

As a ROM the contents are fixed during manufacture, so would be there in a new chip.

However it is worth noting that many SAM devices including this one have the NVM bits that are much like the fuse bits on an ATmega. Here GPNVM bit 1 defaults to 0, enabling the bootloader, but if set to 1 the bootloader will be skipped. Hence it may well be possible to get one into a state where the bootloader is not available. They also have an "erase" pin which if driven high during startup will restore the default state (bootloader invoked) of this NVM bit (and erase whatever you put in flash).

---

In contrast, the Arduino Zero and the Adafruit Feather M0 also use Atmel "SAM" chips with "SAM-BA", however, they use the SAMD21, where the situation is a bit different:

> Unlike existing SAM products, ROM monitor is not available in SAM D21 and SAM-BA will be loaded in Flash memory.
>
> SAM-BA bootloader is not factory programmed on SAM D21 devices and has to be programmed using an external programmer.

---

Incidentally, congratulations on being willing to step beyond the ATmega DIP packages - more people need to learn that surface mounts part (or at least the TSSOP and LQFP varieties) are something that can be worked with by hand. If you do not have hot air tools, make sure to only solder one corner, check alignment, solder the opposite and recheck, etc. But hot air will save you so many headaches and a solder station with it is now in the $60-70 range.

Finally, while you do have the bootloader available in the SAM, to really take advantage of all of its capabilities you will want to get an SWD interface - in addition to programming without reliance on the bootloader, this exposes things like breakpoint debugging, which while almost never "necessary" can still be quite convenient and useful. Atmel used to offer a great deal on the PCB of the SAM-ICE pod less cables kit and housing, unfortunately there was a massive price increase after the Microchip acquisition.

SWD programming is effectively vendor-unique software operations performed on top of a standard signalling scheme, so you do have options for programmers from other sources - you can make a functional if quite slow CMSIS-DAP from an MBED board (or apparently an Arduino Pro Micro) that will work for debugging but be slow at flashing, you can probably use a Raspberry pi, or the more advanced FTDI devices with the MPSSE engine such as FT232H/FT2232H/FT4232H (but not the everyday FT232RL). With alternate programmers you will probably need to use something like openocd for the host software - Atmel Studio likely only supports their own and perhaps a few pricey alternatives.

---
Tags: arduino-due, programmer
---


# Question
Title: Formula / calculation of the function random() / randomSeed()
In which file can I find the calculation that is called with `random()`? If it is not too much could you also post the content in your answer? I am using an Arduino Uno and its standard IDE.

I found this in the "WMath.cpp" but that is not the final calculation.

```
void randomSeed(unsigned int seed)
{
  if (seed != 0) {
    srandom(seed);
  }
}

long random(long howbig)
{
  if (howbig == 0) {
    return 0;
  }
  return random() % howbig;
}

long random(long howsmall, long howbig)
{
  if (howsmall >= howbig) {
    return howsmall;
  }
  long diff = howbig - howsmall;
  return random(diff) + howsmall;
}

```

# Answer
> 7 votes
The underlying `random()` function isn't part of the Arduino code. It's actually part of `avr-libc`. The Arduino IDE only comes with pre-compiled object code for it (as far as I know).

It's open source though. You can get information about it here:

If you look down the page a short way, you'll find the "Source code and documentation" link.

The `random()` function is under `libc/stdlib/random.c`. I would paste the source code here, but technically I'd have to include a whole copyright notice with it.

# Answer
> 1 votes
Read Peter Bloomfield's answer here: https://arduino.stackexchange.com/a/1482/7727

Then read the following:

For everyone's reference, Arduino's WMath.cpp is found here.

Documentation for AVR-Libc's random() function is here.

Source code for AVR-Libc is found here, as linked-to from here.

I downloaded "avr-libc-2.0.0.tar.bz2.sig 08-Feb-2016" and extracted it. Like Peter said, the source code for "random" is in "**avr-libc-2.0.0\libc\stdlib\random.c**"

To save you the hassle, here's the source code, with their included copyright and license statement right at the top of it.

```
/*-
 * Copyright (c) 1990, 1993
 *  The Regents of the University of California.  All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 * 3. Neither the name of the University nor the names of its contributors
 *    may be used to endorse or promote products derived from this software
 *    without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 *
 * Posix rand_r function added May 1999 by Wes Peters <wes@softweyr.com>.
 *
 * $Id: random.c 1944 2009-04-01 23:12:20Z arcanum $
 */

/*
 * From:
static char sccsid[] = "@(#)rand.c  8.1 (Berkeley) 6/14/93";
*/

#include <stdlib.h>
#include "sectionname.h"

ATTRIBUTE_CLIB_SECTION
static long
do_random(unsigned long *ctx)
{
    /*
     * Compute x = (7^5 * x) mod (2^31 - 1)
     * wihout overflowing 31 bits:
     *      (2^31 - 1) = 127773 * (7^5) + 2836
     * From "Random number generators: good ones are hard to find",
     * Park and Miller, Communications of the ACM, vol. 31, no. 10,
     * October 1988, p. 1195.
     */
    long hi, lo, x;

    x = *ctx;
    /* Can't be initialized with 0, so use another value. */
    if (x == 0)
        x = 123459876L;
    hi = x / 127773L;
    lo = x % 127773L;
    x = 16807L * lo - 2836L * hi;
    if (x < 0)
        x += 0x7fffffffL;
    return ((*ctx = x) % ((unsigned long)RANDOM_MAX + 1));
}

ATTRIBUTE_CLIB_SECTION
long
random_r(unsigned long *ctx)
{
    return do_random(ctx);
}

static unsigned long next = 1;

ATTRIBUTE_CLIB_SECTION
long
random(void)
{
    return do_random(&next);
}

ATTRIBUTE_CLIB_SECTION
void
srandom(unsigned long seed)
{
    next = seed;
}

```

---
Tags: arduino-uno, software
---


title: How to delete first voltage reading?

text:
# Question
Title: How to delete first voltage reading?
## I'm trying out a new ADC, ADS1262, below is the code. I want to discard the first voltage reading.

```
*/
#include <SPI.h>
#include <SoftwareSerial.h>
#include <math.h>
#include <ads1262.h>

#define PGA 1                     // Programmable Gain = 1
#define VREF 2.50                 // Internal reference of 2.048V
#define VFSR VREF/PGA
#define FSR (((long int)1<<23)-1)

ads1262 PC_ADS1262;                     // class

float volt_V=0;
float volt_mV=0;
volatile int i;
volatile char SPI_RX_Buff[10];
volatile long ads1262_rx_Data[10];
volatile static int SPI_RX_Buff_Count = 0;
volatile char *SPI_RX_Buff_Ptr;
volatile int Responsebyte = false;
volatile signed long sads1262Count = 0;
volatile signed long uads1262Count=0;
double resolution;

void setup()
{
  // initalize the  data ready and chip select pins:
  pinMode(ADS1262_DRDY_PIN, INPUT);                  //data ready input line
  pinMode(ADS1262_CS_PIN, OUTPUT);                   //chip enable output line
  pinMode(ADS1262_START_PIN, OUTPUT);               // start
  pinMode(ADS1262_PWDN_PIN, OUTPUT);                // Power down output

  Serial.begin(9600);
  //initalize ADS1292 slave
  PC_ADS1262.ads1262_Init();                      // initialise ads1262
  Serial.println("ads1262 Initialised successfully....");

 }

void loop()
{
  volatile int i,data;

 if((digitalRead(ADS1262_DRDY_PIN)) == LOW)               // monitor Data   ready(DRDY pin)
  {
    SPI_RX_Buff_Ptr = PC_ADS1262.ads1262_Read_Data();      // read 6 bytes conversion register
    Responsebyte = true ;
  }

  if(Responsebyte == true)
  {
    for(i = 0; i <5; i++)
    {
      SPI_RX_Buff[SPI_RX_Buff_Count++] = *(SPI_RX_Buff_Ptr + i);
    }
    Responsebyte = false;
  }

  if(SPI_RX_Buff_Count >= 5)
  {

    ads1262_rx_Data[0]= (unsigned char)SPI_RX_Buff[1];  // read 4 bytes adc count
    ads1262_rx_Data[1]= (unsigned char)SPI_RX_Buff[2];
    ads1262_rx_Data[2]= (unsigned char)SPI_RX_Buff[3];
    ads1262_rx_Data[3]= (unsigned char)SPI_RX_Buff[4];

     uads1262Count = (signed long) (((unsigned long)ads1262_rx_Data[0]<<24)| ((unsigned long)ads1262_rx_Data[1]<<16)|(ads1262_rx_Data[2]<<8)|      ads1262_rx_Data[3]);//get the raw 32-bit adc count out by shifting
     sads1262Count = (signed long) (uads1262Count);      // get signed value
     resolution = (double)((double)VREF/pow(2,31));       //resolution= Vref/(2^n-1) , Vref=2.5, n=no of bits
// Serial.print(resolution,15);
     volt_V      = (resolution)*(float)sads1262Count;     // voltage = resolution * adc count
     Serial.print(volt_V,8);

   }

  SPI_RX_Buff_Count = 0;

}

float mapfloat(float x, float in_min, float in_max, float out_min, float out_max)
{
  return (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min;
}

```

# Answer
Here is what the code shown in the other answer will do.

```
int read_first = 0;

```

That allocates `read_first` and sets it to zero.

```
if (read_first ) {
    volt_V      = (resolution)*(float)sads1262Count;     // voltage = resolution * adc count
    Serial.print(volt_V,8);
}
else {
   // discarded first result, now we've read the first one
   read_first = 1;
}

```

First time in, `read_first` evaluates false, so the `else` branch will be taken, and `read_first` set to 1. Note that no reading has been taken yet, so the “// discarded first result, now we've read the first one” comment is incorrect and irrelevant. Second and later times in, `read_first` evaluates true, so `volt_V` readings will be taken and printed.

To correct the problems with that code, use an approach like the following.

```
int useReading = 0;
...
volt_V = resolution*(float)sads1262Count;
if (useReading ) {
    Serial.print(volt_V,8);
    // and otherwise use the reading as desired
}
useReading = 1;

```

After this takes a first reading, it doesn't use that reading because `useReading` evaluates false. Subsequent readings get used because `useReading` is turned on after the first reading.
> 1 votes

# Answer
Simplest way is to have a flag to specify whether you've read the first reading or not. Default to zero:

```
int read_first = 0;

```

Then you can say:

```
if (read_first ) {
    volt_V      = (resolution)*(float)sads1262Count;     // voltage = resolution * adc count
    Serial.print(volt_V,8);
}
else {
   // discarded first result, now we've read the first one
   read_first = 1;
}

```
> 3 votes

---
Tags: arduino-uno
---


title: Need help rewriting a program

text:
# Question
Title: Need help rewriting a program
I can't use this program on my Arduino Uno since the max is 16 bits. I need my water pump to run for 5 min, then wait for 60 min.

```
int motorPin = A0;
int blinkPin = 13;

int watertime = 300000; // how long to water in miliseconds
int waittime = 3600000; // how long to wait between watering

void setup() {
    pinMode(motorPin, OUTPUT);
    pinMode(blinkPin, OUTPUT);
}

void loop() {
    digitalWrite(motorPin, HIGH);
    digitalWrite(blinkPin, HIGH);
    delay(watertime);
    digitalWrite(motorPin, LOW);
    digitalWrite(blinkPin, LOW);
    delay(waittime);
}

```

---

Changed int to:

```
#define watertime 300000
#define waittime 3600000

```

But it does not work.

# Answer
Use the `long` type instead

```
long watertime = 300000; // how long to water in miliseconds
long waittime = 3600000; // how long to wait between watering

```
> 5 votes

# Answer
For any delays longer than a few seconds you really need to use a Real-Time Clock chip, like the popular DS1307 from Maxim. The Arduino's delay() function is only very roughly accurate, and even less so when used as you are using it.

If you can't get a DS1307 or something similar (there's plenty to choose from) or you Arduino has too much connected already to allow anything else to be added, you could use the `Time` library to simulate one. The `Time` library is also useful if you do have an RTC attached.
> 2 votes

# Answer
If did not misunderstand, you want a longer delay. Why don't you use a for loop in order to obtain such a delay.

```
for(int i = 0; i < 50; i++) {
    delay(1000);
}

```

This produces 50 seconds instead of 1 second. You can replace 1000 and 50 according to your needs. This is just an example.
> 0 votes

# Answer
I do not know if you plan on doing anything else on your arduino, but holding a delay inside the loop function is bad idea if you do, things need to happen outside of your code (any serial I/O for sure and others, right?).

That said, I like @zgrknr answer the best, although the others will also work. That answer allows using smaller numbers, that are easier to understand. Just make sure to keep your variables global, and not within loop or else they will get re-initialized every time.

As far as accuracy, do some real by the clock testing, and adjust your numbers, who cares if it is accurately counting as long as you can identify what numbers gives you the time period you want.

response to comment:

My firmware code looks like this, is yours different?

```
int main(void)
{
  init();
  initVariant();

#if defined(USBCON)
  USBDevice.attach();
#endif

  setup();

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

```
> 0 votes

# Answer
I believe it's better to put the Arduino to sleep instead of using the delay function.

You can use a library called *Sleep\_n0m1* for the purpose.

Modify your code like following.

```
#include <Sleep_n0m1.h>

int motorPin = A0;
int blinkPin = 13;

unsigned long watertime = 300000UL; // how long to water in miliseconds
unsigned long waittime = 3600000UL; // how long to wait between watering
Sleep sleep;

void setup()
{
    pinMode(motorPin, OUTPUT);
    pinMode(blinkPin, OUTPUT);
}

void loop()
{
    digitalWrite(motorPin, HIGH);
    digitalWrite(blinkPin, HIGH);
    sleep.pwrDownMode();
    sleep.sleepDelay(watertime);
    digitalWrite(motorPin, LOW);
    digitalWrite(blinkPin, LOW);
    sleep.pwrDownMode();
    sleep.sleepDelay(waittime);
}

```

Hope this would solve the problem.
> 0 votes

---
Tags: arduino-uno
---


title: NodeMCU sensor values to web page

text:
# Question
Title: NodeMCU sensor values to web page
I post NodeMCU sensor values to a web page. But how can I pass those values to a database using PHP?

Here is the code to post sensor values to a web page:

```
#include <ESP8266WiFi.h>

const char* ssid = "CDS_ARDUINO";
const char* password = "arduinotest@wifi";

WiFiServer server(80);

void setup() {
  Serial.begin(115200);
  Serial.print("Connecting to ");
  Serial.println(ssid);
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println("WiFi connected");
  // Start the server
  server.begin();
  Serial.println("Server started");
  // Print the IP address
  Serial.print("Use this URL : ");
  Serial.print("http://");
  Serial.print(WiFi.localIP());
  Serial.println("/");
}

void loop() {
  WiFiClient client = server.available();
  if (!client) {
    return;
  }
  // Wait until the client sends some data
  Serial.println("new client");
  while(!client.available()){
    delay(1);
  }
  String request = client.readStringUntil('\r');
  Serial.println(request);
  client.flush();
  client.println("HTTP/1.1 200 OK");
  client.println("Content-Type: text/html");
  client.println("Connnection: close");
  client.println();
  client.println("<!DOCTYPE HTML>");
  client.println("<html>");
  client.println("<meta http-equiv=\"refresh\" content=\"3\">");
  client.println("<h1>Getting NodeMCU Analog values</h1>");
  int sensorReading = Serial.read();
  client.println("<header>");
  client.println("</header>");
  client.println("<br />");
  client.println("<style>");
  client.println("h1{color: blue;}");
  client.println("</style>");
  client.println("<i>");
  client.print("<h2>");
  client.println("<i>");
  client.print("&nbsp &nbsp &nbsp &nbsp &nbsp");
  client.print(" Analog input value is ");
  client.println("</i>");
  client.print(sensorReading);
  client.print("</h2>");
  client.println("</html>");
  delay(100);
  Serial.println("Client disconnected");
}

```

# Answer
Before your question gets closed, since it's only merely related to Arduino, I'd like to post this answer to give you more of an clue on how to set up the system.

1. Connect PHP and the database of your choice.
2. Connect the Arduino to PHP (probably with TCP/IP or HTTP), to send the values to the database.
3. Use PHP (+ webserver) to generate and serve webpages.

Only point 2 is somewhat related to Arduino.SE, so I'll try to give you some "handles" to get started.

https://www.arduino.cc/en/Tutorial/WebClient

https://www.arduino.cc/en/Tutorial/HttpClient

You can issue a GET request with variables to a webpage using Arduino. In PHP you can read out these variables. And using PHP you can connect and send variables to your database.

*You shouldn't connect the Arduino directly to the database, because exposing your database to the world wide web is a security risk.*

After this, it will be relatively easy to generate a page with the contents from your database.
> 0 votes

---
Tags: nodemcu
---


title: Creating linear motion using motor

text:
# Question
Title: Creating linear motion using motor
I am trying to make a smart lock for bicycles. This lock can be controlled with the help of smartphones. For the purpose, I am using an Arduino interfaced with HC-05 Bluetooth Module which receive commands from an Android smartphone.

The overall project is almost over, except the actual lock. I want to create a lock with a pin which can be slide between the spokes of the wheel to cease the motion of the wheels. I can't find any product in the Indian market. Can you please suggest any product available or how to make one myself?

> I've seen the solenoid locks but their stroke is too small to make a meaningful lock out of it.

Your help will be well appreciated.

# Answer
> 0 votes
The pin that slides between the spokes should be just a metal bar that accepts your "small" pins in the ends to hold it in place. Try looking at it from a different perspective and I think you will find a lot more suitable products.

You could use a worm gear, but this would be susceptible to bruit force attacks (literally) and would be easier to break.

Have you considered what happens when the power fails? Does the lock lock or unlock? If it unlocks on a power fail then it will be quite easy to open. If it remains locked on a power fail then its not very user friendly, you would have to carry spare batteries and changing tools with you.

Sorry, but it is easy to poke holes in other peoples designs.

---
Tags: bluetooth, motor
---


# Question
Title: "port" is greyed out in 1.6.13, running win 10 for an Uno R3
I am new to this, and my kid got an Elegoo smart robot car kit v2.0 for Christmas. We assembled the car, but after downloading the software, the program always states:

> Arduino: 1.6.13 (Windows Store 1.6.13.0) (Windows 10), Board: "Arduino/Genuino Uno"
>
> Sketch uses 2,242 bytes (6%) of program storage space. Maximum is 32,256 bytes.
>
> Global variables use 210 bytes (10%) of dynamic memory, leaving 1,838 bytes for local variables. Maximum is 2,048 bytes. avrdude: ser\_open(): can't open device "\\.\COM1": The system cannot find the file specified.
>
> Problem uploading to board. See http://www.arduino.cc/en/Guide/Troubleshooting#upload for suggestions.
>
> This report would have more information with "Show verbose output during compilation" option enabled in File -\> Preferences.

I don't know what other information is important. Can somebody please help me?

Thank you.

# Answer
> 2 votes
When the port is greyed out its not available (I know you had worked that out) so you have a problem with you serial to USB drivers.

Looking at the kit I think you are connecting the UNO to a USB port on your PC/laptop using a blue cable.
1. Please can you check that the cable is connected properly. 2. Can you try a different USB port on the PC (don't use a USB hub - some don't work). 3. Does Windows recognise a device has been plugged? 4. Are you running it as administrator, you will need to be to install the drivers. 5. Can you try connecting it to a different PC?

If these don't fix it then, please comment and well go through looking at the device manager.

Hope it works, it looks like fun.

---
Tags: arduino-uno
---


# Question
Title: How to calculate the time it takes before the water valve stops dispensing water in an Automatic Water level controller?
I am making a project about an automated water level controller using ultrasonic, potentiometer and Arduino board. I need a mathematical calculation on how it works. So here's a simple scenario:

I have an open top cylindrical container with a radius of 7cm. The ultrasonic sensed that the half height of the container, which is 15cm, is filled with water. At the bottom part of it, a tube with a radius of 1cm is connected alongside with the water valve. How can I calculate the time needed for the water valve to stop dispensing water if I set the potentiometer to keep the level of water at 9cm only? Can you give me a mathematical formula??

I really need a help, please. Any answer will be highly appreciated. Thank you in advance.

# Answer
The concept you have is more complicated than you can imagine. But to answer your question (which is not so arduino-based), the mathematical formula you looking for is Torricelli's Law.

My suggestion for you is design a system which use a feedback concept instead
> 1 votes

# Answer
Sounds like it's the valve's time to close (t\_vc) + half (statistically) the measurement interval (t\_interval) + the software reaction time (t\_sw). So

Add whatever measurement interval the software uses, if any, and the valve's time to close, once activated, and the software's time to react (from decision to actually making the valve-close signal) and you should have it. So:

T = t\_sw + t\_vc + 0.5\*t\_interval

Any software reaction time should be negilgible for practical purposes, so we're down to:

T = t\_vc + 0.5\*t\_interval

If the software doesn't include sleeps or delays but loops continuously, measuring and deciding, then the half-interval reduces to negligibility leaving just the valve closure time:

T = t\_vc
> 0 votes

---
Tags: arduino-uno, sensors, potentiometer, project, mathematics
---


title: Detecting I2C transfer with LED

text:
# Question
Title: Detecting I2C transfer with LED
I am going to do a project with a lot of Arduinos connected via I2C, where like of them can became master for a moment to announce an event. So I would like to see how much is the bus used. As there will be a central point, I thought about putting a LED there, from +5V to clock line, so it would shine when the transfer occurs and be black when the line is free. And so I would be able to guess the utilisation level of the bus. (The clock is effectively PWM going to zero often while in transfer, while being plain +5V when no transfer is active).

Of course direct connection is not the best idea, as it would disrupt the pull-ups and mess with the protocol (as it would drain a lot of power to clock each time it went down), there should be some separator/amplifier.

The question is - does anybody know a simple setting, where the LED would be driven by a small current to zero (that is inverting amplifier as simple as possible with high enough input impedance to not disturb I2C communication)?

Thanks for all hints :)

# Answer
> 1 votes
It can be done with two N-channel MOSFETs or one P-channel MOSFET (depending on what you have locally / can get / is in your bits box):

simulate this circuit – Schematic created using CircuitLab

In the left schematic the first MOSFET acts like a NOT gate, and the second is a simple low-side switch. The pair together make an active-low low-side switch.

The right hand schematic, which is somewhat simpler, uses a single P channel MOSFET as a high-side switch. This is normally driven with an N-channel MOSFET to invert the logic, since it is naturally active-low. You don't want that, so you can just connect direct to the gate.

Note that all MOSFETs are "logic level" with a threshold voltage below 3V (or -3V in the case of the P-channel).

---
Tags: led, i2c, hardware
---


# Question
Title: A class within a class - via an Initialiser Lists: NOT able to update a variable
My test are based on the blog of http://arduinoetcetera.blogspot.be/2011/01/classes-within-classes-initialiser.html.

Because I would like to use this idea, I tried with a simple idea, after the instance is created just ***update*** a value.

But for some reason, the code compiles perfectly and there seems to be no error with the ***update*** method, but it **DOES NOT UPDATE** the variable.

But my output on the serial monitor show that the number (volatile int) doesn't update.

```
Object of class First has value - Number: 6
Object of class Second has value - Number: 13
Object of class Second has value - Double: 26
Object of class Second has value - Update: [0] - 20  // <--
- -
Object of class First has value - Number: 6
Object of class Second has value - Number: 13        // <--
Object of class Second has value - Double: 26
Object of class Second has value - Update: [1] - 70
- -
Object of class First has value - Number: 6
Object of class Second has value - Number: 13

```

code - MAIN : First thing(**6**, **13**); \[edited on request of @Mark Smith\]

```
#include "First.h"
First thing(6, 13);
...
int newValue;
...
int ledPins[] = {
  20, 70, 45, 68, 543, 321
}; // an array of pin numbers to which LEDs are attached
int pinCount = 6; // the number of pins (i.e. the length of the array)
bool plus=true;
int index=-1;
void loop() {
  Serial.print("Object of class First has value - Number: ");
  Serial.println(thing.Number());
  Serial.println();
  Serial.print("Object of class Second has value - Number: ");
  Serial.println(thing.getSecond().Number());
  Serial.print("Object of class Second has value - Double: ");
  Serial.println(thing.getSecond().Double());
  ...
  Serial.print("Object of class Second has value - Update: [");
  if ( plus && index == (pinCount-1) ) {
    plus=!plus;
  }
  if ( !plus && index == 0 ) {
    plus=!plus;
  }
  // change + <--> -
  (plus) ? index++ : index--;
  newValue=ledPins[index];
  Serial.print(index,DEC);
  Serial.print("] - ");
  Serial.println(newValue, DEC);
  thing.getSecond().Update(newValue);
  Serial.println("- - ");

```

code - FIRST

```
#include "First.h"
...
First::First(int firstNumber, int secondNumber) : widget(secondNumber) {
  itsNumber = firstNumber;
}
int First::Number() {
  return itsNumber;
}
Second First::getSecond() {
  return widget;
}

```

code - SECOND : void Second::Update(int **newNumber**)

```
#include "Second.h"
...
volatile int itsNumber;
Second::Second(int newNumber) {
  itsNumber = newNumber;
}
void Second::Update(int newNumber) {
  itsNumber = newNumber;
}
int Second::Number() {
  return itsNumber;
}
int Second::Double() {
  return itsNumber*2;
}

```

For the complete code https://github.com/droopy4u/ARDUINO \- https://github.com/droopy4u/ARDUINO/tree/master/ClassWithClasses -

# Answer
Even without the real code, I think the problem is with the function First::Second().

You need to understand what happens in C++ when values are passed as parameters. The are passed by value by default, this means a *COPY* of the value is passed into the function, you can modify the parameter all you like but when you return those changes are lost.

There are two exceptions to this, the first is pointers. When you pass in a pointer you can modify what is pointed to but you still can't modify the pointer, because that is a copy. If you want to modify the pointer then you need a pointer to a pointer `int** ptr_to_ptr`.

The other exception is a reference. In this case the function can modify the parent function's variable. This is more efficient in terms of memory.

So you have:

```
int AddOne(int value) {++value; return value};   // 5 == AddOne(5);
int AddOne (int value) {return value+1};         // 6 == AddOne(5); - doesn't modify the parameter.
int AddOne(int* pValue) {(*value)+1; return *value;}//6 == AddOne(5); - Pointer
int AddOne(int& value){++value; return value;}   // 6 == AddOne(5); - Referance
int AddOne(const int& value){++value; return value;} // Compiler error, modifying const value.

```

So why it is First::Second() causing the problem? Well the same rules apply to return values as to parameters and you are returning a copy of the value `widget` so you then modify that copy and then dispose of it. So this is what you need to fix the problem.

```
Second& First::getSecond()
{
    return widget;
}

```

EDIT : Its not clear in the preceding text but you don't need `getSecond()` to return a reference if you are not altering the value of `widget` so `getDouble()` will return the expected value because it is working form a copy of the original and not storing any changes. However `update()` will not work as expected because the result of `getSecond()` goes out of scope (gets disposed of) once the call is complete. The changes its made are not save to the original because it is working on a copy.
> 0 votes

# Answer
@MATT, with trying to get the address of variable via

```
    const long SERIAL_SPEED=38400;//baud rate of the serial communication

//global variable
    int a = 15;
    int *b=a;

void infoVar(){
    Serial.print("\n\n");
    Serial.print(" a -  ");  Serial.println(a, DEC );
    Serial.print("*b -  ");  Serial.println(*b, DEC );  // dereferencing
    Serial.print("\n");

    Serial.print("int  b - ");  Serial.println( (int) b, DEC );   // ???
    // This is the content of the pointer variable b
    Serial.print("int &b - ");  Serial.println( (int) &b, DEC );  // address of memory location where b is stored
    Serial.print("int &a - ");  Serial.println( (int) &a, DEC );  // address of memory location where a is stored
}

void setup() {
  // put your setup code here, to run once:
    Serial.begin(SERIAL_SPEED);      // open the serial port at SERIAL_SPEED bps:

    Serial.println("Started : ### reference_pointer ###\n\n");

// *** :  when uncomment next line : the value b = 123
//b=123

    *b=a;
    infoVar();

    a=235;
    *b=a;
    infoVar();

    a=1928;
    *b=a;
    infoVar();

    }

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

```

OUTPUT

```
 a -  15
*b -  15

int  b – 15
        // don't understand here that it is 15
            //thought that is would be the the address of the variable 'a'
            // it seems that it keeps the first initiated value??? ***
int &b - 676
int &a - 256

 a -  235
*b -  235

int  b - 15
int &b - 676
int &a - 256

 a -  1928
*b -  1928

int  b - 15
int &b - 676
int &a - 256

```
> 0 votes

---
Tags: arduino-uno, c++, library, class
---


title: Arduino Uno as keyboard

text:
# Question
Title: Arduino Uno as keyboard
I am trying to make Arduino Uno to act as a keyboard. I have successfully flashed the USB-HID firmware in it using this link also and programmed it like this.

```
uint8_t buf[8] = {
 0
};

int inpin1 = 7;
int inpin2 = 8;
int val1 = 0;
int val2 = 0;

void setup() {
  Serial.begin(9600);
  delay(200);
  pinMode(inpin1, INPUT);
  pinMode(inpin2, INPUT);
}

void loop() {
  val1 = digitalRead(inpin1);
  if(val1 != HIGH) {
   buf[2] = 80; // Left Arrow
   Serial.write(buf, 8);
   releaseKey();
  }
  val2 = digitalRead(inpin2);
  if(val2 != HIGH) {
    buf[2] = 79; // Right Arrow
    Serial.write(buf, 8);
    releaseKey();
  }
}

void releaseKey() {
  buf[0] = 0;
  buf[2] = 0;
  Serial.write(buf, 8);
}

```

The above code works fine but the problem is that when I tried to play a game, which uses right arrow and left arrow, and to control a car I was using the push button, which I connected to Arduino as left and right arrow keys. But suppose I want to turn a car. I have to press the key and then release the key to move it a very little to the right or left. So, if I want to turn the car either left or right, I have to press and release so many times that it becomes impossible to play the game. Do you anyone know how to resolve this problem?

# Answer
> 1 votes
You should just not call the `releaseKey` function, until the button is released.

```
int oldVal1 = 0;
int oldVal2 = 0;

void loop()
{
    val1 = digitalRead(inpin1);
    if( val1!=oldVal1 )
    {
        oldVal1 = val1;
        if(val1 != HIGH)
        {
            buf[2] = 80; // Left Arrow
            Serial.write(buf, 8);
        }
        else
        {
            releaseKey();
        }
    }

    val2 = digitalRead(inpin2);
    if( val2!=oldVal2 )
    {
        oldVal2 = val2;
        if(val2 != HIGH)
        {
            buf[2] = 79; // Right Arrow
            Serial.write(buf, 8);
        }
        else
        {
            releaseKey();
        }
    }

}

```

---
Tags: arduino-uno, usb, arduino-micro, keyboard, code-review
---


# Question
Title: CS5211AGP wireless RF transmitter (433MHZ) address decoding problem
I am using CS5211AGP wireless RF transmitter to transmit some data and another side receive this data through nRf905 as receiver. But now problem is how can I decode RF transmitter address (because transmitter and receiver address must be same).

if any one working on this module then please suggest me how can I decode address.

Please show below image where you can see the connection of address and zone.

Now please say about what address should I set at receiver side for communication.

Thanks in advance.

Regards, rajneesh

# Answer
> 1 votes
I am looking at mine, wich address is 01212012, acording to a sticker in a side. I can see in mine jumpers as follows (starting from A0): -HLHL-HL-H-H where - means no jumper. Based on my sticker I can see that 0 is equivalent to NO-JUMPER, 1 is H and 2 is L. By watching yours I can tell that your code is 21111002. The other 4 jumpers is what I don-t understand, but if I change any of them, my alarm no longer detects any change. Hope this helps... Regards.

---
Tags: wireless
---


# Question
Title: Arduino Nano 3.0 dimensions without the pins
I think the title of this question is quite clear. I am looking for the exact dimensions of the Arduino Nano 3.0, with the electronic components and the USB mini port on the IC (the Atmega328 one), without the external pins.

# Answer
Mini-USB-B is around 4mm tall.

Most PCBs are around 1.6mm.

The FT232RL on the bottom is 2mm (max) according to the datasheet. (voltage regulator is 1.8mm). (I'm sure about this tantalum capacitors)

So that's something around 7.6mm total height
> 1 votes

# Answer
I have a nano so let me get a ruler, ok. The usb port takes up most of the room so 4mms, the board itself is 1mm and a tiny chip adds 2mms as well. So 7mms! Hope this helped!
> 1 votes

---
Tags: arduino-nano
---


# Question
Title: Arduino Starter Kit - firmly wiring longer parts
I am getting started with project 01 on the Arduino starter kit. I'm facing an issue when wiring parts with long ends e.g. led & resistor. To make the simple circuit with led, resistor & switch work, I have to hold down the resistor & led, and then press the button. The parts don't connect well to the wires underneath the breadboard.

I want ask if someone could suggest how to better deal with such parts. On searching, I found people cut their parts short, but are there other approaches ? Thanks.

# Answer
> 1 votes
Cutting them short is proven solution, but there is sometimes still problem with legs too thin to fit good.

Other, even more reliable, is to solder them to pinheader https://commons.wikimedia.org/wiki/File:16\_Pin\_Header.jpg (just break away 2 or 3 pins depending on how many legs you need). Works even for SMD resistors and diodes https://divnoblog.files.wordpress.com/2015/10/005-odpor\_1.jpg

Also you can use small piece of universal stripboard https://en.wikipedia.org/wiki/Stripboard / perfboard https://en.wikipedia.org/wiki/Perfboard, to solder anything on that and solder the pinheader under it. Works perfectly for switches etc.

(of course you can buy "modules" from any suplier, where is the part, maybe accompanied by one or two resistors or such, but the price is higher, than is you do it manually at home and there is not such wide range, as is in normal analog/digital parts, which you can solder to fit your needs)

The problem with https://en.wikipedia.org/wiki/Breadboard is, that usually the holes are good just for the pinheader-sized legs (a lot of IC have the right dimensions too), while nearly any pasive/simple parts are much thinner and do not fit reliably. But for some fast playing with and non-critical application it is usually usable enough.

---
Tags: led, resistor
---


title: Arduino Nano with Mac OS Yosemite 10.10

text:
# Question
Title: Arduino Nano with Mac OS Yosemite 10.10
I have an Arduino Nano and I’m trying to use it with Mac OS Yosemite (10.10). However, I’m having issues with the data transfer between the computer and the device. The Arduino is powered (LED is illuminated), however, I can’t upload anything to it. The serial port is not recognised and after installing a multitude of drivers, nothing seems to work.

Is there a specific driver or process I need to follow to enable data transfer?

# Answer
> 3 votes
Setting kext-dev-mode=1 allows unsigned kernel extensions to load, which is not recommended, as it lowers OS X security.

Instead, try the signed 64-bit kernel extension from FTDI here: http://www.ftdichip.com/Drivers/VCP.htm , version 2.3, which does require changing OS security permissions.

# Answer
> 1 votes
From this blogpost you can download **signed** macOS driver for CH340. Works fine on Sierra 10.12!

---
Tags: arduino-nano, osx
---


# Question
Title: avrdude: stk500_recv(): programmer is not responding after serial
I have searched but have not found any solution to my problem so I am asking it here. I make a program in python that makes serial communication with the Arduino. I started to upload my Arduino code but I forgot that my python program was open in the terminal (I use Ubuntu). So, I think the Arduino code and python output went to the same port which the Arduino is on. After that I couldn't upload any code into the Arduino.

Every time it prints the following error:

> avrdude: stk500\_recv(): programmer is not responding avrdude: stk500\_getsync() attempt 1 of 10: not in sync: resp=0x00

and then makes more 9 attempts. Any help?

# Answer
Likely all you really need to do is exit/kill every process trying to use the Arduino, un-plug it from the USB port, and plug it back in.

This is in part because Linux doesn't really block multiple programs from trying to use the serial device at the same time, unless they take particularly efforts to claim it exclusively, but the attempted sharing may result in serial traffic that doesn't make any sense.

Another issue can be that if a still-running program was using a device that vanished, when that device is reconnected it will not be assigned to the in-use port number, but to a free one.
> 1 votes

---
Tags: serial, avrdude
---


title: Understanding SevSeg

text:
# Question
Title: Understanding SevSeg
I need to write a library for a display I created with eight segments. So, I decided to try to use SevSeg (https://github.com/DeanIsMe/SevSeg) as a starting off point. It can't be *that* different, right?

Well, I think I have hit a roadblock that indicates I must basically do everything from scratch. Here is how the information on what segments correspond to letters are stored in SevSeg:

```
 // The codes below indicate which segments must be
//illuminated to display each number.

static const byte digitCodeMap[] = {
  //     GFEDCBA  Segments      7-segment map:
  B00111111, // 0   "0"          AAA
  B00000110, // 1   "1"         F   B
  B01011011, // 2   "2"         F   B
  B01001111, // 3   "3"          GGG
  B01100110, // 4   "4"         E   C
  B01101101, // 5   "5"         E   C
  B01111101, // 6   "6"          DDD
  B00000111, // 7   "7"
  B01111111, // 8   "8"
  B01101111, // 9   "9"
  B01110111, // 65  'A'
  B01111100, // 66  'b'
  B00111001, // 67  'C'
  B01011110, // 68  'd'
  B01111001, // 69  'E'
  B01110001, // 70  'F'
  B00111101, // 71  'G'
  B01110110, // 72  'H'
  B00000110, // 73  'I'
  B00001110, // 74  'J'
  B01110110, // 75  'K'  Same as 'H'
  B00111000, // 76  'L'
  B00000000, // 77  'M'  NO DISPLAY
  B01010100, // 78  'n'
  B00111111, // 79  'O'
  B01110011, // 80  'P'
  B01100111, // 81  'q'
  B01010000, // 82  'r'
  B01101101, // 83  'S'
  B01111000, // 84  't'
  B00111110, // 85  'U'
  B00111110, // 86  'V'  Same as 'U'
  B00000000, // 87  'W'  NO DISPLAY
  B01110110, // 88  'X'  Same as 'H'
  B01101110, // 89  'y'
  B01011011, // 90  'Z'  Same as '2'
  B00000000, // 32  ' '  BLANK
  B01000000, // 45  '-'  DASH
};

```

As you can see this is a one dimensional array of 8-byte binaries that encode the segment. I don't understand the purpose of the B0 at the beginning of each byte. Could I use the 0 column to encode my eighth segment?

Am I right to assume this will change everything about the code and maybe I should start from scratch with a 2-D array?

This is roughly what I want:

```
//  ABCDEFGH  Segments      8-segment map:
  11000011, // 0   "0"       A BBBBB H
  10000000, // 1   "1"       A C   D H
  01011010, // 2   "2"       A C   D H
  11101010, // 3   "3"       A  C D  H
  00110101, // 4   "4"       A  E F  H
  01011010, // 5   "5"       A E   F H
  11101110, // 6   "6"       A E   F H
  01011000, // 7   "7"       A GGGGG H
  01111110, // 8   "8"
  01100101, // 9   "9"
  11111101, // 10  "A"
  10001110, // 11  "b"
  11000010, // 12  "C"
  00001111, // 13  "d"

```

What data type should I use for the array? Would byte work since I'm not using the B0?

Thanks.

# Answer
> 3 votes
> I don't understand the purpose of the B0 at the beginning of each byte.

That's just Arduino's rather weird way of doing binary constants. For example, in the file binary.h are lines and lines of stuff like this:

```
#define B1011 11
#define B01011 11
#define B001011 11
#define B0001011 11
#define B00001011 11
#define B1100 12
#define B01100 12
#define B001100 12
#define B0001100 12
#define B00001100 12

```

A better way is to use standard C++ constants, eg.

```
0b00001100

```

instead of:

```
B00001100

```

---

> Could I use the 0 column to encode my eighth segment?

Yes, they are just bytes, so you can use all 8 bits.

---
Tags: library, data-type
---


title: LCD 16x2 Blank Display

text:
# Question
Title: LCD 16x2 Blank Display
I am using the following wiring diagram from a tutorial. I need to follow this configuration because later tutorials build on this example. I have looked at other solutions, but they follow a different pattern and I am still learning, so don't have the sophistication to adapt. I've looked at:

Hacktronics StackExchange

The picture shows Freeduino, but I am using an Arduino Uno (does that make a difference?)

Here is the code I am using:

```
#include <LiquidCrystal.h>
int rs = 3;
int enable = 4;
int d4 = 5;
int d5 = 6;
int d6 = 7;
int d7 = 8;

int rows = 2;
int cols = 16;
LiquidCrystal lcd (3, 4, 5, 6, 7, 8);

void setup() {
  // put your setup code here, to run once:
  pinMode (rs, OUTPUT);
  pinMode (enable, OUTPUT);
  pinMode (d4, OUTPUT);
  pinMode (d5, OUTPUT);
  pinMode (d6, OUTPUT);
  pinMode (d7, OUTPUT);
  lcd.begin(cols, rows);
  lcd.clear();
}

void loop() {
  // put your main code here, to run repeatedly:
  lcd.setCursor(0,0);
  lcd.print("Hello World");
  delay(1000);
  lcd.setCursor(0,1);
  lcd.print("Goodbye World");
  delay(1000);
}

```

Unfortunately, I am getting a blank screen (it is lit up, but blank). So questions:

1. Is the diagram correct?
2. Is the code the problem?
3. What else should I look for?

# Answer
1) Diagram seems to be fine. However we don't see pin numbering on LCD. Sometimes pins are like: `15 16 1 2 3 4 ... 14` (at least pin 1 is usualy marked).

2) Library should take care of inputs or outputs. So you can remove pinModes for them. Also change variables to constant variables and use them for lcd initialization: `LiquidCrystal lcd(rs, enable, d4, d5, d6, d7);`

3) Potentiometer in diagram is contrast setting. You have to preset correct value for it. Start with everything is black and find value where this black is almost invisible. If you've something displayed on LCD, it would be even easier to find right position as text just shows up.

Edit: I've just tested it and it's working fine. With the same wiring and contrast pot adjusted to the right position
> 1 votes

# Answer
Check the voltage. your LCD should get 5v to work properly.

if you are powering it through your computer USB, Arduino could be outputting less than 5v.

PS: it happened to me yesterday.
> 1 votes

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


# Question
Title: Can't power mg2639 cellular shield with battery
I have a SparkFun MG2639 cellular shield attached to an Arduino Uno R3. I have had both the cell modem and the GPS unit working when the shield is powered from the Uno. I followed the instructions on SparkFun's site to switch the shield to be powered by battery (cut SJ2, short SJ3) and connected a fully charged Li-ion battery. I measure over 4.1 volts at the battery connection pads on the shield but the power LED isn't on and the shield isn't responding. It looks as though it's not getting any power. I also powered it from my bench supply with 5V and it shows no current draw.

Did I miss something in the conversion instructions?

# Answer
> 0 votes
Turns out the soldered short of SJ3 was not complete. After resoldering the shield powers up as expected.

---
Tags: shields, battery
---


# Question
Title: why leonardo bootloader is bigger than UNO?
Apparently leonardo and UNO are very similar boards.

However, despite that both have the same flash memory size, Leonardo bootloader is considerably bigger than UNO bootloader (4KB vs 0.5KB).

what would be the reason? it is there any way to use smaller bootloader in leonardo?

Uno specs: https://www.arduino.cc/en/Main/ArduinoBoardUno

Leonardo specs: https://www.arduino.cc/en/Main/ArduinoBoardLeonardo

Thanks!

# Answer
> Apparently leonardo and UNO are very similar boards.

No, they are very, very different.

The Uno uses an external USB-UART bridge. This means that the bootloader code only has to read from the UART in order to program the device.

The Leonardo has USB support built into the MCU. This means that the bootloader must contain an entire USB Device stack in order to process the USB packets and then pass the payload to the programming routines.
> 3 votes

---
Tags: arduino-uno, arduino-leonardo, bootloader
---


# Question
Title: Unspecified running error while programing WeMos D1 in wireless mode
I've tried to program `WeMos D1` directly by wireless connection. I've test my `D1` so it had no problem. after setting `SSID` and `Password` I've programed it for wireless using. It ran well. as I want to programing thought wireless there was an Unspecified error for running `python.exe` !

```
java.io.IOException: Cannot run program "python.exe": CreateProcess error=2, The system cannot find the file specified
    at java.lang.ProcessBuilder.start(ProcessBuilder.java:1048)
    at processing.app.helpers.ProcessUtils.exec(ProcessUtils.java:26)
    at cc.arduino.packages.Uploader.executeUploadCommand(Uploader.java:129)
    at cc.arduino.packages.uploaders.GenericNetworkUploader.uploadUsingPreferences(GenericNetworkUploader.java:99)
    at cc.arduino.UploaderUtils.upload(UploaderUtils.java:78)
    at processing.app.SketchController.upload(SketchController.java:709)
    at processing.app.SketchController.exportApplet(SketchController.java:682)
    at processing.app.Editor$DefaultExportHandler.run(Editor.java:2190)
    at java.lang.Thread.run(Thread.java:745)
Caused by: java.io.IOException: CreateProcess error=2, The system cannot find the file specified
    at java.lang.ProcessImpl.create(Native Method)
    at java.lang.ProcessImpl.<init>(ProcessImpl.java:386)
    at java.lang.ProcessImpl.start(ProcessImpl.java:137)
    at java.lang.ProcessBuilder.start(ProcessBuilder.java:1029)
    ... 8 more
An error occurred while uploading the sketch

```

I've python on my PC and it works. to clear my problem I've attached the following `gif`

any help would be appreciated.

# Answer
> 0 votes
You might have Python installed, but can you run it?

Open a command window on you PC. (Windows button R then CMD) Then in that type python.

If python starts up then it should be working, but I suspect you will get an error saying:

`'python' is not recognized as an internal or external command, operable program or batch file.`

To fix this you need to edit you path and restart the IDE. (How you edit you path depends on your version of Windows so you would be best searching for `edit environment path` and your version of windows and that should come back with an answer quickly.

Of course if its Linux/mac then it could still be the same issue.

---
Tags: arduino-ide, wifi
---


# Question
Title: Find the time between HIGH state & LOW state of push button(switch)
I want to find the timing between HIGH state and LOW state of push button. For that, I made a program. You can see my program below. In my program, I made logic like that when switch is pressed then one variable "currentMillis" store the value of millis() and it store value until button pressed. But whenever I pressed button again then it also add previous value. For example, if button pressed for first time then suppose we got 200ms, now suppose if button pressed second time then we got 500ms and if button pressed third time then we got 1000ms. That mean every time value added. No doubt I made a logic which seem to be perfect but I can't figure out what is problem. Please give me some suggestions.

```
const int  buttonPin = 2;

unsigned long currentMillis = 0;
unsigned long previousMillis = 0;
unsigned long finalMillis = 0;

int buttonPushCounter = 0;

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

   pinMode(buttonPin, INPUT);
   digitalWrite(buttonPin, HIGH);
}

void loop()
{
  if (digitalRead(buttonPin) == LOW)
  {
    buttonPushCounter++;
    Serial.println("on");
    Serial.print("number of button pushes:  ");
    Serial.println(buttonPushCounter);

    while(digitalRead(buttonPin) == LOW)
    {
      currentMillis = millis();
    }

    finalMillis = currentMillis - previousMillis;
    Serial.println(finalMillis);

    previousMillis = finalMillis;
    //finalMillis = 0;
  }
}

```

Here, it is my serial monitor output.

```
on
number of button pushes:  1
0
on
number of button pushes:  2
775
on
number of button pushes:  3
873
on
number of button pushes:  4
1425
on
number of button pushes:  5
1496
on
number of button pushes:  6
2073
on
number of button pushes:  7
2010
on
number of button pushes:  8
2643
on
number of button pushes:  9
3052
on
number of button pushes:  10
3195
on
number of button pushes:  11
3396
on
number of button pushes:  12
3575
on
number of button pushes:  13
3737

```

# Answer
> 0 votes
While the previously given answers should work for you, they share a couple of problems with your original code:

* they do not debounce the button
* they block while waiting for the button to be released

Blocking the program is not a big deal if you do not have to do anything else. However, chances are you are showing us only a fraction of what will ultimately be a larger program. In this case, doing a busy wait (like `while (digitalRead(buttonPin) == LOW) ;`) will block the *whole program*, not only this particular feature. Then, I suggest you get immediately in the habit of writing non blocking code:

* when the button is pressed, record that fact and the current time
* when the button is released, report to the user

The important notion is that you never *wait* for anything. Instead, you check whether something has to be done *right now* and, if so, you do it.

Here is a non-blocking version of your program, with some debounce added:

```
const uint8_t button_pin = 2;

void setup()
{
    pinMode(button_pin, INPUT_PULLUP);
    Serial.begin(9600);
}

void loop()
{
    static int last_button_state = HIGH;
    static unsigned int push_count;
    static unsigned long last_press_time;
    int button_state = digitalRead(button_pin);
    unsigned long now = millis();

    // Record when the button is pressed.
    if (last_button_state == HIGH && button_state == LOW) {
        push_count++;
        last_press_time = now;
    }

    // Report when the button is released.
    if (last_button_state == LOW && button_state == HIGH) {
        unsigned long push_duration = now - last_press_time;
        if (push_duration < 10) {  // discard bounce
            push_count--;
        }
        else {
            Serial.print(F("pushes: "));
            Serial.print(push_count);
            Serial.print(F(", duration: "));
            Serial.print(push_duration);
            Serial.println(F(" ms"));
        }
    }

    last_button_state = button_state;
}

```

# Answer
> 1 votes
First of all, frarugi87 is right. Second, why not use this:

```
finalMillis = millis() - previousMillis;
previousMillis = millis();

```

Instead of what you wrote.

```
if (digitalRead(buttonPin) == LOW) {
    buttonPushCounter++;
    Serial.println("on");
    Serial.print("number of button pushes:  ");
    Serial.println(buttonPushCounter);
    finalMillis = millis() - previousMillis;
    previousMillis = millis();
    Serial.println(finalMillis);
    while(digitalRead(buttonPin) == LOW){}
  }

```

It works great.

Hope it helps.

Yoav

# Answer
> 0 votes
You wrote

```
previousMillis = finalMillis;

```

This means that you store the duration of the pulse, not the last time it was pressed.

Change it with

```
previousMillis = currentMillis;

```

and you will be able to detect the high + low time.

By the way, constantly reading the millis function is useless. You can change your code to

```
while(digitalRead(buttonPin) == LOW);
currentMillis = millis();

```

which reads only once.

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


title: DHT sensors with RGB LED

text:
# Question
Title: DHT sensors with RGB LED
I have a DHT11 that outputs temperature and humidity values to my serial monitor. I'm trying to serial the **COLOUR** of the light based on the temperature conditions. So far I only get `1`'s and `0`'s. How can I change these integer values to output string say `RED`, `GREEN` or `BLUE`?

**Code**

```
#include <dht.h>

dht DHT;
#define DHT11_PIN A5
int redPin = 10; // Red LED,  connected to digital pin 10
int grnPin = 9; // Green LED, connected to digital pin 9
int bluPin = 8;  // Blue LED, connected to digital pin 8

void setup() {
  Serial.begin(9600);
  // Sets the pins as output for RGB LED
  pinMode(redPin, OUTPUT);
  pinMode(grnPin, OUTPUT);
  pinMode(bluPin, OUTPUT);
}

void loop() {
  int chk = DHT.read11(DHT11_PIN);
  int t = DHT.temperature;
  int h = DHT.humidity;
  Serial.print("Temperature = ");
  Serial.print(t);
  Serial.print( "," );
  Serial.print("Humidity = ");
  Serial.print(h);
  Serial.print("\n");
  delay(60000);
  if((DHT.temperature < 26) && (DHT.temperature >= 23.2)) {
    // Writing the LED colour pins HIGH or LOW to set colours
    digitalWrite(redPin, HIGH); // yellow
    digitalWrite(grnPin, HIGH);
    delay(100);
    digitalWrite(bluPin, LOW);
  }
  if((DHT.temperature < 23) && (DHT.temperature > 20.2)) {
    digitalWrite(grnPin, HIGH); // green
    delay(100);
    digitalWrite(redPin, LOW);
    digitalWrite(bluPin, LOW);
  }
  if((DHT.temperature < 20) && (DHT.temperature > 17.2)) {
    digitalWrite(grnPin, HIGH); // aqua
    digitalWrite(bluPin, HIGH);
    delay(100);
    digitalWrite(redPin, LOW);
  }
  if(DHT.temperature <= 17) {
    digitalWrite(bluPin, HIGH); // blue
    delay(100);
    digitalWrite(grnPin, LOW);
    digitalWrite(redPin, LOW);
  }
  delay(1000);
  // Sensor shouldn't be read too frequently so delay of 1s
}

```

I will be grateful if I can get some help. Thanks!

# Answer
> So far I only get 1's and 0's

Before moving into the LED parts, you have to make sure that your system can correctly read the DHT sensor. There are debugging example from arduino-info.wikispaces.com

> How can I change these integer values to output string say RED, GREEN or BLUE?

You can do it by simple `if-else` statement. This would be better than your original code, because there are multiple `if`'s without any `else` which is (although not so significant) less optimal.

So, if put together, you can try:

```
void loop()
{
  int t,h,chk = DHT.read11(DHT11_PIN);

  switch (chk)
  {
    case DHTLIB_OK:
                Serial.print("OK,\t");
                break;
    case DHTLIB_ERROR_CHECKSUM:
                Serial.print("Checksum error,\t");
                break;
    case DHTLIB_ERROR_TIMEOUT:
                Serial.print("Time out error,\t");
                break;
    case DHTLIB_ERROR_CONNECT:
        Serial.print("Connect error,\t");
        break;
    case DHTLIB_ERROR_ACK_L:
        Serial.print("Ack Low error,\t");
        break;
    case DHTLIB_ERROR_ACK_H:
        Serial.print("Ack High error,\t");
        break;
    default:
                Serial.print("Unknown error,\t");
                break;
  }
  //moving on into next parts only if you get "OK" from serial reply, which means you successfully read the DHT11
  t = DHT.temperature;
  h = DHT.humidity;
  Serial.print(DHT.humidity, 1);
  Serial.print(",\t");
  Serial.println(DHT.temperature, 1);

  //----end of sensor reading and debugging

  if (t<=17)
  { //blue
   digitalWrite(bluPin, HIGH);
   digitalWrite(grnPin, LOW);
   digitalWrite(redPin, LOW);
   delay(100);
  } else
      if (t<20)
      {
       digitalWrite(grnPin, HIGH);  // aqua
       digitalWrite(bluPin, HIGH);
       digitalWrite(redPin, LOW);
       delay(100);
      } else
      if (t<23)
      {
        //....
      }
      //....
      //and goes on

 delay(1000);
}

```

And yes, as @Matt suggest, it would be better if you use PWM to control the RGB led which will give you (mathematically) 255\*255\*255 colour possibilities instead of 8 combinations from `digitalWrite()`. For example:

```
//....
//....
  if (t<20)
  { //aqua
   new_t = map(t,DHT11_min_temperature_reading,DHT11_max_temperature_reading,0,255);
   //you can do self research about DHT11 maximum and minimum temperature reading
   //parameters 0 and 255 is the minimum value of PWM(0) and the maximum value(255)
   AnalogWrite(bluPWMPin, new_t);
   AnalogWrite(grnPWMPin, 255-new_t);
   AnalogWrite(redPWMPin, 0);
   delay(100);
  }
//....
//....

```

Hope it helps :D
> 2 votes

# Answer
You need to use `analogWrite()`. You use this with a digital pin and it does Pulse Width Modulation (PWM) which will give you are larger range of colours. Have a look at the Reference page for the function.

You might even be able to use the `map` function (something like that) to 'map' the temperature to the colour values without all the if statements.
> 0 votes

---
Tags: temperature-sensor, rgb-led
---