# Question
Title: atmega328: external crystal oscillator and uart
I need an clearity about external crystal oscilator. I got communication between esp32 and atmega8/88/328 processor, I use atmega wih internal oscillator and looks like it have problem with serial communication (some time it lose data, or replace it with nonsences).

So i have read that should use extercal crystal oscillator to achieve stable uart communication.

Question is that, what frequency to choose, and how that gonna effect uart, and atmega processor lifetime. I know if choose 16mhz processor gonna run faster, but assume it life time will decrease compated with 1mhz or 8mhz. What about uart, which one of those frequences are best for it, or it make no difference?

# Answer
There are some specific crystal oscillator frequencies named 'UART friendly'. Using these frequencies would lower % error in UART communications. Please refer to the table in the datasheet, in chapter named "BAUD rate settings" (datasheet of ATMega328: '24.11. Examples of Baud Rate Setting'). There are tables to show error percentage. What to look at is **"Error"** column. **fosc** is selected oscillator/crystal frequency. For succesful UART communication you aim for less than 3.5% Error.
Your crystal speed should depend on your desired communication speed, for example for me the preferred ones are 11059200Hz or 1843200Hz.

or below:

With raising frequency you may expect power consumption and the chip's temperature rise, anyway I wouldn't worry too much about life shortening. More important here would be power consumption rise. Do you want the chip(device) to be battery powered? To save on energy you can also consider lower frequencies like 1.8432MHz or 3.6864MHz.
> 1 votes

---
Tags: uart
---


title: Changing the light state

text:
# Question
Title: Changing the light state
Can someone give me a solution to the following problem?
I have 1 IR remote, blynk app,some pushButtons and also 1 relay module. (I set 1 pin of ATMega as input to be able to read what esp sends when I use the blynk app).
So basically what I want to do is this:
If I press btn1 from the IR Remote or PushBtn nr1, or I send 1 from blynk app then relay 1 must turn on. For now that part works.
Anyway, what I want to do next is this:
If the relay is turned on (closed) I want to be able to turn it off using the same buttons (for which I have set a counter and I call that variable).
Now I can turn the relay off only if I use the same btn that previously I have used to turn it on. But I want to be able to turn it off the other way. If I used the blynk app to turn it on then if I press the pushbtn second time - I want it to be off. Also if I don't press the pushbtn but I use the IR remote and press 1 2 times- the relay should be off.

```
if(cntbtn2 == 1 || cntPushbtn2 == 1)
      {
      digitalWrite(rel2,LOW);
      u8g.setFont(u8g_font_courB10);
      u8g.drawStr(32,10,"Interior");
      u8g.drawFrame(0,12,128,51);
      u8g.drawLine(64,12,64,62);

      if(cntbtn1 == 1 || cntPushbtn1 == 1)
          {
          u8g.setFont(u8g_font_5x8);
          u8g.drawStr(10,23,"Sufragerie");
          u8g.drawStr(15,60,"L.aprinsa");
          u8g.drawBitmapP( 20, 8, 16, 64, LightOn);
          }

      else if(cntbtn1 != 1)
          {
          u8g.setFont(u8g_font_5x8);
          u8g.drawStr(10,23,"Sufragerie");
          u8g.drawStr(15,60,"L.stinsa");
          u8g.drawBitmapP( 20, 8, 16, 64, LightOff);
          }

      u8g.drawStr(73,23,"Dormitor");
      u8g.drawStr(75,60,"L.aprinsa");
      u8g.drawBitmapP( 78, 7, 16, 64, LightOn);
      }

else if(cntbtn2 == 2)
    {
    if(cntbtn1 == 1 || cntPushbtn1 == 1)
        {
        u8g.setFont(u8g_font_courB10);
        u8g.drawStr(32,10,"Interior");
        u8g.drawFrame(0,12,128,51);
        u8g.drawLine(64,12,64,62);
        u8g.setFont(u8g_font_5x8);
        u8g.drawStr(10,23,"Sufragerie");
        u8g.drawStr(15,60,"L.aprinsa");
        u8g.drawBitmapP( 20, 8, 16, 64, LightOn);
        u8g.drawStr(73,23,"Dormitor");
        u8g.drawStr(75,60,"L.stinsa");
        u8g.drawBitmapP( 78, 7, 16, 64, LightOff);
        }
    else{
        digitalWrite(rel2,HIGH);
        u8g.setFont(u8g_font_courB10);
        u8g.drawStr(32,10,"Interior");
        u8g.drawFrame(0,12,128,51);
        u8g.drawLine(64,12,64,62);
        u8g.setFont(u8g_font_5x8);
        u8g.drawStr(10,23,"Sufragerie");
        u8g.drawStr(15,60,"L.stinsa");
        u8g.drawBitmapP( 20, 8, 16, 64, LightOff);
        u8g.drawStr(73,23,"Dormitor");
        u8g.drawStr(75,60,"L.stinsa");
        u8g.drawBitmapP( 78, 7, 16, 64, LightOff);
        }
    }

if(cntbtn2 == 1 && cntPushbtn2 == 2)
    {
    digitalWrite(rel2,HIGH);
    }

//ecran stanga
if(cntbtn1 == 1 || digitalRead(espPin) == 1 || cntPushbtn1 == 1)
    {
    digitalWrite(rel1,LOW);
    u8g.setFont(u8g_font_courB10);
    u8g.drawStr(32,10,"Interior");
    u8g.drawFrame(0,12,128,51);
    u8g.drawLine(64,12,64,62);
    u8g.setFont(u8g_font_5x8);
    u8g.drawStr(10,23,"Sufragerie");
    u8g.drawStr(15,60,"L.aprinsa");
    u8g.drawBitmapP( 20, 8, 16, 64, LightOn);
    if(cntbtn2 == 1 || cntPushbtn2 == 1)
        {
        u8g.drawStr(73,23,"Dormitor");
        u8g.drawStr(75,60,"L.aprinsa");
        u8g.drawBitmapP( 78, 7, 16, 64, LightOn);
        }
    else
        {
        u8g.drawStr(73,23,"Dormitor");
        u8g.drawStr(75,60,"L.stinsa");
        u8g.drawBitmapP( 78, 7, 16, 64, LightOff);
        }

   }

else if(cntbtn1 == 2)
    {
    digitalWrite(rel1,HIGH);
    u8g.setFont(u8g_font_courB10);
    u8g.drawStr(32,10,"Interior");
    u8g.drawFrame(0,12,128,51);
    u8g.drawLine(64,12,64,62);
    u8g.setFont(u8g_font_5x8);
    u8g.drawStr(10,23,"Sufragerie");
    u8g.drawStr(15,60,"L.stinsa");
    u8g.drawBitmapP( 20, 8, 16, 64, LightOff);
    if(cntbtn2 == 1 || cntPushbtn2 == 1)
        {
        u8g.drawStr(73,23,"Dormitor");
        u8g.drawStr(75,60,"L.aprinsa");
        u8g.drawBitmapP( 78, 7, 16, 64, LightOn);
        }
        if(cntbtn2 != 1)
            {
            u8g.drawStr(73,23,"Dormitor");
            u8g.drawStr(75,60,"L.stinsa");
            u8g.drawBitmapP( 78, 7, 16, 64, LightOff);
            }
        }
    else
        {
        digitalWrite(rel1,HIGH);
        digitalWrite(rel2,HIGH);
        u8g.setFont(u8g_font_courB10);
        u8g.drawStr(32,10,"Interior");
        u8g.drawFrame(0,12,128,51);
        u8g.drawLine(64,12,64,62);
        u8g.setFont(u8g_font_5x8);
        u8g.drawStr(10,23,"Sufragerie");
        u8g.drawStr(15,60,"L.stinsa");
        u8g.drawBitmapP( 20, 8, 16, 64, LightOff);
        u8g.drawStr(73,23,"Dormitor");
        u8g.drawStr(75,60,"L.stinsa");
        u8g.drawBitmapP( 78, 7, 16, 64, LightOff);
        }
   }

```

# Answer
> 0 votes
Split the logic and the buttons in separate parts and avoid code duplication.

First step is to determine what should control the relay state:

```
// pseudo code follows
if (pushButton.isPressed() || blinkApp.sentCommand() || conditionAlfa.isMet()) {
  // update condition is met, proceed to state change
  relayState = !relayState; // swap relay state
  updateRelay = true; // activate the part responsible for the change
}

```

Once the new desired state is set, act on the relay and update the screen accordingly:

```
// pseudo code again
if (updateRelay == true) {
  updateRelay = false; // we are now going to update, don’t do it again if not necessary
  relay.setState(relayState); // update the relay, no matter what was the event source
  screen.drawGraphics(); // update the screen, no matter what was the event source
}

```

If you split the two parts you start operating on logical conditions rather than on physical events, making your entire code cleaner and your task simpler.

---
Tags: software
---


# Question
Title: The arduino can't seem to output correctly
i am a beginner at python and I am average at Arduino and I had the idea of using both of them together for a project. I have been trying to make a **Arduino + Python** car which I can control with my computer. I have used Pyfirmata and the code seems perfect to me. When I run the code from CMD i have a weird bug/issue. I have uploaded Standard Firmata to the arduino UNO. I get **no errors while uploading or running** its just that its output is messed up.

Here's the Python Code:

```
from pyfirmata import Arduino, util
import time

board = Arduino("COM3")

MotorLeft = board.get_pin('d:10:o') # Assigning output to PIN
MotorRight = board.get_pin('d:11:o') # Assisging output to PIN

play = True

while play:
    control = input(
        print("Enter W, A or D to move forwards, left or right. Enter 0 to exit"))

    if control != 0:
        if control == "W" or "w":
            MotorRight.write(1)
            MotorLeft.write(1)
            time.sleep(1)
            MotorRight.write(0)
            MotorLeft.write(0)

        if control == "A" or "a":
            MotorLeft.write(1)
            time.sleep(1)
            MotorLeft.write(0)

        if control == "D" or "d":
            MotorRight.write(1)
            time.sleep(1)
            MotorRight.write(0)

        else:
            print("Invalid Commmand")

    else:
        print("Exited Succesfully")

    play = True

```

Currently I have not built the car, I am using a pair of LEDs to do what the motors function and to test out the code.

Heres the **CMD response**:

Here is the link for the output video. I entered "W" which **should ideally turn on both of the LEDs** however, both of them turn on then off and then turn on off one by one.

**https://youtu.be/DjUkkpzF0so**

# Answer
> 0 votes
I cannot check it, but I guess you have to change the or commands like:

```
if control == "W" or "w":

```

Change to

```
if ((control == 'W') or (control == 'w'))

```

And similar for the other if statements.

Also, you can do not need to check for control == 0, since it will not be a character otherwise.

Besides that, the `elif` (else if) construct is normally used in Python, so instead of:

```
if control != 0:
    if control == "W" or "w":
        MotorRight.write(1)
        MotorLeft.write(1)
        time.sleep(1)
        MotorRight.write(0)
        MotorLeft.write(0)

    if control == "A" or "a":
        MotorLeft.write(1)
        time.sleep(1)
        MotorLeft.write(0)

    if control == "D" or "d":
        MotorRight.write(1)
        time.sleep(1)
        MotorRight.write(0)

    else:
        print("Invalid Commmand")

```

You can write:

```
if ((control == 'W') or (control == 'w')):
    MotorRight.write(1)
    MotorLeft.write(1)
    time.sleep(1)
    MotorRight.write(0)
    MotorLeft.write(0)

elif ((control == 'A') or (control == 'a')):
    MotorLeft.write(1)
    time.sleep(1)
    MotorLeft.write(0)

elif ((control == 'D') or (control == 'd')):
    MotorRight.write(1)
    time.sleep(1)
    MotorRight.write(0)

else:
    print("Invalid Commmand")

```

Also, you can combine the `or` in a list (but I cannot check it, no python compiler at hand), e.g.

```
if (control in ['W', 'w']):

```

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


title: serial port on RPi

text:
# Question
Title: serial port on RPi
In the Arduino IDE on my RPi on the top there is a header that says, File, Edit, Tools and help.

Following a Magpi article it said to go to tools then serial port and change that depending on what board you use. The only problem is that it's not there, when I click tools I scroll down and there **grayed out** it says, serial port.

Why is this grayed out? And why can I not change it? Also, what port should be used for an Uno?

# Answer
> 2 votes
It's greyed out because it can't find any serial ports.

That could be because:

* There aren't any detected (not got the right kernel modules loaded)
* You don't have permission to access the serial ports (are you in the `dialout` group?)

Have you followed the Linux installation instructions? http://playground.arduino.cc/Linux/All

# Answer
> 0 votes
That would require RTFM :)

For the last many years (on various linux variants including rpi) a quick solution is:

```
sudo chmod ugo+rw /dev/ttyACM0

```

after plugging in the arduino.

---
Tags: serial
---


# Question
Title: Problems with controlling LED with soil moisture sensor
I'm a beginner at Arduino.

I have a soil moisture sensor and I mapped the lowest and highest moisture value to a value in between 0 and 100.

What I was trying to do was if the value was less than 50, then the LED should turn on. But even when the value was less than 50 (e.g 25) the LED doesn't turn on.

The moisture detection or the value mapping works perfectly fine.

Does the issue lie on my code or my LED wiring?

Code:

```
int mostMoist = 180;
int leastMoist = 600;
int percent;
int raw;
const int threshold = 50;

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

void loop() {
  raw = analogRead(A0);
  percent = map(raw,leastMoist,mostMoist,0,100);

  if (percent < 0){
    percent = 0;
  }

  if (percent < threshold){
    digitalWrite(LED_BUILTIN,HIGH);
  } else {
    digitalWrite(LED_BUILTIN,LOW);
  }

  Serial.println(percent);
  delay(2);
}

```

# Answer
A good way to start debugging this sort of problem is to print out debug statements that say what the hardware should be doing. If the debug statements print out as expected then it's probably hardware, if not, then it's probably your code, e.g.

```
if (percent < threshold){
  Serial.prinln("LED on.");
  digitalWrite(LED_BUILTIN,HIGH);
}
else {
  Serial.prinln("LED off.");
  digitalWrite(LED_BUILTIN,LOW);
}

```
> 2 votes

---
Tags: sensors, led
---


# Question
Title: How to rotate two or more steppers simultaneously by giving ARRAY of angles?
The following is the code that I am trying but the problem is steppers rotate one after each other. However, I want to rotate steppers simultaneously.
This code for two stepper motors.

```
int pulse=3;

int direc=4;

int pulse1=5;

int direc1=6;

int i,j,k;

float angle[5][3]={{360,360,3},{7,8,9},{11,12,13},{14,15,16},{17,18,19}};

float steps;

void motor1(){

  for(k = 0; k<=4; k++){

    Serial.println(angle[k][0]);

    steps = (1600*angle[k][0])/360;

    Serial.println(steps);

    for(j = 0; j<=steps;j++){

      digitalWrite(3,HIGH);

      delayMicroseconds(100);

      digitalWrite(3,LOW);

      delayMicroseconds(100);
        }

}

}

void motor2(){

  for(k = 0; k<=4; k++){

    Serial.println(angle[k][1]);

    steps = (1600*angle[k][1])/360;

    Serial.println(steps);

    for(j = 0; j<=steps;j++){

      digitalWrite(5,HIGH);

      delayMicroseconds(100);

      digitalWrite(5,LOW);

      delayMicroseconds(100);

        }

}

}

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

  pinMode(3, OUTPUT);
  pinMode(4, OUTPUT);
  pinMode(5, OUTPUT);
  pinMode(6, OUTPUT);
}

void loop(){
    motor1();

    motor2();

   //while(1);
}

```

# Answer
(Half a year ago, but what the hey...)

Your motor1() and motor2() are currently written as:

```
do until done:
  take a step
  wait
end

```

, so yeah, one finishes before the next one even starts.

Each motor function needs to do:

```
if motor's current-position is not the final position,
   if it is time to take a step,
      take a step
      calc when to take another step
      calc motor's new current-position
   end
end

```

Now call your motor functions *as frequently as possible*. Notice that either `if` test can cause the function to return without doing anything - that is *intentional*.

This is non-blocking programming - coding in such a way that *nothing keeps control while waiting for something to happen* (clock ticks, in this case), it just does something, or does nothing, *right now*, if there is or is not something to do right now, but it *does release the processor* (the function returns immediately) whether it did something or not.

I call these functions "maybe-do" functions:

* maybe step a motor (if, and only if, a certain interval has passed, step the motor);
* maybe light an LED (if, and only if, the button is being pressed and it wasn't pressed the last time we looked, turn on the LED;
* maybe read the terminal keyboard (if there is at least one character in the Serial input buffer, collect a character).

Then your loop() function should do *nothing but* call each maybe-do function, in sequence, as *fast as possible*. And it follows from the above that your maybe-do functions need to execute as quickly as possible and do no more than is necessary to (1) decide whether to act, and if so, (2) to carry out its action, and (3) in either case, return immediately.

And - Bang-Boom! - right there is a half-semester course in block-free programming without interrupts!
> 4 votes

# Answer
I can't understand clearly what you want, but maybe you want to drive your two servos simultaneously. To do this, after you determine the angle of servos, you can drive them without delay between their commands.

Like you use above, you can't drive them at the same time, there are loops and they have to be completed before the next instruction is run so your servos wait each other.

Here is a good example code for you:

```
#include <Servo.h>

Servo myservo1;  // create servo object to control a servo
Servo myservo2;  // create servo object to control a servo

float angle[5][3]={{360,360,3},{7,8,9},{11,12,13},{14,15,16},{17,18,19}};

void setup() {
  myservo1.attach(9);  // attaches the servo on pin 9 to the servo object
  myservo2.attach(10);  // attaches the servo on pin 10 to the servo object
}

void loop() {
  for(k = 0; k<=4; k++){
    pos = (1600*angle[k][0])/360; //Calculate the angle which you want

    //The most impportant part, there shouldn't be a delay between them
    myservo1.write(pos);              // tell servo to go to position in variable 'pos'
    myservo2.write(pos);              // tell servo to go to position in variable 'pos'

    delay(1000);                       // waits 1000ms for the servo to reach the position
  }
}

```
> 0 votes

---
Tags: arduino-uno
---


# Question
Title: How to upgrade ESP8266 NodeMCU SDK from V2.5.2 to V3?
ESP.getFullVersion() output:

```
SDK:2.2.1(cfd48f3)/Core:2.5.2=20502000/lwIP:STABLE-2_1_2_RELEASE/glue:1.1-7-g82abda3/BearSSL:a143020Connecting to DO_231455

```

I upload sketches from the Arduino IDE. How do I update the SDK?

I have the flasher tool but I can't seem to find documentation on what to do from this point:

I've downloaded the assets from Github

# Answer
The SDK is linked into every Arduino application you flash to the ESP8266 - it's not flashed separately.

Choose it in Tools menu. It is available only if you select "Generic ESP8266 module".
> 1 votes

# Answer
The SDK is linked into every Arduino application you flash to the ESP8266 - it's not flashed separately.

Presumably you've already followed the instructions to put the URL for the ESP8266 Arduino Core in the preferences for the Arduino IDE.

Once that's there, to update the ESP8266 Arduino SDK, go to the Tools menu, select Board, then select the Boards manager (the first item in the menu).

That will bring up a dialog listing all the board families your Arduino IDE knows how to build for. You can limit the list to those with updates available by selecting "Updatable" in the "Type" field. Or just scroll down or search till you find the ESP8266 entry. Click it and if there's an update available you'll see an "Update" button appear on it. You can also reinstall older versions by choosing a version and clicking the "Install" button.

However, there is no version 3 as yet. At the time that I'm writing this, 2.5.2 is the most recent release of the SDK.
> 0 votes

---
Tags: esp8266, nodemcu, software, espressif
---


title: Arduino Uno Issue: No output power

text:
# Question
Title: Arduino Uno Issue: No output power
I am currently a first time Arduino user. I decided to get one and start prototyping basic types of circuits.

I have built various basic circuits with the Arduino Uno prototype board and it worked completely fine. I am using the Arduino board to source power to my circuit (5V). However, after building the following circuit, everything stopped working:

simulate this circuit – Schematic created using CircuitLab

I don't get output from any of the Arduino pins and I cannot upload programs to the board. The yellow LED still blinks, and the green power LED remains green and active.

I cannot figure out how I managed to burn the board. The current is around 22.72mA, which is pretty far of the 40mA absolute rating.

# Answer
You need to have a current limiting resistor for *each* of the LED segments. Sharing one resistor between them all is a very bad idea, as multiple lit LEDs (in parallel) will be using the same resistor - see this excellent answer to Why exactly can't a single resistor be used for many parallel LEDs?:

> The main reason is because you can't safely connect diodes in parallel.
>
> So when we use one resistor, we have a current limit for the whole diode section. After that it's up to each diode to control the current that goes through it.
>
> The problem is that real world diodes don't have same characteristics and therefore there's a danger that one diode will start conducting while others won't.

I would hazard a guess that you've drawn too much current, or, in your case, tried to sink too much through the PWM pin.

Also, it would (probably) be better to use individual data pins, not PWM pins, to turn on each segment, rather than connecting all of the segments to just one pin. It just seems a bit odd to do it that way.
> 0 votes

# Answer
The schematic you have drawn is completely safe to connect to an Arduino PWM pin. It may not be an optimal choice (closing multiple switches will change the brightness of segments), but it's not dangerous. As you said yourself, the current is limited to a safe value even if there's a dead short in the 7-segment display.

Typically, you burn your board when you connect/disconnect stuff while your Arduino is powered (because intermediate circuits may be unsafe even if the final result is OK), or when you built a circuit which is different from what you *think* you have built.
> 0 votes

---
Tags: arduino-uno
---


title: How to repeat an IF statement

text:
# Question
Title: How to repeat an IF statement
My LCD info is called from an IF statement but since it's clock and temperature info i don't want to just show the information but update the information constantly in real time. i don't want to use (while) loop or any other "code-blocking".

Here's the whole code:

```
#include <OneWire.h>
#include <LiquidCrystal_I2C.h>
#include <DS3231.h>
#include <DallasTemperature.h>

#define ONE_WIRE_BUS 2
int Heater= 3;
int Switch1= 4;

Time t;
LiquidCrystal_I2C lcd(0x27, 16, 2);
DS3231  rtc(SDA, SCL);
OneWire oneWire(ONE_WIRE_BUS);
DallasTemperature sensors(&oneWire);

// Push button

boolean oldSwitchState = LOW;
boolean newSwitchState = LOW;
boolean lcdScroll = LOW;
boolean lcdBacklight = LOW;
boolean lcdWelcome = LOW;

unsigned long previousMillis = 0;
const long BacklightTime = 10000;

void setup() {
  Serial.begin(115200);
  pinMode(Heater, OUTPUT);
  pinMode(Switch1, INPUT);
  lcd.begin();
  rtc.begin();
}
void loop() {
  float testTemp = sensors.getTempCByIndex(0);
  sensors.requestTemperatures();
  t = rtc.getTime();
  if(lcdWelcome == LOW){
      lcd.setCursor(0,0);
      lcd.print("Welcome, Admin!");
      lcd.setCursor(0,1);
      lcd.print("press Start");
  }

  // LCD
  newSwitchState = digitalRead(Switch1);
    if (millis() - previousMillis >= BacklightTime) {
      lcd.noBacklight();
      lcdBacklight = LOW;
    }
    else if ( lcdBacklight == LOW ){
      lcd.backlight();
      lcdBacklight = HIGH;
    }
    if ( newSwitchState != oldSwitchState ) {
       if ( newSwitchState == HIGH ){
       previousMillis = millis();
       lcdWelcome = HIGH;
       lcd.clear();
      if ( lcdScroll == LOW ){
        lcd.setCursor(0,0);
        lcd.print(testTemp);
        lcd.print("   ");
        lcd.print(rtc.getTimeStr());
        lcdScroll = HIGH;
      }
      else{
        lcd.setCursor(0,0);
        lcd.print(rtc.getDOWStr());
        lcd.print("   ");
        lcd.print(rtc.getDateStr());
        lcdScroll = LOW;
      }
       }
       oldSwitchState = newSwitchState;
    }
}

```

How can i update the functions inside the `if(lcdScroll == LOW){}` and `else{}` statements constantly to show on display?

# Answer
Like you suggested in your comment, you can implement a state machine, but the simplest would probably be setting a flag `bool a_flag` in this `if(lcdScroll==LOW)` clause and checking `if(a_flag)` in the highest scope of the `loop()` section. This is where you `print("test");`.

In respect to your code this will look like:

```
bool a_flag=false;
void loop() {
  // some irrelevant stuff
  if ( newSwitchState != oldSwitchState) {
    // some stuff
    if ( lcdScroll == LOW ){
      // stuff you would handle here
      a_flag=true;
    }
    else {
      // stuff you would handle here
      a_flag=false;
    }
  }
  if (a_flag) Serial.println("lcdScroll is LOW");
  else Serial.println("lcdScroll is HIGH");
}

```

Beside this general solution you could simply do the following in your specific case:

```
loop(){

  // your actual code

  if (lcdScroll) Serial.println("lcdScroll is LOW");
  else Serial.println("lcdScroll is HIGH");
}

```
> 2 votes

---
Tags: programming, c++
---


# Question
Title: Dynamic Serial port selection and use without instantiating all Serialx objects
I have an arduino project that reads a config file from SD and then receives data on a serial port that is specifed in the config file.

I therefore need to instantiate the Serial (Serial0), Serial1,..2,3, etc based on dynamic data.

I am using a mega2560 with 4x HardwareSerial. Serial (also Serial0) is the USB. Serial 1, 2, 3 are on specific hardware pins.

I started with code something like:

```
uint8_t InitPort(uint8_t port) {
    switch (port) {
        case 0:
            if(Serial.begin(9600) return 1;
            break;
        case 1:
            if(Serial1.begin(9600) return 1;
            break;

        ... etc...

        default:
            return 0;
}

```

However, this instantiates all Serialx objects (using 157 bytes of data/bss each).

I've since written a class wrapper that takes a referece to the desired serial object as an initialising paramter, but this just pushes the problem up-stack to the calling code.

Is there a way that a Serial object can be instanitated dynamically with a port number passed in, to only end up with one instance connected to the desired port?

# Answer
> 2 votes
You can create an instance of `HardwareSerial` referencing a hardware port that depends on a function parameter, as in

```
void initPort(uint8_t port) {
    switch (port) {
        case 0: {
            HardwareSerial serial(&UBRR0H, &UBRR0L,
                     &UCSR0A, &UCSR0B, &UCSR0C, &UDR0);
            serial.begin(9600);
            break;
        }
        case 1:
            // etc...
    }
}

```

However, since only a local variable can be created in this manner, it is not of much use. Ideally, you would want to have a *global* variable for the serial port, and initialize it in `initPort()`, as

```
HardwareSerial serial;

void initPort(uint8_t port) {
    switch (port) {
        case 0:
            // Invoke fictional init() method.
            serial.init(&UBRR0H, &UBRR0L,
                     &UCSR0A, &UCSR0B, &UCSR0C, &UDR0);
            break;
        case 1:
            // etc...
    }
    serial.begin(9600);
}

```

Alas, this is not possible, as the `HardwareSerial` class has no default constructor. This means that binding the object to the hardware port can only be done when it is constructed.

Short of modifying the Arduino core (adding a default constructor and an `init()` method), the only option I can see is to have the global variable be a *pointer*. Then, in `initPort()` the object is instantiated while initializing the pointer. I tried this approach in the example program below. There was a slight technical difficulty though: since the object files from the core defining `Serial`, `Serail1`, etc. will hopefully *not* be linked to the program, the interrupt service routines defined therein must be also defined in the sketch itself. And since an ISR cannot be bound to an interrupt at run time, the ISRs have to be defined for *all* the ports, even though only one ends up being actually used.

Here is my test program:

```
#include <HardwareSerial_private.h>

HardwareSerial *serial;

ISR(USART0_RX_vect) { serial->_rx_complete_irq(); }
ISR(USART1_RX_vect, ISR_ALIASOF(USART0_RX_vect));
ISR(USART2_RX_vect, ISR_ALIASOF(USART0_RX_vect));
ISR(USART3_RX_vect, ISR_ALIASOF(USART0_RX_vect));
ISR(USART0_UDRE_vect) { serial->_tx_udr_empty_irq(); }
ISR(USART1_UDRE_vect, ISR_ALIASOF(USART0_UDRE_vect));
ISR(USART2_UDRE_vect, ISR_ALIASOF(USART0_UDRE_vect));
ISR(USART3_UDRE_vect, ISR_ALIASOF(USART0_UDRE_vect));

void initPort(uint8_t port)
{
    switch (port) {
        case 0:
            serial = new HardwareSerial(&UBRR0H, &UBRR0L,
                         &UCSR0A, &UCSR0B, &UCSR0C, &UDR0);
            break;
        case 1:
            serial = new HardwareSerial(&UBRR1H, &UBRR1L,
                         &UCSR1A, &UCSR1B, &UCSR1C, &UDR1);
            break;
        case 2:
            serial = new HardwareSerial(&UBRR2H, &UBRR2L,
                         &UCSR2A, &UCSR2B, &UCSR2C, &UDR2);
            break;
        case 3:
            serial = new HardwareSerial(&UBRR3H, &UBRR3L,
                         &UCSR3A, &UCSR3B, &UCSR3C, &UDR3);
            break;
    }
    serial->begin(9600);
}

void setup() {
    initPort(0);
    serial->println("Hello, World!");
}

void loop(){}

```

It should be noted that the ISRs do not take that mush flash space. There are actually only two of them, even though each is referenced four times in the interrupt vector table.

---
Tags: serial
---


title: Serial communication questions

text:
# Question
Title: Serial communication questions
I have to arduino's which are communicate using rx/tx. Arduino1 (A1) send data over serial to Arduino2 (A2). My questions are:

1 - If A1 do Serial.print each 50ms and A2 reading serial each 100ms which value will get A2? For example A1 send "1" and after 50ms send "2". Considering A2 will read serial after 100+ ms it will get "2" ?

2 - If A1 send data each 100+ms and A2 read at 50ms which value will get A2 between? For example A1 send "1" and A2 read "1" when read at 50ms but when it read again after 50ms (during that time A1 didn t sent anything ) will read again "1" ?

Thank you

# Answer
> 1 - If A1 do Serial.print each 50ms and A2 reading serial each 100ms which value will get A2? For example A1 send "1" and after 50ms send "2". Considering A2 will read serial after 100+ ms it will get "2" ?

The Arduino has a 64 byte (software) buffer. You will get the numbers in sequence up until that buffer overflows. Then it's not easy to predict what the results will be.

Probably something like:

121212121\[...\]2121212121212111111111111111

> 2 - If A1 send data each 100+ms and A2 read at 50ms which value will get A2 between? For example A1 send "1" and A2 read "1" when read at 50ms but when it read again after 50ms (during that time A1 didn t sent anything ) will read again "1" ?

If there is nothing in the buffer the read function returns -1. That can be mapped (IIRC) into ASCII (depending on your software) as ÿ so you would get:

```
1ÿ1ÿ1ÿ1ÿ1ÿ...

```

You should read my tutorial on reading serial on the Arduino.
> 0 votes

---
Tags: serial, arduino-nano
---


# Question
Title: Help combining digital and analog code in arduino programming
So I'm making a device that does 3 things,

1. Measures frequency of an audio signal through a microphone
2. Checks whether there is a weight placed on a pressure pad (my pressure sensor works through the resistance of the material changing when a weight is placed on it)
3. Measure ambient room temperature

I have coded each individual section and tested them individually to find them work great, here are the sketches.

Frequency sketch :

```
// runs every time thru the loop
  setInputState();

  // count every transision HIGH<->LOW
  if (inputState != lastInputState) {
    count++;
    lastInputState = inputState;
  }

  if (millis() - previousCountMillis >= countMillis) {
    previousCountMillis += countMillis;

    // show Hz on Serial too if available
    Serial.print(count);
    Serial.println(" Hz");
    ledtest = count;
    // reset to zero for the next half second's sample
    count = 0L;
  }
  if (ledtest >= 400 && ledtest <= 850){
    digitalWrite(A2, HIGH);
  }
  else if (ledtest < 400 || ledtest > 850){
    digitalWrite(A2, LOW);
  }
}

```

Here is the pressure sensor sketch

```
int Vin = 5;
float Vout = 0;
float raw1 = 0;

int R1 = 770;

int R2old1 = 0;

int R2new1 = 0;

int R2avg1 = 0;

int pressurelog = 0;

void setup() {
  pinMode(A0, INPUT);             //Receive pressure voltage
  pinMode(A1, OUTPUT);            //Red led, PRESSURE PAD
}

void loop() {
  raw1 = analogRead(A0);
  Vout = raw1*5/1024;
  R2old1 = Vout*R1/(Vin-Vout);

  raw1 = analogRead(A0);
  Vout = raw1*5/1024;
  R2new1 = Vout*R1/(Vin-Vout);

  R2avg1 = (R2new1+R2old1)/2;

  Serial.print("Resistance: ");
  Serial.println(R2avg1);

  if (R2avg1 >= 1000){
    digitalWrite(A1, LOW);
    pressurelog = 0;
  }
  else if (R2avg1 <= 1000){
    digitalWrite(A1, HIGH);
    pressurelog = 1;
  }
}

```

here is the temperature code

```
float raw = 0;
float tempC = 0;
float tempF = 0;

void setup() {
  pinMode(A5, INPUT);
  pinMode(A1, OUTPUT);
  Serial.begin(9600);
}

void loop() {
 raw = analogRead(A5) * 0.004882814;
 tempC = (raw - 0.5) * 100.0;
 tempF = (180.0/100.0)*tempC + 32.0;

 Serial.print("temp: ");
 Serial.println(tempF);
 delay(1000);
}

```

I coupled the "void loop" of all three and defined everything and ran the code to give a peculiar output. It does the temp and pressure reporting just fine but seems to constantly skip the frequency measurement. It seems to like doing the pressure and temperature measurement like 50 times then do an audio measurement which doesn't make sense as it should do it sequentially.

I TRIED:

1. adding a delay between the frequency measurement and the other two. This didn't work as now the audio measurement work, as it relies on the millis () function
2. adding the 3 components in 3 different functions and calling them sequentially. This results in the exact same stupid output.

Does anyone have an idea or solution?

```
Combined code:

int Vin = 5;
float Vout = 0;
float raw1 = 0;

int R1 = 770;

int R2old1 = 0;

int R2new1 = 0;

int R2avg1 = 0;

int pressurelog = 0;

const byte inputPin = 2;

boolean inputState = false;
boolean lastInputState = false;
long count = 0L;
int ledtest = 0L;

unsigned long previousCountMillis = millis();
const long countMillis = 500L;

void setInputState() {
  inputState = digitalRead(inputPin);
}

int crylog = 0;

float raw = 0;
float tempC = 0;
float tempF = 0;

int templog = 0;

void setup() {
  pinMode(inputPin, INPUT);       //Receive microphone data
  pinMode(A0, INPUT);             //Receive pressure voltage
  pinMode(A1, OUTPUT);            //Red led, PRESSURE PAD
  pinMode(A2, OUTPUT);            //Blue led, FREQUENCY/CRYING
  pinMode(A3, OUTPUT);            //Green led, TEMPERATURE
  pinMode(A4, OUTPUT);            //Red led, MAX WARNING
  Serial.begin(115200);
}

void loop() {
  Serial.println("HI");
  Cryometer();
  delay(2);
  Serial.println("YO");
  Pressure();
  Temperature();

  // WARNING SETUP
  if (pressurelog == 1 && templog == 1){
    digitalWrite(A4, HIGH);
  }
  else {
    digitalWrite(A4, LOW);
  }
}

void Pressure() {
  raw1 = analogRead(A0);
  Vout = raw1*5/1024;
  R2old1 = Vout*R1/(Vin-Vout);

  raw1 = analogRead(A0);
  Vout = raw1*5/1024;
  R2new1 = Vout*R1/(Vin-Vout);

  R2avg1 = (R2new1+R2old1)/2;

  Serial.print("Resistance: ");
  Serial.println(R2avg1);

  if (R2avg1 >= 1000){
    digitalWrite(A1, LOW);
    pressurelog = 0;
  }
  else if (R2avg1 <= 1000){
    digitalWrite(A1, HIGH);
    pressurelog = 1;
  }
}

void Cryometer(){
  // runs every time thru the loop
  setInputState();

  // count every transision HIGH<->LOW
  if (inputState != lastInputState) {
    count++;
    lastInputState = inputState;
  }

  if (millis() - previousCountMillis >= countMillis) {
    previousCountMillis += countMillis;

    // show Hz on Serial too if available
    Serial.print("Frequency: ");
    Serial.print(count);
    Serial.println(" Hz");
    ledtest = count;
    // reset to zero for the next half second's sample
    count = 0L;
  }
  if (ledtest >= 400 && ledtest <= 850){
    digitalWrite(A2, HIGH);
    crylog = 1;
  }
  else if (ledtest < 400 || ledtest > 850){
    digitalWrite(A2, LOW);
    crylog = 0;
  }
}

void Temperature() {
   raw = analogRead(A5) * 0.004882814;
   tempC = (raw - 0.5) * 100.0;
   tempF = (180.0/100.0)*tempC + 32.0;

   Serial.print("Temperature (F): ");
   Serial.println(tempF);
   Serial.println();

  if (tempF >= 75 && ledtest <= 50){
    digitalWrite(A3, HIGH);
    templog = 1;
  }
  else if (ledtest < 50 || ledtest > 75){
    digitalWrite(A3, LOW);
    templog = 0;
  }
}

```

# Answer
Your approach is globally sound. However, the code that measures the input frequency is very time sensitive. Thus, you have to make sure this piece of code is never delayed by anything else. This means that everything in your sketch should be fast and *non-blocking*.

I see a few instances of blocking behaviour you should get rid of: the call to `delay()` and the serial prints. The first is particularly useless, so just remove it. Printing to the serial port is fine as long as you do not try to print *too much*. If you try to print at every loop iteration, you end up filling the output buffer. From there on every print becomes a blocking call: the serial library has to wait for the port to send out the data, until there is enough room in the buffer for what you want to send. The solution is to throttle down the output rate by only printing once in a while. You have done this brilliantly in the frequency-meter code:

```
if (millis() - previousCountMillis >= countMillis) {
  previousCountMillis += countMillis;
  Serial.print("Frequency: ");
  Serial.print(count);
  Serial.println(" Hz");
  // ...
}

```

Now you just have to apply the same technique to *every* instance of `Serial.print()` and `Serial.println()`. Well, maybe the "HI" "YO" could just be removed instead...

Once you remove these blocking behaviors from your sketch, it will probably run fast enough for the frequency counting to perform correctly. There is still something you may want to optimize though: the computations in `Pressure()` are horribly inefficient, especially considering that you have an 8-bit CPU with no hardware floating point support. If you need to average, I suggest you average the analog readings rather than computed resistances. Also note that computing the voltage at the analog pin is completely useless:

```
void Pressure() {
    int raw = analogRead(A0) + analogRead(A0);
    float R = (float) R1 * raw / (2048 - raw);
    // ...
}

```

You may even replace `float` by `long` if you don't need a resolution better than 1 Ω.
> 1 votes

---
Tags: arduino-uno, programming, sensors, analogread, digital
---


title: Arduino USB host + RS232

text:
# Question
Title: Arduino USB host + RS232
I'd like to get a word of advice regarding the subject. Basically there's a COM port based device which I need to connect to an Android tablet via USB. The tablet will be exchanging data packages with the COM device, but a) Arduino may need to do same transformation of the packages b) the tablet should not leverage OTG feature and shouldn't be a master itself.

So, my questions are

1) Which Arduino board is the best fit? 2) Is it an option to use Chinese boards for the sake of cost optimization? 3) Do I need separate RS232 and USB shield or it's ok to leverage built in USB and data pins?

Apology for this quite a noob question but that's exactly who I am for Arduino platform. Appreciate any answers.

# Answer
> 1 votes
> 1) Which Arduino board is the best fit? 2) Is it an option to use Chinese boards for the sake of cost optimization? 3) Do I need separate RS232 and USB shield or it's ok to leverage built in USB and data pins?

When communicating with Android you need to make sure that there is software available for doing the communication. That's really down to the application more than the operating system, and because of that it can be quite restricted what boards will work and what won't.

Personally I would go for either an ATMega32U4 based board which provides a standard CDC/ACM interface. This also has the advantage that the (often single) UART on the board is *not* used by the USB communication.

Then you need to convert the UART into RS232 using (for example) a MAX232 board.

---
Tags: usb, android, rs232
---


title: USing arrays, binary data and bitRead

text:
# Question
Title: USing arrays, binary data and bitRead
This is my first manually typed code. I'm sure there may be some glaring "schoolboy errors" in it, so wondered if people could give it the 'once over' In particular, I have never used C++ arrays, storing binary data within, and then trying to read them bit by bit. In perl, much easier; you would simply use a multi-dimensional something like this:

```
@code1=('10101010', '01010101');
$bit=$code1[0][0] (..through to..) code1[0][7]
$bit=$code1[1][0] ... code1[1][7]

```

So this is my Arduino code. Welcome to suggestions.

```
int pinArray[]={2,3,4,5,6,7,8,9};
int code1[]={B10101010, B01010101,B10101010, B01010101,B10101010, B01010101};
int count=0;
int split=0;    // Counter for the bit loop
int led;    // Store bit data
byte x;     // Used to store the binary data in code1

void setup(){
    for (count=0; count<8; count++){
    pinMode(pinArray[count],OUTPUT); // Sets pinMode as output on pinArray pins
    ]
}

void loop(){
    for (count=0; count<6; count++){
    x=code1[count];
    ledDisplay(x);
    }
}

void ledDisplay(){
    for (split=7; split>=0; split--){
    led=bitRead(x,split);
        if (led == 1){
        digitalWrite(split+2,HIGH);
        }
        else{
        digitalWrite(split+2,LOW);
        }
    }
}

```

Have just modified split as realised bit7 is the leftmost digit. In split, I am adding 2 to the value. Does this need to be enclosed in brackets,ie (split+2) ?

# Answer
There are only two errors I can spot in your program:

1. A block of code should be delimited by curly braces:

```
for (count=0; count<8; count++){
    pinMode(pinArray[count],OUTPUT);
}  // ← ‘}’ instead of ‘]’

```
2. If a function expects to be passed arguments, these should be declared as parameters in the function prototype:

```
void ledDisplay(byte x){  // ← mind the “byte x”
    // ...
}

```

Other than that, here a few suggestions to make the code look nicer, and hopefully more maintainable:

* indent consistently
* use `const` to qualify constants
* use named constants instead of magic numbers
* keep variables local if possible
* note that an int that is either 0 or 1 is equivalent to a boolean
* use `pinArray[]` for accessing the pins

Applying those suggestions, I get the following:

```
const int PIN_COUNT = 8;
const int pinArray[PIN_COUNT] = { 2, 3, 4, 5, 6, 7, 8, 9 };
const int CODE_COUNT = 6;
const int code1[CODE_COUNT] = {
    B10101010, B01010101, B10101010, B01010101, B10101010, B01010101
};

void setup() {
    for (int count = 0; count < PIN_COUNT; count++) {
        pinMode(pinArray[count], OUTPUT);
    }
}

void loop() {
    for (int count = 0; count < CODE_COUNT; count++) {
        ledDisplay(code1[count]);
    }
}

void ledDisplay(byte x) {
    for (int split = 7; split >= 0; split--) {
        if (bitRead(x, split)) {
            digitalWrite(pinArray[split], HIGH);
        } else {
            digitalWrite(pinArray[split], LOW);
        }
    }
}

```
> 2 votes

---
Tags: arduino-uno, array, bit, bytes
---


# Question
Title: Arduino controlled LCD 16x2 is very very dim
I was testing out whether my 16x2 LCD works. I hooked it up to the arduino.

Some white box appeared which probably meant it works fine, but the box and the blue background looked very dim even when the potentiometer was turned to the maximum, and did not have the bright blue background which I saw on google.

FYI I soldered copper wire on the LCD and shoved them onto the breadboard since I did not have any pin headers. Would this be a cause of the problem?

# Answer
I suggest you invest a dollar or so and get some proper wires. Those bare wires, which don't look soldered on, from the top view, just don't cut it. It also looks like the individual wires would short with each other (or are actually shorting).

It will light up when the backlight is correctly connected, which is impossible to tell from your photo.
> 1 votes

---
Tags: lcd
---


# Question
Title: Using use the STM32F103C8T6 board with the Arduino
last two days I am trying to program my blue pill with Arduino IDE, helplessly... Actually, I managed to install simple blink program, but after that, all other attempts ended up with:

> Failed to init device.
> stm32flash Arduino\_STM32\_0.9
>
> http://github.com/rogerclarkmelbourne/arduino\_stm32
>
> Using Parser : Raw BINARY
> Interface serial\_posix: 115200 8E1
>
> An error occurred while uploading the sketch

I crawled internet but no help so far... I followed simply tutorial: https://www.youtube.com/watch?v=K-jYSysmw9w just as this https://github.com/rogerclarkmelbourne/Arduino\_STM32/wiki/Installation, and as I said, first time was problem but finally successfully upload it. However, after that when I wanted some real working program to install failed. All mappings ftdi -\> stm32 are correct, jumper booto is set to 1 mode, for programming, I have required files within /etc/udev/rules.d, stm32 library folder in sketch folder, and yet the error above is happening for a last 20 hours... (I am using Ubuntu 16.04) Please, if anyone point me what is wrong (why first time worked and second wont), or to give me precise steps to perform in order to work, I appreciate.

EDIT: Blinking program works just fine when I move jumper to 0, and supply power via usb.

# Answer
> 0 votes
thanx for help... It turns out that I have been sold crappy additional pins to plugin into breadboard. Even STM32 blink, turns out that one of the tx/rx has no contact with board (probably for microns). However, firmed them altogether without breadboard, and it works...I spent 15 hours with this issue...

---
Tags: uploading
---


# Question
Title: Connecting to WiFi on ESP32 using credentials from SD card
I'd like to use an SD card to provide the login credentials to an ESP32. I've already got the ESP32 reading the relative data from the SD card and storing it as a char array on the ESP, but when I use those arrays in the WiFi.begin function it never connects.

Is this something to do with the way arrays work or am I doing something else wrong?

Respective code:

```
if (dataFile) {
Serial.println("File is available");
while (dataFile.available()) {
  byte currbyte = dataFile.read();
  if (currbyte == 58) {
    reading = 1;    //Begin reading data
    i = 0;
  }
  while (reading == 1 and s == 0) {
    byte currbyte = dataFile.read();
    //Serial.print(currbyte);
    //Serial.println(char(currbyte));
    if (currbyte == 13) {
      s = 1;
      reading = 0 ;
    }
    ssid[i] = char(currbyte);
    i++;
    //Serial.println(ssid);
  }
  while (reading == 1 and s == 1) {
    byte currbyte = dataFile.read();
    //Serial.print(currbyte);
    //Serial.println(char(currbyte));
    if (currbyte == 13) {
      s = 2;
      reading = 0 ;
    }
    password[i] = char(currbyte);
    i++;
    //Serial.println(password);
  }
}
dataFile.close();
WiFi.begin(ssid, password);

while (WiFi.status() != WL_CONNECTED and count < 20) {
Serial.println("Connecting to WiFi..");
delay(1000);
count++;}

```

# Answer
> 1 votes
you add the '\13' to the SSID and password string instead of the terminating zero, because `ssid[i] = char(currbyte);` runs for 13 too

use readBytesUntil()

```
  char ssid[33];
  int l = file.readBytesUntil('\n', ssid, sizeof(ssid));
  if (l > 0 && ssid[l-1] == '\r') {
    l--;
  }
  ssid[l] = 0;

```

---
Tags: wifi, sd-card, esp32
---


title: Stuck with bad sketch

text:
# Question
Title: Stuck with bad sketch
How can I get my programmer board/windows computer to recognize my board again. I am using the esp32 cam and have put two boards in a state where I am unable to flash them anymore. here is the error:

```
serial.serialutil.SerialException: could not open port 'COM5'WindowsError(2,'The system cannot find the file specified.')Failed to execute script esptoolthe selected serial port Failed to execute script esptool

```

I tried reinstalling the drivers and understand that the com port is a separate chip https://gist.github.com/wybiral/2a96c1d1605af7efa11b690586c4b13e

Here is the sketch I used. I uploaded it using the dev module board setting as well as with 80mhz and 112500 speed. I uploaded with 3v and then provided 5v to the board to run the sketch. The sketch runs but prints out gibberish.

Edit:

Here is a schematic of the board https://github.com/SeeedDocument/forum\_doc/raw/master/reg/ESP32\_CAM\_V1.6.pdf

# Answer
> 1 votes
This very much looks like the Serial-over-USB-Driver has chosen another port than COM5 on reconnecting the board. Assuming you are using the Arduino IDE, check whether COM5 still shows up in the Board -\> Port menu -- or, in other words, go there and select the port that is listed there *while the board is plugged in*.

Usually, I'd expect this port to be COM3 on Windows, but that may change when you...

* physically disconnect and reconnect the board too fast (i.e. the driver has not yet shut down the old COM port when a "new device on USB!" event comes in)
* still have the Serial Monitor open when disconnecting and reconnecting (because the driver cannot remove the virtual COM port device while the Serial Monitor has it opened, in which case the driver creates another virtual COM port device on a different number)
* disconnect and reconnect while the esptool process is still working (same reason as above).

It also might help to enable verbose output for compiling and uploading (see preferences dialog in Arduino IDE).

---
Tags: esp32
---


# Question
Title: Outputting 400 mV using Arduino Nano PWM pin
I am trying to output analog voltage (400 mV) using Arduino Nano PWM pins. Is it okay to directly connect (using jumper wires) the PWM pins to the Vin+ of the INA219 current sensor?

I badly need it for my graduation project. Thanks for the help.

# Answer
PWM pins don't output analog voltages. They output pulses of 5V. You then need to average the output in order to get an actual analog voltage out of it. You should be able to use a capacitor and resistor to average out the voltage of the PWM pin, making a low-pass filter. You won't get exactly to 400mV. If I remember correctly the PWM pin has a value of 0 - 255, and 1/255 is 0.0196 V after a good low-pass filter, or 19.6 mV, so `analogWrite(pin,20)` should get close to the 400mV you want.

Another option would be to use a voltage divider to the output to get the output you want. That way you can use the full range of `analogWrite()` in producing the 400 mV and smaller voltages, thus gaining precision. Then again, if all you want is a fixed 0 or 400mV you could accomplish that with a digital output pin and a fixed voltage divider - no need for PWM.
> 2 votes

# Answer
Of course it's possible !

Duncan you made a little error of 10^2 ;)

5V / 1023 = 0.004887.. = 4.88mV

For 400mV you got 400/4.88 = 81.9.

So in the arduino a value of 82 (0-1023) will send you an output of 400.16mV after beeing redressed by a RC filter.
> 0 votes

---
Tags: arduino-nano, pwm, current
---


# Question
Title: How to wire a hall effect sensor to arduino?
it's a UGN3503 hall effect sensor, in some schematics they used a 100uf capacitors and data connected to analog pin and in some a pull up resistor and data connected to digital pin.

as someone new to both electronics and arduino i'm a bit confused on how to wire the sensor to the arduino.

what i want is just simply read the data from sensor and if the number is above or under defined value do something.

do i need a pull up resistor and/or capacitor?

what's the right and standard way to wire a UGN3503 to arduino?

# Answer
> 3 votes
The UGN3503 that you use gives out a analog voltage that changes when there's a magnetic field present. So this sensor needs to be connected to an analog pin.

If there is no field present the voltage is around 2.5Volt. If the south pole of a magnetic field is present the voltage will be higher that 2.5V. With a north pole the voltage will be lower that this 2.5Volt. The amount of higher/lower voltage is based on the strength of the field.

A capacitor near the sensor could help reduce, so called, noise. Though 100µF is too high. I think you mean 100nF (0.1µF).

The pull-up is for other types of hall-effect sensors. Some of these sensors just give a HIGH of LOW output, based on whether a magnetic field is present. Those you connect to a normal input pin.

---
Tags: sensors
---


# Question
Title: Public IP for Arduino with Ethernet shield and Arduino Uno
I'm new Arduino and I would like you to help me. I would like to have a public IP so that anyone can get access to it, not only from domestic domain. What could I do?. I'm using Arduino Uno, Arduino Ethernet Shield w5500 and a RTC. My code:

```
#include <SPI.h>
#include <Ethernet.h>
#include "RTClib.h"
#include <EEPROM.h>

#define time 1
// Enter a MAC address and IP address for your controller below.
// The IP address will be dependent on your local network:
byte mac[] = {0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED};
IPAddress ip(192, 168, 0, 177);

// Initialize the Ethernet server library
// with the IP address and port you want to use
// (port 80 is default for HTTP):
EthernetServer server(80);
//----------------------------------------------------------------------------------------------------------------
 int i=0;
String hora="";
String readString;

RTC_DS1307 RTC;

void setup() {

  pinMode(2,OUTPUT);
  // Open serial communications and wait for port to open:
  Serial.begin(9600);
RTC.begin(); // Inicia la comunicaci¢n con el RTC

RTC.adjust(DateTime(__DATE__, __TIME__)); // Establece la fecha y hora (Comentar una vez establecida la hora)

  while (!Serial) {
    ; // wait for serial port to connect. Needed for native USB port only
  }
  Serial.println("Sistemas Digitales");

  // start the Ethernet connection and the server:
  Ethernet.begin(mac, ip);

  // Check for Ethernet hardware present
  if (Ethernet.hardwareStatus() == EthernetNoHardware) {
    Serial.println("Ethernet shield no se encontro.  No se puede correr el programa sin el hardware. :(");
    while (true) {
      delay(1); // do nothing, no point running without Ethernet hardware
    }
  }
  if (Ethernet.linkStatus() == LinkOFF) {
    Serial.println("El cable Ethernet no esta onectado.");
  }

  // start the server
  server.begin();
  Serial.print("El servidor esta en: ");
  Serial.println(Ethernet.localIP());
}

void loop() {
  // listen for incoming clients

delay(1000);
DateTime now = RTC.now(); // Obtiene la fecha y hora del RTC

  EthernetClient client = server.available();
  if (client) {
    while (client.connected()) {
      if (client.available()) {
//---------------------------------------------------------------------------------------------------------------------------------
        char c = client.read();

if(i==11 || i==12 || i==16 || i==17){
 if(i==16){
  hora +=':';
 }
  hora += c;
}

        if(readString.length()< 100){
          readString += c;
        }
        i++;
        //Este escribe el texto en pantalla letra por letra
        Serial.write(c);

        // if you've gotten to the end of the line (received a newline
        // character) and the line is blank, the http request has ended,
        // so you can send a reply
        if (c == '\n') {
            Serial.println("acabo lectura");

            Serial.println(hora);
             Serial.println(readString);

client.println("HTTP/1.1 200 OK"); // Enviar una respuesta tipica
             client.println("Content-Type: text/html");
             client.println("Connection: close");
             client.println("Refresh: 10");
           client.println();
           client.println("<!DOCTYPE HTML>");
          client.println(" <html lang='en-US'>");
          client.println("<html>");
          client.println("<head><meta charset='UTF-8'><title>Sistemas Digitales</title></head>");
          client.println("<body>");
          client.println("<div style='text-align:center;'>");
client.print("<h1>Fecha y hora del servidor:");
client.print(now.day(), DEC);
client.print('/');
client.print(now.month(), DEC);
client.print('/');
client.print(now.year(), DEC);
client.print(' ');
client.print(' ');
int horini;
horini=now.hour();
String horartc = "0";
if(horini<10){
  horartc += horini;
}else{
horartc= String(horini);
}
client.print(horartc);
client.print(':');
int minuto;
minuto=now.minute();
String mainut;
if(minuto<10){
  mainut='0'+ String(minuto);
}else{
mainut= String(minuto);
}
client.print(mainut);
client.println("</h1>");
client.println("<form method='get'>");
client.println("<br /><h2>¿A que horas le quiere dar de comer al chucho?</h2><br />");
client.println("<input type='time' name='hora'>");
client.println("<br/><h2>que dias lo quiere alimentar?</h2><br />");
//dias en checkbox
//client.println("<label><input type='checkbox' name='cbox1' value='?LunesOn'>Lunes</label><br><label><input type='checkbox' name='cbox2' value='?MartesOn'>Martes</label><br><label><input type='checkbox' name='cbox3' value='?MiercolesOn'>Miercoles</label><br><label><input type='checkbox' name='cbox4' value='?JuevesOn'>Jueves</label><br><label><input type='checkbox' name='cbox5' value='?ViernesOn'>Viernes</label><br><label><input type='checkbox' name='cbox6' value='?SabadoOn'>Sabado</label><br><label><input type='checkbox' name='cbox7' value='?DomingoOn'>Domingo</label><br>");
client.println("<input type='submit' value='Enviar' id='enviar'> ");
client.println("</form>");
if (readString.length() >0) {
Serial.println("hora del rtc");
String horiux = horartc +':'+ mainut;
Serial.println(horiux);
EEPROM.put(0, hora);

if(EEPROM.get( 0, hora ) == horiux){
digitalWrite(2, HIGH);
delay(10000);
digitalWrite(2, LOW);
delay(60000);
}
readString="";
i=0;
hora="";

          client.println("</body>");
          client.println("</html>");

          delay(1);
    // close the connection:
    client.stop();

        }

      }
    }

  }

  }
}

```

There it is a part of the code:

```
IPAddress ip(192, 168, 0, 177);

```

I would like to make that IPto be public domain so you can get access anywhere instead of neededing to be in the same ethernet connection.

Any help would be wonderful, thanks for your time.

# Answer
> 1 votes
There is a discussion about the same topic in Arduino's Forum here. The most valuable comment was this:

> To get an internet static IP address, contact your ISP. You will probably have to pay extra for that. Most people use a dynamic IP service such as www.noip.com to forward traffic to your current internet IP address. You put your dynamic ip address url in your web page so the browser request get routed properly.

I assume (by the address) that you want to do something like this:

> The NAT device might have a port forwarding feature. You can use that. Assume the WAN ip is 198.51.100.1 and the server's ip is 10.1.1.1, the server is listening on port 80. So the port forwarding configuration will be something like : 198.51.100.1 80 ---\> 10.1.1.1 80 From the outside you connect to the public IP - 198.51.100.1 80 When the NAT device receives packet, it forwards it to 10.1.1.1. **more info** here

This is direct copy from source. So in your case WAN IP is the static IP (or another else) that is visible about you outside your network and the private one is that 192.168.0.177 which you used. Like stated in first yellow box, you can use dynamic ip service, too.

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


# Question
Title: Combining code for multiple sensors in one program (Arduino)
I need to operate 2 different sensors (gas and DHT11) simultaneously. I have managed to run each one of them separately and I don't know how to manipulate the code so they could work together.

Here are the sketches:

Gas sensor MQ2 code :

```
int redLed = 12;
int greenLed = 11;
int buzzer = 10;
int smokeA0 = A5;
// threshold value
int sensorThres = 400;

void setup() {
  pinMode(redLed, OUTPUT);
  pinMode(greenLed, OUTPUT);
  pinMode(buzzer, OUTPUT);
  pinMode(smokeA0, INPUT);
  Serial.begin(9600);
}

void loop() {
  int analogSensor = analogRead(smokeA0);

  Serial.print("Concentration: ppm ");
  Serial.println(analogSensor);
  // Checks if it has reached the threshold value
  if (analogSensor > sensorThres)
  {
    digitalWrite(redLed, HIGH);
    digitalWrite(greenLed, LOW);
    tone(buzzer, 1000, 200);
  }
  else
  {
    digitalWrite(redLed, LOW);
    digitalWrite(greenLed, HIGH);
    noTone(buzzer);
  }
  delay(100);

```

This is the DHT11 code :

```
#include <SimpleDHT.h>

int pinDHT11 = 7;
SimpleDHT11 dht11(pinDHT11);

void setup() {
    // start working...
  Serial.begin(9600);
  Serial.println("Temperature and Humidity Data");
}

void loop() {

  delay (250);
  // read without samples.
  byte temperature = 0;
  byte humidity = 0;
  int err = SimpleDHTErrSuccess;
  if ((err = dht11.read(&temperature, &humidity, NULL)) != SimpleDHTErrSuccess) {
    Serial.print("Read DHT11 failed, err="); Serial.println(err);delay(1000);
    return;
  }
  Serial.print((int)temperature); Serial.print(" *C, ");
  Serial.print((int)humidity); Serial.println(" H");

  // DHT11 sampling rate is 1HZ.
  delay(1500);
}

```

# Answer
> 1 votes
You need to combine the 3 major area's of the code, the include/declaration section where files are included and global variables are declared. Then combine the setup() functions and then combine the loop() functions. Ends up looking something like below. However you may have to tweek the timing of your delays

```
#include <SimpleDHT.h>
int redLed = 12;
int greenLed = 11;
int buzzer = 10;
int smokeA0 = A5;
// threshold value
int sensorThres = 400;
int pinDHT11 = 7;
SimpleDHT11 dht11(pinDHT11);

void setup() {
  pinMode(redLed, OUTPUT);
  pinMode(greenLed, OUTPUT);
  pinMode(buzzer, OUTPUT);
  pinMode(smokeA0, INPUT);
  Serial.begin(9600);
  Serial.println("Starting");
}

void loop() {
  int analogSensor = analogRead(smokeA0);
  Serial.print("Concentration: ppm ");
  Serial.println(analogSensor);
  // Checks if it has reached the threshold value
  if (analogSensor > sensorThres)
  {
    digitalWrite(redLed, HIGH);
    digitalWrite(greenLed, LOW);
    tone(buzzer, 1000, 200);
  }
  else
  {
    digitalWrite(redLed, LOW);
    digitalWrite(greenLed, HIGH);
    noTone(buzzer);
  }
  delay(250);
  // read without samples.
  byte temperature = 0;
  byte humidity = 0;
  int err = SimpleDHTErrSuccess;
  if ((err = dht11.read(&temperature, &humidity, NULL)) != SimpleDHTErrSuccess) {
    Serial.print("Read DHT11 failed, err="); Serial.println(err);delay(1000);
    return;
  }
  Serial.print((int)temperature); Serial.print(" *C, ");
  Serial.print((int)humidity); Serial.println(" H");

  // DHT11 sampling rate is 1HZ.
  delay(1500);
}

```

The other way you can do it, which keeps it easyer to read, is move the contents of each main loop into its own function, and then call the two functions from inside loop(). This allows you to easly comment out one of the functions to trouble shoot somthing, or even allow you to call one more often then the other depending upon your needs, (can look at the blink without delay example for how to manage timing)

```
#include <SimpleDHT.h>
int redLed = 12;
int greenLed = 11;
int buzzer = 10;
int smokeA0 = A5;
// threshold value
int sensorThres = 400;
int pinDHT11 = 7;
SimpleDHT11 dht11(pinDHT11);

    void setup() {
      pinMode(redLed, OUTPUT);
      pinMode(greenLed, OUTPUT);
      pinMode(buzzer, OUTPUT);
      pinMode(smokeA0, INPUT);
      Serial.begin(9600);
      Serial.println("Starting");
    }

void loop1(){
   int analogSensor = analogRead(smokeA0);

  Serial.print("Concentration: ppm ");
  Serial.println(analogSensor);
  // Checks if it has reached the threshold value
  if (analogSensor > sensorThres)
  {
    digitalWrite(redLed, HIGH);
    digitalWrite(greenLed, LOW);
    tone(buzzer, 1000, 200);
  }
  else
  {
    digitalWrite(redLed, LOW);
    digitalWrite(greenLed, HIGH);
    noTone(buzzer);
  }
  delay(100);
}

void loop2(){
  delay (250);
  // read without samples.
  byte temperature = 0;
  byte humidity = 0;
  int err = SimpleDHTErrSuccess;
  if ((err = dht11.read(&temperature, &humidity, NULL)) != SimpleDHTErrSuccess) {
    Serial.print("Read DHT11 failed, err="); Serial.println(err);delay(1000);
    return;
  }
  Serial.print((int)temperature); Serial.print(" *C, ");
  Serial.print((int)humidity); Serial.println(" H");

  // DHT11 sampling rate is 1HZ.
  delay(1500);
}

void loop() {
  loop1();
  loop2();
}

```

---
Tags: programming, sensors
---


title: How to modify a created byte?

text:
# Question
Title: How to modify a created byte?
I have created a `byte` for 16x2 LCD. It is basically a custom character which I will have to change later.

```
byte char[8]{
 B10000,
 B01000,
 B00100,
 B00010,
 B00001,
 B11000,
 B11100
};

```

I want to edit the third number from fourth row. So, the fourth row will become `B00110` from `B00010`. Is this possible? Are there any alternatives for this?

# Answer
Well first of all you are trying to name the variable char? which is already a keyword for the variable type of char. But you can access it by the index of the array. Also not sure if you intended to make the array 8 bytes in length, and then only use 7, but thats what you had done in your example

```
//define it all at once
// byte byteArray[8] = {B10000,B01000,B00100,B00010,B00001,B11000,B11100};
//or by index
byte byteArray[8];
byteArray[0]=B10000;
byteArray[1]=B01000;
byteArray[2]=B00100;
byteArray[3]=B00010;
byteArray[4]=B00001;
byteArray[5]=B11000;
byteArray[6]=B11100;

//if you need to change one in the code elsewhere
byteArray[3]=B00110;
//or
byteArray[3]=6;
}

```
> 3 votes

# Answer
You can use the following array initialization:

In the setup I shows how to set a bit. For this, the bit operator or (|) is used. To reset a bit, you can use &. You can set/reset multiple bits this way.

Also you can use 1 \<\< 2 which means 1 (most right bit) shifted left two places (thus B100).

Btw, it is common practice to initialize all values.

```
byte lcd[8] =
{
  B10000,
  B01000,
  B00100,
  B00010,
  B00001,
  B11000,
  B11100,
  B00000  // Also initialize last element
};

void setup()
{
   lcd[3] |= B100; // Set 4th row (element 3), 3th bit (from the right)
   lcd[3] |= 1 << 2; // Alternative
}

void loop()
{
}

```

Explanation about the `or` arithmetics: OR means: if at least one bit is 1, the result is 1, otherwise 0.

Truth table:

```
A | B | A or B
--+---+-------
0 | 0 |   0
0 | 1 |   1
1 | 0 |   1
1 | 1 |   1

```

For your example it means:

```
Original value of lcd[3]: B00010
Or mask (in setup):       B00100
                          ------ OR
Result                    B00110

```
> 2 votes

---
Tags: arduino-nano, lcd, bytes
---


title: 74HC595 shift register not working

text:
# Question
Title: 74HC595 shift register not working
I got my Arduino kit a few days ago and I've been going through some of the tutorials.

I got to the 8 LEDs with a shift register tutorial, where I got stuck. Nothing would light up after I plugged everything in and uploaded the sketch.

This is the circuit I've attempted to recreate using Fritzing, and the following is the code I used, from the tutorial :

```
int tDelay = 100;
int latchPin = 11;      // (11) ST_CP [RCK] on 74HC595
int clockPin = 9;      // (9) SH_CP [SCK] on 74HC595
int dataPin = 12;     // (12) DS [S1] on 74HC595

byte leds = 0;

void updateShiftRegister()
{
  digitalWrite(latchPin, LOW);
  shiftOut(dataPin, clockPin, LSBFIRST, leds);
  digitalWrite(latchPin, HIGH);
}

void setup()
{
  pinMode(latchPin, OUTPUT);
  pinMode(dataPin, OUTPUT);
  pinMode(clockPin, OUTPUT);
}

void loop()
{
  leds = 0;
  updateShiftRegister();
  delay(tDelay);
  for (int i = 0; i < 8; i++)
  {
    bitSet(leds, i);
    updateShiftRegister();
    delay(tDelay);
  }
}

```

I have also attempted to use an 8-segment digit display using the same shift register, also failing.

Is there something wrong that I am doing or could it be that the little chip is broken?

I accidentally discovered that when I swap the ground from pin 8 on the 595 to 5V, all the LEDs will light up.

Update : I got the same circuit in Tinkercad, some kind of Arduino simulator. After dropping in the code and running the simulation, after it lights up the 5th LED, I get this warning :

However, when I change the 220 ohm resistors to something like 500 ohm resistors, that pop-up is gone. Could this be another reason of why my chip could be possible broken at the moment?

# Answer
A few thoughts

Connecting 5v to pin 8 (=gnd) is not a good idea. It may not cause any damage if pin 16(=vcc) is also connected to 5v but i would not rely on that. Generally reverse voltage will kill all electronics unless they are specifically protected against it.

For the LEDs I would use 1k to 10k ohm resistors. This is giving still enough current to see them light up. Using 330ohms just takes more current and makes the leds extremely bright (3mA is enough).

For testing whether something simple is working, like a shiftregister, flipflop, or logic gate, I would not use a microcontroller at all. You can just use a couple of switches attached to the CLK and LATCH pins, with a slide switch attached to the DATA pin to select 1 or 0 input bit. This eliminates one point where stuff can go wrong.

Whether or not you put in a bypass cap will not make a difference if your supply is sufficiently capable and stable. I use the charger of my broken laptop that can deliver 5v at up to 2.5amps. In this setup I don't need any bypassing, although it's still best practise to include it.

Adding LEDs to the serial IN, latch, and shift clock, and serial output may also help nail down the problem.

Also make sure you don't have dodgy cables. If any of the wires is broken or has microscopic internal breaks this can lead to misbehaviour and is very difficult to find.

One thing I did when I tried if my chips worked was to first use a known good chip from a colleague to confirm the circuit was ok.

Depending on where you take your power from, adding a power LED is usually a good idea as well. If you power everything from a powerbank you may find that some of them just shutoff the outputs if there is less than a certain threshold current flowing out. This can leads to effects like "the circuit worked for 30 seconds and then died. After disconnecting and waiting a couple of seconds and repluging the power it works again..." For this reason I include a power LED in just about every project of mine.
> 1 votes

# Answer
The only way i found to make this circuit to work is by putting 8 pullup resistors (1k) from vcc to each of the output pins of the 74hc595 whithout them no leds light up ever.
> 1 votes

# Answer
One omission I see is that you don't have a bypass capacitor across Vcc and Gnd of the 74HC595. Without it you would have inconsistent operation.

But if you had the power reversed on the chip then that will be the major problem and I'm sure the chip is damaged.

What I would do is put leds on the clock, data, and latch lines. And then make your delay very long, 1 second, so that you can see what the lines are doing. Just to confirm that you are getting the output that you expect. But first put a bypass cap across the chip.

Also double check that your leds are in the right way.
> 0 votes

---
Tags: led, hardware, shift-register
---


# Question
Title: Connecting Function Generator to Arduino
I want to send a function generator's signal to an Arduino UNO Analog pin. Can I use an Oscilloscope probe connected to the function generator output BNC, set to 1x to connect to the Arduino headers using jumper wires? I did read through the manuals of the function generator, but couldn't find a solution.

The function generator available is Tenma 72-14110.

# Answer
> 1 votes
Sure, you can connect the function generator to an analog pin of the Arduino. The probe and the jumper wires are just wires here, nothing special. You should also connect the function generators ground to the Arduinos ground (!).

But: Be sure to stay in the Arduinos voltage range (0 to 5V) with the function generators signal. If you apply a higher or negative voltage, you can destroy the Arduino. As long, as you stay inside that range, nothing bad will happen.

# Answer
> 1 votes
As a complement to chrisl's answer, I would recommend putting a 10 kΩ series resistor in series between the function generator and the Arduino.

This is just for safety: if the function generator accidentally goes out of the Arduino's safe voltage range, the resistor will limit the current that flows through the input pin's protection diodes. These diodes are rated to only 1 mA, and a 10 kΩ resistor should greatly expand the range of voltages you can send without frying them.

---
Tags: arduino-uno, signal-processing
---


title: How to stringtok this long string?

text:
# Question
Title: How to stringtok this long string?
I have a string,

"id,port,password,ssid,delay,flag,class,category"

Please tell me how can stringtok this and find out the "flag" value(0 or 1)?

Here is what I tried:

```
void setup()
{
    char input[] = {"id,port,password,ssid,delay,flag,class,category"};
    char *ptr;
    Serial.begin(115200);
    ptr = strtok(input, ",");
    Serial.println(ptr);
    while (ptr != NULL) {
        ptr = strtok(NULL, ",");
        Serial.println(ptr);
    }
}

void loop(){}

```

# Answer
For strings with a fixed format like that (I assume it's a fixed format...) I normally just do a manual strtok of the whole thing into a set of pointers. No need for a loop. You can then just test the last one to see if the whole thing tokenised properly, since if anything before that fails then all other subsequent ones will fail and the last one will have failed.

```
void setup()
{
    char input[] = {"id,port,password,ssid,delay,flag,class,category"};
    char *ptr;
    Serial.begin(115200);

    char *id = strtok(input, ",");
    char *port = strtok(NULL, ",");
    char *password = strtok(NULL, ",");
    char *ssid = strtok(NULL, ",");
    char *delay = strtok(NULL, ",");
    char *flag = strtok(NULL, ",");
    char *class = strtok(NULL, ",");
    char *category = strtok(NULL, ",");
    if (category != NULL) { // Everything up to and including category worked
        Serial.print("Flag: ");
        Serial.println(flag);
    }
}

void loop(){}

```

As an aside: if there is ever a chance any of the fields could be empty ("flag,,category" for example) then you should use `strsep()` instead of `strtok()` as I detail in my tutorial on splitting strings in C.
> 2 votes

---
Tags: arduino-uno, string
---


# Question
Title: cross correlation of two analogread value on arduino?
I am working on a final project called sound source localization using Arduino Uno. I want to use two sound sensor to capture a sound. The nature of the sound is clap or speech sound. I want to use the cross correlation method to estimate the time delay between the microphones then find the position and angle. My supervisor said to me you have to store the values on analogRead in two arrays then cross correlation the element of two arrays. But i am struggle the cross correlation part. I will appreciate any help from you guys.

```
#define LED_NORTH 2
#define LED_SOUTH 4

#define MIC_NORTH A0
#define MIC_SOUTH A2

/* let's said we want to read 100 samples */
const unsigned int numReadings = 100;
unsigned int analogVals[numReadings];
unsigned int i = 0;

void setup() {
  Serial.begin(115200);
  pinMode(LED_NORTH, OUTPUT);
  digitalWrite(LED_NORTH, LOW);
  pinMode(LED_SOUTH, OUTPUT);
  digitalWrite(LED_SOUTH, LOW);
}

void loop() {
  int north = analogRead(MIC_NORTH);
  Serial.println(north);
  int south = analogRead(MIC_SOUTH);
  Serial.println(south);
  /* take numReadings # of readings and store into array */
  for(unsigned int i = 0; i < numReadings; i++)
  {
    analogVals[i] = analogRead(A0);
    delay(1000);
  }

```

# Answer
> 2 votes
I am not going to directly answer the question, as I think it is ill-posed. Before posting a question here, you are supposed to have done your research, and come with very *specific* problems you cannot solve by your own. I may be mistaken, but it looks to me like you are at a very preliminary stage where you barely started to *think* about the project.

So, instead of trying to answer an overly broad question, I will try to provide some guidance by asking questions back to you. Below is a list of some problems and challenges you will have to consider for advancing your project. It may not be complete: it's just what I can think off the top of my head. This will hopefully help you tackle the right problems.

## Non-stereo sampling

Your Arduino is incapable of stereo sampling. Since it has only one ADC, it can only sample one channel at a time. This means you will have to alternatingly sample the left channel, then the right channel, then the left channel... Since the left and right samples are not taken at the same time, this will have an implication on how you interpret the results from the cross-correlation. Did you think about how you will handle this? Is this acceptable? Will you have to instead use external ADC chips in order to have real stereo sampling?

## Slow sampling rate

If you `analogRead()` in a tight loop, you are taking at most one sample every 112 µs. And since you are alternating between the channels, on each channel you get one sample every 224 µs. This is a sampling rate of 4.46 kHz, and a Nyquist frequency of 2.23 kHz. Is this fast enough for your application?

In 224 µs, the sound travels about 76 mm, which is thus the spatial resolution of your cross-correlation. How does this translate into angular resolution? Is this resolution satisfactory? Do you plan to use interpolation methods to try to improve it?

If the time resolution is not good enough, you can speed up the ADC by a factor 2 or 4 at the cost of lowered accuracy. You will have to dig on the MCU datasheet (or the Internet...) in order to learn how to do that.

## Inconsistent sampling rate

When you use `analogRead()`, the time between consecutive samples can depend on the code you run between the consecutive calls to `analogRead()`. It can also depend on how your code gets interrupted by, say, the timer interrupt, or the UART interrupt if you are sending data out. An inconsistent sampling rate is something you want to avoid when doing cross-correlations.

You could try to mitigate this problem by running the acquisition with interrupts disabled. However, the only way to guarantee periodic sampling is by configuring the ADC to be triggered automatically, either by a timer or by itself (free running mode). Walking this path will require you to forego the comfort of the Arduino library (`analogRead()` is just so easy to use...), and carefully study the datasheet, which would be a very significant time investment.

Do you have the time and energy for this? If you end up learning all this low-level details on the configuration of the ADC, will this learning be relevant to the course for which this is a project?

## Finite data arrays

Mathematically, the cross-correlation is typically defined for infinite series of samples. In your experiment, you will have to deal with finite arrays, and this makes a subtle difference. Did you think about how you will deal with the finiteness of the arrays? Are you going to zero-pad? Remove the average before zero-padding? Apply a windowing function?

---

I hope it is clear by now that the “cross correlation part” is only one of the many issues you will have to face. I suggest you discuss all these questions with your supervisor. He might be able to advise you on how to tackle them, whether it's worth it, where you may cut corners...

---
Tags: arduino-uno
---


# Question
Title: How do I feed NRF24L01 from Arduino Pro Mini?
I wanted to control speed of my four coreless DC motors using Arduino Nano. Then I realised my 3.7V 380mAh 25C and 720mAh (110mAh on picture is just to hold my battery's place) 25C LiPo batteries won't meet the voltage requirement of a Nano. Then I came up with the idea of using Pro Mini instead of Nano; however I couldn't find a 3.3V pin on Pro Mini to feed NRF24. On Nano, I was using a 3.3V pin and 10uF capacitors between Vin and Gnd legs of NRF24.

So my question is: can I feed NRF24 directly from Vcc pin? Or as an alternative what would happen if I fed NRF24 directly from battery and reduce 3.7V to 3.3V via another TIP122 transistor?

Note: I am using 4 of TIP122 transistors whose gate legs are connected to Pro Mini's 5, 6, 9 and 10 pwm pins (I forgot to add base-resistors). Do you also think it is a reliable way of controlling the motors' speed?

# Answer
> can I feed NRF24 directly from Vcc pin?

NO: the pro mini is either 5V or not strong enough to power the RF24. EDIT: the 3V3 pro mini "could" power the RF24 via VCC, if you use the cap and if it's not the PA&LNA model (or in full power mode). Best practise is to use an external regulator.

> if I fed NRF24 directly from battery and reduce 3.7V to 3.3V via another TIP122 transistor?

NO: lipos are 4.2V when fully charged, and they can be used until 3V (I mean 3V sag voltage, when the load is powered, not when disconnected): External 3V3 regulators is the way to go.

> Do you also think it is a reliable way of controlling the motors' speed?

These are PWM output, so yes, why not? Also, add flyback/freewheeling diodes (and -maybe- 100nF polyester caps should help) between the motors terminals.
> 2 votes

---
Tags: arduino-pro-mini, nrf24l01+
---


title: 20x4 LCD shows up as 20x2

text:
# Question
Title: 20x4 LCD shows up as 20x2
I need help with my LCD. I have a 20x4 LCD and it shows up as 20x2. The LCD address said "// Set the LCD address to 0x27 for a 16 chars and 2 line display". I changed it which says "// Set the LCD address to 0x27 for a 20 chars and 4 line display" and uploaded it, thinking it would show up as 20x4 as it should. But it didn't work:

# Answer
> 3 votes
Nori, just ignore every code that's after the //, they are just comments and the compiler will just discard them.

Look at the LCD rear, you should see your I2C chip, search google typing \["chip's code" 20x4 arduino\]. You'll see which I2C address you most likely need to use. For instance, the PCF8574 has addresses fromm 0x20 to 0x27, the PCF8574A has addresses from 0x38 to 0x3F...

Without this info you are only shooting blindfolded, the 0x27 it's only the "standard" address of the most common PCF8574 module but there are plenty of modules.

Another way to find the address is to upload this code, it's an I2C scanner that will write on the serial monitor any I2C device that replies a "ping" signal.

If you find the address and still it doesn't work or if you can't find the address, check and double and triple check the wiring, especially the false contact.

---
Tags: lcd
---


title: Activating a Relay with Wemos D1

text:
# Question
Title: Activating a Relay with Wemos D1
I have a problem similar to these questions:

Wemos D1 doesnt drive Relay

Wemos D1 is not triggering Relay

I got this BC548B transistor from an old apparatus I scratched. The transistor saturation voltage is 0.6V according to the datasheet:

https://alltransistors.com/pdfdatasheet\_fairchild\_semi/bc548\_bc548a\_bc548b\_bc548c.pdf

When I set up my circuit the wemos d1 inboard leds dim and the board resets so I guess something is going really wrong. Can someone advise if my design makes sense?

# UPDATE

I replaced the 12V relay with a 5V one but still can't get it to work. Basically, the 3.3V signal seems to be too low to activate the solenoid. How can I raise the 3V3 signal to 5V? What was wrong with my idea of using a transistor to do it?

# Answer
> 2 votes
That appears to be a 12 "solid state" relay. That means that it is designed to be both powered by and switched by 12V. You're trying to drive it with slightly more than 1/3 of its rated voltage. Don't do that.

## Edit:

Note that none of the relays being discussed are true solid state relays. These are are all conventional coil relays that include cicuitry that allows them to be driven by CMOS logic signals. A true solid state relay does not have any moving parts, but uses solid state components to do the job of a relay. Those cost significantly more money however.)

---

It might be that you can get away with driving a 5V solid state relay with 3.3V, or 12V relay with 5V, but you shouldn't do those things either.

Also note that even if you are using the correct relay, your relay almost certainly takes more current than the 5V pin on an Arduino can provide (When driven from USB, the entire system is limited to 500 mA, including the power needed to the Arduino.)

## Edit:

These solid state relays come in 12V, 5V, and 3V flavors. Get a 3V one: https://www.adafruit.com/product/3191?gclid=EAIaIQobChMIyY\_dxM344gIVELbICh1ufwivEAQYBSABEgI3wPD\_BwE

---
Tags: esp8266, relay
---


title: RTClib library the second, second

text:
# Question
Title: RTClib library the second, second
I'm using RTClib for my DS3231 module, the problem is the library is displaying the second without zero behind it: `22:1:1` and when i print the time on my 16x2 LCD time is displaying like this:

> 22:22:59
>
> 22:23:19
>
> 22:23:29
>
> ...
>
> 22:23:59
>
> 22:23:10
>
> 22:23:11

the second number of seconds is not getting cleared. i know one solution to this is to use `lcd.clear()` function to update the LCD in each loop but is there any other way to clear that second number or do something so library show zero behind second?

# Answer
It's your responsibility to format the time properly, not the library. The library just gives you a number. If you want a leading zero then it's up to you to provide that leading zero.

For example:

```
if (now.seconds() < 10) {
    lcd.print("0");
}
lcd.print(now.seconds());

```

Or:

```
char timestr[9];
snprintf(timestr, 9, "%02d:%02d:%02d", now.hours(), now.seconds(), now.minutes());
lcd.print(timestr);

```
> 1 votes

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


# Question
Title: Can an Arduino Pro Mini interface with a full-sized WiFi shield?
We have an Arduino Pro Mini on a breadboard connected to a 9V battery and a sensor, reading data. We also have a full-sized Adafruit WINC1500 WiFi Shield with PCB Antenna. I would like to know if they can be connected and, if so, how.

I understand that a shield is usually stacked on a similarly sized board, but can we place the shield on the breadboard with the Mini and use jumper wire to connect the necessary pins so the Mini can use the WiFi (actually, we want to write to the SD card on the WiFi shield)? If so, how would we know which pins are used, and would we need to provide additional power? Or is connecting a Mini to a full-sized shield a ridiculous idea?

# Answer
> 3 votes
> I would like to know if they can be connected and, if so, how.

Yes.

> but can we place the shield on the breadboard

No, the pins are misaligned and won't plug in.

> and use jumper wire to connect the necessary pins so the Mini can use the WiFi

Yes - connect the jumper wires directly to the WiFi shield pins.

> If so, how would we know which pins are used,

Read the manual or schematic for your WiFi shield. It probably uses the SPI pins plus a few more.

> and would we need to provide additional power?

It will need a power connection, yes - though "extra" power? Not sure what you mean.

---
Tags: shields, arduino-pro-mini, wires
---


# Question
Title: Is it possible to execute a code in runtime when gets updated over the air (OTA)?
I would like to build a lib like ArduinoOTA but with no downtime at runtime. To achieve that I am wondering if it is possible to create a simple setup and loop code to

1. Check for new releases
2. If we have a new one start download it
3. As download routine is not finished keep running the current release
4. When download has finished, swap current release to the new one.
5. Now the normal routine is running the new release.

I am pretty interested if it is possible to do by myself something like that.

I didn't find any paper or articles similar to this and I don't known if this is a challenge for Arduino scope or C/C++.

Maybe I am saying something bizarre but I have been thinking of save new release into flash memory, point to it and discard the old release from flash memory.

# Answer
On many Arduinos the processor is only a few dollar part. You are asking for a feature that only starts appearing on platforms where the processor is over an order of magnitude higher in price. Further, such inexpensive processors normally run a single program. Running a sketch while managing a download & update would best be done by two programs existing in an operating system. Again, likely requiring a processor an order of magnitude higher in price.

Instead, consider implementing your design using two different Arduinos. Swapping one out for the other after updating. Hot swapping may not be trivial. This really depends on how your application interfaces with the world. But likely will be much easier than solving the problem of designing the supporting software to make sketch updates transparent to the Arduino user.
> 2 votes

---
Tags: programming, eeprom, flash
---


title: Garage door button with delay feature

text:
# Question
Title: Garage door button with delay feature
I am working on an art project that involves a garage door opener. I am very new to Arduino, and electronics. I have a starter kit with a ton of accessories.

The garage door opener has 2 screws (terminals?) designed to connect a button. If I touch a wire between them, the opener will start. I connected a button to my bread board, and ran wires to those terminals on the opener to see if a simple switch would work, and it does.

I want to:

1. press a button, and the Arduino connects the terminals on the opener, and then it starts
2. button is then ignored (delayed) for a set amount of time (5 seconds for this example)
3. after the set amount of time, the button works as normal (like in step 1)

I ran through some tutorials on buttons, and I think I got ahead of myself.

* I can turn on an LED from a switch on the bread board, and use a `delay(5000)` to ignore any other button presses. I tried to connect the wires that were going to LED to the 2 terminals on the garage door opener, and it did not work
* In code, I setup pin 5 as OUTPUT, and pin 6 as INPUT. I used the button to send a HIGH on pin 5, to see if that signal would work when connected to the 2 terminals on the opener. I tested this a bit in code by reading the state of pin 6, and it appears to have worked. However, it did not work when I connected both pin 5 to one terminal, and pin 6 to the other.

I tried looking for a simple example, but searching for garage door openers and Arduino results in too many tutorials on how to do super fancy wireless stuff. I just want to ignore a button press for 5 seconds after it has been pressed once.

I'm looking for a simple example that allows my button to tell the Arduino to make that connection on the garage door opener. I guess I'm looking for my Arduino to act like a switch instead of my (physical) switch?

My Arduino kit comes with a bread board, wires, switches, Uno R3 and tons of other stuff I haven't gotten to yet. I apologize in advance if I'm not thinking of something super-simple that would solve my problem. I'm very new to this.

Thanks for your time!

Edited for spelling. Elaborated on my attempts. I'm going to read about what a relay is.

# Answer
I figure out a solution - I just needed to use a relay.

I didn't know what a relay was, and had a hard time figuring it out. I've included some notes for anyone who finds this post in the future.

* I can't determine if it took reading 3-4 articles on relays for it to sink in, or if one article was the best. Anyway, for me this one helped the most: https://www.instructables.com/id/How-Electronic-Switches-Work-For-Noobs-Relays-and/
* My relay looked different from most of the tutorials. I figured it out by connecting a couple alligator clips to a 9v battery and listening for the click of the magnetic switch. Then I used my volt meter to determine which leads were working with the relay.

Relay Setup:

* I connected my ~5 to one lead on the relay, and 5v to the other
* The Common (middle) lead connects to one terminal on the garage door opener
* The N/C (Normally Closed) lead connects to the other terminal on the garage door opener

Button Setup:

* The button setup was just like all the other button tutorials
* When the button is pressed (LOW), I start and stop the relay to trigger a "button press" for the garage door opener (it starts)
* I then run a `delay` for the set amount of time I want
* All button presses are ignored until after the `delay` has finished

Now I can move on to the actual project. Thanks!
> 2 votes

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


title: DS3231 and EEPROM

text:
# Question
Title: DS3231 and EEPROM
Currently to get time/date i'm using DS3231 module with the RTClib library, i want to use the Atmel 24C32 chip on the module to store some small values (temperature etc).

Can i use the current library AND an external EEPROM library (which one?) OR i need to change my RTC library in order to use EEPROM feature?

# Answer
> Can i use the current library AND an external EEPROM library (which one?)

Yes. Devices on an I2C bus are separate devices and use their own separate libraries.
> 1 votes

---
Tags: eeprom, rtc
---


# Question
Title: What is the use of reserved pins and SDD2, SDD3 pins of the NodeMCU?
How to use the reserved pins on the NODEMCU? What is their use? Also what is the use of SDD pins?

Thanks.

# Answer
The ESP8266 uses an external flash memory chip to store your program. It communicates with this flash chip over a 4 bit SDIO interface, on GPIO6-11. These pins are labeled SDDn, SDCLK and SDCMD.
Usually, the interface uses all 4 data lines (QIO), but you can also configure it to use only 2 of the 4 lines (DIO), giving you access to two more GPIO pins (9 & 10).
The reserved pins are not mentioned in the schematic. They cannot be IO pins, because there simply are no other pins on the ESP8266/ESP-12. It could be pins connected to the USB chip, connected to power lines, or not connected at all. The designers probably wanted to allow for extra pins on next iterations of the board, without changing the form factor. A quick search online didn't yield any results, so your best bet is to trace the connection on the PCB, or measure it with a multimeter. You probably shouldn't be using them anyway, because they are "reserved".
> 2 votes

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


title: Get 5V output from NodeMCU

text:
# Question
Title: Get 5V output from NodeMCU
I have a sensor that requires used of 5V as input to Vcc. But I dont see any 5V output pins on the NodeMCU 1.0(12E). Is there a way I could get 5V output pins?

Its not a duplicate question. I want a 5V output and not provide 5V input to NODEMCU.

# Answer
> 3 votes
The `VIN` pin outputs 5V approximately (dependent on USB input voltage) from the NodeMCU board.

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


title: ESP8266-01 is not working and it's hot

text:
# Question
Title: ESP8266-01 is not working and it's hot
it has been so long since I tried to connect the esp8266 through Arduino Uno and get it to work my goal is to send data from the Arduino Uno to web site, I have tried everything and a lot of codes but none worked at first I could get a response but sometimes it does and sometimes it does not I even bought an other one but the new one did not respond at all so I flashed the old one following the instructions in here and I got response the next day I tried to reuse it and it does not respond at all not even when I put the serial on 115200 and both NR&CR and tried AT but nothing showed in return .i found this tutorial and I tried to get it to work using a mobile app but as usual, it does not work

```
AT
AT+RST
ATE0
AT+CWMODE=1
AT+CWQAP
AT+CWDHCP=1,1
AT+CWJAP="RemoteXY","12345678"

```

but i did not get hte name of it wifi in my wifi list
this is the code

```
// RemoteXY select connection mode and include library
#define REMOTEXY_MODE__ESP8266_HARDSERIAL

#include <RemoteXY.h>

// RemoteXY connection settings
#define REMOTEXY_SERIAL Serial
#define REMOTEXY_SERIAL_SPEED 115200
#define REMOTEXY_WIFI_SSID "RemoteXY"
#define REMOTEXY_WIFI_PASSWORD "12345678"
#define REMOTEXY_SERVER_PORT 6377

// RemoteXY configurate
#pragma pack(push, 1)
uint8_t RemoteXY_CONF[] =
  { 255,2,0,0,0,30,0,8,13,0,
  2,0,70,25,22,11,2,26,31,31,
  79,78,0,79,70,70,0,1,0,10,
  26,12,12,2,31,88,0 };

// this structure defines all the variables of your control interface
struct {

    // input variable
  uint8_t switch_1; // =1 if switch ON and =0 if OFF
  uint8_t button_1; // =1 if button pressed, else =0

    // other variable
  uint8_t connect_flag;  // =1 if wire connected, else =0

} RemoteXY;
#pragma pack(pop)

/////////////////////////////////////////////
//           END RemoteXY include          //
/////////////////////////////////////////////

#define PIN_SWITCH_1 2
#define PIN_BUTTON_1 12

void setup()
{
  RemoteXY_Init ();

  pinMode (PIN_SWITCH_1, OUTPUT);
  pinMode (PIN_BUTTON_1, OUTPUT);

  // TODO you setup code

}

void loop()
{
  RemoteXY_Handler ();

  digitalWrite(PIN_SWITCH_1, (RemoteXY.switch_1==0)?LOW:HIGH);
  digitalWrite(PIN_BUTTON_1, (RemoteXY.button_1==0)?LOW:HIGH);

  // TODO you loop code
  // use the RemoteXY structure for data transfer

}

```

i wired it like this

one last thing is it gets hot every time so what could be the problem what's wrong with is what should I do

# Answer
> 3 votes
when a chip gets hot as soon as the VCC/GND is connected, it means :

1. **The VCC/GND are internally connected due to a previous failure** (it gets hot AFTER the accident).
2. **An output pin, is connected to a supply rail through a very low resistance load (or short circuited).** pins usually sink or source as low as 20mA of current. so if you connect them to a load less than (3.3/20)\*1000 ~= 150 ohms (in your case with 3.3v supply), you are going to fry the output driver. always be sure that a pin, even if it's defined as an input, has a little resistor (a 220 ohms res). this accident happens between output/supply or output/output pins.

you may have misconnected TX pin to a wrong pin.

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