title: Random number/sequence output

text:
# Question
Title: Random number/sequence output
The program I'm trying to build is:

1. Type in 1st name, hit enter, type in 2nd name and then hit enter again.
2. Register those names from string input to char `naming` in `student` struct.
3. Print out the names in serial monitor.
4. Use those names in the main program.

The problem is I got randomize results whenever I typed in the names.

My target output:

```
Program Starts
Insert 2 students name:

First student: Adam     //When input -> Adam
Second student: Eve     //When input -> Eve
First student: John    //When input -> John
Second student: Amy    //When input -> Amy
//the sequences should repeat

```

...but what happened is the sequences of the names randomized. For example:

```
Program Starts
Insert 2 students name:

First student: Adam
First student: Eve
Second student: John
First student: Amy
//the sequences will keep randomizing

```

Can anyone point out what I've missed out?

The program:

```
typedef struct
    {
        char naming[20];
    }student;

    student record[]{
      {""},
      {""},
    };

    String readString;
    String str="";

    // the setup routine runs once when you press reset:
    void setup() {
      Serial.begin(9600);    // initialize serial communication at 9600 bits per second
      while (!Serial);              // wait for Serial Monitor to open
      SerialUSB.println("Program Starts \n Insert 2 students name:");  // Title of sketch
    }

    void loop() {
        namedata();
        mainprg();
    }

    void namedata()
    {
    for(uint8_t i = 0; i < sizeof(record)/sizeof(student); i++){
          while (Serial.available()) {
            char c = Serial.read();
            readString += c;
            readString.trim();
          }

          if (readString.length() >0) {
            str = readString;
            str.toCharArray(record[i].naming,20);
            if(i==0){
               Serial.print("First student: ");
            }else if(i==1){
               Serial.print("Second student: ");
            }
            Serial.println(record[i].naming);
          }
            readString="";
        }
    }

    void mainprg()
    {
      //main program using student`s name
    }

```

Additional infos:

1.Why use struct? Because I've more data to process/store for one "student" in my main program. 2.Currently using Arduino Yun Mini, Arduino 1.8.7

Thanks in advance!

# Answer
> 1 votes
Even though this is not elegant by any means, for now this is what I've came out with:

```
typedef struct
{
  char naming[20];
} student;

student record[] {
  {""},
  {""},
};

int a = 0;

char buf[20];

// the setup routine runs once when you press reset:
void setup() {
  Serial.begin(9600);    // initialize serial communication at 9600 bits per second
  while (!Serial);              // wait for Serial Monitor to open
  Serial.println("Program Starts \n Insert 2 students name:");  // Title of sketch
}

void loop() {
  if (readline(Serial.read(), buf, 20) > 0) {
    if (a == 0) {
      Serial.print("First student: ");
      strncpy(record[a].naming, buf, 20);
      Serial.println(record[a].naming);
      a = 1;
    }
    else if ( a == 1) {
      Serial.print("Second student: ");
      strncpy(record[a].naming, buf, 20);
      Serial.println(record[a].naming);
    }

  }
}

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

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

```

Basically by using `int a`, the program decides the sequences of the name. Although it will not repeat the sequence after the 2nd input (ie 1st\>2nd\>1st\>2nd), at least the sequence is not randomize anymore.

Btw thanks for the tips @chrisl!

---
Tags: serial, c++, c
---


title: please help with my arduino

text:
# Question
Title: please help with my arduino
My problem is when I run code like this:

```
char directioN;

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

void loop()
{
  if (Serial.available())
  {
    directioN = Serial.read();

    switch (directioN)
    {
      case 'F':
        break;

      case 'B':
        break;

      case 'R':
        break;

      case 'L':
        break;

      default :
        break;
    }

    Serial.print("direction is:");
    Serial.println(directioN);
  }
}

```

My serial monitor add another input, but the second one is empty; this happened here with char both as with int.

But when i tried the same code in tinkercad it worked fine.

So do I really need a new ATMEGA328 or it can be done by software or something?

\**I use an Arduino Uno

# Answer
> 0 votes
So why you don't just ignore it?

```
if(directionN >= 32){   //check if char is readable ascii character
  Serial.print("direction is:");
  Serial.println(directioN);
}

```

---
Tags: arduino-uno, atmega328
---


# Question
Title: How to use millis instead of delay on Arduino for independent time intervals for two output pins
I wanted to use millis for the code below but stuck in between . can anyone help to change the given code to millis? Code here:

```
    void set(){
    digitalWrite(on, HIGH);   // turn the motor on (HIGH is the voltage level)
  delay(1500);
  digitalWrite(on, LOW);
  delay(ont);               //waits for given time
  digitalWrite(off, HIGH );    // stop the motor
  delay(500);
  digitalWrite(off, LOW );
  delay(offt);                  //wait for different

```

# Answer
Here is the code for changing pin value without delay. Read it and try it.

```
#define on 2
#define off 3

//delay times
const unsigned int ont = {1500,  500};
const unsigned int offt = {500, 300};

//last millis
unsigned long last_tm_on = 0;
unsigned long last_tm_off = 0;

//position
byte pos_on = 0;
byte pos_off = 0;

void setup(){
  pinMode(on, OUTPUT);
  pinMode(off, OUTPUT);
}

void loop(){
  if(millis() - last_tm_on >= ont[pos_on]){   //check if millis() - last millis() is bigger than wanted time
    last_tm_on = millis();   //save last millis()
      if(pos_on == 0) digitalWrite(on, HIGH);
      if(pos_on == 1) digitalWrite(on, LOW);

      pos_on ++;   //add position
      if(pos_on > 1) pos_on = 0;   //check max position
  }

 if(millis() - last_tm_off >= offt[pos_off]){
    last_tm_off = millis();
      if(pos_off == 0) digitalWrite(off, HIGH);   // turn the motor on (HIGH is the voltage level)
      if(pos_off == 1) digitalWrite(off, LOW);

      pos_off ++;
      if(pos_off > 1) pos_off = 0;
  }
}

```
> 0 votes

---
Tags: arduino-nano, millis
---


title: firebase arduino uno + esp8266

text:
# Question
Title: firebase arduino uno + esp8266
I am trying to make a project that can read data from usbsheild connected to arduino uno board then send them to firebase through esp8266. But the libraries of firebase and esp8266wifi that i found are not for arduino uno but for the esp8266 board can anyone help me in this problem ?

# Answer
**The best way you can do is connect it to a web and then use firebase-php library**

> https://github.com/ktamas77/firebase-php/blob/master/README.md

*insert this*

**Follow this as your guide**

> https://stilllot2learn.wordpress.com/2017/11/18/arduino\_gps\_gsm/comment-page-1/#comment-47

**Don't forget to create your FIREBASE ACCOUNT**

> look for **database secret** as your TOKEN under User and Permissions TAB
> 1 votes

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


# Question
Title: How to trigger NodeMCU sketch from Arduino Leonardo Micro Pro?
So this is probably a very simple question. I have my NodeMCU set up and working where it connects to wifi and sends a push notification. Currently it does that automatically when connected to power.

What I want to do is connect it to my Leonardo Micro so that at a part in the Leonardo sketch it sends a signal to the NodeMCU to run the sketch to trigger the push notification. So simply, which ports should I connect and what code should I change.

Here is my working NodeMCU code.

```
    #include <ESP8266WiFi.h>

// Wifi Settings
const char* ssid = "MySSID";
const char* password = "MyPassword";
// Pushover settings
char pushoversite[] = "api.pushover.net";
char apitoken[] = "MyAPIToken";
char userkey [] = "MyUserKey";
int length;
WiFiClient client;
void setup() {
  Serial.begin(9600);
  delay(10);

  // Connect to WiFi network
  Serial.println();
  Serial.println();
  Serial.print("Connecting to ");
  Serial.println(ssid);

  WiFi.begin(ssid, password);

  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println("");
  Serial.println("WiFi connected");

  // Print the IP address
  Serial.print(WiFi.localIP());

}

void loop()
{
 pushover("OMG, Yes it works!!!");
 delay(60000);
}

byte pushover(char *pushovermessage)
{
 String message = pushovermessage;

 length = 81 + message.length();

if(client.connect(pushoversite,80))
 {
   client.println("POST /1/messages.json HTTP/1.1");
   client.println("Host: api.pushover.net");
   client.println("Connection: close\r\nContent-Type: application/x-www-form-urlencoded");
   client.print("Content-Length: ");
   client.print(length);
   client.println("\r\n");;
   client.print("token=");
   client.print(apitoken);
   client.print("&user=");
   client.print(userkey);
   client.print("&message=");
   client.print(message);
   while(client.connected())
   {
     while(client.available())
     {
       char ch = client.read();
       Serial.write(ch);
     }
   }
   client.stop();
 }
}

```

And my Leonardo code

```
#include <Keyboard.h>
#include <Mouse.h>
char returnKey = KEY_RETURN;
char tabKey = KEY_TAB;
void setup() {
  Keyboard.begin();
  Mouse.begin();

  delay(4000); //Testing Delay
// Language Select Screen
  Keyboard.write(returnKey);
  delay(30000);
// Welcome Screen
  Mouse.click(MOUSE_LEFT);
  delay(100);
  Keyboard.write(tabKey);
  delay(100);
  Keyboard.write(tabKey);
  delay(100);
  Keyboard.write(' ');
  delay(2000);
// Select Keyboard
  Keyboard.write(tabKey);
  delay(100);
  Keyboard.write(tabKey);
  delay(100);
  Keyboard.write(tabKey);
  delay(100);
  Keyboard.write(' ');
  delay(2000);
  TELL NODEMCU TO SEND PUSH NOTIFICATION HERE
}

void loop() {
}

```

As a reminder the pinout on my boards are as follows.

Leonardo:

NodeMCU:

# Answer
> 2 votes
**HW part:**

It's like button, simply connect arduino micro pin to nodeMCU pin and GND of arduino to GND of nodeMCU.

It's also good idea to use two resistors as voltage divider because arduino micro works with 5V and ESP8266 (nodeMCU) with 3V3. 5V can destroy ESP8266 but this thing is still not really clear. Resistor divider connect as in this link link about resistor divider for uart but instead of TX put arduino micro and instead of RX nodeMCU. resistor divider schematic

---

**Code part:**

On the **arduino micro part** use:

* In `void setup()`: `pinMode(PIN, OUTPUT);`
* In your marked place:

```
digitalWrite(PIN, HIGH);
delay(100);   //short wait time
digitalWrite(PIN, LOW);

```

**nodeMCU part:**

* In `void setup()`: `pinMode(PIN, INPUT);`
* Remove everything from `void loop()` and put there this:

```
if(digitalRead(PIN) == 1) pushover("OMG, Yes it works!!!");

```

In both codes select the `PIN` according to your choice.

---
Tags: nodemcu, arduino-leonardo, arduino-pro-mini, arduino-pro-micro
---


# Question
Title: Connect SD card to Arduino with or without a level shifter
I have some audio files in an SD card and I want to play them using Arduino, thus connect the SD card to the Arduino. Since the transfer of the data will be from the SD card (+3.3V) to the Arduino (+5.0V) and not vice versa, is a level shifter necessary?

# Answer
You can't use SD card without level conversion from 5 V to 3.3 V. Clock and CS line are driven by the master, and the master must request over MOSI the data to read.
> 1 votes

# Answer
i have a cheap generic chinese off-brand sd Card module and it does not even work if i do connect vcc to 3v3 so i use it with 5v. and i do not bother to add a Level shifter on the bus lines. and writing text to a file on the sd Card does work like a charm this way. so i would say no you not neccesarily Need the Level shifter but feel free to add it anyway and see if it works this way too.
> 1 votes

---
Tags: sd-card
---


# Question
Title: How can I reduce current drawn by micro SD card module?
I am using a servo along with a sensor and micro SD card module and speaker in arduino uno in order to play a wav file at certain conditions . But when i run the whole system the sd card module is consuming high current and the servo stops working as the current in that is in order of some micro amps. So please help me to solve the problem.

# Answer
another good practice might be to add a Transistor to your Systems so that you can physically disconnect parts of your System from the power rail while not in use. this will obviously decrease power consumption...
> 2 votes

# Answer
Don't try to drive all of that from the Arduino regulator. The answer is to get a higher current power supply. You might even need to add filter capacitors on the 5V rails "right in front" of your different systems to protect them from voltage drops when other systems suddenly draw large amounts of current from the 5V rail.
> 0 votes

---
Tags: arduino-uno
---


title: Trying to understand Classes

text:
# Question
Title: Trying to understand Classes
I have searched about class and int but I still don't understand.

I have seen this code online I want to understand it

```
class Motor {

  int enablePin;
  int directionPin1;
  int directionPin2;
  public:

  //Method to define the motor pins
  Motor(int ENPin,int dPin1,int dPin2){
    enablePin = ENPin;
    directionPin1 = dPin1;
    directionPin2 = dPin2;
};

```

# Answer
> 4 votes
```
class Motor {

```

This says to start defining a class. A class is like a "container" that holds both data and functions (methods). After defining the class, it becomes like a new variable type that you can declare multiple instances of.

```
  int enablePin;
  int directionPin1;
  int directionPin2;

```

These define the 3 integer variables (int=integer; whole numbers like 2, 3, 1000, -5, etc.) that belong to the class and have the identifiers given (`enablePin`, etc.) Since not otherwise specified, these variables are *private*, meaning that only other functions **in** the class can access them. Other parts of the program are not allowed to access these variables.

```
public:

```

This means that the following definitions *are* accessible by parts of the program that exist outside the class.

```
Motor(int ENPin,int dPin1,int dPin2) {
  enablePin = ENPin;
  directionPin1 = dPin1;
  directionPin2 = dPin2;
}

```

This defines the only "member function" in this class and because it shares the same name as the class (`Motor`), it is called a "Constructor", and allows you to pass arguments to an object created from the class -- in this case, if you declare an object of class `Motor` by `myMotor = Motor(1, 2, 3);`, the constructor is called with parameters `1`, `2`, and `3`. This constructor happens to just set the private variables to be the same as the arguments passed in.

But... All of this is basic C++, so a book or course on C++ programming would be better in-depth resource to understand this.

The code snippet also is incorrect because it has unbalanced curly-braces -- there is one to open the definition of the class and one to open the definition of the constructor, but only one closing brace.

---
Tags: class
---


title: Power Arduino Mega ESP85266

text:
# Question
Title: Power Arduino Mega ESP85266
Is it possible to Power a Arduino Mega 2560 and a NodeMCU V2 ESP8266 ESP-12E from a single 9V Block?

What would be the best solution?

* Can i power the ESP8266 directly via the Arduino Mega 5V output? (3.3V Output seems to weak)
* Is a Power Converter like this for the ESP8266 necessary?
* Should i use another external Power source for the ESP8266?

Thanks for any Help :)

# Answer
> Is it possible to Power a Arduino Mega 2560 and a NodeMCU V2 ESP8266 ESP-12E from a single 9V Block?

Yes. Assuming the "block" can provide enough current.

> Can i power the ESP8266 directly via the Arduino Mega 5V output? (3.3V Output seems to weak)

No.

> Is a Power Converter like this for the ESP8266 necessary?

Yes if you are powering it from more than 3.3V.

> Should I use another external Power source for the ESP8266?

Not necessary if the 9V one can provide enough current as I mentioned above.
> 1 votes

---
Tags: esp8266, nodemcu
---


# Question
Title: What is the state of Arduino pins when the arduino is unpowered?
I'm building a control box to provide logical control of power outlets.

I'm using a 4 channel 5V optically isolated relay system to control 4 separate outlets.

To use optical isolation you connect arduino +5V to the VCC line, and logic inputs to the 4 channels of the relay unit, and connect a separate +5V supply to run the coils of the relays.

To energize one of the relays, you pull that control line LOW. To de-energize the coil, you drive the line HIGH.

If I power on the relay but leave the Arduino unpowered, all the relay coils energize.

Do Arduino pins float when it is powered down, or are they grounded?

Could I wire a pullup resistor to the inputs? And how would I do that without losing optical isolation? If I connect my pullup resistors to the +5V for the relays, the relay's +5 is connected to the Arduino's logic lines. If I instead use the Arudino's +5 rail, then when the Arduino is powered down, it's +5V line is dead.

# Answer
> 3 votes
The pins have input protection diodes that clamp the pins to Vcc and Gnd. If a pin gets to \>VCC +0.5V the positive diode clamp conducts and Vcc is powered via the internal Vcc bus, and if a pin get to \< -0.5V the negative diode clamp conducts. With Vcc = 0V, the pin could act as if it were a low, but more generally folks see the chip acting like it was phantom powered and attempting to run code with perhaps unpredictable results. That's why the datasheet says to not drive the pins when th chip is unpowered. If the clamp current becomes too much, the diode can blow, and either just the one pin is impacted, or the whole chip dies and it will feel warm/hot to the touch when powered up.

So don't power up the relays without also powering up the Arduino.

# Answer
> 0 votes
As it turns out my question was a bit of an X/Y problem. I wanted to know what the pins on the Arduino do when the board is unpowered, because I was feeding +5V into the VCC input on my relay board when the Arduino was unpowered, and having the relay control lines connected to Arduino pins.

If you remove the jumper on my relay board, it has a VCC line that ONLY powers the logic level inputs to the relay control optical isolators and a JVCC line that drives the relay coils. (The VCC line might also power the optical isolators and the other CMOS circuitry on the board, I'm not sure.)

I have my Arduino wired to a USB input that is driven by a regulated AC power supply when it's running stand-alone, and from my computer when it's being programmed. Sometimes I forget to plug the AC powered USB cable into the Arduino when I switch to running it stand-alone off of AC, and in those cases the relay lines tend to energize when I don't want to, **and** I end up driving +5V into the Arduino's relay control GPIO lines, which is not a good idea.

The simple answer is to connect the +5V line from the Arduino to the VCC pin on the relay board. Then when the relay's JVCC is powered but the Arduino is not, the VCC line to the relay and the control lines to the relay are all unpowered, so the relay is off.

Duh.

---
Tags: pins, relay
---


title: What is the voltage between Vin & GND?

text:
# Question
Title: What is the voltage between Vin & GND?
I have NodeMCU ESP8266N Lolin V3, my 5V relay is powered from Vin of the NodeMCU. The NodeMCU is powered from 5V USB.

My difficulty is when I measure voltage between Vin & GND, it is of 1.9V, but supposed to be around 5V as it is directly attached with usb 5V supply. Actually my relay is not working with the power tapped from Vin, but relay's led & NodeMCU led are blinking but relay coil does not trip. Please confirm is my NodeMCU having problems as voltage between vin & GND read 1.9V. https://drive.google.com/file/d/1Z6jYX4sCLmRxnWbtBYZCNW6LpckokaC9/view?usp=drivesdk

# Answer
> 3 votes
The voltage on Vin when you power that board thru USB is not relevant ... Vin is not the pin you are looking for

You clearly have a Lolin NodeMCU (V3) board - the existence of Gnd and VU (looks like VV in your picture!!) between A0 and S3 pins indicates that

In documentaion easily found by searching for Lolin V3 pinout - VU is described a USB power output

Use this pin to connect to JD-VCC on the relays

I've just now successfully done this with a 4 relay board

I would connect (nodemcu -\> relay)

* 3V3 to VCC
* VU to JD-VCC
* Gnd to Gnd
* D*n* to IN*m* \- i.e. choose a D pin on the NodeMCU and connect to an IN pin on the relay

# Answer
> 0 votes
It is hard to tell from your pictures but I don't think you have your relay connected properly.

Some problems i see:

* Your esp8266n seems to be a 3 Volt device; it has 3V output pins
* Vin usually feeds a regulator; the +V rail is usually after it
* Your relay needs 5V but you only have 3V for power and signal

You will need a level shifter, and another powersupply to run your relay. You should be able to put 5v into Vin on your ESP and have it be powered, then you will need a level shifter to connect to the IN1 or IN2 of the realy so that you can control it with 3v. And the relay Vcc and GND also connected to the same power supply.

---
Tags: esp8266, nodemcu
---


# Question
Title: IR module sensor query for Line Follwer Robot
Are the IR sensors used in Line following Robot and Obstacle avoidance Robot with Arduino UNO different ? If yes , where do we buy these parts online ? I used the following sensor in my Line Follower and am not getting result as it’s detecting obstacle instead of black line .

# Answer
The sensor you have used is fine. There is a potentiometer on the sensor PCB that is used for the range. For the line following robot you would want the range small, between 1-4cm. However, for the obstacle avoidance robot you would want to set this for a much larger range, say 10-45cm.

To make an effective line following robot you need at least 2-3 sensors.

Here is one using 2 LEDs either side of the line:

And here is a 3 sensor robot:
Notice that one LED stays on the line.

And finally a 5 sensor robot:

The following websites have good step by step guides where they explain the various techniques:

When I made my line following robot I used 2 of the following sensor:

These sensors were great as they pointed in towards each other, making a focal point. You can do this to your sensor by bending the LEDs slightly towards each other.
> 1 votes

# Answer
For obstacle detection you would usually use a different IR sensor, yes. The IR sensors usually used for line following only work at a very short range (typically \<1cm). For a robot detecting obstacles you want a sensor that detects an obstacle further away, say at a 30-60 cm distance, so the robot can evade the obstacle before it runs into it.

Common IR sensors for obstacle detection look like this:

The IR sensor you showed probably send a 0V or 5V, true or false value to a digital input of your arduino. The IR distance sensor shown above sends an analogue value (range 0-5v) to an analogue input of an arduino. They come in different ranges. Ranges go from ± 10 cm to ±5m (rough indication).

But personally I prefer to use the common HC-SR04 ultrasonic distance sensor instead of infrared ones. They have a larger usable range, a less noisy signal and detect more different types of objects. That's my personal experience from side-by-side comparison.

I'm reluctant to mention online shops on where to buy them. They're very common sensors.
> 0 votes

---
Tags: arduino-uno
---


# Question
Title: Where are the implementations of the SdFat BlockDriver methods?
This is most probably more of a C++ question than an Arduino question; but since this is an Arduino library, I am asking here.

I am using the SdFat library for my project. The library defines a `BlockDriver` object in one of its header file which only declares the `typedef` of `BaseDriver` to some other classes.

```
#if ENABLE_EXTENDED_TRANSFER_CLASS || ENABLE_SDIO_CLASS
typedef BaseBlockDriver BlockDriver;
#else  // ENABLE_EXTENDED_TRANSFER_CLASS || ENABLE_SDIO_CLASS
typedef SdSpiCard BlockDriver;
#endif  // ENABLE_EXTENDED_TRANSFER_CLASS || ENABLE_SDIO_CLASS
#endif // BlockDriver_h

```

`typedef SdSpiCard BlockDriver;` makes sense to me. But if `ENABLE_EXTENDED_TRANSFER_CLASS` or `ENABLE_SDIO_CLASS` are defined, `BlockDriver` is typedeffed into `BaseBlockDriver`. `BaseBlockDriver` is an abstract base class (as defined here). An instance of the `BlockDriver` object is later used directly in the `FatVolume` class here.

**My question is, how does `BlockDriver`'s method get defined when it abstract base class `BaseBlockDriver` is typedeffed to `BlockDriver`?**

# Answer
> 1 votes
The typedef in BlockDriver.h is only for pointer type, not for instance of the object. The object is always of type `SdSpiCard`, but in one case it is not an implementation of BlockDriverBase, so the function parameters can't refer it by base type.

```
#if ENABLE_EXTENDED_TRANSFER_CLASS || ENABLE_SDIO_CLASS
class SdSpiCard : public BaseBlockDriver {
#else  // ENABLE_EXTENDED_TRANSFER_CLASS || ENABLE_SDIO_CLASS
class SdSpiCard {

```

use of BlockDriver typedef

```
class FatFileSystem : public  FatVolume {
 public:
  bool begin(BlockDriver* blockDev, uint8_t part = 0) {

```

I was curious why the version without BaseBlockDriver. I asked the author Bill Greiman and he answered:

> This is due to history. Long ago using a virtual base class cost lots of RAM and flash so I did this mainly for 328 boards

---
Tags: c++, library, sd
---


# Question
Title: ATmega 32A and 2560 R3 register to pin mapping?
I've been doing research for the last few hours trying to determine the mapping of physical pins to memory-mapped I/O registers for the Arduino Mega board (which is an ATmega 2560 R3).

Some of the registers used include `CS11`, `DDB4`, `DDRA`, `DDRB`, `GICR`, `INT0`, `INT1`, `ISC00`, `ISC10`, `MCUCR`, `PA0`, `PB5`, `PB7`, `PD2`, `PD3`, `PIND`, `PORTA`, `PORTD`, `SPCR`, `SPDR`, `SPIF`, `SPSR`, `TCCR1B`, and `TCNT1`. I can't figure out which pins these are and/or what they do.

Here is a diagram provided by the upstream example:

Unfortunately, I'm not very good at reading these diagrams so I'm doing my best.

How can I determine the mapping of these registers to physical ports on both the ATmega 32A, which is the board the example was originally written for, and the ATmega 2560 R3, which is the board I'm currently working with?

# Answer
> 1 votes
What is ATmega2560 R3? There is ATmega2560 MCU or Arduino Mega R3. do you want the mapping of pins of Arduino Mega or the pins of the ATmega2560 MCU.

The mapping of pins of the ATmega 2560 chip is in the datasheet.

The mapping of the Arduino Mega pins to ATmega2560 pins and registers is in the schema of the board or in the Arduino AVR boards package variants mega folder.

The link "Arduino's 2560 pin mapping" in your question shows the mapping too. Registers are PA, PB,... and every register covers to 8 pins with the 8 bits of the register. For example PB3 is pin 50 of the board.

# Answer
> 0 votes
Atmega32A is a 44 pin TQFP part with 4 8-bit IO ports. It is kind of a crippled Atmega1284P. You may have an easier time just switching to a 1284P chip (also 44 pin TQFP) to take advantage of its 16K byte SRAM and 128K byte flash. There's an easy to use add-in to the Arduino IDE to use it. https://github.com/MCUdude/MightyCore I do a lot of 1284P designs and use it all the time.

Atmega2560 is 100 pin TQFP part with 10 8-bit and one 6-bit IO ports.

As your schematic only uses a few IO pins, the electrical connections will be simple - SPI for bootloading or downloading code \- 2 pins for serial \- 2 pins for other IO

If you look at the Arduino Mega2560 schematic, you can pick those out pretty readily. The rest you will have to tweak up in your code.

---
Tags: arduino-mega, pins, atmega2560
---


# Question
Title: give a class's function name as a parameter
I'm trying code using `FastLed` library to have a 3 state ( color or brightness ) led strip, using a physical input switch, while each press will change leds color, using a predefined list.

code below demonstrate 1) create a `colorPallete` of two colors 2) try to use it in `loop` with no success.

```
#include <FastLED.h>

// How many leds in your strip?
#define NUM_LEDS 1

// For led chips like Neopixels, which have a data line, ground, and power, you just
// need to define DATA_PIN.  For led chipsets that are SPI based (four wires - data, clock,
// ground, and power), like the LPD8806 define both DATA_PIN and CLOCK_PIN
#define DATA_PIN 3
//#define CLOCK_PIN 13

// Define the array of leds
CRGB leds[NUM_LEDS];
int colorSelctor = 0;
int birughtSelector = 25;
int inputPin = 13;
char *colorPallete[2] = {"Red","Blue"};

void setup() {
  // FastLED.addLeds<WS2812, DATA_PIN, RGB>(leds, NUM_LEDS);
  // FastLED.addLeds<WS2812B, DATA_PIN, RGB>(leds, NUM_LEDS);
  FastLED.addLeds<NEOPIXEL, DATA_PIN>(leds, NUM_LEDS);
  pinMode(inputPin, INPUT_PULLUP);
}

void loop() {
  // Turn the LED on, then pause
  leds[0] = CRGB::colorPallete[0];
  FastLED.show();
  delay(500);
  // Now turn the LED off, then pause
  leds[0] = CRGB::Black;
  FastLED.show();
  delay(500);
}

```

# Answer
> 3 votes
`CRGB::Red`, etc, are just numbers. You need to treat them as such.

```
uint32_t colorPallette[2] = { CRGB::Red, CRGB::Blue };

```

And then:

```
leds[0] = colorPallete[0];

```

From `pixeltypes.h`:

```
/// Predefined RGB colors
typedef enum {
    AliceBlue=0xF0F8FF,
    Amethyst=0x9966CC,
    AntiqueWhite=0xFAEBD7,
    Aqua=0x00FFFF,
    Aquamarine=0x7FFFD4,
    Azure=0xF0FFFF,
    Beige=0xF5F5DC,
    Bisque=0xFFE4C4,
    Black=0x000000,
      ... etc ...
} HTMLColorCode;

```

---
Tags: class
---


title: Arduino Power project question?

text:
# Question
Title: Arduino Power project question?
I saw a project on the Internet (the one in the photo), and I wonder, would it be a problem for me to connect the Vin and GND of the Arduino to the same place where the Servo Motors are being powered? (to power the Arduino together without having to connect it to another source or USB)

And if instead of the batteries I use one of those Breadboard Power Module (photo two) and connect a 12V / 1A power supply in it, would it have problem ? (connect the 4 Servo + the Arduino in it)

# Answer
> 1 votes
Please provide more information about the power module, or at least a link to it.

But you could supply 12v directly to the Arduino's DC-In barrel-jack. It's not ideal; the Arduino's regulator is likely to get warm, but it would work. This module looks like it regulates its input down to 5v or 3.3v (jumper-selectable). If that is so, then its 5v output would be just right for the Arduino's 5v-In pin. Just make sure your the motors and the Arduino are each directly connected to whatever supply(s) you use. What you need to avoid is trying to power the motors *through* the Arduino. Your first photo has it right.

Update:

After reading about the supply (using your link), I see that its output is limited to 700ma. Some of that will have to go to power the Arduino (you can use the power supply's USB port for that), leaving a little less for the motors. That will be marginal for one motor and insufficient if the motor is stalled or moving more than a trivial load. It won't be sufficient for more than one motor at a time without scheduling them to prevent simultaneous starts.

You haven't described your motors, so I looked up the Tower-Pro SG-90 hobby servos, one of the simplest and least expensive of the hobby servos. I found a very similar looking one (maybe a clone?) described as being similar to the Tower-Pro, the only one for which I could find current specs. At 5 volts, it draws 100mA with no load and 700ma when stalled. With a stalled motor, the output voltage would likely drop, possibly stopping and resetting the Arduino.

So bottom line is, this supply is marginal, even for one hobby servo in a mechanism that won't stall it. With a larger motor or a heavier load, I don't think it will do the job.

---
Tags: arduino-uno, power
---


# Question
Title: 5V DC Mini Water Pump with Arduino Mega 2560?
First of all, it is my first topic and i want to say hi to you all!! Secondly, i am really a terrible noob and sorry for that :(

I need to make a smart greenhouse project with Arduino Mega 2560, and i found a video to help me with my servomotor(MG996R) which will start working when raindrops module detect rain and 12v DC Fan which will start working when LM35 sensor calculates the weather as hot. However, my third actuator, 5V DC Mini Water Pump, which needs to become turned on when soil humidity sensor measures the soil as dry, is where i am left without an opinion. All the water pumps people use is 12 V, so i dont know which specific components i should use. I researched a bit and found that people use transistors and diodes for it. Which ones should i use and how to make the connections?

I would appreciate if someone helps me what components, specifically, should i buy and how to connect them together with Arduino 2560? It would be great if you can draw it, like with fritzing or something.

Thanks if you read this far :)

# Answer
Welcome to arduino.stackexchange.com .

As motor is usually a high current load, controlling a switch to control the motor's power is the solution.

If you are not interested in h/w design just want to use a interface out of box you can use relay module like this relay. For only one load connection will be simple and I don't think Arduino current supply limit will be a problem.

see this answer for example connection using relay. It is almost similar use case I think. Also here is a Fritzing image using the relay in the first link. I have used four 3V battery pack as 12V source. It doesn't have to be battery.

If you like to do from scratch, you can use BJT(Bi polar junction transistor) or MOSFET.

Here is a possible schematic.

simulate this circuit – Schematic created using CircuitLab

Different power supplies are used for Arduino and Motor because recommended voltage range is 7-12V in Vin pin. Different sources, voltage levels like 5V from USB may be used according to your ease.

node b, c and e are base, collector and emitter of the BJT. Diode D1 is called flyback diode.

Let, the current needed for motor IL, motor voltage needed VL, collector current Ic and base current Ib and the resistor between arduino and base Rb. Note that IL = Ic

Operating mode of transistor will be saturation mode. So, the base current (supplied by arduino) will be,

* Ibe = (current gain at saturation)\*Ic

How to find the current gain? Look through the datasheet of transistor for hfe(sat) which is basically Ic/Ib at saturation mode. Some datasheet may use α instead of hfe(sat)

Then find the Vbe(sat) as you will be operating in saturation mode. Find the needed base resistor value Rb,

* Ib = 5-Vbe/Rb

While designing this you have to be careful about these condition (I am talking about design using BJT)

* Vce(max)(max) \> VL
* Ice(max) \> IL
* Arduino digital pin max I \> Ib

All the devices should have same ground. Be sure to use the diode(D1) mentioned in the design as motor is an inductive load, sudden powering down may create large voltage across motor.
> 2 votes

---
Tags: arduino-mega
---


# Question
Title: How to declare a global variable in the .h file?
I have a .h library file in which I want to declare a global variable that can be read in the program loop and in the library's .cpp file.

The question is, is it possible to declare a variable in the .h file and make it global?

# Answer
> 11 votes
.h file is included by the compilation *preprocessor* as text into the .c or .cpp file. It is included as if you would replace the `#include` *preprocessor instruction* with the content of the .h file. (The Arduino .ino file is converted to cpp file before *preprocessing*.)

After the inclusion the cpp file is compiled to 'object' (.o file). If the cpp file contains a variable *definition* the variable is *defined* in this *object* file. If your .h file contained a variable *definition*, the it is also in this object file.

If two cpp files included the .h file with the *definition* of the variable, then the variable will be in two *object* files and the linker will exit with an error, because of two variables with the same name. If only one cpp/ino files includes the variable *definition*, then it is OK. It is not a good practice, but sometimes a necessary compromise. (example of it)

To have one global variable made accessible by a .h file, the variable should be only *declared* in the .h file and be *defined* in one cpp file. Usually it is a pair of .h and .cpp file with same name.

An example of global variable is `Serial`. It is a global object of type `HardwareSerial` *declared* in HardwareSerial.h as

`extern HardwareSerial Serial;`

and *defined* in HardwareSerial0.cpp as

`HardwareSerial Serial(&UBRR0H, &UBRR0L, &UCSR0A, &UCSR0B, &UCSR0C, &UDR0);`

Do you see the difference? The *declaration* has the keyword `extern` and the *definition* has in this case parameters for the constructor of the object. The *declaration* with extern keyword makes object Serial visible in all cpp files which include HardwareSerial.h (or an include file which includes HardwareSerial.h like Arduino.h included by ino to cpp conversion).

# Answer
> 4 votes
You can declare the variable as a `static` variable inside an `inline` function, and then just call this function to get a reference to this variable. Example:

```
inline int& getMyInteger()
{
    static int x;
    return x;
}

```

This definition can be in a header file, included into multiple `*.cpp` files, and any call to `getMyInteger` will return reference to the same object. You don't need any `extern`, nor to actually put the variable in any compilation unit as you would need with a simple namespace-scope variable. This trick just uses the linker's ability to de-duplicate `inline` functions.

See also: static variables in an inlined function question on StackOverflow.

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


# Question
Title: expected unqualified-id before '.' token
//my coding

```
#include<DHT.h>              // Including library for dht
#include<LiquidCrystal.h>
LiquidCrystal lcd(14,15,16,17,18,19);
#include<Timer.h>
Timer t;
#include <SoftwareSerial.h>
SoftwareSerial Serial1(2, 3);

#define dht_dpin 12
#define heart 13

DHT dht;

char *api_key="0UXHCZ777V0PAWPW";     // Enter your Write API key from ThingSpeak
static char postUrl[150];
int humi,tem;
void httpGet(String ip, String path, int port=80);

void setup()
{
 lcd.begin(16, 2);
 lcd.clear();
 lcd.print("   Humidity   ");
 lcd.setCursor(0,1);
 lcd.print("  Measurement ");
 delay(2000);
 lcd.clear();
 lcd.print("Circuit Digest ");
 lcd.setCursor(0,1);
 lcd.print("Welcomes You");
 delay(2000);
 Serial1.begin(9600);
 Serial.begin(9600);
 lcd.clear();
 lcd.print("WIFI Connecting");
 lcd.setCursor(0,1);
 lcd.print("Please wait....");
 Serial.println("Connecting Wifi....");
 connect_wifi("AT",1000);
 connect_wifi("AT+CWMODE=1",1000);
 connect_wifi("AT+CWQAP",1000);
 connect_wifi("AT+RST",5000);
 connect_wifi("AT+CWJAP=\"1st floor\",\"muda1884\"",10000);
 Serial.println("Wifi Connected");
 lcd.clear();
 lcd.print("WIFI Connected.");
 pinMode(heart, OUTPUT);
 delay(2000);
 t.oscillate(heart, 1000, LOW);
 t.every(20000, send2server);
}

void loop()
{
***DHT.read11(dht_dpin);     error in this line***
  lcd.setCursor(0,0);
  lcd.print("Humidity");
 **humi=DHT.Humidity;**   error in this line

  lcd.print(humi);   // printing Humidity on LCD
  lcd.print(" %    ");
  lcd.setCursor(0,1);
  lcd.print("Temperature");
**tem=DHT.Temperature;**  error in this line
  lcd.print(tem);   // Printing temperature on LCD
  lcd.write(1);
  lcd.print("C   ");
  delay(1000);
  t.update();
}

void send2server()
{
  char tempStr[8];
  char humidStr[8];
  dtostrf(tem, 5, 3, tempStr);
  dtostrf(humi, 5, 3, humidStr);
  sprintf(postUrl, "update?api_key=%s&field1=%s&field2=%s",api_key,humidStr,tempStr);
  httpGet("api.thingspeak.com", postUrl, 80);
}

//GET https://api.thingspeak.com/update?api_key=0UXHCZ777V0PAWPW&field1=0
void httpGet(String ip, String path, int port)
{
  int resp;
  String atHttpGetCmd = "GET /"+path+" HTTP/1.0\r\n\r\n";
  //AT+CIPSTART="TCP","192.168.20.200",80
  String atTcpPortConnectCmd = "AT+CIPSTART=\"TCP\",\""+ip+"\","+port+"";
  connect_wifi(atTcpPortConnectCmd,1000);
  int len = atHttpGetCmd.length();
  String atSendCmd = "AT+CIPSEND=";
  atSendCmd+=len;
  connect_wifi(atSendCmd,1000);
  connect_wifi(atHttpGetCmd,1000);
}

void connect_wifi(String cmd, int t)
{
  int temp=0,i=0;
  while(1)
  {
    lcd.clear();
    lcd.print(cmd);
    Serial.println(cmd);
    Serial1.println(cmd);
    while(Serial1.available())
    {
      if(Serial1.find("OK"))

      i=8;
    }
    delay(t);
    if(i>5)
    break;
    i++;
  }
  if(i==8)
  {
   Serial.println("OK");
        lcd.setCursor(0,1);
      lcd.print("OK");
  }
  else
  {
   Serial.println("Error");
         lcd.setCursor(0,1);
      lcd.print("Error");
  }
}

```

# Answer
> 3 votes
You declare an object of type `DHT` and name `dht`. Then you try to call a method of `DHT.read11()`.

Instead, you should be using the object name, `dht.read11()`, or as @Gerben points out, change the way you declare the object: `DHT dht;`.

---
Tags: arduino-uno
---


title: Length of uint8_t* const array

text:
# Question
Title: Length of uint8_t* const array
I've an array of type uint8\_t\* const with 6 items, defined like this

```
uint8_t* const neighbourSet[] = {PEER1, PEER2, PEER3, PEER4, PEER5, PEER6};

```

Whereas each element in this array is `static uint8_t` defined like this

```
static uint8_t PEER1[] {0x86, 0xF3, 0xEB, 0x7A, 0xE8, 0x3B};
static uint8_t PEER2[] {0x86, 0xF3, 0xEB, 0x7A, 0xA1, 0x09};
static uint8_t PEER3[] {0x84, 0x0D, 0x8E, 0x03, 0x95, 0xED};
static uint8_t PEER4[] {0x84, 0x0D, 0x8E, 0x03, 0x99, 0xD5};
static uint8_t PEER5[] {0x80, 0x7D, 0x3A, 0xC5, 0x2B, 0x79};
static uint8_t PEER6[] {0x84, 0x0D, 0x8E, 0x03, 0x95, 0x1D};

```

When I do

```
  Serial.print("size:");
  Serial.println(sizeof(neighbourSet));

```

I get `size:24`. I am expecting the size to be 6. could someone explain ? I don't want to hardcode the total number of PEER in a separate integer variable. I want my for loop to run through each element till the total size of array.

```
    for (int i = 0; i < sizeof(neighbourSet); i++) {
         //do something for each PEER.
         delay(50);
    }

```

# Answer
> 1 votes
`sizeof()` gives the number of bytes. You are looking for `membersof()`. It is often defined as:

```
#define membersof(x) (sizeof(x) / sizeof(x[0]))

```

And in the example above:

```
for (int i = 0; i < membersof(neighbourSet); i++) {
     //do something for each PEER.
     delay(50);
}

```

For more practical C/C++ macro and type extensions please see the Cosa Types.h file.

---
Tags: arduino-ide, c, array
---


title: NodeMCU NeoPixel

text:
# Question
Title: NodeMCU NeoPixel
I am attempting to control a single NeoPixel with a NodeMCU, but I'm not having any luck. Even just loading the default Adafruit NeoPixel library sketch yields unsuccessful results. I've tested the exact same sketch on a regular Arduino with sucess. I've got the data line hooked up to D5 on the NodeMCU board and here is my configuration of the Pixel in the sketch.

```
Adafruit_NeoPixel strip = Adafruit_NeoPixel(1, D5, NEO_GRB + NEO_KHZ800);

```

Any suggestions??

# Answer
> 1 votes
The node mcu is an esp8xxx with 3.3V outputs.

The neopixel is an ws2812 led controller that normally uses 5V logic.

They cannot communicate. This is why it's failing.

Lower the voltage used for the neopixel so that 3.3V is within 70% of the neopixel VIN or use a logic level translator.

# Answer
> 1 votes
I had the same problem. It were resolved by initializing the pin as OUTPUT:

```
  pinMode(PIN, OUTPUT);
  pixels.begin(); // This initializes the NeoPixel library.

```

As I understand Arduino bootloader does it by itself but bootloader of ESP8266 does not.

# Answer
> 0 votes
I had the same issue on a LoLin NodeMCU board while it worked with the Amica NodeMCU board.

When powered via USB, the Amica board provided 5V on the `Vin` pin, but the LoLin board didn't. I had to use the `VU` pin instead and it worked.

I did not need a logic shifter. I used the D2 pin with a 220 Ohm resistor for the data.

---
Tags: led, nodemcu
---


title: ESP8266 deep sleep and MQTT

text:
# Question
Title: ESP8266 deep sleep and MQTT
I am working on a project were I am putting my board into deep sleep mode, and it wakes up with an interrupt from a sensor. When it wakes from deep sleep I would like to send a message to my MQTT broker. The wiring works, the interrupt works, however, the code does not.

When I use the posted code, everything looks fine in the console, I get all my print statements which would make me assume it is working. However, my MQTT broker does not show any messages. But, if I move "sendMQTTMessage()" to the loop function it works fine and the messages come through to my broker.

Any suggestions would be greatly appreciated

```
#include <ESP8266WiFi.h>
#include <PubSubClient.h>

const char* ssid = "*";
const char* ss_pswd = "*";
const char* mqtt_server = "*";
WiFiClient EspClient;
PubSubClient client(EspClient);

void wifi_setup() {
  Serial.print("Connecting to: ");
  Serial.println(ssid);
  WiFi.begin(ssid, ss_pswd);
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.println(".");
  }
  Serial.println("");
  Serial.println("WiFi connected");
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());
}
void reconnect() {
  while (!client.connected()) {
    Serial.print("Attempting MQTT connection...");
    String ClientId = "ESP8266";
    ClientId += String(random(0xffff), HEX);
    if (client.connect(ClientId.c_str())) {
      Serial.println("connected");
      client.publish("outtopic", "hello world, finally");
      client.subscribe("/room/test");
    } else {
      Serial.print("failed, rc=");
      Serial.println(client.state());
      Serial.println("Try again...");
      delay(5000);
    }
  }
}
void sendMQTTMessage() {
  Serial.println("sending your message");
  if (!client.connected()) {
    reconnect();
  }
  client.publish("belmont/sensor/pir/hallway", "on");
}
void callback(char* topic, byte* payload, unsigned int length) {
  Serial.print("Message arrived: ");
  Serial.println(topic);
  for (int i = 0; i < length; i++) {
    Serial.print((char)payload[i]);
  }
}
void setup() {
  Serial.begin(115200);
  wifi_setup();
  client.setServer(mqtt_server, 1883);
  client.setCallback(callback);
  sendMQTTMessage();
  Serial.println("going into deep sleep");
  ESP.deepSleep(10 * 1000000);
}

void loop() {
//  sendMQTTMessage();
//  delay(5000);
}

```

# Answer
The answer for this actually goes to Juraj. It was the fact that I was missing a delay. In hindsight it makes sense, as even though I am competing tasks in order, the system is shutting down, before the actual message is sent. I added a delay(1000) between the "sendMQTTMessage()" and "ESP.deepsleep()" and it worked.
> 1 votes

---
Tags: esp8266, sleep, mqtt
---


# Question
Title: How to print not enough credits if the credits is not sufficient
The problem of my code is in the serial monitor it print the not enough credits even i did not pressed the button. The output that i want is it must be print not enough credits when i pressed the button.

```
#include <Servo.h>
const int coinpin = 2;
const int buttonPin = 7;

// Variables
volatile int credits = 0;
int buttonState = 0;
const int servoPin = 8;
 Servo servo;

// Setup
void setup() {
  servo.attach (servoPin);
  Serial.begin(9600);
  attachInterrupt(digitalPinToInterrupt(coinpin), coinInterrupt, RISING);
  pinMode(buttonPin, INPUT);
  servo.write(0);

}

// Main loop
void loop() {

Serial.println(credits);
delay(2000);
buttonState = digitalRead(buttonPin);
if (buttonState == HIGH && credits == 5) {

  Serial.println(credits);
  servo.write(180);
  delay(1000);
  servo.write(0);
}

if(credits !=5) {
  Serial.println("NOT ENOUGH CREDITS");
  delay(2000);
}

}

// Interrupt
void coinInterrupt(){

  // Each time a pulse is sent from the coin acceptor, interrupt main loop to add 1 cent and flip on the LED
  credits = credits + 1;
}

```

# Answer
Look at lines of code I marked:

Each loop you check for credits being equal to 5, and if it's not equal to 5 you write "NOT ENOUGH CREDITS" You might want to modify your "if" structure to only check for credits when the button is pressed.

Immediately I see two bugs:

1. What happens when number of credits is 6? Is it enough or not?
2. What happens when user presses the button for 2 or more "loop"s?

The physical button press looks to the hardware as several consecutive button presses because the button "bouncess" under your finger. Fixing that issue is called "debouncing" and there are several ways to do that. Read more about that.
> 2 votes

# Answer
The second if statement is standalone and not inside the button press check if statement so will always print 'not enough credit' whenever credit is not exactly 5. You might also want to look at debouncing the button as you're liable to get multiple triggers on one press.
> 1 votes

---
Tags: arduino-uno
---


# Question
Title: Combining 2 sensors in one code with 1 push button
I am trying to create a circuit with one tactile pushbutton, and LCD and two sensors: 1) temperature, and 2) pulse sensor. When the circuit is on, the LCD initially shows the reading from the temp sensor, when the button is pressed the LCD shows the reading from the pulse sensor.

The code compiles, the LCD shows both of the temperature function and pulse reading work.

I attached a picture of the schematic of the circuit.

The problem is that when the button is pressed, it takes many pushing of the button for the circuit to go from temperature reading to pulse reading. I thought maybe debouncing the button was unnecessary so I tried to write a code without the code, but it made no difference. My coding skills are still in the beginner side but I am trying my best for my coding to make sense. I just need some guidance and advice on what the problem could be and how I can tackle the problem. My code is attached here:

```
#include <LiquidCrystal.h>
#define BUTTON 2

const int rs = 12, en = 11, d4 = 7, d5 = 6, d6 = 5, d7 = 4;
LiquidCrystal lcd(12, 11, 7, 6, 5, 4);

//TEMPERATURE
const int tempPin = A0;              // LM35 in A0

int T1=60;

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

int PulseWire = A1;                 // Pulse Sensor purple wire connected to analog pin A0
int blinkPin = 13;                // pin to blink led at each beat
int Threshold = 550;           // Determine which Signal to "count as a beat" and which to ignore.
// Use the "Gettting Started Project" to fine-tune Threshold Value beyond default setting.
// Otherwise leave the default "550" value.
PulseSensorPlayground pulseSensor;  // Creates an instance of the PulseSensorPlayground object called "pulseSensor"

//=========BUTTON DEBOUNCE============
boolean lastButton = LOW;     // last button state
boolean currentButton = LOW; // current button state
int switchMode = 1;             //cycle between function
//====================================
void setup()
{

  lcd.begin(16, 2);
  // Configure the PulseSensor object, by assigning our variables to it.
  pulseSensor.analogInput(PulseWire);
  //pulseSensor.blinkOnPulse(LED13);       //auto-magically blink Arduino's LED with heartbeat.
  pulseSensor.setThreshold(Threshold);

  // Double-check the "pulseSensor" object was created and "began" seeing a signal.
  if (pulseSensor.begin()) {
    Serial.println("We created a pulseSensor Object !");  //This prints one time at Arduino power-up,  or on Arduino reset.

  }//end if

}//end void setup()

//Debouncing Function
boolean debounce(boolean last) {
  boolean current = digitalRead(BUTTON);
  if (last != current)
  {
    delay(T1);         //wait #ms
    current = digitalRead(BUTTON); //read it again
  }//end if
  return current;     //return the current value
}//end boolean debounce

void setMode(int mode) {

  //TEMP ON
  if (mode == 1)
  {
    Serial.begin(9600);
    int value = analogRead(tempPin); // read the value from the sensor
    lcd.setCursor(0, 1);
    float millivolts = (value / 1024.0) * 5000;
    float celsius = millivolts / 10;
    lcd.clear();
    lcd.setCursor(0, 0);
    lcd.print("Temp = "); lcd.print((celsius * 9) / 5 + 32);  lcd.print((char) 223); //turning the celsius into fahrehait
    lcd.print("F");
    lcd.setCursor(7, 2);
    lcd.print(celsius); lcd.print((char) 223);
    lcd.print("C");
    delay(1600);

    lcd.clear();
    delay(T1);
  }//end if TEMP ON

  //RED ON
  else if (mode == 2) {
    {
      Serial.begin(9600);
      int myBPM = pulseSensor.getBeatsPerMinute();  // Calls function on our pulseSensor object that returns BPM as an "int".
      // "myBPM" hold this BPM value now.

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

        lcd.setCursor(0, 0);
        lcd.print("HeartBeat Found!");
        lcd.setCursor(4, 1);
        lcd.print("BPM: "); lcd.print(myBPM);

        delay(1600);
        lcd.clear();
        delay(T1);
      }//end if
    }//end setMode void function
  }
}
    void loop()
    {
      currentButton = debounce(lastButton); //read debounced state
      if (lastButton == LOW && currentButton == HIGH) /// if it was pressed
      {
        switchMode++;
      }
      //if cycled through the different options,
      //reset the counter to 0
      if (switchMode == 3) switchMode = 1;
      setMode(switchMode);
    }//end loop

```

I also considered doing a switch case statement, but so far it hasn't worked either. Please let me know some ideas!

Thank you!!

# Answer
Your code has various issues, but the main one is that you can’t use `delay()` when you’re trying to more than one thing at a time. Delay causes your program to freeze, and not do anything else.

(Basically you should forget about the `delay()` function and never write any Arduino code that uses it. It is a code smell.)

You need to rewrite your code to record the value of `millis()` and then check back the next time through your loop function to see if enough time has passed. Do a Google search on “Arduino blink without delay” for an explanation of how to do this. Here’s an example article: https://learn.adafruit.com/multi-tasking-the-arduino-part-1/using-millis-for-timing

(Note that some solutions suggest that you increment a counter every time through your loop and see if some magic number of counts has gone past based on how frequently you expect your loop to be called. That is a bad approach. You want to use the `millis()` function.
> 1 votes

# Answer
Your loop function needs to call debounce() and setMode() as often as possible, and none of your functions must use delay(). Instead, they compute the time elapsed since the last action, and if it is greater than what you now use as a delay value, perform its next action; otherwise, it should just return.

Just as a curiosity, your present code will probably function (better...) if you press and hold the button until you get a response, instead of press-and-releasing multiple times, hoping to get one. The latter way depends on your pressing the button just as the system is reading it, but the system reads it too infrequently for that to be workable, as you found out. The delay() calls are the reason.
> 0 votes

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


# Question
Title: Adding esp32_komoot_ble library to Arduino IDE
I am an absolute beginner with Arduino IDE and I want to build an interesting device I stumbled upon on github https://github.com/jstiefel/esp32\_komoot\_ble Problem is I really can not add it to Arduino IDE. I did the wiring for the lcd and all, but please bear in mind i'm an electrician, with a very basic understanding of arduino/ absolute beginner. What i'm asking is which is the "main file" in the src folder so i can rename it 'ino' to work with the arduino IDE and upload it to the esp32 board? I downloaded the esp32 library and all the dependencies that says in the readme.md file. I download the esp32\_komoot\_ble.zip file. Now how do I get the .cpp and .h files on the arduino IDE and finally my esp32 device. I have been watching tutorial for 1 week now but could not figure it out yet! Thank you for everything guys!

# Answer
> 0 votes
The file, that you are searching, is the one, which contains the `setup()` and `loop` functions: `esp32_komoot_ble.cpp`

These functions are part of the Arduino framework and wrap the classic `main()` function. `setup()` is called once at startup, `loop()` after it repeating forever.

---
Tags: arduino-ide, esp32
---


title: AVR software reset without watchdog

text:
# Question
Title: AVR software reset without watchdog
I wrote a generic avr program wrapper which already use the watchdog timer to restart - and after the watchdog reset - recover the the bad situation.

After this recover process i have to restart the avr. Everything i've found in topic "software reset arduino" is about to set the shortest watchdog (15ms) timeout, then spins the CPU (for(;;);) until it cause watchdog reset.

But this results to enter the recovery process which is already done in this point.

It is any elegant way to achieve this?

Some non or less elegant way:

* I can bind a digital pin to the reset and pull up with a resistor.
* I can write to a fixed address in the flash or eeprom (but this maybe happens frequently) before soft restart, to prevent entering to recovery mode.

---

Is there any register that "survives" soft resets?

Edit:

I add mock example code to hint what i trying to do.

In the actual code, in the recovering the microcontroller connect to the serial bus, waits for commands then resets itselft in oder to return to application mode.

```
/*************************** Application wrapper ******************************/

//define call_application and call_recover as weak empty functions
//so they can be rewritten.

bool isWatchdogReset()
{
    return MCUSR == 8;
}

void softwareReset()
{
    //  wdt_enable(WDTO_15MS);for(;;);// (this way enters recovery mode)
    //or
    //  asm ("jmp 0x0");// (this way function registers not being resetted)
}

bool isSoftwareReset()
{
    //???
}

int main()
{
    bool needRecover = isWatchdogReset() && !isSoftwareReset();
    MCUSR = 0;
    init_board();
    wdt_enable(WDTO_1S);
    while(1)
    {
        if(!needRecover)
        {
            call_application();
        }
        else
        {
            call_recover();
        }
        wdt_reset();
    }
}

/********************************* Application ********************************/

void call_application()
{
    if(randomTrue())
    {
        //stuck more that 1 secounds, that results WDT reset
    }
    else
    {
        //proper operation
    }
}

/********************************** Recover ***********************************/

void call_recover()
{
    //initialize UART, attach interrupts, Write flash and EEPROM, modify
    //function registers.

    //recovering completed, returning to the original application as like
    //nothing's happened.
    softwareReset();
}

```

**Edit:** I try explain short to spot the point:

1) I already use the watchdog timer to detect when the application code is flawed.

2) soft reset is an inproper solution, because it doesn't reset the registers. So onyl the program will be resetted, the state of the microcontroller doesn't.

3) To commit a proper reset, the solution is to timeout the watchdog timer. But see point 1), it is already used, so how can you make the difference of a requested reset and a flawed code recovery reset?

# Answer
The reset is basically jumping to the reset vector address `0x0000` (if you don't have the bootloader, or you don't want to start it).

There is also the `MCUSR` register, indicating which reset source caused the reset. It won't be set if you do simple jump to the reset adress.

The memory is also preserved, but C/C++ init code takes place and initialize your global variables. This can be ommited by placing variable/variables into the `.noinit` section. But it's not defined, what is there after the reset. With combination with `MCUSR` register you can init the variables for regular reset sources and keep it unchanged if you jump to the reset vector address.

Also the regular reset sources jumps to the bootloader, so it can use the same memory locations as your `.noinit` variables and trash them.
> 2 votes

# Answer
The logic of you applications is wrong. You set the `needRecover` at the beginning of `main`, but test it in your infinite `while (1)` loop. **The `needRecover` value will not change in the loop.**

Do your initialization first no matter if normal power-up or watchdog restart and then do stuff in the infinite loop.

You could put the initialization in a function called `setup` and the infinite loop in a function called `loop`. And have a `main` function like this:

```
int main( void )
{
  setup();

  for (;;)
  {
    loop();
  }

  return 0;
}

```

wait, a saw this somewhere already :-)
> 2 votes

---
Tags: avr, reset, watchdog
---


title: Conveyor and Counter Project

text:
# Question
Title: Conveyor and Counter Project
I am new to Arduino and looking for advice if Arduino is the right microcontroller for this project.

My project is quite simple, I want to build 3 conveyors using 3 DC motors. At the end of each conveyor I plan to implement 3 IR break beam sensors to each respective conveyor to count when an object passes through. When **n** objects passes through each respective conveyor and falls into a catching mechanism the DC motor stops until object(s) are cleared. For the catching mechanism for each conveyor, I plan to use IR break beam sensors to detect if it’s cleared or not as well. (If you have an alternative suggestion to IR break beam sensors, please advice)

Question: Can a single Arduino uno microcontroller board handle this project? From what I know, Arduino can only run one program at a time and I’m not sure if my project can be run in one program; I believe it can. Additionally, what if I wanted to add a LCD display?

# Answer
Your project is pretty simple, and Arduino can handle it easilly. (Pretty much any microcontroller could do it) It's true that only ome program can be run at a time on Arduino (same as on 99% of other microcontrollers) but that one program can handle all three conveyors at the same time. Though I suggest using 3 different Arduinos and separating the systems. If somethig goes wrong on one conveyor it will not affect other ones. Price of Arduino is very low in comparison to price of industrial conveyors. (I didn't believe how much a meter of conveyor costs when you setup a facory line)
> 2 votes

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


# Question
Title: Is my code triggering the N-Channel MOSFET as I have intended to
I have a certain bit of code that I believe after 10 seconds will send a high signal to the second digital pin for 50 seconds. After it will not do anything.

For some reason the nichrome wire is not heating up. I realize there could be a problem with my circuit but just want to make sure for the final time it is not an issue with my code. Thanks.

```
int nichromePin = 2;

unsigned long burnTime = 10000;
unsigned long dt = 50000;
unsigned long time;

void setup()
{
  pinMode(nichromePin, OUTPUT);
  Serial.begin(9600);
  Serial.println("Balloon Countdown...");
  Serial.print("When Will It Burn: ");
  Serial.println(burnTime);

}

void loop()
{
  time = millis();

  if (time > burnTime && time < burnTime+dt)
  {
  digitalWrite(nichromePin, HIGH);
  Serial.print("Time: ");
  Serial.println(time);
  }
}

```

# Answer
The code is as follows: After 10 seconds following Arduino power up, burn the nichrome for 60 seconds, after which do nothing. I just tested it on my UNO and it works fine, so it must be your circuit. Post your nichrome question in the EE forums for help on that.

P.S. This code is kinda silly tho there's no trigger event!
> 1 votes

---
Tags: digital, mosfet
---


title: Simple multiplication bug

text:
# Question
Title: Simple multiplication bug
Executing the following code always gives -511 as a result, I performed many tests, and it seems that results are correct from 0 * 0 to 181 * 181, beyond that, results are abnormal, I tried many types for the z variable (int, long, float) without success, any idea? I'm using the Arduino Uno.

```
long z = 0;

void setup() {

Serial.begin(9600);

}

void loop() {

  z = 255 * 255;
  Serial.println(z);
  delay(200);

}

```

# Answer
No, this is not a bug. You are using a compile time constant expression which is `signed int` unless told otherwise. Therefore you can only represent numbers between -32768 and 32767. Your computation of `255 * 255 = 65025` exceeds the range. Thus you see an overflow. In the C/C++ standard the overflow of signed types is actually undefined behavior. That means that the compiler is allowed to do anything from showing the correct answer to halt and catch fire. Only unsigned types with a known size like `uint16_t` have a well-defined overflow behaviour. You should promote your right hand side computation to unsigned type like this:

```
z = 255U * 255U;

```

This way you tell the compiler your intention and don't land in "Undefined-Behaviour-Land".
> 12 votes

# Answer
Assuming long is 4 bytes, it should work.

However, if somehow a long type is only 2 bytes, or (more likely) you used another type or there is some wrong define/typedef, and it is a signed long (default if you do not used the unsigned keyword), the value range is -32,768 to 32,767 and 255 * 255 = 65,025 which is out of range.

So you can first try to use `unsigned long`.
> 0 votes

---
Tags: arduino-uno
---


# Question
Title: Selected board depends on 'arduino' core (not installed)
When I load the Arduino IDE with `Board: Pololu A-Star 32U4` selected, I see:

```
The current selected board needs the core 'arduino:arduino' that is not installed.

```

I installed the board manually via these instructions.

When verifying the initial empty sketch, I see:

```
Arduino: 1.8.8 (Linux), Board: "Pololu A-Star 32U4"

The current selected board needs the core 'arduino:arduino' that is not installed.
/usr/share/arduino/arduino-builder -dump-prefs -logger=machine -hardware /usr/share/arduino/hardware -hardware /home/ravi/Arduino/hardware -tools /usr/share/arduino/tools-builder -libraries /home/ravi/Arduino/libraries -fqbn=pololu:avr:a-star32U4 -ide-version=10808 -build-path /tmp/arduino_build_299010 -warnings=none -build-cache /tmp/arduino_cache_842714 -prefs=build.warn_data_percentage=75 -verbose /tmp/untitled689103723.tmp/sketch_feb05a/sketch_feb05a.ino

Selected board depends on 'arduino' core (not installed).

Error compiling for board Pololu A-Star 32U4.

```

How do I prevent this error and compile a sketch?

# Answer
I needed to install the boards package for:

```
Arduino AVR Boards

```

Under Tools -\> Board -\> Board Manager
> 3 votes

---
Tags: linux, compilation-errors
---


# Question
Title: AnalogRead value constant for a varying voltage (for LED brightness variation)
Having the 11~ pin on OUTPUT mode that delivers a varying voltage (from 0 to 5 : 0 to 255).

and the A0 pin on INPUT mode to read the voltage, I find that the value read by A0 being either 0 or 1016 instead of it gradually taking multiple values between the two. what is the catch?

The circuit and the code i am using:

```
int volt = 0;
int sign = 1; //values: (1, -1), increments or decrements "volt" by 5.
float potential;

void setup() {

  pinMode(11, OUTPUT);
  pinMode(A0, INPUT);
  Serial.begin(9600);

}

void loop() {

if (volt == 0){sign = 1;}
if (volt == 255){sign = -1}

volt = volt + sign * 5; //raises brightness to 255 from 0, then to 0 from 255.
analogWrite(11, volt);

potential = analogRead(A0);

Serial.println(potential);

delay(30);
/*
*/

}

```

# Answer
As CrossRoads says, there really isn't any such thing as analog output on an Arduino. (Any Arduino unless it has a built-in DAC.) It uses pulse-width modulation to vary the "duty cycle" of the output from 100% on to 0% on, which simulates an analog voltage.

If you drive an LED with PWM (and the required current limiting resistor) your eyes will not see the flashes, and will average out the brightness based on the duty cycle of the PWM signal.

If you want an actual analog voltage from PWM you will need to add a filter capacitor to average out the voltage over time. With a simple single capacitor filter you'll still have flutter in the output but it will be closer. If you want a clean constant voltage you'll need a more complex filter.
> 5 votes

# Answer
The PWM output pin does not vary voltage - it only outputs 0, or 5V. The amount of time that 5V is on, from 1/255 of about a 2mS period, to 255/255 of the same period, determines how bright the LED is perceived to be.

You really need a current limit resistor in series with the LED to keep from burning out the uC output pin, or from burning up the LED.
> 3 votes

---
Tags: arduino-uno, analogread
---


title: NPN sensor to Arduino

text:
# Question
Title: NPN sensor to Arduino
I have a beam sensor providing NPN and also PNP output. It as 4 wires and works on 24V. I hooked the brown(+) and blue(-) to a small 24V power supply and the sensor is working!!! Yeah!

Now I would like to recieve the signal in my arduino. I dont know where to plug the black and white and I dont want to frie everything. I know I need to have an NPN configuration but I dont know how to achieve that.

This is the sensor in question: https://literature.rockwellautomation.com/idc/groups/literature/documents/in/42ef-in005\_-en-p.pdf

And a little shema of my conections:

If someone could help me. Thanks, Nicolas

# Answer
I would connect the - from the supply and the sensor to Arduino Gnd.

Then the NPN output can pulldown an Arduino input with pullup resistor enabled.

Brown to 24V, Blue to Gnd, White to Arduino input. No resistor to Brown. Black not used.

simulate this circuit – Schematic created using CircuitLab
> 1 votes

---
Tags: arduino-uno, sensors, raspberrypi
---


# Question
Title: Is every Arduino comes with onboard compass?
The doubt was came in mind after seeing Arduino documentation. I have to turn my Arduino uno robot 20 degrees without using encoders. So I surfed on Internet for how can I do that. Interestingly I found the reference available on above link. They are not saying about any specific Arduino board. So I have to know that can I do this stuff on my Arduino uno? Also I have to know is that every Arduino comes with onboard compass?

# Answer
> 3 votes
No current Arduino board comes with an on-board compass. That function description comes from the documentation for the Arduino Robot, which is a retired product.

There may be other "maker" dev boards, such as the Adafruit Circuit Playground Express which have on-board compass peripherals.

---
Tags: arduino-uno
---


# Question
Title: Which is a better? GPRS SIM800L or GPRS SIM900?
I will implementate the GPRS technologity in my Arduino project, but before buy the module, I want to know which is a better. If GPRS SIM800L or GPRS SIM900? My needs are send JSON array through POST request.

Thanks and best regards.

# Answer
SIM900 is older type. SIM800L has FM build it and it uses same AT cmds as SIM900. Also, they are in same quadband. I guess both will work just fine.
> 1 votes

---
Tags: arduino-uno, json
---


title: Several Software Serial Ports

text:
# Question
Title: Several Software Serial Ports
I am planning to use an Arduino (Nano ideally, or Other) to send and receive information from several software serial ports to other arduinos, over their available pins, ideally 8 ports.

I could understand an Asynchrounous Communication having one *master* and 8 *slaves*, with the master enabling communication from one port, receiving the data from that port, and then move onto the next port, into a sampling loop.

The `SoftwareSerial` library allows to set up the pins individually, and set the `listen()` port (thanks Juraj).

I read the `AltSoftSerial` library handle some of the limitations of the `SoftwareSerial` library, but I just realized the pins cannot be configured (without... cloning the full library?).

Question is:

* Option 1: Should I stick with the `SoftwareSerial` library?,
* Option 2: Should I try the `AltSoftSerial` library, and figure how to duplicate it (i think this is a NO)?
* Option 3: Understand that none of these libraries are prepared for this, and seek for other alternative?
* Option 4: It is pointless to have several serial trunks in Arduino, if only one will work at a time, and should hence try to arrange just one serial trunk?

# Answer
I tried to use MIDI (which is quite slow: 31,250 bps), and that didn't work reliable with the software serial on the Arduino Uno. Since I wanted multiple ports, I switched to the Arduino Mega which has FOUR harware serial ports. I would suggest this above using so many software serial ports; it also will relieve your processor to use hardware serials.
> 2 votes

# Answer
You could use a part with 2 hardware serial ports (Atmega1284P), and use a simple mux chip to switch between the slaves for the master to receive from, such as DG406 https://www.digikey.com/products/en/integrated-circuits-ics/interface-analog-switches-multiplexers-demultiplexers/747?k=dg406&k=&pkeyword=dg406&sv=0&pv1989=0&pv433=170&sf=0&quantity=&ColumnSort=0&page=1&stock=1&pageSize=25

Hardware serial will allow for faster comm's too, vs software serial. 1284P is Arduino friendly too.
> 1 votes

---
Tags: serial, softwareserial
---