title: ESP32 - JPEGDecoder from SPIFFS

text:
# Question
Title: ESP32 - JPEGDecoder from SPIFFS
Hello i've try to decode JPG image from FS so, i create and upload spiffs image (using /data directory and Arduino Ide Plugin )

On every jpg i've same error: "pjpeg\_decode\_init() failed with status 19"

here is my same code:

```
#include <TFT_eSPI.h> // Hardware-specific library
#include <SPI.h>
#include "GfxUi.h"

TFT_eSPI tft = TFT_eSPI(); // Invoke custom library

#define DEBUG
#define LOAD_SPIFFS

GfxUi ui = GfxUi(&tft);

void writeFile(fs::FS &fs, const char * path, const char * message);
void readFile(fs::FS &fs, const char * path);
void listDir(fs::FS &fs, const char * dirname, uint8_t levels);

void setup(void)
{
  Serial.begin(115200);
  Serial.print("Start");
  SPIFFS.begin(true);
  tft.begin();
  tft.setRotation(3);
  tft.fillScreen(TFT_BLACK);

  listDir(SPIFFS, "/", 0);
  fs::File jpeg = SPIFFS.open("/star.jpg", "r");
  //readFile(SPIFFS, "/star.jpg");
  boolean decoded = JpegDec.decodeFsFile(jpeg);
  Serial.println("===============");
  Serial.println("JPEG image info");
  Serial.println("===============");
  Serial.print  ("Width      :"); Serial.println(JpegDec.width);
  Serial.print  ("Height     :"); Serial.println(JpegDec.height);
  Serial.print  ("Components :"); Serial.println(JpegDec.comps);
  Serial.print  ("MCU / row  :"); Serial.println(JpegDec.MCUSPerRow);
  Serial.print  ("MCU / col  :"); Serial.println(JpegDec.MCUSPerCol);
  Serial.print  ("Scan type  :"); Serial.println(JpegDec.scanType);
  Serial.print  ("MCU width  :"); Serial.println(JpegDec.MCUWidth);
  Serial.print  ("MCU height :"); Serial.println(JpegDec.MCUHeight);
  Serial.println("===============");
  Serial.println("");
}

void listDir(fs::FS &fs, const char * dirname, uint8_t levels){
    Serial.printf("Listing directory: %s\r\n", dirname);

    File root = fs.open(dirname);
    if(!root){
        Serial.println("- failed to open directory");
        return;
    }
    if(!root.isDirectory()){
        Serial.println(" - not a directory");
        return;
    }

    File file = root.openNextFile();
    while(file){
        if(file.isDirectory()){
            Serial.print("  DIR : ");
            Serial.println(file.name());
            if(levels){
                listDir(fs, file.name(), levels -1);
            }
        } else {
            Serial.print("  FILE: ");
            Serial.print(file.name());
            Serial.print("\tSIZE: ");
            Serial.println(file.size());
        }
        file = root.openNextFile();
    }
}

void readFile(fs::FS &fs, const char * path){
    Serial.printf("Reading file: %s\r\n", path);

    File file = fs.open(path);
    if(!file || file.isDirectory()){
        Serial.println("- failed to open file for reading");
        return;
    }

    Serial.println("- read from file:");
    while(file.available()){
        Serial.write(file.read());
    }
}

void writeFile(fs::FS &fs, const char * path, const char * message){
    Serial.printf("Writing file: %s\r\n", path);

    File file = fs.open(path, FILE_WRITE);
    if(!file){
        Serial.println("- failed to open file for writing");
        return;
    }
    if(file.print(message)){
        Serial.println("- file written");
    } else {
        Serial.println("- frite failed");
    }
}

void loop() {

}

```

Output from serial:

```
Listing directory: /
  FILE: /logo.jpg       SIZE: 16346
  FILE: /arduino.jpg    SIZE: 8426
  FILE: /star.jpg       SIZE: 3853
pjpeg_decode_init() failed with status 19 <--- here is
===============
JPEG image info
===============
Width      :0
Height     :0
Components :0
MCU / row  :0
MCU / col  :0
Scan type  :0
MCU width  :0
MCU height :0
===============

```

# Answer
as far as I can determine uploading to SPIFFS via the Arduino IDE is broken as of the beginning of 2018. The files are uploaded but are corrupted on a read. There are a few fixes reported. I am using a core from Dec 2017 and that works fine.
> 1 votes

---
Tags: esp32
---


title: Pull-down resistor value for interrupts

text:
# Question
Title: Pull-down resistor value for interrupts
I wonder how to calculate pulldown resistor to make interrupt work? I need to connect 5 buttons to A0 and get pressing event via interrupts. Using different resistors, finally, I made work only 4 buttons. On 5th interrupt does not fire. Currently I use the following resistors for the buttons:

```
R1      Vout
0       5,00
2,7K    4,45
5K      3,70
10K     2,77
22K     1,78

```

And Pulldown Resistor = 22K.

If pulldown Resistor = 10K I can get event for 1-3 button only. Looks like the voltage 1,78V is quite low. But I’d liked make it work with 1V at most. I use RISING mode.

PS. Arduino Nano

# Answer
> 0 votes
An Arduino running at 5V needs at least 3.0V on the pin to read it as rising high. You probably want to go a little more than that. So that means your lowest voltage has to be like 3.3V or so.

Note that the analog pins don't have an external interrupt, you'll have to use pin change interrupts and then read with analogRead in the ISR. So you can't use "RISING". The pin change interrupts act on any edge. So they'll trigger when falling as well.

That's a pretty poor way to handle these buttons. Normally one would just poll buttons like this. If your loop takes so long that you might miss a human pressing a button then perhaps you should look at that instead.

---
Tags: arduino-nano, interrupt
---


# Question
Title: How to connect Sparkfun M6E Nano UHF Rfid reader and ESP8266 NodeMCU 0.1
I am using an ESP8266 NodeMCU v0.1 and Sparkfun M6E Nano UHF Rfid reader. How to connect NodeMCU to M6E Nano UHF Rfid reader?

# Answer
> 0 votes
The interface of Sparkfun M6E Nano UHF Rfid reader is Serial TTL. So you should connect it to Serial pins of the NodeMcu. Don't use USB then, because it is connect to Serial too.

---
Tags: arduino-uno, nodemcu, rfid
---


# Question
Title: Elechouse Voice Recognition v3 module not responding when I send command using Access port serial tool
I have this challenge of receiving data when I send a command to voice recognition v3 module. The UART connections are okay, but when I send a command I don't receive a response on the terminal.

The prolific USB-TTL with drivers installed blinks when I send a command but still I get no response. Please help with debugging.

# Answer
> 1 votes
The module can't communicate with Serial Monitor over a USB to TTL Serial adapter. It uses binary communication. Use Arduino, Arduino library and one of the example sketches of the library to communicate with the VR module.

And read the manual.

---
Tags: serial
---


# Question
Title: How can I connect nodemcu with laptop wifi
Question is odd, but I want to know that how I connect nodmcu with a laptop wifi without using any router. Is it possible if yes then how?

# Answer
> 1 votes
Configure and activate the access point mode on NodeMCU. It creates a WiFi network and you can connect to this network with your computer.

---
Tags: arduino-uno, nodemcu
---


# Question
Title: How does one get the correct serial port?
I don't have a correct serial port from the resource I'm working from - Getting Started with Arduino by Massimo Banzi and Micheal Shiloh. I'm using the Arduino Uno. I'm a complete noob to Arduino. In this image below, from the resource I'm working from, it specifies to use either of the ports: `/dev/cu.usbmodemfa141` or `/dev/tty.usbmodem`.

*Getting started with Arduino by Massimo Banzi and Michael Shiloh* \- Figure 3-2 shows a list of available serial ports.

I only have two available: `/dev/cu.SSDC` and `/dev/cu.Bluetooth-Incoming-port`.

How do I get the 'correct' serial port? Correct being: `/dev/cu.usbmodemfa141` or `/dev/tty.usbmodem`.

Here's some possibly useful information:

I'm using Mac OS - which I'm new to - Sierra version 10.13.2.

I only have two ports on the computer a USB type - C and a headphone jack. So I have an 'adapter' that allows me to 'daisy chain' the USB - B and USB - A for the Arduino cable into the port of my computer. If any additional information is required, feel free to ask for it and I'll try and get back to you ASAP. Thanks.

# Answer
Sorry guys I solved it. It was really simple I just needed to plug the device in and it then detected the device and port name.
> 0 votes

# Answer
I had the same problem and had even fewer options under my Tools \> Port menu. Looked at the user forums but most answers did not work for me. After watching a YouTube video, I fixed the problem by following its suggestion of installing the CH34X driver. There are some other suggested drivers if you search for some other related StackOverflow and StackExchange posts, but I did not test them (once the Mac-Arduino communication worked, I did not want to spend more time on this) and nor can I explain why this solution works.

I wrote a short article on this for myself. If you are interested, please take a quick look.

Best luck! :)
> 1 votes

---
Tags: arduino-uno, serial, arduino-ide, genuine
---


title: Voltage Regulator getting too hot

text:
# Question
Title: Voltage Regulator getting too hot
I have an Arduino mega that is being used to control relays and ultrasonic sensors. The relays that I am using is a 4 DPDT Signal Relay Module Model: D-256 Series and the other is a 4 channel Single pole Relay for Arduino. I am only using 3 channels of each relay. At any given time I only output to 2 channels from each relay at a time. I tested the relay to ensure they worked with the Arduino and they ran fine.

Once I connected the Ultrasonic sensors to the board as well, the board would not power and the voltage regulator got extremely hot. I would assume the total current draw was too high from the outputs and VCC of the Arduino.

I think that if I take my 9V battery and run it through a voltage regulator 7805 then I can run the VCC power of the relays with the battery instead of the VCC from the Arduino. This would result in me only running a VCC to the 4 ultrasonic sensors, the triggers for the ultrasonics from the Arduino, and the output signals fora maximum of 2 channels per relay board resulting in 4 relays. Most of the time it is only 2 relays.

Would I be able to power the relay boards VCC with the 9V running through a 5v regulator instead of the arduino so that I can reduce the current running through the Arduino?

# Answer
What could be going on here apart from what @JRobert has suggested, is, LM7805 could be generating a lot of heat loss.

4 X Ultrasonic sensors (SR HC-04) would draw 60mA.

2 X Relays (SRD-05VDC-SL-C) would draw 71.4 X 2 i.e 142.8mA.(Depends on from where you signal it) The Arduino mega would draw anywhere between 200 - 500 mA.(even more)

The amount loss you will have is (9-5)V * (202.8 + 250)mA i.e. around **2 Watts**. **This is a lot of heat**. I'm not even sure the LM7805 would be able to handle it.

**Solution**: use a switching regulator like the one mentioned here: https://electronics.stackexchange.com/questions/21131/efficient-low-power-regulation-i-e-9-5-volts
> 1 votes

# Answer
It sounds like a power-to-ground short circuit, either a fault in the Ultrasonic sensor or in the connection to the Arduino.

Check your connections, and if you have an Ohm-meter, check the resistance between the sensor's power and ground pins.

Current consumption is a function of the device being powered, not of the power-supply, unless the supply lacks the capacity to provide as much current as the device needs.

Note that 9v batteries (the small brick aka a "transistor battery") is not well suited to supplying much current and probably will not power your Mega, or not for long, anyway. They are much better suited for long-term powering of very low current devices, such as a smoke detector.
> 1 votes

---
Tags: arduino-mega, relay
---


title: Turn Arduino on with timer every 24h

text:
# Question
Title: Turn Arduino on with timer every 24h
I'm currently working on an Arduino project that sends the charge of my car battery once a day via an ESP8266 to me. During the winter I don't drive my car, and I would like to get informed when the battery drops beyond a critical value, so I can charge it and prevent damage.

So energy efficiency is important for the project, so it doesn't discharge the battery itself. I read a lot about sleep mode, efficient drop down regulators etc. These all have in common that the voltage regulator is always running, which is not what I want.

I'm looking for some kind of "swich-on-timer circuit". It should count down 24 hours and then turn on a relay or MOSFET, which connects the voltage regulator to power and with that turns on the Arduino and the ESP8266. When the Arduino has finished with the transmission, it resets the timer, which disconnects the voltage regulator from power, and so on. Of course, the timer circuit should use only very little power.

Does anybody know a circuit like that? I searched on AliExpress with all variations of words that came to my mind, without success. Or maybe an IC which can be used (easily) to create such a circuit?

# Answer
One approach would be use of a DS3231 (Precision Real Time Clock) module. Such modules sell on Ebay for under $1. Search for `ds3231 arduino`.

Typically, these modules have a six-pin connector, with pins labeled 32K, SQW, SCL, SDA, VCC, and GND. As noted in DS3231 specs, the INT/SQW pin is used either for square-wave output or for interrupt output. On page 13 of specs, in the Control Register section, it says:

> Bit 2: Interrupt Control (INTCN). This bit controls the INT/SQW signal. When the INTCN bit is set to logic 0, a square wave is output on the INT/SQW pin. When the INTCN bit is set to logic 1, then a match between the time-keeping registers and either of the alarm registers activates the INT/SQW output (if the alarm is also enabled).

Initially, you would run a sketch to set up the DS3231: turn on a daily alarm, enable an interrupt rather than square wave, set the current time, etc. Then, load an operational program that reads car-battery voltage each time it runs, and acts appropriately.

The DS3231 INT/SQW pin would be wired to the gate of a P-channel mosfet that switches 12V power to the Arduino. The P-fet would turn on when the alarm's open-drain output pin INT/SQW turns on. The operational program does its business and then clears the DS3231 interrupt flag, to shut down power until the next alarm occurs. (For debugging, set briefer intervals than a day; for example, once a minute, as described in Table 2, Alarm Mask Bits, on page 12 of specs.)

Typically, the DS3231 draws 0.84 μA when running from a 3.3V battery, or 1 μA from 5V. See Electrical Characteristics, page 3 of specs.
> 5 votes

# Answer
The timer or timer-circuit itself would have to draw some current. Any of the pico-power AVR chips draw very little current in sleep mode - in the 10s of micro-amps for the 328, if I recall correctly. Sleeping an AVR for the least current draw needs just about everything shut down but the watchdog timer, and the maximum WDT period is 8 sec. A library like Narcoleptic will manage longer periods for you. What you would need to do though, is to provide a much more efficient regulated power supply than the one built onto the Arduino board (if that is what you'll be using). That done, the Arduino's load on your car battery should be microscopic.

One possible design for an efficient supply is an array of alkaline batteries, say 3 in series for a 4.5 output (while fresh) times 2 or more such strings in parallel, connected directly to the 5v bus.

I haven't done the power budgeting to know the capacity you'd need and whether you'd need D cells or could make a practical array from smaller ones, say AAs, but that is a way to achieve zero load on the car battery (discounting the car-battery voltage sensor's requirement). You might want to include the Arduino battery-array's health in the daily report, or, for the price of a few Alkalines, you might so over-design the Arduino battery that monitoring it would become unnecessary.

A couple of data points suggest a separate battery is a feasible approach:

* A single 9v Alkaline runs a smoke detector for over a year including over-wintering in an unheated attic (in my own experience), and 9v Alkalines are *not* known for their capacity.
* My digital setback thermostat has run for a couple of years on 2 AA cells, before a) they died, and b) I wised-up and started changing them annually. :)
> 3 votes

# Answer
Consider using "Adafruit TPL5110 Power Timer"
https://learn.adafruit.com/adafruit-tpl5110-power-timer-breakout/overview
> 0 votes

# Answer
you can use a timer switch. you can buy it from ebay for around 5 euros. i am using this one

https://www.ebay.com/itm/CN101-DC-12V-16A-Digital-LCD-Power-Programmable-Timer-Time-Relay-Switch-New/401190616827?hash=item5d68d2fefb:g:K3sAAOSwNRdX3ggT

i have also tried ds3231 but the arduino is on standby mode and it consume energy. this is the best solution i found
> -1 votes

---
Tags: power, timers, relay
---


# Question
Title: Arduino IDE c++ 11 raw string literal have issues with // in http://, complier thinks // is comment
```
char webpage[] PROGMEM = R"=====(
<html>
  <head>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/svg.js/2.6.6/svg.min.js"></script>
  </head>
  <body>
  </body>
</html>
)=====";

```

I found a problem when using the raw string literal in Arduino IDE. My code cannot compile if i have http:// link inside the string.

I found that it should be related to how Arduino IDE thought the string after // are comments and during compile time those string are ignored and my codes break.

It looks like the arduino ide's compiler removes all //comment in the code first, before it try to compile the raw string literal and then cause the issue.

As a test I try to debug it by changing my code to https:/-/ the program can be compile as now there is no // in the raw string literal

Is there any workaround?

# Answer
Escape the two quote marks inside the string using a backslash (literal quotes).

Without the escape characters, the URL is "outside" of a string because the quote marks are string delimiters.

```
char webpage[] PROGMEM = R"=====(
<html>
  <head>
    <script src=\"https://cdnjs.cloudflare.com/ajax/libs/svg.js/2.6.6/svg.min.js\"></script>
  </head>
  <body>
  </body>
</html>
)=====";

```
> 3 votes

# Answer
```
char webpage[] PROGMEM = R"=="==(
<html>
  <head>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/svg.js/2.6.6/svg.min.js"></script>
  </head>
  <body>
  </body>
</html>
)=="==";

```

inspired by answer provided by @jsotola if i used the syntax like this R"=="==()=="==" the link will become inside the quote. and hence the ide's complier regards it as a string and won't think // is comment and now the code can complie and the link works.
> 3 votes

# Answer
The C & C++ compilers don't look for language syntax inside quoted strings (except for character-escapes such as '\n'). That is the point of quoting the string.

This program just compiled Ok for me:

```
const char webpage[] PROGMEM = R"=====(
<html>
  <head>
    <script src=\"https://cdnjs.cloudflare.com/ajax/libs/svg.js/2.6.6/svg.min.js\"></script>
  </head>
  <body>
  </body>
</html>
)=====";

void setup() {
}

void loop() {
}

```

'//' within the string did not cause any problem. Your example did get an error message that the variable 'webpage' had to be const to put it in Flash memory so I added the 'const' keyword, but that is the only change I made.

If you do that, and your compiler is still complaining, there is some other issue than the '//'.
> 0 votes

---
Tags: string, compiler
---


title: Arduino pins not working

text:
# Question
Title: Arduino pins not working
I'm building my first arduino project and I encountered a strange problems;

I build a haunted house based upon that instructables tutorial: https://www.instructables.com/id/Control-Your-Halloween-Decorations-With-Arduino/

Every prop works, I tried to light them on and off (it works), but when I try to use all of them, a few doesn't work.

There is my code; Is it something I'm doing wrong?

```
int propSqueDans = 4;
int propClownImmo = 5;
int propClownJambes = 6;
int propSqueBal = 7;
int propSqueMini = 8;
int propSpider = 9;
int propChauSou = 10;
int propFantChai = 11;

int SensorPin = 3; // sensor connected to analog pin 3
int SensorVal = 0; // variable to store the value read

void setup() {
  pinMode(propSqueDans, OUTPUT);// sets the digital pin as output
  pinMode(propClownImmo, OUTPUT);
  pinMode(propClownJambes, OUTPUT);
  pinMode(propSqueBal, OUTPUT);
  pinMode(propSqueMini, OUTPUT);
  pinMode(propChauSou, OUTPUT);
  pinMode(propFantChai, OUTPUT);
  pinMode(propSpider, OUTPUT);
  Serial.begin(9600);

  }

void loop() {
    SensorVal = analogRead(SensorPin); // read the input pin

    if (SensorVal >100) {
    Serial.write("Danse + Clown Immo \n");
    digitalWrite(propSqueDans, HIGH);
    digitalWrite(propClownImmo, HIGH);
    delay(10000);
    Serial.write("Spider + Fangtôme + Clown jambes \n");
    digitalWrite(propSpider, HIGH);
    digitalWrite(propFantChai, HIGH);
    digitalWrite(propClownJambes, HIGH);

    delay(5000);
    Serial.write("Squelette balance + sque mini \n");
    digitalWrite(propSqueBal, HIGH);
    digitalWrite(propSqueMini, HIGH);

    delay(5000);
    Serial.write("Chauve souris \n");
    digitalWrite(propChauSou, HIGH);

    delay(20000);

    digitalWrite(propSqueDans, LOW);
    digitalWrite(propClownJambes, LOW);
    digitalWrite(propSqueBal, LOW);
    digitalWrite(propSqueMini, LOW);
    digitalWrite(propChauSou, LOW);
    digitalWrite(propFantChai, LOW);
    digitalWrite(propSpider, LOW);
    digitalWrite(propClownImmo, LOW);
    delay(5000);
    }

  }

```

Thank you for your help !

# Answer
My best guess (not knowing what the pins are driving) is that your trying to draw too much current from the Arduino gpio.

Ref: https://playground.arduino.cc/Main/ArduinoPinCurrentLimitations
> 1 votes

---
Tags: arduino-uno
---


# Question
Title: My Ultrasonic sensor is only showing 4cm range?
I am using an ultrasonic sensor SR04 with Arduino Uno and a sample program which I got from the library. However, my output reading is only 4 cm even when there is no object in front of it. I even used another sample program which had the same output. Is the problem in sensor or library?

```
#define TRIGGER_PIN  12
#define ECHO_PIN     11
#define MAX_DISTANCE 200

NewPing sonar(TRIGGER_PIN, ECHO_PIN, MAX_DISTANCE);

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

void loop() {
  delay(50);
  Serial.print("Ping: ");
  Serial.print(sonar.ping_cm());
  Serial.println("cm");
}

```

# Answer
I recommend, if you want reliability, that you upgrade to the HY-SRF05 sensor. The problem with the SR04 is that when there is nothing in front of the sensor (or the target is beyond the limit) the sensor sometimes "locks up," and you have to reset it to get it working correctly again. The SR04's are a few cents cheaper than the others; there's a reason for that.

Also, there's more than one library available for these sensors. I recommend the NewPing library by Tim Eckel available from here: https://bitbucket.org/teckel12/arduino-new-ping/wiki/Home

I am not affiliated with Tim in any way, but he's got a good library.
> 0 votes

# Answer
Looks to me like your powering the SR04 with 3.3v instead of 5v.
> 1 votes

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


# Question
Title: How to copy IPAddress class into character buffer? Getting error: "inet_ntop' was not declared in this scope"
I am using the WiFi library and trying to store the IP address in a character buffer so that I can print it out to an lcd that only accepts character buffers. My code for doing this:

```
 char * IPAD = new char[40
 IPAddress ip = WiFi.localIP();
 Serial.println(ip);
 char * bufIP = new char[40]();
 sprintf(bufIP, "%s", inet_ntop(ip));
 lcd.string(ip);

```

But when I compile this I get the error:

```
"inet_ntop' was not declared in this scope"

```

Help?

# Answer
> 2 votes
An `IPAddress` is a class. You can't use it like a number (although in certain circumstances you can assign it to a `uint32_t` and it gives you the numeric representation).

Also, the `inet_*` functions are only really relevant on a POSIX system with a full network stack - i.e., a computer, not a little Arduino without a proper networking stack.

You can, though, easily access the individual bytes of the IP address through the `[]` operator and place them into a char array with the right format:

```
sprintf(bufIP, "%d.%d.%d.%d", ip[0], ip[1], ip[2], ip[3]);

```

---
Tags: wifi
---


# Question
Title: How to create objects with their own variables?
So i created a class and when i created objects and use them, they seem to share their variables between each other ( the currentReading, previousReading and the time variable). how can i create objects that have their own variables so that type of conflict cant happen?

code : ( read the buttons and print them in the lcd screen)

```
#include <LiquidCrystal.h>

LiquidCrystal lcd(6, 5, 3, 2, 1, 0);

class button {
  public:
    void SetupButton(int pino);
    int Read();

  private:
    int _pin;
};

void button::SetupButton(int pin) {
  pinMode(pin, INPUT_PULLUP);
  _pin = pin;

}

int button::Read() {
  static boolean currentReading, previousReading = 1;
  static unsigned long time;

  currentReading = digitalRead(_pin);// reading
  if (previousReading - currentReading  == 1) { // when reading gos from 1 to 0
    time = millis();
  }

  if (currentReading - previousReading == 1 && (50 < (millis() - time) < 500)) {     // when reading gos back to 1 before 500ms
    previousReading = currentReading;
    return 1;
  }

  if (3000 > (millis() - time) && (millis() - time) > 500 && !currentReading) { // when reading keeps in 0 after 500ms
    previousReading = currentReading;
    return 2;
  }

  if ((millis() - time) > 3000 && !currentReading) { // // when reading keeps in 0 after 3000ms
    previousReading = currentReading;
    return  3;
  }

  previousReading = currentReading; // current reading becomes the previous

  return 0;
}

button up;
button down;

void setup() {
  lcd.begin(16, 2);
  up.SetupButton(A0);
  down.SetupButton(A1);

}
void loop() {

  lcd.setCursor(0, 0);
  lcd.print(up.Read());
  lcd.print(down.Read());

}

```

ps : i already know how to do this without using classes but doing it with classes makes the code much cleaner so i am trying to achieve this

# Answer
> 0 votes
I was tempted to re-write your code (I am quite rusty on c++), but you may be better to start with an existing class.

There is a Button class on the Arduino site. See https://playground.arduino.cc/Code/Button

You could use this or study to see a more usual c++ implementation and adapt your code.

Virtually ALL c++ classes include a constructor. I would use instead of SetupButton

```
void button::button(int pin) {
  this->_pin=pin;
  pinMode(pin, INPUT_PULLUP);
}

```

and add `uint8_t previousReading;` and `unsigned long time;` to your class as private variables.

---
Tags: lcd, button, object-oriented
---


title: Problem with Pulse Sensor signal

text:
# Question
Title: Problem with Pulse Sensor signal
I'm making alarm with input from pulse sensor. When it detect high heart rate then it send a text message. Everything works fine when i am using potentiometer (as input) for simulating triggering SMS. I made several heart rate trigger options based on ages, so i'm using switch-case in my loop. I'm using PulseSensor Playground library and some sample skecth that came from with it, but when i put program that read beat per minute and put that value inside if statement it become doesn't work at all. Even if i put the BPM value to serial monitor it only display 0. What can i do to fix this problem? Thanks

Here is my program:

```
#define USE_ARDUINO_INTERRUPTS true
#include <PulseSensorPlayground.h>
#include <SoftwareSerial.h>
#include <JC_Button.h>

const int OUTPUT_TYPE = SERIAL_PLOTTER;
const int PulseSensor = A0;
const int THRESHOLD = 550;

PulseSensorPlayground pulseSensor;
SoftwareSerial SIM800L(2, 3);  //(RX | TX)
const byte switchButton = 4;
int LED1 = 5;   //ages range 1
int LED2 = 6;   //ages range 2
int LED3 = 7;   //ages range 3
int greenLED  = 8;    //for normal heart rate
int yellowLED  = 9;   //for medium heart rate
int redLED = 10;      //for high heart rate

Button mybutton(switchButton);
boolean SMSsent = false;
int x = 0;

void setup(){
  mybutton.begin();
  pinMode(LED1, OUTPUT);
  pinMode(LED2, OUTPUT);
  pinMode(LED3, OUTPUT);
  pinMode(greenLED, OUTPUT);
  pinMode(yellowLED, OUTPUT);
  pinMode(redLED, OUTPUT);

  Serial.begin(115200);
  pulseSensor.analogInput(PulseSensor);
  pulseSensor.setSerial(Serial);
  pulseSensor.setOutputType(OUTPUT_TYPE);
  pulseSensor.setThreshold(THRESHOLD);

  SIM800L.begin(115200);
  Serial.println("SIM800L ready");
}

void led_for_ages_range_1(){
  digitalWrite(LED1, HIGH);
  digitalWrite(LED2, LOW);
  digitalWrite(LED3, LOW);
}
void led_for_ages_range_2(){
  digitalWrite(LED1, LOW);
  digitalWrite(LED2, HIGH);
  digitalWrite(LED3, LOW);
}
void led_for_ages_range_3(){
  digitalWrite(LED1, LOW);
  digitalWrite(LED2, LOW);
  digitalWrite(LED3, HIGH);
}

void led_indicator_1(){
  digitalWrite(greenLED, HIGH);
  digitalWrite(yellowLED, LOW);
  digitalWrite(redLED, LOW);
}
void led_indicator_2(){
  digitalWrite(greenLED, LOW);
  digitalWrite(yellowLED, HIGH);
  digitalWrite(redLED, LOW);
}
void led_indicator_3(){
  digitalWrite(greenLED, LOW);
  digitalWrite(yellowLED, LOW);
  digitalWrite(redLED, HIGH);
}

void range_1_indicator(){
  int BPMval = pulseSensor.getBeatsPerMinute();

  if (BPMval > 60 && BPMval < 85){
    led_indicator_1();
    SMSsent = false;
  }
  else if (BPMval > 86 && BPMval < 100){
    led_indicator_2();
    if(SMSsent == false){
      text_message_1();
      SMSsent = true;
    }
  }
  else if (BPMval > 101){
    if(SMSsent == false){
      text_message_2();
      SMSsent = true;
    }
  }
  else {
    SMSsent = false;
  }
}

void range_2_indicator(){
  int BPMval = pulseSensor.getBeatsPerMinute();

  if (BPMval > 60 && BPMval < 75){
    led_indicator_1();
    SMSsent = false;
  }
  else if (BPMval > 76 && BPMval < 90){
    led_indicator_2();
    if(SMSsent == false){
      text_message_1();
      SMSsent = true;
    }
  }
  else if (BPMval > 91){
    if(SMSsent == false){
      text_message_2();
      SMSsent = true;
    }
  }
  else {
    SMSsent = false;
  }
}

void range_3_indicator(){
  int BPMval = pulseSensor.getBeatsPerMinute();

  if (BPMval > 60 && BPMval < 70){
    led_indicator_1();
    SMSsent = false;
  }
  else if (BPMval > 71 && BPMval < 80){
    led_indicator_2();
    if(SMSsent == false){
      text_message_1();
      SMSsent = true;
    }
  }
  else if (BPMval > 81){
    if(SMSsent == false){
      text_message_2();
      SMSsent = true;
    }
  }
  else {
    SMSsent = false;
  }
}

void text_message_1(){
  int BPMval = pulseSensor.getBeatsPerMinute();
  SIM800L.write("AT+CMGF=1\r");
  delay(100);
  Serial.println("SIM800L set destination number.");
  SIM800L.write("AT+CMGS=\"0123456789\"\r");
  delay(100);
  Serial.println("Sending text message...");
  SIM800L.write("Your heart rate are: ");
  SIM800L.write(BPMval);
  SIM800L.write(" BPM");
  SIM800L.write("\r");
  Serial.println("Your heart rate are: ");
  Serial.print(BPMval);
  Serial.println(" BPM");
  SIM800L.write((char)26);
  delay(100);
  Serial.println("SMS sent.");
}

void text_message_2(){
  int BPMval = pulseSensor.getBeatsPerMinute();
  SIM800L.write("AT+CMGF=1\r");
  delay(100);
  Serial.println("SIM800L set destination number.");
  SIM800L.write("AT+CMGS=\"0123456789\"\r");
  delay(100);
  Serial.println("Sending text message...");
  SIM800L.write("Warning! Your heart rate are: ");
  SIM800L.write(BPMval);
  SIM800L.write(" BPM");
  SIM800L.write("\r");
  Serial.println("Warning! Your heart rate are: ");
  Serial.print(BPMval);
  Serial.println(" BPM");
  SIM800L.write((char)26);
  delay(100);
  Serial.println("SMS sent.");
}

void loop(){
  //int BPMval = pulseSensor.getBeatsPerMinute();
  static enum {OPTION_ONE, OPTION_TWO, OPTION_THREE} condition;
  while (x == 0){
    mybutton.read();
    switch (condition){
      case OPTION_ONE:
      led_for_ages_range_1();
      range_1_indicator();
      if (mybutton.wasReleased()){
        condition = OPTION_TWO;
      }
      break;

      case OPTION_TWO:
      led_for_ages_range_2();
      range_2_indicator();
      if (mybutton.wasReleased()){
        condition = OPTION_THREE;
      }
      break;

      case OPTION_THREE:
      led_for_ages_range_3();
      range_3_indicator();
      if (mybutton.wasReleased()){
        condition = OPTION_ONE;
      }
      break;
    }
  }
}

```

# Answer
> 1 votes
You forgot `pulseSensor.begin()` and you don't use `pulseSensor.sawNewSample()`. See the examples of the library.

The library uses interrupts to measure the pulse. (It takes time, which would otherwise block the loop execution). The `begin()` function starts this interrupts.

The value measured by interrupts is accessible with `getBeatsPerMinute()` and `sawNewSample()` function indicates that new value is available.

The library can work without interrupts (PulseSensor\_BPM\_Alternative.ino), but even then the `begin()` function initializes the library and `sawNewSample()` is then the function which **reads** the sensor.

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


# Question
Title: TimeAlarms stops working when using setSyncProvider(RTC.get) DS1307
Been working on this project for some time now, like title states when I un-comment `setSyncProvider(RTC.get)` in the setup the program fails to get any of the `Alarm.timerOnce` to run.

I have been stuck for a while and couldn't find anything while just googling so I thought I might enlist the minds of stack.

```
#include <Wire.h>
#include <TimeLib.h>
#include <TimeAlarms.h>
#include <DS1307RTC.h>  // a basic DS1307 library that returns time as a time_t

//#define DS1307_I2C_ADDRESS 0x68 // the I2C address of Tiny RTC
//byte second, minute, hour, dayOfWeek, dayOfMonth, month, year;

int curPin = 7, //  Current sense (middle terminal) connected to analog pin A7
  prePin = 6,     //  Pressure sense (green terminal) connected to analog pin A6
  ignPin = 7,     //  Igniter output pin D7
  solPin = 8,     //  Solenoid output pin D8
  genPin = 9,     //  Generator output pin D9
  tonePin = 11,   //  Tone output pin D11
  ligPin = 3,     //  Light sense pin A3
  intPin = 3,     //  Interupt pin D3 runs double bang

  runTime = 20,   //  minutes to run for

  state = 0;      //  state of operation

bool operate = false, // True if within operating time
   timeIsSet = false; // true if time till next opperation is set
double cur;

void setup() {
  Wire.begin();
  pinMode(13,OUTPUT);
  pinMode(ignPin, OUTPUT);
  pinMode(solPin, OUTPUT);
  pinMode(genPin, OUTPUT);
  Serial.begin(9600);
  //setSyncProvider(RTC.get);  //******************************************
  Alarm.alarmRepeat(dowMonday,7,30,0,OnAlarm);
  Alarm.alarmRepeat(dowTuesday,7,30,0,OnAlarm);
  Alarm.alarmRepeat(dowWednesday,7,30,0,OnAlarm);
  Alarm.alarmRepeat(dowThursday,7,30,0,OnAlarm);
  Alarm.alarmRepeat(dowFriday,7,30,0,OnAlarm);
  Alarm.alarmRepeat(dowSaturday,8,30,0,OnAlarm);
  Alarm.alarmRepeat(dowSunday,10,0,0,OnAlarm);
  Alarm.alarmRepeat(20,0,0,OffAlarm);
  tone(tonePin, 31, 1000);
  randomSeed(analogRead(0)); // nothing connected to 0 so read sees noise

  OnAlarm();
}

void loop() {
  if ((analogRead(ligPin) > 30) && operate == true)
  {
    if (timeIsSet == false)
    {
      tone(tonePin, 58, 500);
      int randm = random(27,36);
      Alarm.timerOnce(randm,operation);
      Serial.println(randm);
      timeIsSet = true;
    }
  }
  digitalClockDisplay();
  Alarm.delay(1000); // wait one second between clock display
}

void operation(){
  tone(tonePin, 100, 1000);
  Alarm.timerOnce(12,after20m);
  digitalWrite(genPin, HIGH);
}

void after20m(){
  digitalWrite(genPin, LOW);
  Alarm.timerOnce(5,after5s);
  digitalWrite(solPin, HIGH);
  tone(tonePin, 494, 1000);
  timeIsSet = false;
}

void after5s(){
  tone(tonePin, 200, 1000);
  digitalWrite(solPin, LOW);
  Alarm.timerOnce(1,after1s);
}

void after1s()
{
  digitalWrite(ignPin, HIGH);
  Alarm.delay(500);
  digitalWrite(ignPin, LOW);
}

void OnAlarm() {
  operate = true;
}

void OffAlarm() {
  operate = false;
}

// Convert normal decimal numbers to binary coded decimal
byte decToBcd(byte val)
{
return ( (val/10*16) + (val%10) );
}
// Convert binary coded decimal to normal decimal numbers
byte bcdToDec(byte val)
{
return ( (val/16*10) + (val%16) );
}

void digitalClockDisplay() {
  // digital clock display of the time
  Serial.print(hour());
  printDigits(minute());
  printDigits(second());
  //Serial.print(operate);
  Serial.println();
}

void printDigits(int digits) {
  Serial.print(":");
  if (digits < 10)
    Serial.print('0');
  Serial.print(digits);
}

```

# Answer
> -1 votes
Problem existed in the TimeAlarms library,

```
Q: How many alarms can be created?
A: Up to six alarms can be scheduled.
The number of alarms can be changed in the TimeAlarms header file (set by the constant
dtNBR_ALARMS,
note that the RAM used equals dtNBR_ALARMS  * 11)

```

so how I fixed it was to edit `#define dtNBR_ALARMS 6 // max is 255` to `#define dtNBR_ALARMS 14 // max is 255` in the `TimeAlarms.h` file.

---
Tags: arduino-nano, time, rtc
---


# Question
Title: control vibrator motor speed with ultrasonic sensors
First, thank you for taking the time to read my post.

I am attempting to use 3 ultrasonic sensors to control 3 DC vibrator motor using the PWM output of an Arduino. Fairly simple, I know, but I'm just a beginner. :)

Here's my code,

```
int trigpin_1 = 2;
int echopin_1 = 3;
int trigpin_2 = 4;
int echopin_2 = 5;
int trigpin_3 = 6;
int echopin_3 = 7;
int motor_1 = 8;
int motor_2 = 9;
int motor_3 = 10;

void setup() {
  // put your setup code here, to run once:
  Serial.begin (9600);
  pinMode(trigpin_1, OUTPUT);
  pinMode(echopin_1, INPUT);
  pinMode(trigpin_2, OUTPUT);
  pinMode(echopin_2, INPUT);
  pinMode(trigpin_3, OUTPUT);
  pinMode(echopin_3, INPUT);
  pinMode(motor_1, OUTPUT);
  pinMode(motor_2, OUTPUT);
  pinMode(motor_3, OUTPUT);
}

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

  long duration, distance;
  digitalWrite(trigpin_1, HIGH);
  digitalWrite(trigpin_2, HIGH);
  digitalWrite(trigpin_3, HIGH);
  delayMicroseconds(1000);
  digitalWrite(trigpin_1, LOW);
  digitalWrite(trigpin_2, LOW);
  digitalWrite(trigpin_3, LOW);
  duration = pulseIn(echopin_1, HIGH);
  duration = pulseIn(echopin_2, HIGH);
  duration = pulseIn(echopin_3, HIGH);
  distance = (duration/2) /29.1;
  if (distance > 200)
  {
    analogWrite(motor_1, 0);
    analogWrite(motor_2, 0);
    analogWrite(motor_3, 0);
  }
  else if(200 == distance > 160)
  {
    analogWrite(motor_1, 50);
    analogWrite(motor_2, 50);
    analogWrite(motor_3, 50);
  }
  else if(160 >= distance > 90)
  {
    analogWrite(motor_1, 100);
    analogWrite(motor_2, 100);
    analogWrite(motor_3, 100);
  }
  else if(90 >= distance > 60)
  {
    analogWrite(motor_1, 150);
    analogWrite(motor_2, 150);
    analogWrite(motor_3, 150);
  }
  else if(60 >= distance > 40)
  {
    analogWrite(motor_1, 200);
    analogWrite(motor_2, 200);
    analogWrite(motor_3, 200);
  }
  else if(40 >= distance)
  {
    analogWrite(motor_1, 255);
    analogWrite(motor_2, 255);
    analogWrite(motor_3, 255);
  }

  Serial.print (distance);
  Serial.println (" cm");
  delay(100);
}

```

but the problem is the DC motors it will be on all the time with 100% duty cycle. if anyone can help me will be thankful

# Answer
> 2 votes
There is quite a bit wrong with your code I'm afraid.

Firstly the if statements. If the values are kept in descending order then you can do this:

```
if (distance > 200)
{...}
else if (distance > 160)  // This point won't be reached unless the value is less than 200.
{...}
else if (distance > 100)
{...}

```

I think what you were trying to do was:

```
if (distance < 200 && distance > 160)
{...}

```

but its not necessary.

You are reading the pulse lengths into a single variable overwriting the previous values. This means you are only reading sensor 3. If you want to average the values then try this:

```
duration = pulseIn(echopin_1, HIGH);
duration += pulseIn(echopin_2, HIGH); // take the result and add it to duration.
duration += pulseIn(echopin_3, HIGH);
duration /= 3;   // divide duration by three and assign the result to duration.

```

Also I'm not sure about the positioning of your sensors, its possible that they might interfere with each other. In which case write a function to read from the sensor and store the results in an array.

i.e. const int sensorTriggerPins\[\] = {2, 4, 6}; const int sensorEchoPins\[\] = {3, 5, 7};

```
long readSensor (const int& triggerPin, const int& eechoPin)
{
  digitalWrite(triggerPin, HIGH);
  delayMicroseconds(1000);
  digitalWrite(triggerPin, LOW);
  return pulseIn(echoPin, HIGH);
}

void setup()
{
   long duration[3]; // Define a three element array.
   for (int sensor = 0; sensor < 3; ++sensor)
   {
      duration[index] = readSensor(sensorTriggerPin[index], sensorEchoPin[index]);
   }
}

```

I don't know if this will fix all your problems, but it should help. (It might have been better if you posted this in the Arduino forum)

# Answer
> 0 votes
You don't want to use GPIO outputs to drive motors directly. You'll likely burn-out your Arduino with the schematic you've given. At a minimum you'll want to use transistors (that can handle the motor current load) to switch the motors on/off.

---
Tags: motor
---


# Question
Title: cannot show free space of SD card with arduino nano
I'm using a nano v3, the SD module and a 64GB microSD card. Writing to the card works fine. But I can't print out the free space left on the card.

I'm using this code:

```
/*
  SD card read/write

 This example shows how to read and write data to and from an SD card file
 The circuit:
 * SD card attached to SPI bus as follows:
 ** MOSI - pin 11
 ** MISO - pin 12
 ** CLK - pin 13

 created   Nov 2010
 by David A. Mellis
 modified 9 Apr 2012
 by Tom Igoe

 This example code is in the public domain.

 */

#include <SPI.h>
//#include <SD.h>
#include "SdFat.h"
SdFat SD;

#define csPin 4
File myFile;
SdFat sd;

int startMillis;
int duration;

uint32_t freeKB;

void setup() {
  // Open serial communications and wait for port to open:
  Serial.begin(9600);
  while (!Serial) {
    ; // wait for serial port to connect. Needed for native USB port only
  }

  Serial.print("Initializing SD card...");

  if (!SD.begin(csPin)) {
    Serial.println("initialization failed!");
    return;
  }
  Serial.println("initialization done.");

  // open the file. note that only one file can be open at a time,
  // so you have to close this one before opening another.
  myFile = SD.open("test.txt", FILE_WRITE);
  if (myFile) {
    myFile.close();
    Serial.println("done.");
  } else {
    // if the file didn't open, print an error:
    Serial.println("error opening test.txt");
  }
}

void loop() {
  myFile = SD.open("test.txt", FILE_WRITE);

  for (int j = 0; j < 1000; j++) {
    myFile.println(j);
  }
  myFile.close();
  startMillis = millis();
  ShowFreeSpace();
  duration = millis() - startMillis;
  Serial.print("Took ");
  Serial.print(duration);
  Serial.println("ms to calculate");
  delay(1000);
}

void ShowFreeSpace() {
  // Calculate free space (volume free clusters * blocks per clusters / 2)
  long lFreeKB = sd.vol()->freeClusterCount();
  lFreeKB *= sd.vol()->blocksPerCluster()/2;

  // Display free space
  Serial.print("Free space: ");
  Serial.print(lFreeKB);
  Serial.println(" KB");
}

```

What am I doing wrong?

# Answer
You have two instances of SdFat class. In setup() you `begin` the `SD` and for free space you try to use `sd`. Delete `SdFat sd;` line and in ShowFreeSpace use `SD.vol()`.
> 1 votes

---
Tags: sd-card
---


# Question
Title: avrdude: stk500_getsync() attempt 10 of 10: not in sync: resp=0x17
Every time I try to upload code to my arduino I always get this error : avrdude: stk500\_getsync() attempt 10 of 10: not in sync: resp=0x17. How do i fix it ?

# Answer
> 0 votes
Welcome to the community! I'm not able to comment yet so i'll answer here. Try changing the connection to other USB port. If that doesnt work check this question, the solutions can be similar (Juraj is right in the comments) : avrdude: stk500\_getsync(): not in sync: resp=0x00," aka Some Dude Named Avr Won't Let Me Upload My Program

Good Luck!

---
Tags: arduino-uno
---


# Question
Title: How to boil down analog input to just three cases?
I am investigating the use of a 3-position-switch for one of my projects to switch between different settings using just one analog input pin. For the three positions I am using ground/0V, ~2.5V (via 2x10k voltage divider) and full 5V. I am doing this also because I am planning to use a 5-position rotary switch in a similar way in the future.

Due to tolerances and noise, the readings on the analog pin are not precisely 0, 511, 1023, but rather 0-1, 509-512 and 1021-1023. To take this into account, I am using the `map` function like this:

```
const byte alarmSwitchPin = A0;
int alrmSwState;
byte alrmSet;
byte alrmPrevSet;

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

}

void loop() {

  alrmSwState = analogRead(alarmSwitchPin);       // Read input

  byte alrmSet = map(alrmSwState, 0, 1023, 0, 2); // Boil input down to three cases

  if (alrmSet != alrmPrevSet) {                   // Only if state of switch has changed
    switch (alrmSet) {
      case 0:
        Serial.println("Low");
        break;
      case 1:
        Serial.println("Medium");
        break;
      case 2:
        Serial.println("High");
        break;
    }
    alrmPrevSet = alrmSet;
    delay(200);                                   // For testing purposes
  }
}

```

I only want the setting to change (or, in this case, the console to print) when the state has actually changed. This does not work, though, because the `map` function is doing its math in integer, which fails in mapping the High position (in this case).

What are my options if I want to stick with the `switch` method? I am curious if it is possible to get this done without `if` statements and conditions or, as a more general question, what the best option is to properly map the 10 bit analog input to just 3 cases/numbers.

PS: I thought `analogReadResolution()` might be an option but I am working with Arduino UNO where this is unavailable.

# Answer
The simplest fix to your problem is to change the `map()` call to

```
byte alrmSet = map(alrmSwState, 0, 1024, 0, 3);

```

In the call above, the mapped intervals are of the semi-open type, e.g. \[a, b), where the start values (namely 0) are understood as being *inclusive* and the end values (1024 and 3) are *exclusive*.

Although not clear from the documentation, this is the proper way to use the `map()` function. Otherwise, the truncated division gives you very uneven intervals. Compare:

```
     x       map(x, 0, 1023, 0, 2)
----------------------------------
   0 –  511     0
 512 – 1022     1
1023            2

     x       map(x, 0, 1024, 0, 3)
----------------------------------
   0 –  341     0
 342 –  682     1
 683 – 1023     2

```

The result you get is very close to Jeff Wahaus’ answer.

What I find annoying about this approach is that a 32-bit integer division, which `map()` uses internally, is a very expensive operation on the small 8-bit Arduinos. If instead of 342 and 683, you use 256 and 768 as thresholds, then you can make the decision by just looking at the high byte of the analog reading:

```
uint16_t alrmSwState = analogRead(alarmSwitchPin);

alrmSet = alrmSwState / 256;

if (alrmSet != alrmPrevSet) {
    switch (alrmSet) {
        case 0:
            Serial.println("Low");
            break;
        case 1:
        case 2:
            Serial.println("Medium");
            break;
        case 3:
            Serial.println("High");
            break;
    }
    alrmPrevSet = alrmSet;
    delay(200);
}

```

Note that the division by 256 is optimized by the compiler into a much cheaper bit shift, but this is the case only if `alrmSwState` is of an unsigned integer type. That's why it is declared above as `uint16_t`.
> 4 votes

# Answer
Replace the line:

byte alrmSet = map(alrmSwState, 0, 1023, 0, 2);

with

byte alrmSet = alrmSwState / ((1023 / 3) + 1);

And this should do what you want. Note that in C fractional results are truncated (not rounded)
> 3 votes

# Answer
Just three lines of code are needed for the conversion.

```
almSet=0;
if (alrmSwState>300) almSet++;   // increment almSet
if (alrmSwState>600) almSet++;

```
> 2 votes

# Answer
You might also consider reading the value several times and summing them, then base your decision on the sum.

This is equivalent to averaging the values but without dividing by 'n', since you don't care about the actual number, just the band it falls into. This will have the effect of improving the signal to noise ratio, since we assume that high-reading errors are as likely as low-reading errors, so their sum tends toward zero as the sum of the real value, V, tends toward (n\*V).

Use an int or larger variable for the sum, depending on how many readings you choose to take each time.
> 0 votes

---
Tags: analogread, switch, map
---


title: ESP32 Dimmable LED Panel with MOSFET

text:
# Question
Title: ESP32 Dimmable LED Panel with MOSFET
I want to use ESP32 to control and use a dimmer for 6 LED panels in my bedroom. The specification of each panel is mentioned in the diagram. Although in the diagram it shows ONLY 1 MOSFET and 1 LED Panel but in reality there are 6 LED Panels therefore I am guessing that each of the 6 LED Panel will need a separate MOSFET.

I would like to know:

1. What MOSFET (Part number or model number, company name, etc) should I use for the above LED panel connected with ESP32 (I guess voltage of ESP32 is 3.3 v) ?
2. Will each LED panel need separate MOSFET (6 LED Panels will need 6 seperate MOSFET) or can 1 MOSFET be connected to all 6 LED Panel ?
3. If I am using 6 LED Panels what should be the specification of Power Supply (Voltage & Amps) ?
4. If I use 6 set of MOSFET & LED Panels, can all MOSFETs be connected to a single PWM pin in ESP32 or does each MOSFET needs to be connected to separate PWM pins in ESP32 ?
5. Is the above circuit okay, or would you suggest some other components to be added apart from MOSFET?
6. What will be connection between power supply, LED and MOSFET. I am guessing that 'Positive of Power Supply --\> Positive of LED Panel', 'Negative of LED Panel --\> Source of MOSFET' and 'Drain of MOSFET --\> Negative of Power Supply'. Kindly correct me if I am wrong.

Thanks.

---

To add more information regarding the LED panel:

1. It is 15W LED Panel (note it is not LED Bulb or LED Strip). Link to LED panel is 15W LED Panel

2. Below is the picture of Driver that came with the LED Panel, note the below driver is non-dimmable.

Kindly help.

# Answer
> 2 votes
Your plan has more flaws. First as Juraj wrote in a comment, you can't dim a switching power supply of the LED bulb. But this would not work as you plan even if you use a classic incandescent light bulb with AC. You can't control it with PWM. AC is dimmed with phase control, which requires a zero crossing detection to turn off power for part of the AC wave.

---
Tags: power, led, pwm, esp32, mosfet
---


# Question
Title: ATmega328, arduino nano v3 code error saying insufficient ram memory
the code error says this and im not sure what to do please i need urgent help :(\`

```
// Easy bluetooth controlled scrolling text

// by Yoruk for Instructable

// 26 02 15 : first code
// 03 03 15 : buffer updating
// 04 03 15 : faster version, both buffers
// 05 03 15 : cleaning and help

/*
WIRING :
 pin 12 - DataIn of the first led matrix module
 pin 11 - CLK of the first led matrix module
 pin 10 - CS of the first led matrix module

 pin 9 : RX pin of the bluetooth module
 pin 8 : TX pin of the bluetooth module

 5V : 5v of the matrix module, 5v of the bluetooth module
 GND : the two GND signals of the matrix modules and the bluetooth module

 WARNING : Use a 3v3 arduino card (nano...) or a level converter !!!

 Wire the matrix modules in serie. See the Instructable steps.

 */

//Librairie for the LEDs matrix
#include "LedControl.h"

// virtual serial lib, used with bluetooth
#include <SoftwareSerial.h>

//How many matrixes we have ?
int MatrixNumber =5;

//virtual serial port bluetooth configuration
SoftwareSerial BT(8, 9);   //pin 8 : virtual RX    pin 9 :  virtual TX

// the delay between each screen display (ms)
int SpeedDelay = 12;

//total string lenght. The first message is 25 characters long (including spaces)
int LongueurChaine=25;

char incomingByte; //incoming data from the BT link

// the two pixels arrays
char Buffer[200];   //contient tout les pixels de TOUTE LA PHRASE
char Buffer_inverse[200]; //contient tout les pixels de TOUTE LA PHRASE, mais symetrises pour affichage sur ecran inverses

// the message array
char Phrase[50];

//here we set up the led matrix
LedControl lc=LedControl(12,11,10,MatrixNumber);

// character lib
int fontDefinitions[480] = {
    0x00,0x00,0x00,0x00,0x00,/*space*/ // is 32 in ASCII
    0x00,0xF6,0xF6,0x00,0x00,/*!*/
    0x00,0xE0,0x00,0xE0,0x00,/*"*/
    0x28,0xFE,0x28,0xFE,0x28,/*#*/
    0x00,0x64,0xD6,0x54,0x08,/*$*/
    0xC2,0xCC,0x10,0x26,0xC6,/*%*/
    0x4C,0xB2,0x92,0x6C,0x0A,/*&*/
    0x00,0x00,0xE0,0x00,0x00,/*'*/
    0x00,0x38,0x44,0x82,0x00,/*(*/
    0x00,0x82,0x44,0x38,0x00,/*)*/
    0x88,0x50,0xF8,0x50,0x88,/***/
    0x08,0x08,0x3E,0x08,0x08,/*+*/
    0x00,0x00,0x05,0x06,0x00,/*,*/
    0x08,0x08,0x08,0x08,0x08,/*-*/
    0x00,0x00,0x06,0x06,0x00,/*.*/
    0x02,0x0C,0x10,0x60,0x80,/*/*/
    0x7C,0x8A,0x92,0xA2,0x7C,/*0*/
    0x00,0x42,0xFE,0x02,0x00,/*1*/
    0x42,0x86,0x8A,0x92,0x62,/*2*/
    0x44,0x82,0x92,0x92,0x6C,/*3*/
    0x10,0x30,0x50,0xFE,0x10,/*4*/
    0xE4,0xA2,0xA2,0xA2,0x9C,/*5*/
    0x3C,0x52,0x92,0x92,0x0C,/*6*/
    0x80,0x86,0x98,0xE0,0x80,/*7*/
    0x6C,0x92,0x92,0x92,0x6C,/*8*/
    0x60,0x92,0x92,0x94,0x78,/*9*/
    0x00,0x00,0x36,0x36,0x00,/*:*/
    0x00,0x00,0x35,0x36,0x00,/*;*/
    0x10,0x28,0x44,0x82,0x00,/*<*/
    0x28,0x28,0x28,0x28,0x28,/*=*/
    0x00,0x82,0x44,0x28,0x10,/*>*/
    0x40,0x80,0x8A,0x90,0x60,/*?*/
    0x7C,0x82,0xBA,0xBA,0x62,/*@*/
    0x3E,0x48,0x88,0x48,0x3E,/*A*/
    0xFE,0x92,0x92,0x92,0x6C,/*B*/
    0x7C,0x82,0x82,0x82,0x44,/*C*/
    0xFE,0x82,0x82,0x82,0x7C,/*D*/
    0xFE,0x92,0x92,0x92,0x82,/*E*/
    0xFE,0x90,0x90,0x90,0x80,/*F*/
    0x7C,0x82,0x82,0x8A,0x4E,/*G*/
    0xFE,0x10,0x10,0x10,0xFE,/*H*/
    0x82,0x82,0xFE,0x82,0x82,/*I*/
    0x84,0x82,0xFC,0x80,0x80,/*J*/
    0xFE,0x10,0x28,0x44,0x82,/*K*/
    0xFE,0x02,0x02,0x02,0x02,/*L*/
    0xFE,0x40,0x20,0x40,0xFE,/*M*/
    0xFE,0x60,0x10,0x0C,0xFE,/*N*/
    0x7C,0x82,0x82,0x82,0x7C,/*O*/
    0xFE,0x90,0x90,0x90,0x60,/*P*/
    0x7C,0x82,0x82,0x86,0x7E,/*Q*/
    0xFE,0x90,0x98,0x94,0x62,/*R*/
    0x64,0x92,0x92,0x92,0x4C,/*S*/
    0x80,0x80,0xFE,0x80,0x80,/*T*/
    0xFC,0x02,0x02,0x02,0xFC,/*U*/
    0xF8,0x04,0x02,0x04,0xF8,/*V*/
    0xFC,0x02,0x0C,0x02,0xFC,/*W*/
    0xC6,0x28,0x10,0x28,0xC6,/*X*/
    0xC0,0x20,0x1E,0x20,0xC0,/*Y*/
    0x86,0x8A,0x92,0xA2,0xC2,/*Z*/
    0x00,0x00,0xFE,0x82,0x00,/*[*/
    0x00,0x00,0x00,0x00,0x00,/*this should be / */
    0x80,0x60,0x10,0x0C,0x02,/*]*/
    0x20,0x40,0x80,0x40,0x20,/*^*/
    0x01,0x01,0x01,0x01,0x01,/*_*/
    0x80,0x40,0x20,0x00,0x00,/*`*/
    0x04,0x2A,0x2A,0x2A,0x1E,/*a*/
    0xFE,0x12,0x22,0x22,0x1C,/*b*/
    0x1C,0x22,0x22,0x22,0x14,/*c*/
    0x1C,0x22,0x22,0x12,0xFE,/*d*/
    0x1C,0x2A,0x2A,0x2A,0x18,/*e*/
    0x10,0x7E,0x90,0x80,0x40,/*f*/
    0x18,0x25,0x25,0x25,0x1E,/*g*/
    0xFE,0x10,0x10,0x10,0x0E,/*h*/
    0x00,0x12,0x5E,0x02,0x00,/*i*/
    0x02,0x01,0x01,0x11,0x5E,/*j*/
    0xFE,0x08,0x08,0x14,0x22,/*k*/
    0x00,0x82,0xFE,0x02,0x00,/*l*/
    0x3E,0x20,0x1C,0x20,0x1E,/*m*/
    0x3E,0x20,0x20,0x20,0x1E,/*n*/
    0x1C,0x22,0x22,0x22,0x1C,/*o*/
    0x3F,0x24,0x24,0x24,0x18,/*p*/
    0x18,0x24,0x24,0x3F,0x01,/*q*/
    0x3E,0x10,0x20,0x20,0x10,/*r*/
    0x12,0x2A,0x2A,0x2A,0x04,/*s*/
    0x00,0x10,0x3C,0x12,0x04,/*t*/
    0x3C,0x02,0x02,0x02,0x3E,/*u*/
    0x30,0x0C,0x02,0x0C,0x30,/*v*/
    0x38,0x06,0x18,0x06,0x38,/*w*/
    0x22,0x14,0x08,0x14,0x22,/*x*/
    0x38,0x05,0x05,0x05,0x3E,/*y*/
    0x22,0x26,0x2A,0x32,0x22,/*z*/
    0x00,0x10,0x6C,0x82,0x82,/*{*/
    0x00,0x00,0xFF,0x00,0x00,/*|*/
    0x04,0x02,0xFF,0x02,0x04,/*|, arrow*/
    0x82,0x82,0x6C,0x10,0x00,/*}*/
    0x08,0x10,0x18,0x08,0x10/*~*/
};

void setup() {

    //matrix modules init
    for(int adresse=0;adresse<MatrixNumber;adresse++) {
        /*The MAX72XX is in power-saving mode on startup*/
        lc.shutdown(adresse,false);
        /* Set the brightness to a medium values */
        lc.setIntensity(adresse,4);
        /* and clear the display */
        lc.clearDisplay(adresse);
    }

//    BufferBuilding("Hi ! Sent me a message...", 25);   //first message on the led screen

    BufferBuilding("text", 4);   //first message on the led screen

    Serial.begin(9600); //we also set the normal serial link, for debug

    BT.begin(9600);      // bluetooth initialisation

    //we sent a message on the phone to tell the user that he can do someting...
    BT.println("Hi ! I'm waiting for a message. Type it and press SEND.");

}

void loop() {

    DrawText( LongueurChaine); //draw the message, in a loop

    //or, if we get something on the virtual bluetooth port...
    if (BT.available() > 0) {

        LongueurChaine = BT.available(); //incoming string lenght

        for  (int i = 0; i < LongueurChaine; i++) {

            // read the incoming byte:
            incomingByte = BT.read();

            Phrase[i] = incomingByte; ///store the character into the string array

        }

        //debug features, to check :
        Serial.print("Display: ");
        Serial.println(Phrase);
        Serial.print("Length : ");
        Serial.println(LongueurChaine);

        //buffers cleaning, to store the new message
        for(int k = 0; k < 200; k++) {
            Buffer[k]=0;
            Buffer_inverse[k]=0;

        }

        //we create the new buffers, so the new message will be drawn when leaving the sub
        BufferBuilding(Phrase, LongueurChaine);
    }

}

void BufferBuilding(char * stringToDisplay, byte stringLength)
{
    int i =0;

    //loop on every characters (on the string)
    for(int k = 0; k < stringLength; k++) {
        //here we call the characters library
        int caract= k;
        Buffer[i+0] =  fontDefinitions[((stringToDisplay[caract] - 32) * 5) + 0];
        Buffer[i+1] =  fontDefinitions[((stringToDisplay[caract] - 32) * 5) + 1];
        Buffer[i+2] =  fontDefinitions[((stringToDisplay[caract] - 32) * 5) + 2];
        Buffer[i+3] =  fontDefinitions[((stringToDisplay[caract] - 32) * 5) + 3];
        Buffer[i+4] =  fontDefinitions[((stringToDisplay[caract] - 32) * 5) + 4];
        Buffer[i+5] =  B00000000;  //one blank column of leds between two characters
        i=i+6;
    }

    // here, we create a second buffer, to display the message on the switched matrixes
    for(int k = 0; k < stringLength*6; k++) {
        for(int i = 0; i < 8; i++) {
            bitWrite(  Buffer_inverse[k] ,i,  bitRead(Buffer[k] ,7-i) )   ;
        }
    }
}

void DrawText( byte stringLength) {

    for(int k = 0; k < stringLength*6; k++) {

        delay(SpeedDelay);

//delay(10000);
        //k is the column

        //buffer drawing
        for (int m = 0; m < MatrixNumber; m++) {  //loop on the matrix
            if (m % 2 ==  0) //check is the module is upside-down or not...
            {
                //here, the matrix is flipped upside-down
                for (int i = 0; i < 8; i++) {  //loop on the columns

                      lc.setRow(m,7-i,Buffer[i+k+8*m]);
                }
            }
            else
            {
                //classical
                for (int i = 0; i < 8; i++) {  //loop on the columns

                       lc.setRow(m,i,Buffer_inverse[i+k+8*m]);
                }
            }
        }
    }

}

```

# Answer
> 3 votes
The font definition table takes 960 bytes of RAM - nearly 1/2 of the the total usage. You can regain 480 bytes just by declaring that array as `uint8_t`; 1 byte each entry instead of 2 bytes each for `int`s. You can regain the remaining 480 if you still need to, by moving that table to program memory. The Arduino.cc site has a good discussion with examples. Just pay attention to the data-types you use if you do that; the functions to read data out of program memory each return one specific type.

# Answer
> -1 votes
You can free up RAM by moving large arrays and strings into Flash. By default all strings and arrays are placed into RAM. The disadvantage to putting data into Flash is that you will not be able to modify it at runtime.

To place an array in Flash use the PROGMEM compiler directive:

```
static const unsigned char PROGMEM my_array[] = { 0x00, 0x01, 0x02 ... };

```

When doing this your likely to notice, besides more available RAM, that many library functions can longer access the array you've placed into FLASH. The AVR microcontrollers have to use special instructions to read data out of Flash memory. Some library functions handle this automatically but many do not. In order to access the data you'll have to implement a function that copies the data out of Flash and into RAM.

Here is an example of a function to copy Flash data into RAM:

```
char *Get_Flash_String(const char *FlashString)
{
    static char buff[MAX_FLASH_STRING_LENGTH+1];
    int i, len;

    len = strlen_P(FlashString);
    for (i = 0; i <= len; i++)
        buff[i] = pgm_read_byte_near(FlashString + i);

    return(buff);
}

```

Note that the function above assumes you're reading a NULL terminated string out of flash. If you're reading an array you don't want to use strlen() to determine the length.

---
Tags: arduino-nano, memory, progmem
---


# Question
Title: How to connect NRF24 receiver and Micro SD Card Module to Arduino UNO
I would like to know how to connect a NRF24 receiver and Micro SD card module to Arduino board. I have already connected the NRF24 module to the arduino board but now i can't connect the Micro SD card module since the ports like 13,12,11 are used by the NRF24 module. Is there a way to connect those two modules?. I'm trying to save the receiving data on the Micro SD card.

# Answer
SPI is a *multi-drop bus* protocol. That means that multiple devices can share the same physical communication medium (wires).

The only thing that needs to be "unique" for a device is its *chip select* pin which the master device (Arduino) uses to choose which of the devices on the SPI bus it's talking to.

So you can share pins 11, 12 and 13, but choose a different *chip select* pin for each device.

However, SD cards are notorious for not working well with other devices (especially with some cheap breakout boards) and your mileage may vary.
> 1 votes

---
Tags: arduino-uno, sd-card, nrf24l01+
---


# Question
Title: Can an ultrasonic sensor differentiate b/w objects?
Can we potentially use an ultrasonic sensor to differentiate between objects based on the reflective capacity of the object? For example to differentiate between metals and biodegradable wastes.

# Answer
> 1 votes
No. No, you can't. All they sense is the "time of flight".

The closest you would come would be to have a sensor which can detect physical properties of the target. That could be colour, sound absorption, etc. You'd need something that sends out a "broad spectrum" signal (white light, white noise, etc) and detects the *reflected spectrum* (colour sensor, wide-band microphone) and do spectral analysis of it. The signal would also have to be fairly tightly focussed to exclude signals from the environment.

All-in-all not something for a little Arduino to consider without lots of extra expensive hardware.

---
Tags: sensors
---


# Question
Title: why my arduino uno r3 restart when plugged in to a battery(9v)
i have a personal challenge that is to make a arduino avoidance robot it has a"hc-sr04 ultrasonic sensor, a servo, bread board(for the sharing of vcc and gnd), l9110s motor driver, and two dc motors, and also the arduino uno itself" but when i assembled it and upload the code it works if it's plugged in my laptop but if i plugged it in to a battery it keeps on restarting and doesn't run

# Answer
> 1 votes
Let me guess: the Arduino resets just as one of the motors starts (or should start) right?

The 9v battery is incapable of supplying enough current for much of anything but a few LEDs. When the Arduino first turns on a motor, it needs, and tries to draw, more current than the battery can supply, resulting in the battery voltage dropping below the Arduino's voltage-regulator's minimum input voltage, and the Arduino is shut off. That stops the current draw, the battery voltage recovers, power up the Arduino, which resets (as they always do on power-up), and the cycle keeps repeating.

Try powering it from a more capable battery of greater than 7 volts. 5 AA cells in series, for example would provide 7.5 volts. This won't last terribly long but should work for a while. A second (third, ...) string of 5 in parallel with the first should double the life. Using C or D cells instead will increase the life a lot more.

---
Tags: arduino-uno
---


# Question
Title: Serial monitor doesn't work with piezo buzzer
So I can't see the distance of the proximity sensor anymore as soon as I type the code for the piezo buzzer. I've tried many things but it doesn't work.. Can anybody help me fixing this?

```
int trigPin = D7;
int echoPin = D8;
int BLUE = D3; //D3 zit in blauw
int GREEN = D4;
int RED = D5;
int piezoPin = D10;

void setup() {// deze code gaat maar 1 keer
  Serial.begin (115200);
  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);

  pinMode(GREEN, OUTPUT);
  pinMode(BLUE, OUTPUT);
  pinMode(RED, OUTPUT);

}

void loop() { //code wordt steeds herhaalt
  long duration, distance;
  digitalWrite(trigPin, LOW);
  delayMicroseconds(2);
  digitalWrite(trigPin, HIGH); // trig zendt een signaal uit
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);
  duration = pulseIn(echoPin, HIGH); // kijkt hoelang het duurt totdat signaal heen en weer gaat
  distance = (duration/2) / 29.1;
  // omdat het signaal heen wordt gezonden moet het door twee gedeelt worden
  // snelheid van geluid door lucht is circa 29 microseconden per cm dus gedeelt 29.

    Serial.print(distance);
    Serial.println(" cm");

//afstand wordt in cm weergegeven in serial monitor

  delay(500);

   if ((distance > 100) && (distance <= 150)){ //dit gebeurd er als de afstand vanaf sensor tussen groter dan 100 cm en gelijk aan of kleiner dan 150 cm is.
    analogWrite(BLUE, 0);
    analogWrite(GREEN, 255);
    analogWrite(RED, 0);

    tone(piezoPin, 1000, 1000); // toon duurt 1 seconden
    delay(2000); // 2 seconden geen geluid
    tone(piezoPin, 1000, 1000);
    delay(2000);

   }

   else if ((distance > 50) && (distance <= 100)){ //dit gebeurd er als de afstand vanaf sensor tussen groter dan 50 cm en gelijk aan of kleiner dan 100 cm is.
    Serial.println("Ga weg!");

    analogWrite(BLUE, 0);
    analogWrite(GREEN, 102);
    analogWrite(RED, 252);

    tone(piezoPin, 1000, 700); // toon duurt 0.7 seconden
    delay(1000); // 1 seconde geen geluid
    tone(piezoPin, 1000, 700);
    delay(1000);

  }

  else if ((distance >= 0) && (distance <= 50)){ //dit gebeurd er als de afstand vanaf sensor tussen groter dan of gelijk aan 0 cm en gelijk aan of kleiner dan 50 cm is.

    analogWrite(BLUE, 0);
    analogWrite(GREEN, 0);
    analogWrite(RED, 255);

    tone(piezoPin, 1000, 200); // toon duurt 0,2 seconden
    delay(100); // 0,1 seconden geen geluid
    tone(piezoPin, 1000, 200);
    delay(100);

  }

   else {
    analogWrite(BLUE, 0);
    analogWrite(GREEN, 0);
    analogWrite(RED, 0);

 }

}

```

# Answer
> 2 votes
Pin D10 of NodeMcu is io 1 which is RX pin of Serial interface of the esp8266. Serial is on NodeMCU connected to USB. The pin is on board labeled RX.

D8 is boot config pin io 15. It must have pulldown on board. The pulldown can disturb the input on this pin. Use D6 (io 12) as echoPin.

---
Tags: serial, led, nodemcu, piezo, proximity
---


# Question
Title: Problem with Arduino driver! Port option not visible. How to resolve it?
I am not able to upload sketch because my Windows 8.1 PC is not able to recognise it. It used to work fine but suddenly my driver disappeared from my device manager and no light is shown on the Arduino uno led also.

I tried to uninstall and install the Arduino IDE again but still didn't work.

Note:- whenever I connect the USB cable to my PC, I see a dim light glowing for few milli seconds.

Update:- Also my Arduino board is not dead since it worked when connected to other pc but not working with my windows pc.

What could be the problem? How do I install the port driver back?

# Answer
> 0 votes
Problem solved

I connected the arduino with my motor shield on top of it which stopped the power supply from pc. Now its working fine.

# Answer
> 0 votes
Sometimes Windows will disable a given USB port if it think's the attached device is malfunctioning. Try using a different USB port on your PC. If that does't work try rebooting your PC.

# Answer
> 0 votes
No LED = no power being supplied. That would imply a bad port, a bad cable, or a damaged board (open circuit due to a damaged trace or part).

A brief LED can mean the board was drawing too much current and the computer shut down that port to protect itself. That would imply a damaged board (short circuit due to burned out part, bad wiring if you have any on the board, or something conductive touching your board where it shouldn't (anywhere!).

Try substituting ports, cables, & Arduinos - one thing at a time - until something changes to give you a clue to what component is faulty.

You might also have a driver problem, but a good board/cable/port should power up anyway.

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


# Question
Title: Speed controller for Ceiling Fan 220V AC 100W
I would like to use ESP32 to speed control my AC ceiling fan which is 220V AC 100 W.

Will the below AC dimmer work with ESP32 to speed control the ceiling fan which is 220V AC 100 W?

If not, kindly suggest a commonly used PWN dimmer that works with ESP32 to speed control ceiling fan with 220V 100W?

This is the link to Speed controller available on Amazon.

# Answer
> 1 votes
In theory, it should work to control the speed of fan. The manufactures description mentions "fan regulator". One of the pictures shows on the backside of the module that it is for 2 A (5 A peek). This should be good for 230 V / 100 W motor.

The module gives you a basic circuit to control AC. It reports zero-crossing and has an optocoupler switch to turn AC on and off. The dimming does your sketch, by cutting parts of the AC wave out in precise timing.

The example sketch is not good. It has delay in interrupt. With this implementation the sketch will not be able to do much else.

EDIT: I tested it and it works with fan too. The delay in interrupt is to create a short pulse to turn on the triac. The triac then turns self off on next zero-crossing. And Robotdyn changed the specs to 10 A.

---
Tags: motor, esp32, speed
---


# Question
Title: How do I stop the slave from running the code until master sends a new value? I2C
I'm a total noob when it comes to Arduino. I'm slowly learning stuff. I was trying this code which basically gets input in Arduino1(master) and displays the character in serial monitor of Arduino2(slave). The code words just find but I just need the slave to wait until the master sends the next character. Right now, the slave is continuously printing the character.

Master code:

```
    #include "Wire.h"
    char ch;

    void setup() {

      Serial.begin(9600);
      Wire.begin();

    }

     void loop() {
      while(Serial.available()==0)
      {}
      ch=Serial.read();
      delay(1000);
      Serial.print("The character that you entered is ");
      Serial.println(ch);

      Wire.beginTransmission(9);
      Wire.write(ch);
      Wire.endTransmission();

        }

```

Slave code:

```
#include "Wire.h"
char x;

void setup() {

  Serial.begin(9600);
  Wire.begin(9);
  Wire.onReceive(Event);

}
void Event(char bytes){
  x = Wire.read();
}

void loop() {

  Serial.print("The character that you entered in the other Arduino is ");
  Serial.println(x);
}

```

I know that this will be simple but I just can't quite figure out what to do. Please help me out

# Answer
> 2 votes
```
#include "Wire.h"
volatile char x;
volatile bool received;

void setup() {
  Serial.begin(9600);
  Wire.begin(9);
  Wire.onReceive(Event);
}

void Event(char bytes){
  x = Wire.read();
  received = true;
}

void loop() {

  if (received) {
    received = false;
    Serial.print("The character that you entered in the other Arduino is ");
    Serial.println(x);
  }
}

```

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


# Question
Title: Motor not working when connected to motor driver shield?
My code is getting uploaded to arduino without problem but still my motor is not moving when i connect it to the motor driver shield. I am supplying 6V battery to the shield which is connected to dc motor at M2

What could be the problem?

Code:-

```
#include <AFMotor.h> //import your motor shield library

AF_DCMotor motor2(2,MOTOR12_2KHZ); // set up motors.
AF_DCMotor motor3(1, MOTOR34_1KHZ);

void setup() {
  Serial.begin(9600); // begin serial communitication
  Serial.println("Motor test!");
  motor2.setSpeed(105); //set the speed of the motors, between 0-255
  motor3.setSpeed(105);
}

void loop() {
   motor2.run(FORWARD);
   motor3.run(FORWARD);
  }

```

# Answer
> 1 votes
I cannot tell all of your connections from the photo, but I'm guessing you're supplying power to the Arduino through its power connector and also to the motors, both from the battery. The power connector on the Arduino is specified for 7-12v because the kind of voltage regulator it has needs that 2v difference to operate properly. You're kind of at the edge by supplying 6v, and when the motors come on, their current draw will cause the 6v battery voltage to drop somewhat. It probably drops below the regulator's ability to supply 5v from it, shutting down the Arduino.

Adding one more cell to your battery will give you 7.5v (5x1.5v) and will may be enough to run the Arduino and the motors. Two more cells would work even better. (Don't make the mistake of trying the small 9v batteries with snap-clips on top - their utterly incapable of supply the current your motors need).

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


title: Baud rate of Arduinos bootloader

text:
# Question
Title: Baud rate of Arduinos bootloader
I am learning UART and the problem that i have is understanding what happens when i send serial data to my PC via USB which is built in to the Arduino uno board.

For incoming serial data i am using Terminal v1.9b and it basically lets me to set some parameters and listen to incoming data on Software serial port and or write to it.

The process:

1. Atmega328p's Baud rate is set to 9600
2. Terminal connects to it (it performs a reset) and i get my data in.

Very simple, it all works and i don't have a problem with it. What my question is: I assume that my PC doesn't talk to atmega328p directly since it has no USB interface. it talks to a bootloader chip which converts the USB to UART and then i receive that message on my atmega328p. How does that chip know which baud rate we agreed to. OR "Terminal" sends the baud rate to that bootloading chip via usb protocol and it sets its UART settings ?

# Answer
> 4 votes
The bootloader runs in the 328, and just as your application programs do, it sets a UART baud-rate for uploading programs to the Uno.

Current bootloaders use 115200 baud for upload; the most recent previous ones used 57600 baud. Setting that is part of the bootloader code. Whatever your application program last set for a baud-rate doesn't matter; if you reset the Uno, the bootloader sets the UART to the known upload baud-rate, and waits briefly for the PC to begin an upload, and jumps to the currently loaded application program if no upload is begun.

Your PC's Arduino IDE configuration is written to use the known bootloader baudrate (you can see that in the avrdude command). In fact, since I have some boards with soldered-in chips with the older, 57600 baud bootloader burned in them, I have two Uno-board configurations in my IDE; one for those older chips, and one for the current ones.

---
Tags: uart
---


# Question
Title: Make Arduino send and receive at the same time
I am working on a project where I connect a GPS module and GPRS SIM900 shield. The location will be sent when it recives a certain character.

Now my question is, can the Arduino receive from GPRS and GPS module data at the same time? The GPS is not given coordinates, however it works properly without receiving a message from the GPRS.

I am using softwareserial for both. Should/can I use hardware serial and softwareserial?

# Answer
> I am using `SoftwareSerial` for both.

As others have said, you cannot listen to 2 `SoftwareSerial` ports at the same time.

> Should/can I use `HardwareSerial` and `SoftwareSerial`?
>
> ... can the Arduino receive from GPRS and GPS module data at the same time?

Yes, but...

This answer provides full details on choosing "good" combinations of hardware and software serial ports. To summarize:

* Use the `HardwareSerial` port (i.e., `Serial`) for one of the devices. You can still use it for debug prints, as long as the device has some kind of command "format". For example, if commands start with "AT", just make sure that none of your debug prints start with "AT". It is the absolute best choice. You would have to disconnect RX pin 0 from the device in order to upload new sketches over USB.
* Use `AltSoftSerial` for the other device. It is the most efficient software serial port, and it can be used at the same time as `Serial`. It only works on two specific pins.
* `NeoSWSerial` is the next best choice, at limited baud rates. It can be used with the above choices, but transmitting on `NeoSWSerial` prevents them from receiving.
* `SoftwareSerial` is the worst choice. Receiving **or** transmitting on `SoftwareSerial` prevents all of the above from receiving anything. It disables interrupts for long periods of time.
> 1 votes

# Answer
Probably you don't need to use both GPS and GPRS in same time. Just check for a certain character from GPRS in the loop and when it comes check the GPS data.

Why not connect GPS module to hardware serial?
> 0 votes

# Answer
you can connect gps to hardware serial port rx and gsm to software serial. in similar way, I solve the problem
> 0 votes

---
Tags: gsm, softwareserial, gps
---


# Question
Title: Circuit diagram for ACS712 and ZMPT101B with ESP8266 using ADS1115
This is probably a cry for help for a circuit diagram which involves connecting ESP8266 with ADS1115 with ACS712 and ZMPT101B(voltage sensor). Since both of them uses analog pins, and using a diode separator is not a proper idea in real-life. Therefore I ended up using the ADS1115 for more analog pins, which should be working fine. I am not a electrical engineer so I am having real trouble as to how to fix all Four of them together. Can any one help me with a circuit diagram for this? Any links or research papers links, etc. Thanks

# Answer
> 0 votes
The ADS1115 use I2C a.k.a. Wire to communicate with MCU. Default Wire pins on esp8266 are io 5 SCL and io4 SCA. I recommend to use this pins. Of course the module needs 3.3 V and ground.

# Answer
> 1 votes
Step one is to get the ADC working. Once that is done everything else will fall pretty much into place.

The ADC you have chosen is an I2C device. The ESP8266 doesn't have I2C as such, but it does provide a software-emulated I2C implementation. This can be used on any pair of pins, but the default ones are GPIO4 for the data (SDA) and GPIO5 for the clock (SCL) (this corresponds to the Arduino Uno using pins A4 and A5 for I2C, so it should be easy to remember).

Once you have that working the wiring for the rest is the same as for any other system. The only thing that differs is that your analogue inputs are on the ADC chip, not the main module.

Here's a block diagram to get you started:

simulate this circuit – Schematic created using CircuitLab

This is assuming:

* Single voltage output from each of your sensor modules
* I2C pullup resistors provided by either ESP8266 or ADS1115 (add your own if not)
* All modules providing the required support components for the chip

---
Tags: esp8266, nodemcu
---


# Question
Title: Unexpected accident of my board, CH341 issue for Linux or Dead ESP?
I have early midnight accident of my Lolin/Wemos boards. I tried uploads my sketch with a assembly `VIN` to `GND` as my reset button, when i uploads my sketch at more one hundred times, i get my boards cannot be online again or my port cannot readable to my Ubuntu as `/dev/ttyXXX`. usually when i plugged the Usb3.0 cable, the blink led should be turn on at my boards but i didn't get it. How i can re-flash my boards to be online again?

Thanks in advance.

# Answer
Thanks to @Majenko my pal, from him advice i get a alternative ideas for fixed my issue.

**What i tried :**

1. I found this and I took my Uno, i pined 5v (Uno) to 5v (Esp) and i declared 13 pinout as the led blinky and then i uploaded "BlinkyWithoutDelay" sketch, it's seems doesn't work.
2. I pined 5v (Uno) to 5v (Esp), Gnd (Uno) to Gnd (Esp) and i declared 13 pinout (Uno) to D3 pinout (Esp) and then i uploaded "BlinkyWithoutDelay" sketch, it's seems doesn't work.
3. I tried from Majenko advice to provide a Usb phone charger and connected white wire to 5v (Esp) and black wire to Gnd (Esp) without Uno board, and then i uploaded "BlinkyWithoutDelay" sketch, it's seems doesn't work.
4. From the 2nd point and the 3rd point, i run 2nd point without declared D3 pinout as the led blinky, and i changed from 5v to 3v3 (Uno and Esp), and after uploaded the sketch, it's seems the dim light (Esp) works like dim light (Uno) but i still cannot get my port for my esp, i had idea to unplugged my Uno and i changed from 5v to 3v3 and i uploaded my sketch, it's seems works to me. but i still cannot 5v properly or really death.

**The Solution**

From the 4th points , the solution is i provide a external power to 3v3 (esp) and i plugged to Usb2.0, i also plugged Usb3.0 as serial communication. when i uploaded "BlinkyWithoutDelay" sketch, it's seems works. The conclusion is my 5v pinout really death cause the diode for 5v pinout is blown up therefore i changed to 3v3 pinout.

**See my damaged board below**

That's also solved another my Esp boards. hope anyone didn't make a shorted between 5v to Gnd like me.

Thanks.
> 0 votes

# Answer
Shorting VIN to GND will over-stress the diode that is in-line with the power coming in from the USB.

## The result

* The diode will blow and you will not get power from the USB to power the board.
* The PC may detect "over-current" and shut down the USB port
* The USB port on the computer may be damaged

## How do you fix it?

* Replace the diode if blown.
* Use a different USB port.

## How do you work around it?

* Provide an external 5V power source to VIN & GND if the diode is blown

## How do you avoid it happening in future?

* **NEVER short VIN to GND, even for a short time.** There is a reset pin **RST** provided for the purpose of resetting the board.
> 1 votes

# Answer
If the device still blinks and boots and whatnot, but doesn't connect to the computer, you've probably only broken the USB part of the NodeMCU.

Use the USB-TTL of another MCU. If you have an Uno, it's RST\>GND, GND\>GND, TX-RX, RX-TX. Mind GPIO 0+15 for programming. You can also use a USB TTL adapter, aka "an FTDI", the kind they used to use before everything had cheap built-in USB chips.
> 0 votes

---
Tags: serial, esp8266
---


# Question
Title: Can anyone please help me to modify the code so that it runs faster?
this is a program for a blindspot detection system using 4 ultrasonic and 2 ir sensors. can someone help me in modifyng the code so that this runs faster?

```
#include<LiquidCrystal.h>
#define trigbl 14
#define echobl 15
#define trigbr 16
#define echobr 17
#define trigfl 18
#define echofl 19
#define trigfr 8
#define echofr 9
#define bl 10
#define br 11
long durationbl;
long durationbr;
long durationfl;
long durationfr;
int distancebl;
int distancebr;
int distancefl;
int distancefr;
int irr;
int irl;
int a;
int b;
LiquidCrystal lcd(7, 6, 5, 4, 3, 2);
void setup()
{
  lcd.begin(16, 2);
  pinMode(trigbl, OUTPUT);
  pinMode(echobl, INPUT);
  pinMode(trigbr, OUTPUT);
  pinMode(echobr, INPUT);
  pinMode(trigfl, OUTPUT);
  pinMode(echofl, INPUT);
  pinMode(trigfr, OUTPUT);
  pinMode(echofr, INPUT);
  pinMode(bl, INPUT_PULLUP);
  pinMode(br, INPUT_PULLUP);
}
void loop()
{
  digitalWrite(trigbl, LOW);
  delay(2);
  digitalWrite(trigbl, HIGH);
  delay(10);
  digitalWrite(trigbl, LOW);
  durationbl = pulseIn(echobl, HIGH);
  distancebl = durationbl * 0.034 / 2;
  int a1=distancebl;
  digitalWrite(trigbr, LOW);
  delay(2);
  digitalWrite(trigbr, HIGH);
  delay(10);
  digitalWrite(trigbr, LOW);
   durationbr = pulseIn(echobr, HIGH);
   distancebr = durationbr * 0.034 / 2;
  int a2=distancebr;
  digitalWrite(trigfl, LOW);
  delay(2);
  digitalWrite(trigfl, HIGH);
  delay(10);
  digitalWrite(trigfl, LOW);
  durationfl = pulseIn(echofl, HIGH);
  distancefl = durationfl * 0.034 / 2;
  int a3=distancefl;
  digitalWrite(trigfr, LOW);
  delay(2);
  digitalWrite(trigfr, HIGH);
  delay(10);
  digitalWrite(trigfr, LOW);
  durationfr = pulseIn(echofr, HIGH);
  distancefr = durationfr * 0.034 / 2;
  int a4=distancefr;
  irl =digitalRead(bl);
  irr =digitalRead(br);
  lcd.setCursor(1, 0);
  lcd.print("RL  RR  FL  FR");
  if (a1<30 && irl==0)
  {
  a=0;
  }
  else
  {
    a=1;
  }
   if (a2<30 || irr==0)
  {
  b=0;
  }
  else
  {
    b=1;
  }
   if  (a==1 && b==1 && a3>30 && a4>30)
  {
    lcd.setCursor(1, 1);
    lcd.print("No Obstacle    ");
  }
  else if ( a==0 && b==1 && a3>30 && a4>30)
  {
    lcd.setCursor(1, 1);
    lcd.print("XX            ");
  }
  else if ( a==1 && b==0 && a3>30 && a4>30)
  {
    lcd.setCursor(1, 1);
    lcd.print("    XX        ");
  }
  else if ( a==1 && b==1 && a3<30 && a4>30)
  {
    lcd.setCursor(1, 1);
    lcd.print("        XX    ");
  }
   else if ( a==1 && b==1 && a3>30 && a4<30)
  {
    lcd.setCursor(1, 1);
    lcd.print("            XX");
  }
  else if ( a==0 && b==0 && a3>30 && a4>30)
  {
    lcd.setCursor(1, 1);
    lcd.print("XX  XX        ");
  }
  else if ( a==1 && b==0 && a3<30 && a4>30)
  {
    lcd.setCursor(1, 1);
    lcd.print("    XX  XX    ");
  }

  else if ( a==0 && b==1 && a3<30 && a4>30)
  {
    lcd.setCursor(1, 1);
    lcd.print("XX      XX    ");
  }
  else if ( a==0 && b==1 && a3>30 && a4<30)
  {
    lcd.setCursor(1, 1);
    lcd.print("XX          XX");
   }
  else if ( a==1 && b==0 && a3>30 && a4<30)
  {
    lcd.setCursor(1, 1);
    lcd.print("    XX      XX");
  }
  else if ( a==0 && b==0 && a3<30 && a4>30)
  {
    lcd.setCursor(1, 1);
    lcd.print("XX  XX  XX    ");
  }
  else if ( a==1 && b==1 && a3<30 && a4<30)
  {
    lcd.setCursor(1, 1);
    lcd.print("        XX  XX");
  }
  else if ( a==1 && b==1 && a3>30 && a4<30)
  {
    lcd.setCursor(1, 1);
    lcd.print("XX  XX      XX");
  }
  else if ( a==1 && b==0 && a3<30 && a4<30)
  {
    lcd.setCursor(1, 1);
    lcd.print("XX      XX  XX");
   }
  else if ( a==1 && b==0 && a3<30 && a4<30)
  {
    lcd.setCursor(1, 1);
    lcd.print("    XX  XX  XX");
  }
  else if ( a==0 && b==0 && a3<30 && a4<30)
  {
        lcd.setCursor(1, 1);
        lcd.print("Call Help ......  ");
  }
}

```

# Answer
You may want to check the datasheet of your sonar sensors to see what is the recommended trigger pulse duration. On a typical HC-SR04, it is ten **micro**seconds, not **milli**seconds. So use `delayMicroseconds(10);`.

If your program runs really slowly, the culprit is most probably `pulseIn()`. This function will wait for an incoming pulse and, if there is no incoming pulse, it waits one full second before timing out. This can be simply fixed by providing a third argument to `pulseIn()`, which is the desired timeout in microseconds. Set it to something reasonable, maybe around 25,000 µs for a maximum detection range of 4 m.
> 6 votes

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