title: 3 sensors and wemos d1 r1 and web

text:
# Question
Title: 3 sensors and wemos d1 r1 and web
I need to build an app that will display on browser data from 3 sensors. My 3 sensors are: Humidity and temperature (DHT22), vibration sensor and distance sensor (HC-SR04).

I want to connect these 3 sensors to my WeMos D1 R1 and to send the data to be displayed on a webpage. Until now, I can locally (from Serial monitor of Arduino IDE) read the sensors one by one - I mean, I upload the code for each one... I don't know how to combine the 3 codes to work.

So my main question is how to combine these 3 codes into one and access the data from a webpage?

My codes are : vibration (I want to get rid of the LED, just to display the vibration value)

```
int LED_Pin = D13;
int vibr_Pin = D2;

void setup(){
  pinMode(LED_Pin, OUTPUT);
  pinMode(vibr_Pin, INPUT); //set vibr_Pin input for measurement
  Serial.begin(9600); //init serial 9600
}

void loop(){
  long measurement =TP_init();
  delay(50);
  Serial.println(measurement);
  if (measurement > 4000){
    digitalWrite(LED_Pin, HIGH);
  } else {
    digitalWrite(LED_Pin, LOW);
  }
}

long TP_init(){
  delay(10);
  long measurement=pulseIn (vibr_Pin, HIGH);  //wait for the pin to get HIGH and returns measurement
  return measurement;
}

```

DHT22 code:

```
#include <SimpleDHT.h>

// for DHT22,
//      VCC: 5V or 3V
//      GND: GND
//      DATA: 2
int pinDHT22 = D8;
SimpleDHT22 dht22;

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

void loop() {
  // start working...
  Serial.println("=================================");
  Serial.println("Sample DHT22...");

  // read without samples.
  // @remark We use read2 to get a float data, such as 10.1*C
  //    if user doesn't care about the accurate data, use read to get a byte data, such as 10*C.
  float temperature = 0;
  float humidity = 0;
  int err = SimpleDHTErrSuccess;
  if ((err = dht22.read2(pinDHT22, &temperature, &humidity, NULL)) != SimpleDHTErrSuccess) {
    Serial.print("Read DHT22 failed, err="); Serial.println(err);delay(2000);
    return;
  }

  Serial.print("Sample OK: ");
  Serial.print((float)temperature); Serial.print(" *C, ");
  Serial.print((float)humidity); Serial.println(" RH%");

  // DHT22 sampling rate is 0.5HZ.
  delay(2500);
}

```

HC-SR04 CODE :

```
// defines pins numbers
const int trigPin = D5;
const int echoPin = D6;
// defines variables
long duration;
int distance_cm;
int distance_in;
void setup() {
  pinMode(trigPin, OUTPUT); // Sets the trigPin as an Output
  pinMode(echoPin, INPUT); // Sets the echoPin as an Input
  Serial.begin(9600); // Starts the serial communication
}

void loop() {
  // Clears the trigPin
  digitalWrite(trigPin, LOW);
  delayMicroseconds(500);
  // Sets the trigPin on HIGH state for 10 micro seconds
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(500);
  digitalWrite(trigPin, LOW);
  /* Reads the echoPin, returns the sound wave
     travel time in microseconds */
  duration = pulseIn(echoPin, HIGH);
  // Calculating the distance
  distance_cm = duration / 58;
  distance_in = duration / 148;
  Serial.print("Distance: ");
  Serial.print(distance_cm);
  Serial.println(" centimeters");
}

```

---

I managed to merge the 3 codes into 1. I still need to adapt it to send the information on a webpage. Up to now, the code for 3 sensors is:

```
#include <SimpleDHT.h>

// for DHT22,
//      VCC: 5V or 3V
//      GND: GND
//      DATA: 2
const int trigPin = D5;
const int echoPin = D6;
long duration;
int distance_cm;
int distance_in;
int vibr_Pin = D8;
int pinDHT22 = D2;
SimpleDHT22 dht22;

void setup() {
  Serial.begin(9600);
  pinMode(vibr_Pin, INPUT);
  pinMode(trigPin, OUTPUT); // Sets the trigPin as an Output
  pinMode(echoPin, INPUT); // Sets the echoPin as an Input
}

void loop() {
  // start working...
  Serial.println("=================================");
  Serial.println("TEMPERATURE & HUMIDITY");

  // read without samples.
  // @remark We use read2 to get a float data, such as 10.1*C
  //    if user doesn't care about the accurate data, use read to get a byte data, such as 10*C.
  float temperature = 0;
  float humidity = 0;
  int err = SimpleDHTErrSuccess;
  if ((err = dht22.read2(pinDHT22, &temperature, &humidity, NULL)) != SimpleDHTErrSuccess) {
    Serial.print("Read DHT22 failed, err=");
    Serial.println(err);delay(2000);
    return;
  }

  Serial.print("Temperature & Humidity: ");
  Serial.print((float)temperature); Serial.print(" *C, ");
  Serial.print((float)humidity); Serial.println(" RH%");

  // DHT22 sampling rate is 0.5HZ.
  delay(2500);
  Serial.println("=================================");
  Serial.println("VIBRATION");
  long measurement =TP_init();
  delay(50);
  Serial.print("measurement = ");
  Serial.println(measurement);
  Serial.println("=================================");
  Serial.println("DISTANCE");
  // Clears the trigPin
  digitalWrite(trigPin, LOW);
  delayMicroseconds(500);
  // Sets the trigPin on HIGH state for 10 micro seconds
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(500);
  digitalWrite(trigPin, LOW);
  /* Reads the echoPin, returns the sound wave
     travel time in microseconds */
  duration = pulseIn(echoPin, HIGH);
  // Calculating the distance
  distance_cm = duration / 58;
  distance_in = duration / 148;
  Serial.print("Distance: ");
  Serial.print(distance_cm);
  Serial.println(" centimeters");
}

long TP_init(){
  delay(10);
  long measurement=pulseIn (vibr_Pin, HIGH);  //wait for the pin to get HIGH and returns measurement
  return measurement;
}

```

So, in the serial monitor of Arduino IDE, we will see the values displayed for our 3 sensors. I would really appreciate if somebody can help me to integrate this code to an IoT platform.

# Answer
> 0 votes
I would suggest using thinger.io. It has a library that is insanely simple to use.

This is code for a greenhouse monitor that I wrote using their library. It exposes the temperature and humidity from a DHT22, the time the unit has been running, and when it was last programmed. And all with OTA support as well.

```
#include <ESP8266WiFi.h>
#include <dht.h>
#include <ThingerESP8266.h>
#include <ArduinoOTA.h>
#include <Average.h>

dht dht22;

Average<float> temperature(10);
Average<float> humidity(10);

ThingerESP8266 thing("myaccount", "thisunit", "somekey");

void getSample() {
    static uint32_t ts = 0;
    if (millis() - ts < 10000) {
        return;
    }
    ts = millis();

    dht22.read22(D6);
    int samples = 0;
    while (
        (dht22.temperature < -100) ||
        (dht22.temperature > 200) ||
        (dht22.humidity < -100) ||
        (dht22.humidity > 200))
    {
        delay(10);
        dht22.read22(D6);
        samples++;
        if (samples > 10) {
            return;
        }
    }
    temperature.push(dht22.temperature);
    humidity.push(dht22.humidity);
}

void setup() {
    WiFi.hostname("Greenhouse");
    thing.add_wifi("MyWiFiSSID", "MyWiFiPSK");

    thing["temperature"] >> [](pson& out) {
        getSample();
        out = temperature.mean();
    };
    thing["humidity"] >> [](pson& out) {
        getSample();
        out = humidity.mean();
    };
    thing["uptime"] >> [](pson& out) {
        out = millis() / 1000.0;
    };
    thing["compiled"] >> [](pson& out) {
        out = __DATE__ " " __TIME__;
    };

    ArduinoOTA.setHostname("Greenhouse");
    ArduinoOTA.setPassword("MyOTAPassword");
    ArduinoOTA.begin();
}

void loop() {
    thing.handle();
    ArduinoOTA.handle();
}

```

It's a little more complex that you may need, since I do averaging and filtering of the sampled data to clean it up a little. All the magic of when to take samples and how to deal with the data is done on the thinger.io website. But the code, as you can see, is insanely simple.

---
Tags: esp8266, sensors
---


# Question
Title: Thin battery to power arduino micro with nRF8001?
I'm building a project which needs to fit in a wallet. I have an Arduino Micro hooked up to a nRF8001. I attempted three button cells wired in series, which provided a solid 7.5 volts, but only `20mA`.

A 9V battery successfully powers it, but that's too big to fit in a wallet. I was considering using an `A27` battery, but even that's thicker than I would like.

Is there any battery I can use that's a reasonable thickness, and won't explode on me? Thanks!...

# Answer
I think you should use a 3.7v mini battery that are around 200-300mAh capacity. These batteries are variable on online stores and are very thin. Now as you require 5v there are mini DC-DC boost converters available what you can use with them.
> 1 votes

# Answer
Either of these two are pretty good depending on how long you want it to live and how much current your device draws:

https://www.sparkfun.com/products/731

https://www.sparkfun.com/products/10718

You can still probably power the micro from these even though they're 3.7v. When charged they'll be closer to 4.2v and it will still probably run down to 3.5v anyway.

Or you could just put two in series to increase the voltage
> 0 votes

# Answer
I run my projects directly from a 3v CR2032 lithium cell. Bypassing any voltage regulator. You could use something like a I'd get a 3.3v arduino, something like a Arduino Pro Mini. (You can also use your micro, but you'd have to "underclock" them, as the ATMega32u4 isn't necessarily capable of running 16Mhz at 3V.)

By bypassing the voltage regulator, you don't get any of the losses.
> 0 votes

# Answer
You can use rechargeable `Ni-Cd` batteries of 3 AAA size cells with wired connection.There are also small 4V rechargeable `lead-acid` batteries,which are mostly used in led torch.
> 0 votes

---
Tags: battery
---


# Question
Title: How to get separate BPM readings from two pulse sensors using one Arduino
Here is the code I used to get BPM from pulse sensor.

```
#define USE_ARDUINO_INTERRUPTS true    // Set-up low-level interrupts for most
acurate BPM math.
#include <PulseSensorPlayground.h>     // Includes the PulseSensorPlayground
Library.

```

// Variables

```
const int PULSE_SENSOR_COUNT = 2;
const int PulseWire = A0;
const int PulseWire2 = A1;
const int LED13 = 13;
int Threshold = 550;

void setup() {
  Serial.begin(9600);
  pulseSensor.analogInput(PulseWire, 0);
  pulseSensor.analogInput(PulseWire2, 1);
  pulseSensor.blinkOnPulse(LED13);
  pulseSensor.setThreshold(Threshold);
  if (pulseSensor.begin()) {
  }

  void loop() {
    int myBPM = pulseSensor.getBeatsPerMinute();  // Calls function on our pulseSensor object that returns BPM as an "int".

    if (pulseSensor.sawStartOfBeat()) {            // Constantly test to see if "a beat happened".
      //Serial.println("♥  A HeartBeat Happened ! "); // If test is "true", print a message "a heartbeat happened".
      Serial.print("BPM1: ");                        // Print phrase "BPM: "
      Serial.println(myBPM);                        // Print the value inside of myBPM.
    }
    delay(20);                    // considered best practice in a simple sketch.
  }

```

I wish to separate display the BPM that get from A0 wire and A1 wire. Serial could print something like this: `BPM1(A0):75, BPM2(A1):80`. I don't know how to do that, can anyone help me with it?

# Answer
Change "#define USE\_ARDUINO\_INTERRUPTS **true**" to "#define USE\_ARDUINO\_INTERRUPTS **false**".

> If, instead, your Sketch does not use interrupts to read PulseSensor data, your Sketch must instead contain the following two lines, in order:
>
> #define USE\_ARDUINO\_INTERRUPTS false
>
> #include \<PulseSensorPlayground.h\>

Source: https://github.com/WorldFamousElectronics/PulseSensorPlayground/blob/master/src/PulseSensorPlayground.h
> 1 votes

---
Tags: arduino-uno
---


title: Relay with mechanical fallback

text:
# Question
Title: Relay with mechanical fallback
In my circuit I have a relay that will turn on some light bulbs this is my circuit:

The switch over the 5V is in fact my Arduino. A HIGH will turn on the relay and a LOW will turn it off.

This is working fine, but because of security measures I need to add a mechanical switch to be able to turn on and off whenever needed. This is the circuit I'm using for this configuration:

This circuit also works fine, the lamp is turned on and off by changing either switches but the Arduino loses track of the status of the lamp. The only thing it knows is if the relay is on or off.

Is there a simple way to tell when the lamp is on?

# Answer
If you add an optical sensor appropriate for the lamp (UV, IR, visible light?) and add a test line to your code, the Arduino would "know" if the light is on. Your second circuit could remain as presented, while the sensor would provide a status of the light.

If the light failed for an unknown reason, the code for your Arduino would not know the difference between that and a manually opened override switch.
> 1 votes

# Answer
I got the terminology wrong in my comment. My suggestion is not to use what is commonly called a “three way switch”, but instead a single pole triple throw switch. This is not available in the schematic editor, so I had to improvise. Imagine that the switch labeled “SP3T” below has three contacts on its left side:

simulate this circuit – Schematic created using CircuitLab

* The top contact connects to nothing: this is the OFF position
* the middle contact connects the controlled circuit with the relay: this is the AUTO position where the Arduino is in charge
* the bottom contact closes the controlled circuit: this is the ON position
> 0 votes

---
Tags: relay, system-design
---


title: Using TTGO TS 1.0 TFT display

text:
# Question
Title: Using TTGO TS 1.0 TFT display
I'm trying to use the TTGO TS 1.0 display with a demo app from a different source. The demo app wants the following to be configured:

```
#define PIN_NUM_MISO 17     // SPI MISO
#define PIN_NUM_MOSI 23     // SPI MOSI
#define PIN_NUM_CLK  5      // SPI CLOCK pin
#define PIN_NUM_CS   26     // Display CS pin
#define PIN_NUM_DC   17     // Display command/data pin
// ** If you want to use them, set them to some valid GPIO number
#define PIN_NUM_RST  0      // GPIO used for RESET control

```

According to the TTGO readme the following wiring is used:

CS:16 DC:17 SDA:23 SCK:5 RST:9

My guess is:

```
PIN_NUM_MISO ?
PIN_NUM_MOSI 23
PIN_NUM_CLK  5
PIN_NUM_CS   16
PIN_NUM_DC   17

```

How to update the demo app to match with this? Reset is optional in the demo and there is 1 additional pin there as well which I can't figure out...

# Answer
If it is, as I think it may be now I have dug into the code a little, simply an SPI interface with no MISO (which is quite common for TFT screens) you just map the pins 1:1 and ignore MISO.

* PIN\_NUM\_MISO =\> Ignore
* PIN\_NUM\_MOSI =\> SDA
* PIN\_NUM\_CLK =\> SCL
* PIN\_NUM\_CS =\> CS
* PIN\_NUM\_DC =\> DC
* PIN\_NUM\_RST =\> RST or Ignore

If the demo code insists on there being a MISO pin you can just assign that to any unused GPIO pin. You don't need to connect it to anything.

The majority of TFT and OLED driver code only ever writes to a screen and never reads from it, so MISO is not needed to actually control the screen.
> 0 votes

---
Tags: pins, tft
---


# Question
Title: Can the TimedAction library be used to call functions of an object
Currently to use TimedAction for a function a program would look like so:

```
#include <TimedAction.h>
void functionX();
TimedAction funtionTimed = TimedAction(1000, functionX);

void setup()
{

}

void loop()
{
functionTimed.check();
}

void functionX()
{
 //run function
}

```

My question is say I have an object class with some functions I would like to use with this TimedAction library. How would this be written?

# Answer
You can't. The TimedAction class doesn't support the function prototype required for your undefined class (it has to match your class, so can't be written).

You have to call a normal function which then calls the class function, or you have to have your class function as `static` so it doesn't include the class in the function prototype.

```
class foo {
    public:
        static void runMe() {
            // blah blah
        }
};

TimedAction funtionTimed = TimedAction(1000, foo::runMe);

```

However, TimedAction is pretty simplistic and you don't really need it. You can just write a function to only run every so often:

```
class foo {
    private:
        uint32_t _runMeTimestamp;
    public:
        void runMe() {
            if (millis() - _runMeTimestamp < 1000) return;
            _runMeTimestamp = millis();
            // blah blah
        }
};

foo myFoo;

void loop() {
    myFoo.runMe();
}

```

Those two lines of code, plus a variable to store the timestamp in, are all you need to make a function run at periodic intervals.
> 1 votes

---
Tags: arduino-uno, object-oriented
---


title: No potential across output of H-bridge

text:
# Question
Title: No potential across output of H-bridge
I’m working on a robot with a club at my school. So far, our team has an H-bridge shield (https://www.freetronics.com.au/products/hbridge-dual-channel-h-bridge-motor-driver-shield#.WwI9omh\_WEc) to drive motors in a toy tank. The H-bridge is powered by 6 AA batteries and the arduino is powered through the H-bridge shield with these batteries also. When everything is connected up and code uploaded to make the motors run forward, nothing happens - the motors don’t run. So far to debug, I’ve used a multimeter to check the voltages being output to the H-bridge from the arduino controller. These are all as expected. I’ve touched the motors to the positive and negative terminals of the battery and they run as expected. Lastly, I’ve substituted the H-bridge shield for a known working one. This did not fix the problem. I disconnected the motors and tested the voltage being output, which measured as +6V for both terminals of the motor relative to the negative terminal of the battery as well as relative to the ground pin. I also disconnected the jumper powering the arduino from the H-bridge shield and instead powered the arduino from my laptop. This did not fix the problem either. This seems completely contradictory. Any ideas on what the problem could be? Thanks so much ❤❤

# Answer
It sounds either (i) like your motor driver is broken or (ii) your code does not operate the H bridge properly. Check which digital outputs pins of the Arduino control the H bridge and make sure that they do not short out the H bridge.

If you want to try another H bridge, this one is suitable for your application: https://www.pololu.com/product/2990 . I have worked with this before and it's very easy to use.
> 1 votes

---
Tags: arduino-uno, hardware
---


# Question
Title: Utilizing two different serial ports simultaneously on a due
I am trying to understand how the serial ports are configured on the due board. Please correct me if i'm wrong, but to my understanding, the due has:

* Four separate serial ports ("serial", and "serial 1-3"), each with SX and TX pin functions
* A USB port paired with serial, simultaneously sending and receiving data from the serial function via USB protocol

I'm currently sending MIDI data over serial1 with the required baud rate of 31250. I want to configure another serial function (assumingly with a different baud rate to match the IDE serial monitor) in order to monitor Serial.print messages simultaneously for debugging.

In setup():

```
Serial1.begin(31250);  //MIDI baud rate
Serial.begin(115200);

```

and then, in a for loop i want to monitor each value i in the array loop1\[i\]):

```
Serial.print(String(loop1[i]) + " ");

```

However, i can't seem to make it work... My question is, is it possible to transmit the MIDI data via serial, in parallel with serial.print data with a separate serial function?

# Answer
You can't use MIDI on `Serial` and use `Serial.print` at the same time. You can though use MIDI on `Serial1` and use `Serial.print` at the same time (or `Serial2` etc).
> 1 votes

---
Tags: serial, arduino-due
---


# Question
Title: Trying to read the current position of a flex sensor and store it as a variable? NANO ATmega328p
I am trying to write a code to read the current position of a flex sensor when a button is pushed and use that data to pulse a piezo. I set it up to read the flex sensor and to alarm when it gets 100 or below, that works! So what I want to do is integrate a button where you push it to set the current state of the flex sensor and then when its moved and is less than the number logged when the button was pressed then it alarms. I used to write in Basic and quick basic and am now (many years later in life) trying to learn C and am struggling. I'm using a NANO ATmega328p - here is my code so far:

```
int flexSensorPin = A0;//analog pin 7= tiny2=A1
const int Piezo = 3; //digital pin 3 = tiny0
const int inPin = 2; // Push Button to set current Bend Status
void setup() {
  pinMode (Piezo, OUTPUT);
  pinMode(inPin, INPUT);    // declare pushbutton as input
  Serial.begin(9600);
}
void loop() {
  int val = 0;
  val = digitalRead(inPin);
  int flexSensorReading = analogRead(flexSensorPin);
  Serial.println(flexSensorReading);
  if (flexSensorReading < 100) {
    Serial.println("Alarm! Set Angle Exceeded");
    digitalWrite(Piezo, HIGH);
    delay(100);
    digitalWrite(Piezo, LOW);

  }
  delay(250);
}

```

# Answer
You will need to add this at the start of your code.

```
int LoggedPosition=100;

```

Change this line

```
if (flexSensorReading < 100) {

```

To this

```
if (flexSensorReading < LoggedPosition) {

```

and add this at just before the delay, at the end of the `loop()` function

```
if(digitalRead(inPin)){
    LoggedPosition=flexSensorReading;
}

```
> 1 votes

---
Tags: programming, arduino-nano, button
---


title: CMDmessenger library

text:
# Question
Title: CMDmessenger library
I am trying to use the CMDmessanger library on my Arduino uno, and am facing an issue.

My issue starts right from the ArduinoController.ino example.

When i send the frequency command

```
3,1;

```

The led starts blinking correctly, once per second.

But when I send a wrong command (basically a command without an argument)

```
3;

```

The led just stops blinking. The state of the led depends on which state it was in when I sent the command.

I realised that, when I send the wrongly formatted command, it takes the frequency as 0.

Is there any method by which I can make sure that the command is received in the right format, before it is executed? Ideally I would love it if there is a method to know how many arguments were received, and I could call the readBoolArg, or other equivalent functions to retrieve the argument data.

I am planning on using this library for quite a few projects, and I don't want to be in a situation where things went wrong because there was not formatting check.

Thanks in advance.

# Answer
The example code uses `cmdMessenger.readFloatArg();` (source) to read an argument.

```
void OnSetLedFrequency()
{
  // Read led state argument, interpret string as boolean
  ledFrequency = cmdMessenger.readFloatArg();
  // Make sure the frequency is not zero (to prevent divide by zero)
  if (ledFrequency < 0.001) { ledFrequency = 0.001; }
  // translate frequency in on and off times in miliseconds
  intervalOn  = (500.0/ledFrequency);
  intervalOff = (1000.0/ledFrequency);
  cmdMessenger.sendCmd(kAcknowledge,ledFrequency);
}

```

That function will set `ArgOk` to `false` if there was no next argument.

```
float CmdMessenger::readFloatArg()
{
    if (next()) {
        dumped = true;
        ArgOk = true;
        //return atof(current);
        return strtod(current, NULL);
    }
    ArgOk = false;
    return 0;
}

```

Thus you should try to use public function

```
bool isArgOk();

/**
 * Returns if the latest argument is well formed.
 */
bool CmdMessenger::isArgOk()
{
    return ArgOk;
}

```

of the `CmdMessenger` object (which will return `ArgOk`) to check if the read argument was okay. You could e.g. modify the code as follows

```
void OnSetLedFrequency()
{
  // Read led state argument, interpret string as boolean
  ledFrequency = cmdMessenger.readFloatArg();

  //Did we just read garbage because the argument wasn't there?
  if(!cmdMessenger.isArgOk()) {
      //Using Serial might be a bad idea because that cmdMessanger operates on the same Serial stream.. but you get the idea.
      Serial.println("You didn't supply a correct argument! Error.");
      return; //goodbye
  }

  // Make sure the frequency is not zero (to prevent divide by zero)
  if (ledFrequency < 0.001) { ledFrequency = 0.001; }
  // translate frequency in on and off times in miliseconds
  intervalOn  = (500.0/ledFrequency);
  intervalOff = (1000.0/ledFrequency);
  cmdMessenger.sendCmd(kAcknowledge,ledFrequency);
}

```
> 2 votes

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


# Question
Title: wire up usb to pins rather than on board usb socket
I have an uno r3 clone in an enclosure and one of these usb ports on the enclosure.

It's pretty tight in there so I was wondering if there was a way to bypass the usb port on the board and plug it in directly to the pins.

So do something like plug the usb into the outer port on the enclosure and then cut off the usb end and plug the wires directly into the board rather than using the onboard arduino usb port.

The group of 4 just above the i2c seems promising but couldn't find much on it.

Thanks for your help.

# Answer
> 4 votes
You will have to (optionally) desolder the existing USB socket and solder the wires to the pins where that socket was on the board. It connects directly to the pins of the CH340G surface mount chip (rectangular one by the USB socket) and soldering wires to those pins would be tricky.

# Answer
> 2 votes
The USB actually goes through the 16 pin chip that will translate the USB to serial to the RX and TX pins. None of the external sockets or plated through holes are connected to the data lines of the USB port.

You are better off soldering the wire to the pins on the connector itself. Or try and find a proper wire with the correct connectors.

---
Tags: arduino-uno, usb
---


# Question
Title: What will happen if I set ARef to 3.3V and try to use adc connected to 5V
What will happen, if I try to measure voltage higher than ARef? For example, my ref is 3.3V, and I try to measure 4.5V. Will it damage adc?

# Answer
The datasheet of the Atmega328P does not give a direct answer to this, but

> Single ended channels that exceed V REF will result in codes close to 0x3FF.

(Datasheet Chapter 24.5.2)

sounds, as it would not destroy the ADC, but only result in a value very close to the maximum. I also found another side, where this is also stated. They linked to the Arduino forum, where a similar question is handled in this thread.

So all in all it should be save to provide more than the reference voltage at the ADC pins, as long as it does not exceed the supply voltage (for the UNO 5V).

---

As Majenko pointed out in his answer, the datasheet states, that it is safe to provide VCC+0.5V at any pin (except for reset). I just wasn't sure, if this can easily be applied to this special hardware, but it seems, that it can.
> 3 votes

# Answer
Contrary to what @chrisl says, the datasheet *does* give a direct answer to this:

* Voltage on any Pin except RESET with respect to Ground: -0.5V to VCC+0.5V

So when running at 5V anything up to 5.5V is safe - regardless of what VRef has fed into it.

The VRef just sets the range of the ADC when comparing the incoming voltage to a DAC generated voltage, so anything over the VRef voltage will just read as "max" (1023).
> 3 votes

---
Tags: arduino-nano, adc
---


title: Merging of two functions

text:
# Question
Title: Merging of two functions
This is my Arduino code that checks the water Level of two different water reservoirs via 2 water Level Sensors A and B:

```
#define Water_Level_A 5;
#define Water_Level_B 6;

boolean Water_Level_Check_A(){
boolean Result = digitalRead(Water_Level_A);
return Result;
}
boolean Water_Level_Check_B(){
boolean Result = digitalRead(Water_Level_B);
return Result;
}

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

void loop() {
if (Water_Level_Check_A() == LOW){
--> Water Pump A
}
if Water_Level_Check_B() == LOW{
--> Water Pump B
}

```

What's the best way to simplify this code so that I only need one `Water_Level_Check` function so that the distinction between A and B and Water\_Level\_A and Water\_Level\_B is made within the function and the loop part looks like this:

```
void loop() {
if (Water_Level_Check_(A) == LOW){
--> Water Pump A
}
if Water_Level_Check_(B) == LOW{
--> Water Pump B
}

```

# Answer
> 1 votes
I think what you're asking for is something like this:

```
boolean Water_Level_Check(uint8_t level_pin){
   boolean Result = digitalRead(pin);
   if( level_pin == Water_Level_A ){
      // manage pump A here
   }
   else if( level_pin == Water_Level_B ){
      // manage pump B here
   }
   else {
      Serial.println("Water_Level_Check: unknown pin number.");
      // or some other way of dealing with a bad-pin-number bug.
      return -1;
   }

   return Result;
}

```

for the level testing function, which will simplify you loop function to:

```
void loop() {
   (void)Water_Level_check(Water_Level_A);
   (void)Water_Level_check(Water_Level_B);
}

```

The `(void)` expression before each call is a "cast to void", telling the the compiler to consider the function's boolean return value to have been intentionally "voided", i.e. you *intended* not to read it, and not to give an error message.

# Answer
> 3 votes
Functions like

```
boolean Water_Level_Check_A(){
   boolean Result = digitalRead(Water_Level_A);
   return Result;
}

```

Are really overcomplicated. You're just calling one function and returning that value, so it can be simplified to

```
boolean Water_Level_Check_A(){
   return digitalRead(Water_Level_A);
}

```

Or just the expression

```
digitalRead(Water_Level_A)

```

whenever you need it.

So all you're doing is calling `digitalRead()` on a pin number and check if the result is low. If you really want to move this to a different function then you could give it the pin number argument and directly invert the result so that a `true` from this function means that some action needs to be done.

```
boolean Water_Level_Check(int sensorPin){
   return !digitalRead(sensorPin);
}

```

And then call it as

```
void loop() {
   if (Water_Level_Check(Water_Level_A)){
       //--> Water Pump A
   }
   if (Water_Level_Check(Water_Level_B )){
       //--> Water Pump B
   }
}

```

---
Tags: code-optimization
---


# Question
Title: why of 2 identical micro-controllers, only one can connect to a given device?
I am working with 2 identical (Arduino) Adafruit Feather M0 Bluefruit LEs. Only one of them can connect to a Universal Windows Platform app running on a Windows 10 machine. The other connection fails with Unreachable status.

I am only trying to connect with one MCU at one time. Both MCUs are loaded with the same program which resets the Bluetooth Unit. Both MCUs can connect to an Android app. Neither board appear damaged.

Why could a UWP app be able to connect to one board but not another?

# Answer
Other than a software issue, there is no reason it shouldn't work. Only thing may be identical Bluetooth names or ids. Clear the device from windows and try again.

I have some cheap Bluetooth obd 2 readers that all use the same Bluetooth mac address and name. I have to delete one from my android phone before adding the new one to connect to it.
> 2 votes

---
Tags: bluetooth, windows
---


title: PC Fan Speed Control

text:
# Question
Title: PC Fan Speed Control
I am working on a project to blow air gently through a number of pipes and variable speed. I would like to use a standard PC case fan and have control of whether the fans are on/off and also what speed they spin at. My hope is to attach temperature sensors later and eventually blow are depending on the temperature.

It appears that PC fans on 3-wire and 4-wire systems provide variable speed by changing input voltage ranging from 3-12V (linear voltage regulator) or with PWM set to 3.3V or 5V. Furthermore, it looks like inexpensive products exist to split/copy a single signal to multiple fans (see here).

I am hoping to control 4-8 fan speeds, as independently as possible while using as simple/standard a case fan as possible. What is the best way to drive PC case fans using the Arduino?

Reference: https://en.wikipedia.org/wiki/Computer\_fan\_control

# Answer
> 1 votes
To put the comments into an answer:

You can drive most PC fans (which have at least 3 pins) with any PWM source and change their speed through the duty cycle. The Arduino Uno itself has 6 PWM channels. If you want to control more fans, you have to use an extra chip, that provides PWM. You can use the breakout board from Adafruit, but also any other external PWM chip (they are often marked as servo drivers, since servos use PWM signal too).

The speed of most fans can also be changed through providing a different input voltage, but this is not intended for direct variation. Instead this is normally used to set the speed interval, in which the fan should run. For example some PC fans have extra adapters, which lower the supply voltage to let them run more silent. For short term variation you should definitely use PWM. If your fans are too fast at their nominal voltage, you can provide them with a lower voltage permanently.

As dandavis pointed out, the 4th pin is usually connected to a feedback loop. They provide a defined number of pulses per full rotation, so that you can really measure the speed, instead of just estimating. When you don't need this functionality both kinds of fans (3 pin or 4 pin) are good for you.

---
Tags: arduino-uno, pwm, voltage
---


# Question
Title: When I try to compile the following code in Arduino ,I get the error "expected initializer before 'void'".How can I get the code to work?
When I try to compile the following code in Arduino ,I get the error "expected initializer before 'void'".How can I get the code to work?

```
const int LED = 9;
const int BUTON = 2

void setup() {
  pinMode (LED, OUTPUT);
  pinMode (BUTON, INPUT);
}

void loop() {
  if (digitalRead(BUTON) == HIGH);
  {
    digitalWrite(LED, HIGH);
  }
  else
  {
    digitalWrite(LED, LOW);
  }
}

```

# Answer
You are missing a semi-colon after `const int BUTON = 2`

Each expression should be terminated with a semi-colon. Your code should look like this:

```
const int LED = 9;
const int BUTON = 2;

void setup() {
  pinMode (LED, OUTPUT);
  pinMode (BUTON, INPUT);
}

void loop() {
  if (digitalRead(BUTON) == HIGH)
  {
    digitalWrite(LED, HIGH);
  }
  else
  {
    digitalWrite(LED, LOW);
  }
}

```
> 4 votes

---
Tags: arduino-uno
---


# Question
Title: Long term connection between Arduino and computer
I am looking to make indicator lights for my computer to indicate things such as system load, IO usage, et cetera, using an Arduino and NeoPixels. I would like to just plug it into my computer, and have some custom software connect to it and send it the data it needs as my computer runs.

The part I am having trouble with is figuring out how to connect the Arduino to the computer in a way that is consistent in the long term.

I have had issues with the Arduino switching which /dev/ttyAMC\* port it is assigned, so I looked for options other than the USB serial. The only other way seems to be USB, as that is the only common general purpose port these days.

This is where my problem lies. People don't seem to be doing this sort of thing, or at least they don't post about it.

The Teensy can act as a USB HID, but the raw HID feature hasn't been updated in almost a decade, the host side code is based on deprecated libraries, and it seems oriented more for Teensy to computer transfers.

There doesn't seem to be any consumer level USB interface chips available, either.

I found V-USB, which seems like a solution to my problems, in fact someone even used it to do basically what I want to do. However, I would still need to learn the library.

---

So, my question is what is the recommended way of interfacing between a computer and Arduino in the long term? Is USB support really necessary, or have I just overthought the entire thing?

# Answer
I think the easiest option may be to keep the USB (ACM) link, so you don't have to do anything special on the Arduino, and try to figure out a way to identify the correct device on the computer side.

On Linux, providing consistent device names for specific peripherals is normally the job of udev. You could add your own udev rule to create a symbolic link for your Arduino every time you plug it in. Then, your custom software would always open `/dev/neopixel-monitor`, which would be a symlink to the proper `/dev/ttyACMx` device.

Actually, you may not need write your own rule. I took a look at the udev rules installed by default on my Ubuntu 16.04 and found a file named `/lib/udev/rules.d/60-serial.rules` meant to populate the `/dev/serial/by-path/` and `/dev/serial/by-id/` directories. Then I plugged in my Arduino Uno R3 and saw the symlink `/dev/serial/by-id/usb-Arduino__www.arduino.cc__0043_93140364233351E00101-if00` automatically created, which right now points to `../../ttyACM0`. In this name, `0043` is the USB device ID of the Uno, and the following alphanumeric sequence looks like a serial number. The `if00` looks like an interface number, ~~and may vary~~ (it won't, se Majenko's comment). The link name should be a good way to uniquely identify that particular Arduino.
> 2 votes

---
Tags: usb, communication
---


# Question
Title: How to control Neopixel LEDs in parallel?
Imagine a collection of LEDs (Neopixel or otherwise) labeled 2 through 12. There may be more than 11 LEDs, so repeat numberings are allowed. I want a simple way to control them from a single Arduino *based on their label*. So e.g. I should be able to implement a function whose arguments are a label value and an RGB value, and which turns all LEDs of that label value to the given RGB value. Most importantly, the solution has to be order-independent; that is, I should be able to re-wire the LEDs (or equivalently, scramble around the hex labels) in any manner, and still have everything work without rewriting any code. (For context, my goal is to make a custom Settlers of Catan edition, where the labels on each hex light up when their die value is rolled.)

I know I can't just use Neopixels out of the box, since the addressing depends on the order in which they're wired. So I assume I need to hack together a way for each LED to "know" its label, wire them all in parallel, and then write a custom library to . But I have no idea how to get each LED to know its label without having an entire Arduino for each LED, which would take up way too much space. (I'd like to fit everything in roughly the volume of a typical Catan hex label; think 2-3 quarters stacked together.)

I'm fairly comfortable with Arduinos, but I'm an electronics noob. Is it possible to reprogram the Neopixel controller? Or is there a tiny logic board I can hook up to a Neopixel or dumb LED that would do the job? Anything else I'm missing?

# Answer
> 1 votes
It will not be easy to “re-wire the LEDs \[...\] and still have everything work without rewriting any code.” Those LEDs are not that smart, and the only way to address them is by the order in which the color data is sent through the data line.

What you can do, however, is write the code is such a way that rewiring requires only a *minimal change* in the code. I would use an array to map the LED indices to their labels. Something like this:

```
const uint16_t LED_COUNT = ...;

// Map LED indices along the strip to hex labels.
const uint8_t ledLabels[LED_COUNT] = {
    2, 2, 2, 2,  // LEDs 0 to 3 are labeled "2"
    8, 8, 8, 8,  // LEDs 4 to 7 are labeled "8"
    // etc...
};

```

Then, assuming your LED strip is declared as follows:

```
const uint8_t LED_STRIP_PIN = ...;
Adafruit_NeoPixel ledStrip(LED_COUNT, LED_STRIP_PIN);

```

the “function whose arguments are a label value and an RGB value, and which turns all LEDs of that label value to the given RGB value” can be quite easily written:

```
// Turn all the LEDs sharing that hex label to the given color.
void setHexColor(uint8_t label, uint32_t color)
{
    for (uint16_t n = 0; n < LED_COUNT; n++)
        if (ledLabels[n] == label)
            ledStrip.setPixelColor(n, color);
    ledStrip.show();
}

```

Now, if you rewire the strip, you just need to update the `ledLabels` array and recompile. If you can manage to send that information to your Arduino while it's running (a serial connection, an IR link, an SD card inserted in an appropriate socket, whatever...), then you could even have a procedure where the Arduino updates the array itself. Obviously the `const` qualifier should then be removed. But you now have to devise a way to “tell” the Arduino about your wiring.

# Answer
> 0 votes
The data wires of individually addressable LEDs of various descriptions are typically wired as a daisy chain, with each LED driver having input and output for the data (and clock). Each LED driver will then manipulate the signal it sends onward to trick the next LED into thinking it is the first in the chain.

Most libraries to drive them can easily have a few 100 LEDs it can driver at a time depending on available RAM.

---
Tags: led, neopixel, ws2812
---


# Question
Title: Get USB host controller serial number or ID using Teensy or other HID devices
I have a Teensy board and would like to know if there's a way to get a serial number (or any other kind of ID that is preferably unique) of the **host** controller that I plug my Teensy into. E.g. can I get any unique identification numbers of my Macbook's USB controller when I plug my Teensy into it? C/C++ code examples for Teensy would be highly appreciated.

# Answer
> 1 votes
Nothing in the USB spec requires the host to provide any sort of identification to connecting devices. The standard way of implementing what you want consists in writing a custom driver which communicates the necessary information to the device. If installing a custom driver is not an option, all you can do is try to detect the OS by observing what it does during the enumeration process. Such identification will not be reliable (enumeration process can change after an OS update) and by no means unique.

Note that if your goal is to make sure the host is *trusted*, a simple ID will not be enough as it can be easily spoofed. You'll have to implement some sort of authentication scheme, e.g. challenge-respose.

---
Tags: usb, teensy
---


# Question
Title: Simple webpage serve with Arduino ethernet shield on SD card
I have been experiment with the arduino uno board from few days but can't seem to make it serve web page stored in SD card of ethernet shield.

If I print the contents of the file to serial it works properly, even embedding the HTML code works fine, but `client.write()` just produces a never ending garbage text of `ÿÿÿÿÿÿÿÿÿÿÿÿ`

```
#include <SPI.h>
#include <Ethernet.h>
#include <SD.h>
byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
IPAddress ip(192, 168, 0, 115);
EthernetServer server(80);

File webFile;

void setup()
{
    pinMode(4, OUTPUT);
    digitalWrite(4, HIGH);
    Ethernet.begin(mac, ip);
    server.begin();
    Serial.begin(9600);

// initialize SD card
Serial.println("Initializing SD card...");
if (!SD.begin(4)) {
    Serial.println("ERROR - SD card initialization failed!");
    return;
}

Serial.println("SUCCESS - SD card initialized.");
// check for index.htm file
if (!SD.exists("index.htm")) {
    Serial.println("ERROR - Can't find index.htm file!");
    return;  // can't find index file
}
Serial.println("SUCCESS - Found index.htm file.");
}

void loop()
{
EthernetClient client = server.available();  // try to get client

if (client) {  // got client?
    boolean currentLineIsBlank = true;
    while (client.connected()) {
        if (client.available()) {   // client data available to read
            char c = client.read(); // read 1 byte (character) from client
            // last line of client request is blank and ends with \n
            // respond to client only after last line received
            if (c == '\n' && currentLineIsBlank) {
                // send a standard http response header
                client.println("HTTP/1.1 200 OK");
                client.println("Content-Type: text/html");
                client.println("Connection: close");
                Serial.println("starting to open htm");
                client.println();
                // send web page
                webFile = SD.open("index.htm");        // open web page file
                if (webFile) {
                    while(webFile.available()) {
                        client.write(webFile.read()); // send web page to client
                    }
                    webFile.close();
                }
                break;
            }
            // every line of text received from the client ends with \r\n
            if (c == '\n') {
                // last character on line of received text
                // starting new line with next character read
                currentLineIsBlank = true;
            }
            else if (c != '\r') {
                // a text character was received from client
                currentLineIsBlank = false;
            }
        } // end if (client.available())
    } // end while (client.connected())
    delay(1);      // give the web browser time to receive the data
    client.stop(); // close the connection
} // end if (client)
}

```

Sorry for the poor formatting, I just copied it from tutorial, please help me out.

# Answer
"ÿ" is character code 255, the erased state of a Flash/EPROM/SD. Check if your SD card format OK, 'index.htm' file is there, and your code can read it.
> 1 votes

# Answer
Me I solve the problem by using : "/index~1.htm" I see that the file name is seen like that using the cardinfo.ino from Example
> 1 votes

---
Tags: arduino-uno, ethernet, sd-card, web-server
---


# Question
Title: Need help with using LED matrix with pushbuttons
I am building a small project that uses a pair of 8x8 LED matrix (driven by the MAX7219), a pair of SG90 servos, a HC-SR04 ultrasonic sensor, a 16x2 LCD (Hitachi HD44780 driver), some push buttons and all controlled with the Arduino Uno. All the components are powered using another usb port on my pc.

When I tried intergrating all the compenents, I noticed the LED matrix does not light up at all. I've decided to combine serveral basic code samples to test their interaction with eachother, where i noticed the use of `pinMode` to declare my pins for the push buttons will cause the LED matrix to stop working. Removing the section using `//` will get the led matrix(s) to work again.

Does anyone have any experience with this issue and can explain to me what causes this conflict? I've tried going through the LedControl documentation on the arduino page and I still could not understand what causes this issue.

```
/*

test build for debug

log:

LED Matrix : test code added, no issues
LCD Display: test code added, no issues
Sensor: test code added, serial clashed with LED Matrix. Working with disabled serial, Main build still not resolved.
Servo: test code added, no issues
Buttons: test code added, LED Matrix no longer light up. issue appears to be at the (pinMode) section when declaring buttons as inputs.

*/

//buttons

#include <Button.h>

const int positiveButtonPin = A1;
 int positiveButtonState = LOW;

const int negativeButtonPin = A2;
 int negativeButtonState = LOW;

// servo library setup
#include <Servo.h>
Servo servo1;
Servo servo2;

// lcd setup
#include <LiquidCrystal.h>
const int rs = 12, en = 11, d4 = 10, d5 = 9, d6 = 8, d7 = 7;
LiquidCrystal lcd(rs, en, d4, d5, d6, d7);

//led matrix library setup
#include "LedControl.h"
LedControl lc=LedControl(2,1,0,2);  // Pins: DIN,CLK,CS, # of Display connected
unsigned long delayTime=200;  // Delay between Frames

// sensor setup
const int trigPin = 6;
const int echoPin = 5;
long duration;
int distance;

// led matrix arrays (test with 2 formats)

byte invader1a[] = {0x7C,0x7C,0x60,0x7C,0x7C,0x60,0x7C,0x7C};

byte invader1b[] = {0x78,0x7C,0x66,0x66,0x66,0x66,0x7C,0x78};

byte invader2a[] =
{
  B00100100, // First frame of invader #2
  B00100100,
  B01111110,
  B11011011,
  B11111111,
  B11111111,
  B10100101,
  B00100100
};

byte invader2b[] =
{
  B00100100, // Second frame of invader #2
  B10100101,
  B11111111,
  B11011011,
  B11111111,
  B01111110,
  B00100100,
  B01000010
};

void setup() {
  // put your setup code here, to run once:

//button setup
{
//  pinMode(positiveButtonState, INPUT);                    //         <----------------- THIS CAUSES ISSUE WITH LED MATRIX
//  pinMode(negativeButtonState, INPUT);
}

// servo setup
  servo1.attach(4);
  servo2.attach(3);

//sensor serial test code
// sensor setup
  pinMode(trigPin, OUTPUT); // Sets the trigPin as an Output
  pinMode(echoPin, INPUT); // Sets the echoPin as an Input
//  Serial.begin(9600);                                         //     <----------------- THIS CAUSES ISSUE WITH LED MATRIX, DISABLED

    //led matrix setup
  lc.shutdown(0,false);  // Wake up displays
  lc.shutdown(1,false);
  lc.setIntensity(0,2);  // Set intensity levels
  lc.setIntensity(1,2);
  lc.clearDisplay(0);  // Clear Displays
  lc.clearDisplay(1);

    //lcd hello world code
  // set up the LCD's number of columns and rows:
  lcd.begin(16, 2);
  // Print a message to the LCD.
  lcd.print("hello, world!");

}

//  Creating array strings

void sinvader1a()
{
  for (int i = 0; i < 8; i++)
  {
    lc.setRow(0,i,invader1a[i]);
  }
}

void sinvader1b()
{
  for (int i = 0; i < 8; i++)
  {
    lc.setRow(0,i,invader1b[i]);
  }
}

void sinvader2a()
{
  for (int i = 0; i < 8; i++)
  {
    lc.setRow(1,i,invader2a[i]);
  }
}

void sinvader2b()
{
  for (int i = 0; i < 8; i++)
  {
    lc.setRow(1,i,invader2b[i]);
  }
}

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

//servo test code
    // servo attach
    servo1.attach(4);
    servo2.attach(3);

     servo1.write (120);  // change angle here below. adjust until it looks like it's looking at user
  servo2.write (90);
  delay(250);
  servo1.write (90);
  servo2.write (120);
  delay(250);
// servo detach to reduce noise
servo1.detach();
servo2.detach();

// led matrix test code
    sinvader1a();
    delay(delayTime);
    sinvader2a();
    delay(delayTime);

    sinvader1b();
    delay(delayTime);
    sinvader2b();
    delay(delayTime);

    //lcd hello world code
    // set the cursor to column 0, line 1
      // (note: line 1 is the second row, since counting begins with 0):
      lcd.setCursor(0, 1);
      // print the number of seconds since reset:
      lcd.print(millis() / 1000);

//sensor test code
// Clears the trigPin
digitalWrite(trigPin, LOW);
delayMicroseconds(2);

// Sets the trigPin on HIGH state for 10 micro seconds
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
duration = pulseIn(echoPin, HIGH);
distance= duration*0.034/2;

// no longer useful due to disabled serial
/*
if (distance<1000){
Serial.print("Distance: ");
Serial.println(distance);}
else {}
*/

}

```

# Answer
> 1 votes
It appears you are attempting to use the hardware UART for both talking to your MAX7221 or MAX7219:

```
LedControl lc=LedControl(2,1,0,2);

```

And for talking to, maybe, the SDK's serial monitor:

```
Serial.begin(9600);

```

There is only 1 UART on the Atmel processor used on an Arduino Uno. Consider using a larger Arduino / processor where there are more UARTs on the processor. Be aware that it may be necessary to re-write the library to use the alternative hardware on larger processors.

Also, there is an error in your code and it is causing you to think about it incorrectly:

The lines:

```
pinMode(positiveButtonState, INPUT);
pinMode(negativeButtonState, INPUT);

```

...interfere with the LED matrix because they are changing pin zero from a UART Receive to a GPIO Receive. Likely you meant to type:

```
pinMode(positiveButtonPin, INPUT);
pinMode(negativeButtonPin, INPUT);

```

---
Tags: arduino-uno, button, max7219
---


# Question
Title: Minimum value I2C-pull up resistor for arduino
I'm trying to determine the minimum value of pull resistor for Arduino Uno

The datasheets says for arduino; VOL = 0,4 for IOL = 20 mA. (VDD = 5V)

For formula for calculation of minimal pull-up is: Rmin=Vcc−0.4V/20mA = 4,6V / 20mA = 230 ohms.

But I saw that people use 0,4V for 3mA. Than the minimal value is 1,6K ohms.

So whats the minimum value of pull-up for arduino?

(also my slave has 0,4 Vol for 20 mA IOL)

# Answer
> 1 votes
The full datasheet of the atmega328p can be found here: https://www.microchip.com/wwwproducts/en/ATmega328P.
It is called "ATmega328/P AVR MCU with picoPower Technology Data Sheet".

In section "32.7 Two-Wire Serial Interface Characteristics" in table 32-10 on page 372 it shows different voltage levels for the input.

On page 110 it says: "*When the TWEN bit in TWCR is set (one) to enable the 2-wire Serial Interface, pin PC4 is disconnected from the port and becomes the Serial Data I/O pin for the 2-wire Serial Interface. In this mode, there is a spike filter on the pin to suppress spikes shorter than 50 ns on the input signal, and the pin is driven by an open drain driver with slew-rate limitation*".

I wrote here before that the i2c (the twi hardware inside the microcontroller) did not use the digital pin hardware. However, the i2c pins can still sink a lot of current. Thanks to @Berkay for noticing the same behaviour of the sink current as a normal digital pin.

According to the datasheet the atmega328p of the Arduino uno **might** not use the digital pin hardware for i2c. It is not known if the same mosfet circuit is used with the same (large) sink current. Perhaps the chip uses a similar mosfet circuit with added slew rate for the output and added spike filter for the input. Perhaps the same mosfet of the digital pin is used after all.

In the Arduino sketch, calling `Wire.begin` turns on the dedicated i2c hardware in the atmega328p chip. The sink current and voltage levels are according to the i2c specifications.
As you can see in the i2c tutorial by Nick Gammon, the Arduino can sink more than 3 mA.

When the pullup resistors are too low, for example for a sink current of 4 mA, the Arduino uno can handle that, but the slave might not.

When all the pullup resistors are combined, the required sink current can be calculated. The maximum is 3 mA to meet the i2c specifications. To compensate for wire capacitance the i2c bus speed can be lowered.

The i2c bus is not ment to go into a cable, it is not ment for long wires. A cat6 cable is 46 pF/m. That means your 800 pF is for 17 meters cable? That is not what the i2c bus is for. It is for 17 centimeters. The rule of thumb is maximum 50 cm for a normal 100 kHz to 400 kHz i2c bus.

# Answer
> 0 votes
I assume you want to work out the minimum value for a pullup resistor that will give a voltage below *VIL* for an IO pin in open-drain mode.

That is not a simple task, chiefly because you don't know the ON resistance (*RDSON*) of the low-side MOSFET in the chip.

It's possible to come up with a rough estimate (see here) though.

With VIL of 1.5V and maximum current of 40mA that's an estimated theoretical resistance of 1.5/0.04 = 37.5Ω.

Note: this is just an estimate based on the *absolute maximum* and *DC Characteristics* values from the datasheet.

So if we take that value as actually true you can work out the upper half of a voltage divider that would result in 1.5V coming out. There's two ways of doing that - using the resistance or using the current.

Taking the resistance R1=R2(Vin/Vout-1), 37.5 x (5/1.5-1) = 87.5Ω.

If you want to do it with the current (40mA "absolute maximum"), then R=V/I = (5-1.5) / 0.04 = 87.5Ω.

However, that comes with a *big* caveat. The IO pin, while it can, for short periods, sink 40mA, it's not designed to do that for long periods. For that 25mA is the *recommended* maximum. So a resistor should be chosen that keeps the current *below* 25mA.

Assuming 37.5Ω for the MOSFET resistance, and 25mA through it, that gives a voltage drop across it of 0.94V (well below *VIL*). The upper resistor in that divider would then be (5-0.94)/0.025=162.5Ω

So to sum up:

* The *absolute minimum* resistor would be 87.5Ω
* The *recommended minimum* resistor would be 162.5Ω
* The resistor you would choose to use would bear no real relationship to those values since you would normally choose something more sensible, like 3.3kΩ unless you wanted to run the I2C bus at insanely high speeds or with massive load capacitances.

You really don't need to know the theoretical minimum. You know the maximum already, and all you really need to know is "is the value I'd like to use safe for the IO pin" - i.e., does it draw less than 20mA?

For that you can ignore all the other values. All you care about is your resistance, the Vcc voltage, and the resultant current.

For instance, for a 900Ω resistor with 5V across it you get 5.6mA. You know for a fact that you can never have more than 5.6mA regardless of the resistance of the MOSFET - it can only go down from there.

5.6mA is below the recommended maximum of 20mA, so you're perfectly safe with that resistor.

---
Tags: arduino-uno, i2c, resistor, pull-up
---


# Question
Title: Problem in bootloading my ATmega32U4 chip
I have developed my own development board using ATmega32U4. I want to bootload my ATmega32U4 and hence I used Arduino Uno to bootload it. I have given the connections as per https://www.arduino.cc/en/Tutorial/ArduinoISP and I followed this instructions:

1. Open the ArduinoISP firmware (in Examples) to your Arduino board.
2. Select the items in the Tools \> Board and Serial Port menus that correspond to the board you are using as the programmer (not the board being programmed).
3. Upload the ArduinoISP sketch.
4. Wire your Arduino boards..
5. Select the item in the Tools \> Board menu that corresponds to the board on which you want to burn the bootloader (not the board that you're using as the programmer). See the board descriptions on the environment page for details.
6. Select the Arduino as ISP in the Tools\>Programmer menu.
7. Use the Burn Bootloader command.

But I am getting the error message as

```
avrdude: Device signature = 0x000000
avrdude: Yikes!  Invalid device signature.
         Double check connections and try again, or use -F to override
         this check.

```

I am using 16Mhz crytsal oscillator along with 22pf

What might be the problem?

# Answer
If you are developing your own board there are a number of things which can go wrong, although the problem is usually very simple and bootloading will be easy once you fix the bugs.

Possible hardware problems are:

* You have bad solder joints / connections. Even if you think the solder joints are good, try reflowing them again
* ISP leads are too long - can lead to data corruption during bootloading
* Pins are not correct. E.g. are MOSI and MISO the correct way around?
* Reset pin needs a pullup resistor

Most likely, you have some sort of hardware problem. Post your board layout (or at least schematic) and we can look at it. If you have a pro micro board to hand (if not, buy one one ebay or similar), try bootloading that and see whether your procedure works.
> 0 votes

---
Tags: atmega32u4
---


# Question
Title: Is it possible to program an Arduino Pro Mini using an Arduino Uno R3?
I've recently received an Arduino Pro Mini as a gift, and I don't have an external USB programmer to program the Pro Mini. However, I do own an Arduino Uno R3, and I think it would be possible because they both have the same clock speed and micro-controller (16Mhz with an atmega328).

Is it possible to program an Arduino Pro Mini using an Arduino Uno? If yes, how does one do so?

# Answer
> 7 votes
Just hook up the pins (RX, TX, reset, Power, and Ground) to the corresponding pins on your Uno.

You may have to take the ATMega328 out of your Uno for this to work.

Keep in mind that you need to hook it up to the correct power pin! If your pro mini is running at 3.3v then you must hook it up to the 3.3 pin on your Uno.

Check out the ArduinoToBreadboard page for a bit more info. Scroll down to "Uploading Using an Arduino Board". Although it shows you how to program an Arduino on a breadboard, the wiring is the same.

# Answer
> 3 votes
you can program with an SMD board, you dont link the reset line, hold down the reset on the uno throughout the whole process, and tap the reset on the mini soon as the ide says upload to upload the sketch, by holding the uno in reset it doesn't interfere with the serial comms

# Answer
> 2 votes
There is another method by which you can upload your sketch programs. Program the UNO with the "Arduino as ISP" sketch and connect the pro mini via the SPI pins (plus reset line). See "Upload with Programmer" on the Arduino website and elsewhere on the internet including stack exchange. This method will allow you to use the full memory of the chip and avoid using the bootloader, but you will need to upload with SPI each time.

---
Tags: uploading, arduino-uno
---


title: Increase sample rate in ESP32 board

text:
# Question
Title: Increase sample rate in ESP32 board
For my final project on the university as a Systems Engineer, I'm working on a "electronic stethoscope", which is giving me a lot of headaches.

I bought a Adafruit Feather ESP32 Huzzah (https://learn.adafruit.com/adafruit-huzzah32-esp32-feather/overview) which has a dual core processor that works around 240 MHz of speed, it has support of wireless communication with Bluetooth classic (which is the one I'm using) and also works with the I2S protocol.

That is the reason why I bought an I2S MEMS Microphone SPH0645 (https://www.adafruit.com/product/3421), which according with its documentation works under 50Hz-15KHz.

As a first approach, I thought that it would be enough, but I'm getting a very slow sample rate that is around 800 samples per second. With these values, I can't reproduce any sound with the expected quality.

On the other hand, since the ESP32 has not a high level library to interact with I2S such as ArduinoSound I had to create my own code based on the specification (https://esp-idf.readthedocs.io/en/v2.0/api/peripherals/i2s.html).

My code on the Arduino IDE looks like this:

```
#include "libraries/SmappioSound/SmappioSound.cpp"
#include "BluetoothSerial.h"

int *buffer;
BluetoothSerial serialBT;
int value = 0;
int framesRead = 0;

SmappioSound smappioSound(6835); //value for stabilization

void setup() {
  // put your setup code here, to run once:

  pinMode(DATA_PIN, INPUT); // Supuestamente necesario para que no haya ruido
  serialBT.begin("smappio_PCM");
  Serial.begin(115200);
  while (!Serial) {
    ; // wait for serial port to connect. Needed for native USB port only
  }

  smappioSound.begin(buffer);
}

void loop() {

  //gets the amount of bytes readed from the buffer.
  framesRead = smappioSound.read() / I2S_BITS_PER_SAMPLE_32BIT;

  for(int index = 0; index <= framesRead; index++)
  {

      value = smappioSound.getSampleValue(index);
      if(index % 2 == 0)
      {
          serialBT.print(String(value) + ",");
          Serial.println(value);
      }
  }
}

```

The SmappioSound.h library is where the interaction with I2S occurs. The configuration for i2S is the following:

```
#pragma region // Sección de Configuración
  static const print_mode_t PRINT_MODE = BYTES;                                   // Tipo de impresión: BITS | BYTES | INTEGER | FULL_DETEAILED
  static const bool PRINT_BOTH_CHANNELS = false;                                    // Indica si imprime solo el "Canal 0" ó el "Canal 0" y el "Canal 1"
  static const int FRAMES_REQUESTED = 1;                                           // Parece relacionarse con la cantidad de buffers
  static const int TICKS_TO_WAIT = 0;                                            // Investigar
  static const i2s_bits_per_sample_t BITS_PER_SAMPLE = I2S_BITS_PER_SAMPLE_32BIT;   // Datasheet: 24. Ejemplo: 32.

  static const i2s_config_t SPH_CONFIG = {
    .mode = (i2s_mode_t)(I2S_MODE_MASTER | I2S_MODE_RX),                                            // El controlador es el Maestro y Recibe, el microfono es Esclavo y Transmite
    .sample_rate = 32000,                                                                           // Entre 32KHz y 64KHz (Datasheet)
    .bits_per_sample = BITS_PER_SAMPLE,
    .channel_format = I2S_CHANNEL_FMT_RIGHT_LEFT,                                                   // El formato que usa el micrófono. No se encontró el Datasheet
    .communication_format = (i2s_comm_format_t) I2S_COMM_FORMAT_PCM,    //(I2S_COMM_FORMAT_I2S | I2S_COMM_FORMAT_I2S_MSB) // Investigar
    //MSB: most significant byte -> BIG ENDIAN
    .intr_alloc_flags = ESP_INTR_FLAG_LEVEL1,                                                       // High interrupt priority (investigar)
    .dma_buf_count = 2,                                                                            // Cantidad de buffers, 128 max.
    .dma_buf_len = 32 * 2                                                                           // Tamaño de cada buffer
  };

#pragma endregion Sección de Configuración

```

As you can see, I'm trying to get 32KHz as **sample rate** with **32 bit-depth** (not working for 16, and 24 bits), and I'm setting 115200 baud-rate in the Arduino IDE.

On the other hand, I created a .NET Winforms application that is receiving the generated PCM values over bluetooth 4.0. After 1 second is giving me only 693 samples which is very few.

**Can I reach at least 20KHz as sample rate with these hardware components? Do you see something wrong in my code?**

# Answer
Here's a few tips on optimization.

```
  for(int index = 0; index <= framesRead; index++)
  {

      value = smappioSound.getSampleValue(index);
      if(index % 2 == 0)
      {
          serialBT.print(String(value) + ",");
          Serial.println(value);
      }
  }

```

Doing

```
          serialBT.print(String(value) + ",");
          Serial.println(value);

```

is very wasteful. First of all you're debug-outputting every value as an ASCII string to `Serial`, second you're doing the same thing over `serialBT` with an additional `,`.

It's wasteful because:

* your baud rate is extremely low (115200 on `Serial`)
* converting every value to ASCII will induce an overhead

Your `int value` is 32 bits / 4 bytes which may take arbitrary values. Say the value is at its positive max at `0x7fffffff` = 214748364. Then transmitting the ASCII string will take 9 bytes (10 bytes for largest negative value), sending the raw binary value will *always* take 4 bytes. Thus you should always send your samples in raw binary format, not converted to an ASCII `String`.

At a wanted sampling rate of 32KHz with 32-bit values, you'd need an effective bit rate of 32000\*32 = 1,024,000 Bits/s. Your `Serial` on which you are also printing every 2nd value, is on 115,200 bit/s (and you'd still have to account for the UART overhead, aka start and stop bits for every 8 data bits!).

Depending on the quality of the USB-UART converter on your board (FTDI, CP2102: good, CH340: bad), you can actually get to over 1 megabaud. The ESP32's UART periphal will allow you to set whatever clock divider you want to divide the 80 MHz APB clock (source, chapter 13.3.2). ESP-IDF has the `UART_BITRATE_MAX` defined to 5,000,000 (source), and since Arduino-ESP32 derives from ESP-IDF, that should be possible there, too.

As I said, the USB-UART adapter between the ESP32 and your PC is critical. It has to support such a high speeds with a sufficiently large TX/RX buffer. The max baud rate of a CP2101 is 921600 (source), an FT232RL (source) up to 3 megabaud.

In general you don't want to give your sample values to the peripheral value-wise. Both your `Serial` and your `BluetoothSerial` have the possibility to enqueue a whole buffer at once (source). I don't know the real underlying implementation where the final samples will be stored (and held stable for a while) but you might just be able to do

```
framesRead = smappioSound.read() / I2S_BITS_PER_SAMPLE_32BIT;
serialBT.write((uint8_t*) buffer, framesRead * sizeof(int32_t));

```

to send the whole buffer at once. You'd also have to check how to handle or set the transmission speed on the bluetooth peripheral. I don't know much about the ESP32's BT / BLE radio to answer that.

Speed on a UART adapter could further be advanced to a non-blocking DMA backed variant. Since both I2S and the UART periphal support DMA transfers. Thus, the maximum transfer speed would be reachable.

Another posisbility would be to change the transission medium. You could have your ESP32 join a WiFi network and transmit its audio buffers via UDP or TCP to some server listening on the PC. I think however Bluetooth and UART (with the right tweaks) would also be possible.
> 3 votes

---
Tags: arduino-ide, c++, adafruit, esp32
---


# Question
Title: attachInterrupt for mega 2560 not triggering
I recently bought a mega 2560 to toy around with as a hobby. It's pretty fun so far, but I've recently gotten stuck while trying to use attachInterrupt with a button. I'm using the CHANGE mode, and have read the documentation pretty thoroughly ( I think ).

I've looked up multiple questions and tried to fix my setup and I still can't seem to make it work.

Here's my code:

```
int buttonPin = 18;
int ledPin1 = 11;
int ledPin2 = 9;
int ledPin3 = 5;

int value = 0;

void setup() {
  //declare inputs and outputs
  pinMode(buttonPin,INPUT_PULLUP);
  pinMode(ledPin1,OUTPUT);
  pinMode(ledPin2,OUTPUT);
  pinMode(ledPin3,OUTPUT);

  //create interrupt for button
  attachInterrupt(digitalPinToInterrupt(5),count,CHANGE);

  Serial.begin(9600);
}

void loop(){
  if(value == 0){ digitalWrite(ledPin1,HIGH);}
  else{ digitalWrite(ledPin1,LOW); }

  if(value == 1){ digitalWrite(ledPin2,HIGH);}
  else{ digitalWrite(ledPin2,LOW); }

  if(value == 2){ digitalWrite(ledPin3,HIGH);}
  else{ digitalWrite(ledPin3,LOW); }

  delay(500);
  Serial.print(digitalRead(buttonPin));

}

//count occurs when button is pressed
void count(){
  //incremement a counter
  value++;
  //reset counter from 3 to 0
  if(value >= 2){ value = 0; }
}

```

It's a pretty simple sketch. I'd attach a picture of my current setup but I don't really think It's needed. The button is indeed working as I'm debugging using serial.print().

If not clear, the objective of the sketch is to change the LED lit when the button is pressed. Currently, the variable value is stuck at 0.

# Answer
> ```
> //create interrupt for button
> attachInterrupt(digitalPinToInterrupt(5),count,CHANGE);
>
> ```

The code does not match the comment.

```
attachInterrupt(digitalPinToInterrupt(buttonPin),count,CHANGE);

```
> 2 votes

---
Tags: button, input, atmega2560
---


# Question
Title: Simulating a real time clock module with software
I am building a clock with an Arduino.

Most clocks have a RTC module or some kind of RTC chip in order to get the time. I do not.

How do i replace this chip with software? Is there a C/C++ library equivalent to the Java library `java.util.date`?

Can I run a Java program instead of a C program on my Arduino so I can use this Java library? I only know Java and have little experience with C/C++. I have looked into ways to program this clock in Java which I have had success with, but this is only in my computer, not in the Arduino.

# Answer
> 3 votes
> how do i replace \[an RTC\] chip with software?

You can't. An RTC is made of basically two things:

* a carefully trimmed crystal oscillator that has a very stable and well calibrated frequency
* some logic to count the oscillations and convert that to time and date.

The logic can be easily replaced by software, but the crystal cannot. Any “pure software” solution you may find ultimately relies on counting cycles of the system clock (the signal that clocks the whole microcontroller). On most Arduinos, including the Uno, the system clock is based on a ceramic resonator. These are usually specified with 0.5% frequency tolerance, and they typically have a frequency offset of about ±0.1%. That's a drift of ±44 minutes per month!

You can get better accuracy by calibrating your Arduino's clock, and correcting by software the frequency offset you measure. However, the frequency is not only off, it is also quite unstable, and very sensitive to temperature variations. So even with calibration you end up with a clock that is ridiculously bad compared with the cheapest quartz watch.

> is there a c++ library equivalent to the java library java.util.date?

I don't know Java, but there are C++ libraries available for managing time. For example, you could initialize Paul Stoffregen's TimeLib as follows:

```
setTime(hr,min,sec,day,mnth,yr);  // set initial time
setSyncInterval(-1);  // pretend we don't need to resync

```

and then periodically query the time with `now()`. That should be all you need to build a “proof of concept” of your clock: it will tell you the time, but with an awfully bad long-term accuracy.

Note that, once you add an RTC or another good time source, you can add a “time provider” to that library, keep the rest of your code unchanged, and benefit from the accuracy of your new time source.

> Can i run a java program instead of a c program on my arduino \[...\]?

No, you can't. A Java runtime will never fit in your Arduino.

# Answer
> 1 votes
Having looked at you other question it seems you are trying to run before you can walk. You may be a good java programmer, but you need to get your head around C++ before you go all in and build a clock.

To answer this question, yes there are ways to get software to keep time, but when you power it up, how do you know what the time is? This is where having a RTC will help, there are plenty of bare ICs out there and even ones with libraries.

If you had a network then you could grab the header data from the network packets, but you are running this on a Mega, which seems an odd choice for something as simple as a network time clock, surly a nano would do, or an ESP8266.

These links will help you, but personally I think you need to break the problem down into smaller chunks.

https://www.arduino.cc/reference/en/

https://playground.arduino.cc/Code/Time

---
Tags: c++, rtc, java
---


title: How to make I2C work on RS485?

text:
# Question
Title: How to make I2C work on RS485?
I'm trying to optimize the communication (minimize wires) on a project where I can control a motor and toggle some 230V devices by using RS485 and I2C.

On this project, I'm using an Arduino (Mega) for the control panel (buttons, potmeters, LED segment display (I2C) etc.).

I'm using the RS485 protocol (Modbus RTU) to control an inverter by using a MAX485 TTL converter. Now I also have a relay board (8 channel) to be able to toggle some lightning and sound devices. Both the inverter and the relay board, as well as the power supply, are located in another box, which I call the power box. Between the control panel and the power box will be a cable.

\[Control Panel (with arduino mega)\] \<--cable--\> \[power box (with inverter, 8 channel relay board and 230V devices)\]

**I've got the following requirements:**

* The cable should have a minimum amount of wires (5V, Ground, 485+(A) and 485-(B) for sure)
* The total length of the cable varies from 1 to 3 meters.
* The signal should be reliable.

Now the relay board uses 8 channels. I've bought an I2C expander (PCF8574) to minimize that to 2 wires (SDA, SCL).

I'm thinking of using the existing 485 lines to control the inverter AND the relay board. So no additional wires are required. But theoretically I can't get it to work. So before I try to invent it.

1. Can I do I2C communication over the RS485 as well somehow by putting another converter?
2. If you recommand to just go with 6 wires (power, RS485 and I2C), how reliable is my I2C line going to be on 3 meters? What pull-up values do you recommand? (24AWG wire in mind, but also using a close-by LED segment display, so 2 I2C devices on different distances). I've read posts saying:

> The rule of thumb is maximum 50 cm for a normal 100 kHz to 400 kHz I2C bus.

Or can I use some other protocol/trick? Either minimalize wires, or boost signal by a I2C buffer? (recommendations?)

# Answer
> 2 votes
I2C and RS485 are such vastly different protocols with such vastly different signalling needs that they cannot share the same cables.

Further, I2C is not designed for connecting with long cables - it's meant for use between chips on a PCB.

The simplest "Arduino" solution would be to create a new RS485 device on your RS485 bus using another MAX485 and a small Arduino (micro, nano, etc) that responds to MODBUS RTU instructions and controls the relay board for you.

---
Tags: serial, i2c, rs485, modbus, convert
---


# Question
Title: Set avrdude transfer baud rate in Arduino IDE
I just got an Arduino nano (from arduino.cc, not a knock-off), and have issues uploading sketches. It refuses to upload, with the error message "programmer is not responding".

Some searching led to an incorrect transfer baud rate. Indeed, the IDE (1.8.5) output before uploading displays "overriding baud rate: 57600", and the command line has a `-b57600` argument. By copying this command in a terminal and removing this parameter, the upload works. It also works with `-b115200`. All other values I tried do not work.

Is there a way to configure the IDE to use the correct baud rate ? I know I could use the command line, but that's not very practical, I would prefer to keep the *Integrated* part of the IDE :).

# Answer
> 4 votes
Update the boards package for the AVR hardware. That will give you new options in the tools menu.

Then you should just select the right CPU variant.

From top to bottom those are 115200, 57600 and 19200 baud.

---
Tags: arduino-nano, uploading, avrdude
---


title: My "avoid car" can't move straight

text:
# Question
Title: My "avoid car" can't move straight
I use 2 gearbox motors with 2 wheels .. but if I try to run it, he can not walk straight. he always moves slightly to the right or to the left.

How i fix it ?

# Answer
Likely the two gearbox motors you have are running at slightly different speeds for the same voltage. This is probably within normal tolerances, given that you say it moves *slightly* to the right or left.

You can use PWM-capable pins for motor control so you can adjust how fast the motors turn. If you do this, you have a couple of paths you can take:

You can, through trial-and-error, lower the PWM value (`analogWrite(pin, speed)`) for the faster-turning motor so that they both turn at the same speed.

or

You can find some way to detect the actual rotational speed of each motor and do the calibration in real-time on the Arduino. This might mean adding new sensors such as rotary encoders (mechanical or optical), or light-break sensors, etc.
> 2 votes

---
Tags: arduino-uno, motor, robotics
---


title: USB host shield help

text:
# Question
Title: USB host shield help
Hello, I apologise for being such a noob but can someone help with this. I am having trouble working with this. When I insert the arduino's pins into my new usb host shield , there is no indication light and when I plugged my Xbox receiver into the shield it does not turn on as it would with my desktop. Any thoughts? Please post below

# Answer
> 2 votes
Posting the clear photo is helpful because it shows the USB host board has the following problem.

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


# Question
Title: Removing and using programmed Atmega 328 of Arduino UNO on customised PCB
I am a newbie. I would like to kno whether the original Atmega328 on Arduino Uno, programmed with my own sketch, can be removed from an Arduino Uno board and used on my customised PCB?

# Answer
Yes, it can. Your board will need to provide +5v and ground, a reset signal, and a crystal for the chip's programmed clock frequency (unless you reprogrammed it to use its internal clock). The power and clock signals will need filter capacitors. You can even re-program it on the board with an FTDI (USB-TTL Serial) cable.

There are lots do-it-yourself instructions to build an Arduino board, which is a good place to start, even if what you eventually want is a larger system board with an Arduino integrated into it. This is one I can vouch for; I built Mr. Alves' Version-1 as my only Uno-like board and have been using it for several years.
> 2 votes

# Answer
Yes. Just need a few components:

10K reset pullup resistor.

0.1uF or 100nF ceramic caps:

1 to bring in DTR signal from an FTDI Basic if you plan to reprogram the '328P, or to have a serial interface for debugging

1 on the Aref pin for analog voltage reference decoupling

1 on the VCC pin

1 on the Avcc pin. Avcc also connect to Vcc.

Crystal and two 22pF caps as noted already, or a 3-pin resonator, at 16 MHz. Alternately, you can use the internal 8 MHz circuit for the clock, but the clock source fuses will need to be re-Programmed (using a Programmer).

If you will using a Reset switch, then a diode across the 10K pullup resistor (cathode to the 5V supply, anode to the Reset pin) can also prevent any high voltage glitches on the Reset signal from looking like a High Voltage programming pulse and making the chip look hung up as it waits for the programming sequence to begin.
> 2 votes

# Answer
Yes I did it. Making the board was not so difficut but took quite some time to solder all the components the others mentioned (chrystals,capacitors, resistors and connectors. However,I found the Nick Gammon site very useful, particularly for the programming

part.http://www.gammon.com.au/forum/bbshowpost.php?bbtopic\_id=123
> 0 votes

---
Tags: arduino-uno
---


title: currentbuttonstatus

text:
# Question
Title: currentbuttonstatus
I'm trying to use momentary push buttons to switch bi color LED between RED and GREEN. I've got one working, but when I try to adapt the code for more buttons, it doesn't work. I'm just changing the buttonnumbers (which are defined).
It compiles and uploads without error.

```
void loop() {
  byte currentButton1Status = digitalRead(button1);
  if (currentButton1Status == button1Status)
    lastEqualButtonTime = millis();
  else if ((millis() - lastEqualButtonTime) > debounceTimeMs)
  {
    lastEqualButtonTime = millis();
    button1Status = currentButton1Status;

    if (button1Status == LOW) {
      digitalWrite(17, !digitalRead(17));
      digitalWrite(16, !digitalRead(16));
    }
  }

  byte currentButton2Status = digitalRead(button2);
  if (currentButton2Status == button2Status)
    lastEqualButtonTime = millis();
  else if ((millis() - lastEqualButtonTime) > debounceTimeMs)
  {
    lastEqualButtonTime = millis();
    button2Status = currentButton2Status;

    if (button2Status == LOW) {
      digitalWrite(15, !digitalRead(15));
      digitalWrite(14, !digitalRead(14));
    }
  }
}

```

# Answer
> 1 votes
You've only said "... it doesn't work" which doesn't give much to go on, but the first thing I see that might contribute it not working as (I think) you expect it o, is only one `lastEqualButtonTime` variable for both buttons (is it a global? I don't see a definition). I think you'll need one for each.

---
Tags: arduino-mega, button
---


title: OneButton with pins A6 and A7

text:
# Question
Title: OneButton with pins A6 and A7
I noticed that OneButton library does not work with pins A6 and A7 (with A1 and A2 it works good) on my Arduino Nano. Is it because A6 and A7 are Analog only? There is possibility to make them work properly?

sketch example is here https://github.com/mathertel/OneButton/blob/master/examples/TwoButtons/TwoButtons.ino

# Answer
Pins A6 and A7 are *analog only* pins. They have no digital functionality at all.

You can see that pins 19 and 22 only have ADCn on them - no Pxn for digital operation (ignore the colour scheme of those pins - that's an error in the datasheet).
> 3 votes

---
Tags: arduino-nano, button
---


# Question
Title: LiquidCrystal library and timers don't seem to be compatible
If I set timer2 to Compare Match mode, my LCD display stops working. If I use Overflow Interrupt it works fine.

Here's my test code. I have a loop() function which does its thing, and a timer interrupt which increments another variable, just to show it's working.

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

LiquidCrystal lcd( 8, 9, 4, 5, 6, 7 );   //Pins for the freetronics 16x2 LCD shield. LCD:

int i;
volatile int j;
void setup()
{
  i=0;
  j=0;
  //button adc input
  pinMode( A0, INPUT ); //ensure A0 is an input
  digitalWrite( A0, LOW ); //ensure pullup is off on A0
  //lcd backlight control
  pinMode( 10, OUTPUT ); //D10 is an output
  digitalWrite( 10, HIGH ); //backlight control pin D10 is high (on)
  //set up the LCD number of columns and rows:
  lcd.begin( 16, 2 );

  // setup timer interrupt
  cli(); //disable global interrupts
  TCCR1A = 0;   //set tccr1a and tccr1b to 0
  TCCR1B = 0;
  //set cs10 and cs12 bit so timer runs at clock iSpeed/ 1024
  TCCR1B |= (1 << CS10);
  TCCR1B |= (1 << CS12);

  // Compare Match Mode **Doesn't work**:
  //set compare match register
  OCR1A = 15624;
  // turn on CTC mode
  TCCR1B |= (1 << WGM12);
  // enable Timer1 compare interrupt
  TIMSK1 = (1 << OCIE1A);

  // Overflow mode **Works**
  // enable overflow interrupt
  // TIMSK1 = (1 << TOIE1);

  //enable global interrupt
  sei();
}
void loop()
{
  lcd.setCursor( 0, 0 ); //top left
  lcd.print(i);
  lcd.setCursor(0,1); //bottom left
  lcd.print(j);
  delay(500);
  lcd.clear();
  i++;
}

ISR(TIMER1_OVF_vect)
{
  j++;
}

```

If I use overflow interrupts it works fine, the loop() counter is displayed on the top line and the interrupt counter on the second, but by using overflow interrupts I'm limited to the whatever timing the various prescalers give me.

If I use compare match the LCD display just shows faint flickering squares on its first line, like it's doing something but too quickly for the LCD to display.

I looked at the source for liquidcrystal.cpp, and it doesn't seem to use any timer or interrupts, so I'm completely mystified.

# Answer
> 1 votes
Dang, it was a bit of a noobish error. I had the interrupt handler setup for the overflow interrupt, but when I swapped the code in for the Compare Match interrupt I didn't make a handler for it. So since there's an interrupt without a handler it seems it just resets, hence the flashy-flashy garbage I was seeing on the LCD.

Adding this fixed the problem:

```
ISR(TIMER1_COMPA_vect)
{
  j++;
}

```

---
Tags: lcd, interrupt, library, timers
---


# Question
Title: How can I initialize an array of objects in setup?
How can I declare an empty global array, to be initialized in setup?

What I would like to do is this:

```
#include <ResponsiveAnalogRead.h>

const size_t ANALOG_SIZE = 3;
const int ANALOG_PINS[ANALOG_SIZE] = {A0,A1,A2};
ResponsiveAnalogRead analog_reads[ANALOG_SIZE];

void setup() {
  for(size_t i=0; i<ANALOG_SIZE; i++){
    analog_reads[i]=ResponsiveAnalogRead(ANALOG_PINS[i], true, 0.01);
  }
}

```

But the error I get is:

```
sketch_may29c:5: error: no matching function for call to 'ResponsiveAnalogRead::ResponsiveAnalogRead()'
 ResponsiveAnalogRead analog_reads[ANALOG_SIZE];

                                              ^

```

Is it impossible to declare an empty array of a given size?

# Answer
> 6 votes
As Craig wrote, the declaration of an class typed array will call the default constructor of the class, which is the one without any arguments. The class, that you use, does not provide a default constructor, since it needs it's parameters. You cannot do it this way.

But you can use dynamic allocation. In global scope only declare an array of pointers to `ResponsiveAnalogRead` objects:

```
ResponsiveAnalogRead *analog_reads[ANALOG_SIZE];

```

This array only holds pointers, that can point to `ResponsiveAnalogRead` objects. The objects themselves are not created yet. In `setup()` you can then create the objects dynamically with the `new` statement:

```
analog_reads[0] = new ResonsiveAnalogRead( input_parameters);

```

(Of course you have to replace `input_parameters` with all parameters, that the constructor needs). To call a member of the object, you can dereference it like this:

```
analog_reads[0]->member_function();

```

If you don't know about pointers yet, you should google for a tutorial (there are plenty), so that you understand the principle behind them.

Important note: Dynamic allocations of memory geht written to the heap in RAM. Since the Arduino (especially the Atmega based ones) has only very limited RAM, dynamic allocations have to be handled with great care. You should not create and delete data often in your program, since this would make swiss cheese out of your heap. But allocating the memory only once in your program and never deleting it, will not be a problem, as long as you don't try to allocate too much memory.

# Answer
> 4 votes
Craig already explained the reason of the error is the lack of a default constructor, and chrisl suggested a reasonable alternative. I would like to suggest two other alternatives.

## Static initialization

You state that you want to do the initialization in `setup()`, but you don't explain *why* you want that. I will guess that what you *really* want is to have all those objects in array. The library page provides this example showing how to statically initialize multiple instances:

```
ResponsiveAnalogRead analogOne(A1, true);
ResponsiveAnalogRead analogTwo(A2, true);

```

The problem with this example is that you don't have an array, so you cannot loop through the instances. This problem, however, can be easily fixed:

```
const size_t ANALOG_SIZE = 3;
ResponsiveAnalogRead analog_reads[ANALOG_SIZE] = {
    ResponsiveAnalogRead(A0, true),
    ResponsiveAnalogRead(A1, true),
    ResponsiveAnalogRead(A2, true)
};

```

Note that you don't need the `ANALOG_PINS` array anymore. And you don't need to pass `0.01` as the last argument to the constructor, as this is the default value anyway. This would be my preferred solution: it is simple enough and doesn't increase the number of lines of code.

## Patching the library

If you *really* want to initialize the array in `setup()`, then you can patch the file ResponsiveAnalogRead.h from the library:

1. Add default values to all the parameters of the constructor. For example:

```
ResponsiveAnalogRead(int pin=0, bool sleepEnable=0, float snapMultiplier=0.01);

```
2. Add a method for setting the pin after initialization:

```
void setPin(int newPin) { pin = newPin; pinMode(pin, INPUT); }

```

The first change will enable you to compile your code as-is. The second change will allow you to update the objects in `setup()` rather than overwriting them (which I don't find very elegant):

```
for (size_t i = 0; i < ANALOG_SIZE; i++) {
    analog_reads[i].setPin(ANALOG_PINS[i]);
    analog_reads[i].enableSleep();
}

```

Note that using the default constructor now has the side effect of setting pin 0 to input. This should not be a big deal, as the constructor is called before `setup()`, and all the IO pins are inputs at this point. If you want nevertheless to void that side effect, then set the default pin to `-1`, and patch the constructor to only configure the pin if it's not `-1`.

Patching the library creates a maintenance burden though: you will have to reapply the patch each time the library is updated. This may not be that bad if you know how to `git rebase` or `git merge`, but ideally you would want to get a pull request accepted by the original maintainer.

**Edit**: Before patching the library, consider weighting in this issue and using this fork.

**Update**: A pull request addressing this issue has been accepted. As of version 1.2.0, the class has now a default “do nothing” constructor.

# Answer
> 1 votes
When you declare an array it will call the default constructor for the type. ResponsiveAnalogRead does not have a default constructor so it cannot initialize the entries in the array.

---
Tags: array
---


title: L298 with stepper.h disable break

text:
# Question
Title: L298 with stepper.h disable break
I try to control a Stepper motor with an arduino and a L298. I use the library stepper.h and it works well but i have a problem : the L298 become very hot. So i want to disable the break (the thing that we can't turn the motor by hand), but i don't know how to do this. Do you have an idea ? My code is simple :

```
#include <Stepper.h>

const int stepsPerRevolution = 200;  // change this to fit the number of steps per revolution
// for your motor

// initialize the stepper library on pins 8 through 11:
Stepper myStepper(stepsPerRevolution, 8, 9, 10, 11);

void setup() {
  // set the speed at 60 rpm:
  myStepper.setSpeed(60);
  // initialize the serial port:
  Serial.begin(9600);
}

void loop() {
  // step one revolution  in one direction:
  Serial.println("clockwise");
  myStepper.step(stepsPerRevolution);
  delay(500);

  // step one revolution in the other direction:
  Serial.println("counterclockwise");
  myStepper.step(-stepsPerRevolution);
  delay(500);
}

```

I took it from here : https://coeleveld.com/arduino-stepper-l298n/

Thanks !

# Answer
There is no facility in the stepper library to do what you want - however the stepper library just sequences IO pins in the right order.

There's nothing to stop you just placing those same IO pins in a different state - the library won't care.

```
void sleepStepper() {
    digitalWrite(8, LOW);
    digitalWrite(9, LOW);
    digitalWrite(10, LOW);
    digitalWrite(11, LOW);
}

```

That will effectively set every port of the L298 LOW, which is equivalent to "brake" mode on a normal DC motor, or "not actively driving" on a stepper (not perfect freewheel, there is still some flyback braking).

Another option is to connect the EN pin(s) of your L298 chip to a GPIO and use that to turn the whole system on and off. That will disconnect the drivers from the motor and give you even less movement resistance than the "all low" method above.
> 0 votes

---
Tags: stepper, l298n
---


title: Connecting and using ESP8266 wifi

text:
# Question
Title: Connecting and using ESP8266 wifi
My ESP8266 has stopped working. The red power light comes on and the blue TX light is on solid.

Here's what I did.

Connecting

ESP8266 -\> Arduino nano

`VCC`, `CH_PD`, `RST` -\> `5V` (external supply)

`TX` -\> `TX`

`RX` -\> `RX`

I could send AT commands via the serial monitor.

Then I connected

`RX` -\> `11`

`TX` -\> `10`

and set up software serial intending to repeat the experiment. I was getting garbage characters in the response, and found that I had to `esp8266.println("AT+IPR=9600");` to reduce the baud rate.

Then the blue TX light cam on permanently and it's stopped working at all.

# Answer
> 1 votes
Serial devices should be connected RX to TX and TX to RX.

When you connected the RX to RX you connected the esp8266 to USB chip on Nano. Because the USB chip is connected to Atmega on Nano RX to TX, so if you connect the esp8266 to the same line, the it is connected RX to TX to USB.

On this picture esp8266 is connected to Atmega and not accessible from USB:

Communication from Serial Monitor over USB to esp8266 on pins 10 and 11 of the Atmega could work only with SerialPassthrough sketch resending data between Serial and SoftwareSerial on pins 10 and 11.

---
Tags: esp8266, arduino-nano, wifi
---