# Question
Title: Sending data through esp8266 using arduino
I'm trying to send GPS data using esp8266 using Arduino board. I've used neo-6m receiver and esp8266-01 module. Below is my program using AT commands. The program is successfully compiled and loaded to the Arduino board, but the only output it gives on serial monitor is a simple begin. None of the AT commands are being executed. Not even the module connects to wi-fi. I can't point the error in my code. Please help me find the possible error. Thank you

```

#include <TinyGPS++.h>
#include <SoftwareSerial.h>

TinyGPSPlus gps;

String ssid = "JioFi_244DB1D";

String password = "q52fq74c9s";

SoftwareSerial esp(6,7);

SoftwareSerial ss(8,9);

char Lat[12], Lon[12], alt[12],ch;

byte NOS;

byte l;

String webpage;

void reset(){

  esp.println("AT+RST");

  delay(1000);

  if(esp.find("OK"))

    Serial.println("Module Reset");

    }

    void ConnectWifi(){

      esp.println("AT+CIPMUX=1");

      esp.println("AT+CWMODE=1");

      String cmd = "AT+CWJAP=\""+ssid+"\",\""+password+"\"";

      esp.println(cmd);

      delay(4000);

      if(esp.find("OK"))

      Serial.println("Connected!");

      else {

        ConnectWifi();

        Serial.println("Connecting..");

        }

      }

void setup(){

  esp.begin(9600);

  Serial.begin(9600);

    Serial.println("begin");

  reset();

  ConnectWifi();

  esp.println("AT+CIFSR");

  while(esp.available()>0){

  if(esp.find("STAIP"))

  {Serial.println("IP Address:");

  while(esp.available()>0)

  {ch=esp.read();

  Serial.print(ch);}

  }}}

void loop() {

    ss.listen();

    delay(2000);

    while(ss.available()>0)

    {

    gps.encode(ss.read());

    {

      if(gps.location.isValid()){

           // dtostrf(gps.location.lat(),1,6,Lat);

      //dtostrf(gps.location.lng(),1,6,Lon);

      webpage = "<!DOCTYPE html><html><body><form method = \"post\" action =\"http://localhost/php/esppost.php\"><label for = \"latitude\">Latitude:<\label><input type=number id = \"latitude\" name= \"latitude\" readonly value=";

        //                L = Lat.length();

      l= webpage.length();

      esp.println("AT+CIPSEND=0,");

      esp.print(9+l+5);

      esp.println(webpage);

      esp.print(gps.location.lat(),6);

      esp.print("\">");

      delay(500);

      webpage = "<Label for = \"Longitude\">Longitude:</Label><input type = \"number\" id = \"Longitude\" name = \"Longitude\" readonly value =\"";
      l=webpage.length();

      //L = Lon.length();

      esp.println("AT+CIPSEND=0,");

                        esp.print(9+l+5);

      esp.println(webpage);

      esp.print(gps.location.lng(),6);

      esp.print("\">");

      }

      else

      webpage="Location Invalid";

      l=webpage.length();

      esp.println("AT+CIPSEND=0,");

      esp.print(l+2);

      esp.println(webpage);

      delay(500);

      if(gps.altitude.isValid()){

      dtostrf(gps.altitude.meters(),1,6,alt);

      webpage = "<label for=\"Altitude\">Altitude:<\label><input type = number id=\"Altitude\" name=\"Altitude\" readonly value=";

      l=webpage.length();

      //L= alt.length();

      esp.println("AT+CIPSEND=0,");

      esp.print(9+l+2);

      esp.println(webpage);

      esp.print(gps.altitude.meters(),6);

      esp.print("\">");

      }

     if(gps.satellites.isValid()){

        NOS= gps.satellites.value();

        webpage= "<lable for = \"NOS \"> Number of Satellites:<\label><input type=number id=NOS name= NOS readonly value =";

        l= webpage.length();

        esp.println("AT+CIPSEND=0,");

        esp.print(2+l+22);

        esp.println(webpage);

        esp.print(gps.satellites.value());

        esp.print("></body></html>");

        delay(500);

     }}

    esp.println("AT+CIPCLOSE");

      }
}

```

# Answer
> 1 votes
SoftwareSerial can't listen on two instances. There is a `.listen()` function to switch between SoftwareSerial instances.

The esp8266 AT firmware doesn't wait until you listen on the SoftwareSerial instance. If there is a connection to the server it sends +IPD and data. If the SoftwareSerial instance doesn't listen the information about client connection is lost.

You must listen to esp8266 all the time, so you can't use two SoftwareSerial instances.

You could use the RX pin of Uno to receive data from GPS module over hardware Serial.

---
Tags: esp8266, gps
---


# Question
Title: ARDUINO IDE debug level for stack trace only (nodeMCU 1.0)
What is the minimum `debug level` (`TOOLS` tab) which will display the stack trace on crash?

I would like to reduce information clutter in the serial monitor.

I understand that `debug port` must point to my serial monitor.

In case it makes a difference, it is a NodeMCU, running C++, in Arduino IDE on a Ubuntu 16.04 machine.

# Answer
The crash report is printed to 'standard output' by `__wrap_system_restart_local` in `core_esp8266_postmortem.c` in esp8266 Arduino core.

The standard output is considered as debug output in esp8266 Arduino core. Debug output to hardware Serial can be enabled in runtime by `Serial.setDebugOutput(true);`.

At compile time the initial debug output is controled by `-DDEBUG_ESP_PORT=`, for example `-DDEBUG_ESP_PORT=Serial1`. The Tools menu "Debug port" sets the `DEBUG_ESP_PORT` define. The crash report is not controlled by "Debug level" setting.
> 1 votes

---
Tags: arduino-ide, c++, nodemcu
---


# Question
Title: Locate devices that can move among multiple connections
I don’t know if this is even doable, but the idea is to have a large board with many (500+) locations where I objects can connect, each object having a single LED, and be able to illuminate the LED on any object, no matter where it is connected on the board. So the requirement is that the objects can be moved to any of the connections on the board and and that the board can have any number if it’s connections occupied.

It seems obvious that each object would have to be able to identify itself and that each connection would have to be able to supply both a signal both ways and and provide power to light the LED. On the code side, I’d need to be able to iterate through the connections and identify the desired object by some unique identifier and send a signal to turn the LED on and off. I’m a .Net developer with little knowledge of electronics, but I’m willing to learn if it’s possible to do this. I haven’t been able to find any arduino examples similar enough to provide some idea of where to start. I don’t know if this is something that can even be done with Arduino or what components would be required if it is possible.

I’d appreciate any guidance on how this could be done or even suggestions as to what might be a better approach toward finding the guidance necessary to build this.

# Answer
> 2 votes
Your question is awfully vague.

There is a protocol called I2C that's commonly used for microcontrollers. It's a serial bus that has a data line, a clock line, power, and ground. That might meet your needs.

Each device on an I2C bus is supposed to have a unique address. You send commands to it using that address, and it doesn't matter where it is located physically.

I2C is designed to be a chain, and each device has 2 connectors that pass the connection on to the next device on the chain.

I2C also uses a byte address, so you could only have 255 unique devices.

---
Tags: led
---


title: Why am only hearing noise or no sound?

text:
# Question
Title: Why am only hearing noise or no sound?
Alright, there is something missing in the question, **I was able to hear one sound of the files** and the others apply to the question I asked and that is why I am wondering. what is happening!

Here is the code:

```
#include <SD.h>                      // need to include the SD library
#define SD_ChipSelectPin 4  //using digital pin 4 on arduino nano 328, can use other pins
#include <TMRpcm.h>           //  also need to include this library...
#include <SPI.h>

TMRpcm tmrpcm;   // create an object for use in this sketch

void setup(){

  tmrpcm.speakerPin = 9; //5,6,11 or 46 on Mega, 9 on Uno, Nano, etc

  Serial.begin(9600);
  if (!SD.begin(SD_ChipSelectPin)) {  // see if the card is present and can be initialized:
    Serial.println("SD fail");
    return;   // don't do anything more if not
  }
  tmrpcm.play("music.mp3"); //the sound file "music" will play each time the arduino powers up, or is reset
}

void loop(){

  if(Serial.available()){

    if(Serial.read() == 'p'){ //send the letter p over the serial monitor to start playback

      /* These are spkean Numbers */

     // tmrpcm.play("1-24bit.wav");
     // tmrpcm.play("1-16bit.wav");
     // tmrpcm.play("200-insane.mp3");
     // tmrpcm.play("music.mp3")       // Strangely this is the working perfectly with good sound
     // tmrpcm.play("200-standard.mp3");
        tmrpcm.play("200.wav");        // from https://evolution.voxeo.com/library/audio/prompts/numbers/index.jsp
    }
  }

}

```

Everything is good when I play this `tmrpcm.play("music.mp3");` but the others I hear aliens sounds expect this `tmrpcm.play("200.wav");` which I can hear the number two hundred but I feel the sound is 4-bit depth which very noisy. The files used in the code are **here**

For clarification previously, I thought it was amplifying issues which then I had to used **LM386** but the sound was the same noise with `tmrpcm.play("200.wav");` and later when I tried this `tmrpcm.play("music.mp3");` I was shocked it worked perfectly like what I need it to be! so I was curious I removed the **LM386** and played this `tmrpcm.play("music.mp3");` again and worked alright just maybe less volume.

# Answer
As @Juraj mentioned it was solved by changing the setting and I was able easily to play the sound when I matched the setting to this file:

So, I could not create one from scratch matches above setting but I was able to convert existing sound through this site which allowed me to convert with desire setting and here finally the exiting sound has matched the setting:
> 1 votes

---
Tags: speaker, tmrpcm
---


title: Run a loop for only 60 secondes

text:
# Question
Title: Run a loop for only 60 secondes
How do run a code on arduino for only 60 secondes and than shut it down? I know I have to use the millis() function, but I do not know how to it in my code. Sorry if it looks unclear, but I only need to know how to program the millis() function. This is my first code so I have no experience.

```
int main(void)
{
pin_mode(A13,INPUT);
pin_mode(A12,INPUT);
pin_mode(A11,INPUT);
pin_mode(A10,INPUT);
pin_mode(A15,INPUT);
pin_mode(D0,OUTPUT);
pin_mode(D1,OUTPUT);
pin_mode(D2,OUTPUT);
pin_mode(D3,OUTPUT);

while (1)
{
    int potmeter1 = read_analog_pin(A13);
    if (potmeter1 >= 1000 && potmeter1 < 1100){
    gen_pwm(D0, 1000, 100);

        int potmeter2 = read_analog_pin(A12);
        if (potmeter2 >= 2000 && potmeter2 < 2050){
        gen_pwm(D1, 1000, 100);

            int potmeter3 = read_analog_pin(A11);
            if (potmeter3 >= 500 && potmeter3 < 525){
                gen_pwm(D2, 1000, 100);

                    int potmeter4 = read_analog_pin(A10);
                    if (potmeter4 >= 3500 && potmeter4 < 3510){
                        gen_pwm(D3, 1000, 100);

    {
        int lichtsensor = read_analog_pin(A15);
        if (lichtsensor >= 2000 && lichtsensor < 3500 && potmeter1 >= 1000 && potmeter1 < 1100 && potmeter2 >= 2000 && potmeter2 < 2050 && potmeter3 >= 500 && potmeter3 < 525 && potmeter4 >= 3500 && potmeter4 < 3510){
            gen_pwm(D0, 1000, 100);
            gen_pwm(D1, 1000, 100);
            gen_pwm(D2, 1000, 100);
            gen_pwm(D3, 1000, 100);
            _delay_ms(250);
            gen_pwm(D0, 1000, 0);
            gen_pwm(D1, 1000, 0);
            gen_pwm(D2, 1000, 0);
            gen_pwm(D3, 1000, 0);
            _delay_ms(250);

        }
    }
                }else{
                gen_pwm(D3, 1000, 0);
                }
            }else{
            gen_pwm(D3, 1000, 0);
            gen_pwm(D2, 1000, 0);
            }
        }else{
        gen_pwm(D3, 1000, 0);
        gen_pwm(D2, 1000, 0);
        gen_pwm(D1, 1000, 0);
        }
    }else{
    gen_pwm(D3, 1000, 0);
    gen_pwm(D2, 1000, 0);
    gen_pwm(D1, 1000, 0);
    gen_pwm(D0, 1000, 0);
    }

                }
            }

```

I have merged my program with your program and I have added the `#include "Arduino.h"`. The `millis()` function is colored now and works. My code still won't stop at 60 secondes, did I do something wrong?

```
#include "hva-xmega.h"
#include "Arduino.h"

unsigned long EndTime;

void setup()
{
    pin_mode(A13,INPUT);
    pin_mode(A12,INPUT);
    pin_mode(A11,INPUT);
    pin_mode(A10,INPUT);
    pin_mode(A15,INPUT);
    pin_mode(D0,OUTPUT);
    pin_mode(D1,OUTPUT);
    pin_mode(D2,OUTPUT);
    pin_mode(D3,OUTPUT);

    EndTime = millis() + (60*1000L);
}

void loop() {
    if( millis() < EndTime ){

while (1)
{
    int potmeter1 = read_analog_pin(A13);
    if (potmeter1 >= 1000 && potmeter1 < 1100){
        gen_pwm(D0, 1000, 100);

        int potmeter2 = read_analog_pin(A12);
        if (potmeter2 >= 2000 && potmeter2 < 2050){
            gen_pwm(D1, 1000, 100);

            int potmeter3 = read_analog_pin(A11);
            if (potmeter3 >= 500 && potmeter3 < 525){
                gen_pwm(D2, 1000, 100);

                int potmeter4 = read_analog_pin(A10);
                if (potmeter4 >= 3500 && potmeter4 < 3510){
                    gen_pwm(D3, 1000, 100);

                    {
                        int lichtsensor = read_analog_pin(A15);
                        if (lichtsensor >= 2000 && lichtsensor < 3500 && potmeter1 >= 1000 && potmeter1 < 1100 && potmeter2 >= 2000 && potmeter2 < 2050 && potmeter3 >= 500 && potmeter3 < 525 && potmeter4 >= 3500 && potmeter4 < 3510){
                            gen_pwm(D0, 1000, 100);
                            gen_pwm(D1, 1000, 100);
                            gen_pwm(D2, 1000, 100);
                            gen_pwm(D3, 1000, 100);
                            _delay_ms(250);
                            gen_pwm(D0, 1000, 0);
                            gen_pwm(D1, 1000, 0);
                            gen_pwm(D2, 1000, 0);
                            gen_pwm(D3, 1000, 0);
                            _delay_ms(250);

                        }
                    }
                    }else{
                    gen_pwm(D3, 1000, 0);
                }
                }else{
                gen_pwm(D3, 1000, 0);
                gen_pwm(D2, 1000, 0);
            }
            }else{
            gen_pwm(D3, 1000, 0);
            gen_pwm(D2, 1000, 0);
            gen_pwm(D1, 1000, 0);
        }
        }else{
        gen_pwm(D3, 1000, 0);
        gen_pwm(D2, 1000, 0);
        gen_pwm(D1, 1000, 0);
        gen_pwm(D0, 1000, 0);
            }
        }
    }
}
 else {
     // Time is up! Hang here
     for(;;)
     ;      // infinite loop here stops further processing
    }
 }

```

# Answer
Note that in an Arduino environment, `main()` is already provided for you. It calls your function `void setup(void){ ... }` once, then loops forever, calling your function `void loop(void){ ... }`. Either function may be empty but both must be present.

Without going into the specifics of your code, here is a program that fits the Arduino conventions, and will execute some procedure for 60 seconds, then hang, doing nothing:

```
unsigned long EndTime;

void setup()
{
   // Any setup code you need goes here.

   EndTime = millis() + (60*1000L);
}

void loop() {
   if( millis() < EndTime ){
      // Do your processing here
   }
   else {
      // Time is up! Hang here
      for(;;)
         ;      // infinite loop here stops further processing
   }
}

```

> My setup codes are the pin\_modes right? and everything below is my processing?

Update:

Correct - Put pin modes and anything else that needs to be done once, at the beginning of the run in setup(). Everything else goes in loop(). Or if you're more comfortable writing your entire program starting with main() (as we do in other environments than Arduino), you can use the setup() function exactly as you would use main(), and leave loop() empty. The idea of a loop function is that embedded programs are typically not meant to end as long as the device has power. There are instances when this isn't strictly true and you seem to have one example.

> I have to remove the int main(void) from my code when I use your code right?

Correct - the Arduino environment provides a main() function, so writing your own - within that environment - would result in a multiple-definition error.

Update 2:

"WProgram.h" is obsolete. Instead, use: `#include <Arduino.h>`. There is no function called `elapsedMillis()`, just `millis()`. You won't need an include statement for it, or any of the other standard or common stuff: Serial I/O, digital I/O, analog I/O, pin definitions for specific boards, etc. 'Arduino.h' pulls in all that stuff. Your university should have add a description of the proprietary board to the Arduino's board description file.

(But if you/they are not using standard Arduino libraries, board descriptions, etc., then there is a lot of behind-the-scenes "housekeeping" you may be responsible for. That isn't something we can know; you may have to ask those kinds of questions of others more familiar with your university's programming environment. I think it is unlikely they would abandon the existing/working resources, but it's something to keep in mind.)
> 2 votes

---
Tags: programming, atmel-studio, atmel
---


title: LED array flashes once before being lit

text:
# Question
Title: LED array flashes once before being lit
I've built this simple Arduino controlled led-array. The Arduino sets a 5v pin on a relay to connect the high current power supply to a led array. However, just before the led array is being fully turned on I'm getting this fast flash of the led array. I really would like to have the led working in an "on/off" manner.

I remember that working with some motors one have to use capcitator in parallel because of resistence drop. Is it also the case with led array? And if it is why so, and why a capcitator would help?

Thank you very much.

# Answer
As Wendall says in his comment, you probably have an issue with the power-on state of your logic pins before the Arduino finishes booting up.

In addition to that, you should **not** drive a relay directly from an Arduino logic pin, for a couple of reasons:

1. It can't provide enough current to drive a relay coil.
2. The relay emits a strong surge of reverse current when you switch it off. This will likely destroy the logic pin you are using to drive the relay, or it might even destroy the whole Arduino board.

For these reasons you should drive the relay using a transistor, and you should put a properly sized diode wired across the relay coil backwards from the flow of current when the relay is energized. The diode bleeds off the reverse current from the relay coil.
> 1 votes

---
Tags: arduino-uno, led, relay
---


# Question
Title: Unexpected results when creating 32-bit int from byte array
I'm having problems creating a 32-bit integer from a 4-byte array. In the following complete, minimal, and verifiable example, converting a byte array containing `0x00, 0x04, 0x04F, 0x45` results in `4F45` (expected result would be `44F45`). I must be overlooking something fundamental here.... can anyone see where I went wrong?

```
void setup()
{
    Serial.begin(9600);
    while(!Serial);
}

void loop()
{
    uint8_t bytes[4] = {0x00, 0x04, 0x4F, 0x45}; //00044F45
    int32_t theInt = byteArrayToInt32(bytes);
    Serial.println(theInt, HEX); //Print 4F45
    delay(250);
}

uint32_t byteArrayToInt32(uint8_t* bytes)
{
    uint32_t i = 0;
    i |= bytes[0] << 24;
    i |= bytes[1] << 16;
    i |= bytes[2] << 8;
    i |= bytes[3];
    return i;
}

```

# Answer
> 1 votes
The problem is that you are trying to shift `uint8_t` more than 8 bits and then `OR` it with `int32_t`.

You have to `cast` the `uint8_t` to `int32_t` before doing the shift.

```
void setup()
{
    Serial.begin(9600);
    while(!Serial);
}

void loop()
{
    uint8_t bytes[4] = { 0x00, 0x04, 0x4F, 0x45}; //00044F45
    int32_t theInt = byteArrayToInt32(bytes);
    Serial.println(theInt, HEX); //Print 4F45
    delay(1000);
}

int32_t byteArrayToInt32(uint8_t* bytes)
{
    int32_t i = 0;
    i |= (int32_t) bytes[0] << 24;
    i |= (int32_t) bytes[1] << 16;
    i |= (int32_t) bytes[2] <<  8;
    i |= (int32_t) bytes[3];
    return i;
}

```

---
Tags: c++, data-type
---


title: External Interrupt Pins on Nano Clones

text:
# Question
Title: External Interrupt Pins on Nano Clones
Long time lurker, first time poster here.

Do the cheap Arduino Nano clones such as this one have external interrupt pins?

For example, the original Nano has pins 2 and 3 usable for interrupts. Do clones tend to incorporate this feature? If so, can anyone recommend one which does?

I'm planning on using an encoder for my next project and want to make sure I can use interrupts so my code doesn't skip over encoder counts.

Thank you!

# Answer
> 1 votes
I understand your doubt. In a world where Uno WiFi i not Uno it is better to ask. And the Wawgat boards which are named Uno but use a different 8-bit MCU are a trap too.

The Nano in your link has Atmega 328p and interrupts are a feature of the MCU. There is no reason for the clone manufacturer to not use the standard Nano pinout as specified in Open Hardware Nano schematics. Then the board is compatible with Arduino Nano as defined in Arduino AVR boards package.

The clones usually use a cheaper chip for USB. You will maybe need to install a driver for the CH340.

In a few days Nano Every will be available and I expect clones of it in a short time because it is a very simple board. It will use the ATmega 4809 and Arduino advertises exact pin compatibility with old Nano. But I expect in details problems similar to Uno WiFi R2 versus classic Uno problems. One of the problems could be the mapping of interrupt pins.

And later this year Nano 33 will be released. It is a Nano format board with SAMD or nRF52 MCU so 3.3 V (the 33 in name).

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


title: I2C wire.h send 2 variables

text:
# Question
Title: I2C wire.h send 2 variables
I am trying to send 2 variables with `wire.h`. I tried with this code:

MASTER RECEIVER:

```
#include <Wire.h> // include la libreria
#include <LiquidCrystal_I2C.h>
#include "RTClib.h"

LiquidCrystal_I2C lcd(0x3E, 2, 1, 0, 4, 5, 6, 7, 3, POSITIVE);
RTC_DS1307 RTC; // orologio

static int anno;
static int giorno;
static int mese;
static int ora;
static int secondo;
static int oldSecondo;
static int minuto;
static int oldMinuto;
static int annoGrezzo;
char t[10] = {};
char v[10] = {};

void setup() {
  Wire.begin(); // join i2c bus with address #4
  lcd.begin(16, 2);
  Serial.begin(9600); // start serial for output
  //-----------orologio-----------
  RTC.begin();
  // Check to see if the RTC is keeping time. If it is, load the time from your computer.
  if (! RTC.isrunning()) {
    Serial.println("RTC is NOT running!");
    // This will reflect the time that your sketch was compiled
    RTC.adjust(DateTime(__DATE__, __TIME__));
  }
  //-----------fine orologio-----------
}

void loop() {
  //------------------------------------------------------------
  //   si stampano i dati ricevuti e ricomposti
  //------------------------------------------------------------
  Wire.requestFrom(8, 6);
  int i = 0;
  while (Wire.available()) {
    Serial.println(i);
    t[i] = Wire.read();
    // every character that arrives it put in order in the empty array "t"
    i = i + 1;
  }
  Serial.println(t);
  DateTime now = RTC.now();
  annoGrezzo = now.year();
  anno = (annoGrezzo % 100);
  mese = now.month();
  giorno = now.day();
  ora = now.hour();
  minuto = now.minute();
  lcd.setCursor(0, 0);
  lcd.print(t);
  lcd.setCursor(5,0);
  lcd.print(v);
  lcd.setCursor(0, 1);
  lcd.print(giorno);
  lcd.print(" ");
  lcd.print(mese);
  lcd.print(" ");
  lcd.print(anno);
  lcd.print("  ");
  lcd.print(ora);
  lcd.print(":");
  lcd.print(minuto);
  delay (1000);
  lcd.clear();
}

```

SLAVE SENDER

```
#include <Wire.h> // si include la libreria
//---------------------------------------------------------
char t[10];
char v[10];

void setup() {
  Wire.begin(8);
  // join i2c bus (address optional for master)
  Wire.onRequest(requestEvent);
}

void loop() {
  int mioInt = random(30000);
  int mioInt2 = 1234;
  dtostrf(mioInt, 3, 2, t);
  //convers the float or integer to a string. (floatVar, minStringWidthIncDecimalPoint, numVarsAfterDecimal, empty array);
  dtostrf(mioInt2, 3, 2, v);
  //------------------------------------------------------
  delay (500);
}

void requestEvent() {
  Wire.write(t);
  Wire.write(v);
}

```

I'm unable to receive `v` in my master receiver. Thanks for your help.

# Answer
I2C is 8-bit data bus, where address can be 7 bit or 10 bit, you can't send more than 8 bit at a time, if you want to send data more than 8 bit you will be sending them like this, for example let you need to send 16 bit data then you send 8 bit LSB first and then 8 bit MSB or vice versa as per your configuration.

Secondly I had noticed you code and noticed many errors, the major one is that **you hadn't followed the rules of I2C protocol** in your code. I am here attached a link for sample program of arduino i2c slave and master. Go through it you will get your answer.
> 1 votes

---
Tags: i2c, variables, wire-library
---


# Question
Title: Reading a rotary encoder using digital pins of Mega 2560 directly using port registers?
I'm trying to write an interrupt service routine for an Arduino Mega 2560 to decode a quadrature rotary encoder. I've got an ISR (Interrupt Service Routine) that responds to the falling edge of digital pin 2.

I then need to look at the value of pin 3 and see if it is high or low to tell which direction the encoder is being turned. I've built a simple debouncing circuit using a couple of resistors and a .01 μF capacitor per line from the encoder, so those signals are clean now.

Based on the reading I've done, it's best to read the pin states directly rather than using digitalRead in an ISR since the `digitalRead()` function is rather slow.

I am finding it hard to find and figure out the port mappings for the port registers to read the pins.

I believe that I should use

`(PIND & (1 << 3) != 0` to read digital pin 3, since I think pins 2-9 are on register PIND?

I found this chart https://www.arduino.cc/en/Hacking/PinMapping2560 that lists the pin mappings for the Mega 2560, but I'm not sure how to read it.

If I use `bool pinBState = digitalRead(rotaryPinB) == LOW` in my ISR it works, but it seems to miss state changes sometimes.

If instead I use the code \`bool pinBState = (PIND & (1 \<\< 3)) == 0;

The value of `pinBState` never changes.

## Can somebody tell me what I'm doing wrong?

See the self-answer below. It seems that digital pins 0-7 are read from PINE, not PIND.

However, now I have a new problem:

With the code shown in my answer I am getting readings that increase for clockwise rotation, and decrease for counterclockwise rotation, as expected:

If I rotate it very slowly through a full revolution, I can usually get exactly 12 steps in a rotation. If I rotate my encoder rapidly, or through several full turns, it gives me values that aren't exact multiples of 12, and rotating it several turns clockwise, and then the same number of turns counterclockwise does not return the value to 0 like it should.

I'm using a simple debouncing circuit as recommended from the spec sheet for the encoder:

https://www.bourns.com/docs/Product-Datasheets/PEC11R.pdf

The circuit looks like this:

Shouldn't that circuit work? I wired it up on a breadboard, and have pretty long leads, and didn't cut the wires on the resistors or capacitors since this is still a test circuit. I wouldn't think this would be sensitive to RF noise though. The only other thing I've got on the project is an I2C LCD display. I've triple-checked my wiring and don't think I've made any mistakes.

I'm stumped as to why an interrupt-driven rotary encoder, with the recommended debouncing circuit, that reads port registers to read the data from it's PIN B doesn't give reliable results for normal rates of turning on the control.

# Answer
> 1 votes
Ok, it looks like digital pins 0-7 are read from the PINE (That's PIN E) register, not PIND.

I am setting up my pins as input using normal Arduino code:

```
#define rotaryPinA 2
#define rotaryPinB 3

void setup() {
  attachInterrupt(digitalPinToInterrupt(rotaryPinA), encode, FALLING);

  pinMode(rotaryPinA, INPUT);
  pinMode(rotaryPinB, INPUT);
  //The rest of the setup function
}

```

And then my encode method:

```
void encode() {
  rotaryValueChanged = true;
  //Read my PinB (Digital Pin 3) using port register PINE, 5th bit
  bool pinBState = (PINE & (1 << 5)) == 0;
  //Here is the equivalent code using digitalRead:
  //bool  pinBState =  digitalRead(rotaryPinB) == LOW;
  rotaryValue +=  pinBState ? -1 : 1;
}

```

That code seems to work, but the value I'm getting from my rotary encoder drifts.

# Answer
> 0 votes
Have you tried some hardware denouncers - like MC14490?
Using Interrupts you can then detect all four phases of each encoder step.

---
Tags: rotary-encoder, port-mapping, debounce
---


title: Start / end events using milis

text:
# Question
Title: Start / end events using milis
I want to start a relay, have it run for 3 seconds, stop for 10 seconds, repeat.

I can't use delay, because I have a motor driver starting / stopping every 100 milis.

So I put together this code, but it does not work. Any help appreciated.

There's a 500ms delay to stop too much debugging info.

Also for some reason, tenSecondsBool switches to true as soon as you run the code.

```
unsigned long threeSeconds=3000; // the time we need to wait
unsigned long threeSecondsMillis=0; // millis() returns an unsigned long.
unsigned long fourSeconds=7000; // the time we need to wait
unsigned long fourSecondsMillis=0; // millis() returns an unsigned long.

unsigned long previousMillis=0; // millis() returns an unsigned long.
bool ledState = false; // state variable for the LED
bool led2State = false; // state variable for the LED
unsigned long tenSecondMilis=0; // millis() returns an unsigned long.
unsigned long tenSeconds=10000; // the time we need to wait

unsigned long paliGasiMilis=0; // millis() returns an unsigned long.
unsigned long paliGasi=1000; // the time we need to wait

unsigned long ventMilis=0; // millis() returns an unsigned long.
unsigned long ventInt=100; // the time we need to wait

bool threeSecondBool = false;
bool tenSecondBool = false;

int Fin1 = D7;

#define enA D1
#define in1 D2
#define in2 D3
#define button 4

int rotDirection = 0;
int pressed = false;

void setup() {
  Serial.begin(9600); // send and receive at 9600 baud
  pinMode(enA, OUTPUT);
  pinMode(in1, OUTPUT);
  pinMode(in2, OUTPUT);
  pinMode(button, INPUT);
  digitalWrite(in1, LOW);
  digitalWrite(in2, HIGH);
  pinMode(Fin1, OUTPUT);
  digitalWrite(Fin1, HIGH);
  threeSecondBool = false;
  tenSecondBool = false;
}

void loop() {

 unsigned long currentMillis = millis(); // grab current time

 if ((unsigned long)(currentMillis - tenSecondMilis) >= tenSeconds) {
    Serial.print("---------------\n");
    Serial.print("10 second end\n");
    Serial.print("---------------\n");
    tenSecondBool = true;
    tenSecondMilis = millis();
}

Serial.print("10 second bool = ");
Serial.print(tenSecondBool);
Serial.print("\n");
Serial.print("3 second bool = ");
Serial.print(threeSecondBool);
Serial.print("\n");

 if (tenSecondBool) {
  if ((unsigned long)(currentMillis - threeSecondsMillis) >= threeSeconds) {
   Serial.print("---------------\n");
   Serial.print("3 second end\n");
   Serial.print("---------------\n");
   threeSecondBool = true;
   threeSecondsMillis = millis();
  }
 }

if (!tenSecondBool && threeSecondBool){
  Serial.print("Both triggered!\n");
  digitalWrite(Fin1, HIGH);
}

if (!tenSecondBool && !threeSecondBool){
  Serial.print("Both triggered!\n");
  digitalWrite(Fin1, HIGH);
}

if (tenSecondBool && threeSecondBool){
  threeSecondBool = false;
  tenSecondBool = false;
  digitalWrite(Fin1, LOW);
}

delay(500);

  if ((unsigned long)(currentMillis - ventMilis) >= ventInt) {
    digitalWrite(in1, HIGH);
    digitalWrite(in2, LOW);
    ventMilis = millis();
  } else {
    digitalWrite(in1, LOW);
    digitalWrite(in2, HIGH);
  }

}

```

# Answer
If you want a timer with millis with different intervals, then you can change the interval.

I use the Blink Without Delay to start with, and I borrow the 'relay\_is\_on' from the answer by Edgar Bonet.

```
unsigned long previousMillis;
unsigned long interval;
bool relay_is_on;

void loop() {
  unsigned long currentMillis = millis();

  if (currentMillis - previousMillis >= interval) {
    previousMillis = currentMillis;
    if (relay_is_on) {
      // Relay was on, now turn it off.
      interval = 10000;
      digitalWrite (relayPin, LOW);
      relay_is_on = false;
    } else {
      // Relay was off, now turn it on.
      interval = 3000;
      digitalWrite (relayPin, HIGH);
      relay_is_on = true;
    }
  }
}

```

The global variables can be set to a value to start with (for example 3000 for the interval) or they can be set in the setup() function. You have to choose what you want to start with. For example one second or one minute delay before it starts is also possible.
> 1 votes

# Answer
Your code is somewhat confusing, probably because it has too many variables. For doing what you describe, the program only needs to remember two things:

* is the relay in the ON state or in the OFF state?
* when was the last time the relay changed state?

These can be represented as follows:

```
bool relay_is_on = false;
unsigned long last_relay_change = 0;

```

Then, I recommend you use descriptive names for your variables and constants. Calling a constant `threeSeconds` is not useful. It has no added value over just typing `3000`. Having the constant named `RELAY_ON_TIME` makes it a lot clearer what it is intended for. It is a common convention to name the constants with all caps to make them stand out relative to variables:

```
const uint8_t RELAY_PIN = ...;
const unsigned long RELAY_ON_TIME  =  3000;  //  3 s ON
const unsigned long RELAY_OFF_TIME = 10000;  // 10 s OFF

```

With this in place, periodically switching the relay on and off can be achieved as follows:

```
void loop()
{
    unsigned long now = millis();
    if (relay_is_on && now - last_relay_change >= RELAY_ON_TIME) {
        // Turn off.
        digitalWrite(RELAY_PIN, LOW);
        relay_is_on = false;
        last_relay_change = now;
    }
    if (!relay_is_on && now - last_relay_change >= RELAY_OFF_TIME) {
        // Turn on.
        digitalWrite(RELAY_PIN, HIGH);
        relay_is_on = true;
        last_relay_change = now;
    }
}

```
> 2 votes

---
Tags: timers
---


# Question
Title: Removing CH340g chip from Arduino Nano clone.. any issues?
In trying to figure out how to solve another problem with Arduino Nano clone using CH340 chip, I was just now wondering, would there be any issues if I were to simply remove the CH340 chip? As it stands, I have the slight suspicion that the chip itself might be causing some problems with communicating using only the Tx Rx pins, could this be the case? More importantly, can I just remove the chip with no issues (other than the already lacking ability to use it as USB-Serial bridge)? In a working board, would removing the chip cause any other problems?

# Answer
No problem whatsoever as long as you aren't powering the board over USB. You may still be able to do that though depending on what role the CH has in managing the power.

Personally I think all CH chip should be removed from all boards. They are horrible chips and cause no end of problems.

I assume you have an FT232 adapter board (or similar) to then use for the programming of your Arduino.
> 1 votes

# Answer
Looking at the datasheet, I see no problem with removing it.

I'd suggest using a sharp knife and cut all the pins, one at a time, right where they come out of the black epoxy. Make sure you don't accidentally stab into the PCB. Remove the main body of the chip. After that, remove the legs still attached to the PCB, one by one, using a soldering iron.
> 0 votes

# Answer
Once I removed a burned ch340 from a dysfunctional uno, and it didn't brought it back to life, I couldn't program it by other means, because reset remained shorted to ground. It might have other problems, but I still recommend digging more into the problem (eg. Check the diagram for your board)
> 0 votes

# Answer
You could probably get away with just removing 3 legs - Tx, Rx, and DTR. The rest don't anything. The pins are rather far apart, you could heat them one at a time gently pry/lify up with tweezers too. Better than a knife I would think.
> 0 votes

---
Tags: arduino-nano, ch340
---


# Question
Title: Arduino Mega not recognized on Raspberry Pi 3b+
I'm developing an interactive LED table for an university assignment that is being controlled by an Arduino Mega2560 which gets the information about which LEDs should be lit in which colour from a Java application that runs on a Raspi 3b+. So far everything is almost finished and the program is running quite smoothly.

The whole time I've been developing the Java application on a PC and it worked just perfect. Now I wanted to move the application to the Pi to have a runnable demo for a meeting with my advisor. Therefore I wanted to check on which USB port the Arduino connects to the Pi so I can setup the corresponding part of the Java code correctly. As I also wanted to set a specific descriptive port name on which the Arduino is always accessible for the Java application I followed this tutorial.

In a previous attempt where I still used 2 Arduino Duemilanove that step worked however when I now try to find the Arduino Mega with `dmesg | grep ttyUSB` I get no results and `ls -l /dev/ttyUSB*` only tells me that there is no such path or directory. I also retried that with one of the Arduino Duemilanove in case the USB cable was defective but in that case it returned a valid result.

As the code that I need to run on the Arduino is too extensive for using 2 Arduino Duemilanove (due to the array size to represent the table) I definitely need to run this on the Mega. After many attempts to find a solution I didn't find anything that helps me in my situation as every thread on a similar topic was about a board that wasn't recognized on any machine (whereas my Mega gets recognized on my normal Windows PC). As the Duemilanoves get recognized seamlessly I conduct that it's probably not a problem caused by the Pi (or at least not only the Pi).

I read that using a powered USB hub could be a possible solution. However, as the Arduino itself is powered by a power supply I suppose that using a powered USB hub would not help much in this case? However I'd be happy if someone proved me wrong in this case and solving the issue was as easy as that.

# Answer
> 1 votes
The newer Arduinos, like the Uno or Mega 2560, have a different way of managing the Serial ↔ USB translation, compared with the older Duemilianove. From the Linux side, you shouldn't see much difference, except that the device is now `/dev/ttyACM0` instead of `/dev/ttyUSB0`.

---
Tags: serial, arduino-mega, raspberrypi
---


# Question
Title: How to independently control two lights with a single button and a menu system?
I'm stuck and don't know how to get over it. The problem: i want to use a push button for a menu with 2 screens(frames) Frame1: if i push the button i want to turn on the light from the room1 if i press it again i want to turn the light off in the room1

Frame 2: using the same button: i want to turn on the light in the room2 pressing it again i want to turn the light off in the room2

Now.. the problem i encounter... if i'm in frame 1 and press the button then the light from room1 will turn on but also the light from the room2 will turn on. and i don't want that. All i want is to tell somehow to uC that in the frame1 it should turn on only the light from the room1 Please, someone smarter than me ..give me an ideea how can i do that. i cannot post the code because there are over 3000lines and would be time consuming for you to read it all.

for the buttons i use a counter to see if the state has changed and if so then increment and do what it has to do. Also i think that the problem is here because i use the same counter in both functions.

---

```
int btn1 = 46,starebtn1, stareVechebtn1 = 0, btn2 = 50, starebtn2, stareVechebtn2 = 0;
int btn3 = 42, starebtn3, stareVechebtn3 = 0,btn4 = 40, starebtn4, stareVechebtn4 = 0,btn5 = 44, starebtn5, stareVechebtn5 = 0;
int cntbtn1 = 0, cntbtn2 = 0,cntbtn2_1 = 0, cntbtn3 = 0, cntbtn4 = 0, cntbtn5 = 0;
int soilMoisture = A0;
int buzzer = 3;
boolean frame1 = false, frame2 = false;
int procentajUmiditate(){
  int mSensorValue = analogRead(soilMoisture);
  mSensorValue = map(mSensorValue,0,1023,180,0);
  return mSensorValue;
}
void setup()
{
  Serial.begin(9600);
  dht.begin();
  rtc.begin();
  pinMode(ledVerde,OUTPUT);
  pinMode(buzzer,OUTPUT);
  pinMode(soilMoisture,INPUT_PULLUP);
  pinMode(btn1,INPUT);
  pinMode(btn2,INPUT);
  pinMode(btn3,INPUT);
  pinMode(btn4,INPUT);
  pinMode(btn5,INPUT);
  imagineSistemDomotic();
  delay(3000);
  imagineCasaWifi();
  delay(4000);
  tone(buzzer,1000);
  delay(500);
  noTone(buzzer);
  delay(500);
  digitalWrite(ledVerde,HIGH);
}

void loop()
{

  starebtn1 = digitalRead(btn1);
  starebtn2 = digitalRead(btn2);
  starebtn3 = digitalRead(btn3);
  starebtn4 = digitalRead(btn4);
  starebtn5 = digitalRead(btn5);
  int h = dht.readHumidity();
  int t = dht.readTemperature()-2;
  int f = dht.readTemperature(true);
  temp = t;
  hum = h;
  houR = rtc.getTimeStr();
  dateR = rtc.getDateStr();

//conditii procentaj umiditate si pornire automata irigare
if(procentajUmiditate()<20)
{
  //relayOn
}
else
{
  //relayOff
}

//btn1
 if(starebtn1 != stareVechebtn1)
  {
    if(starebtn1 == HIGH)
    {
      Serial.println(cntbtn1);
      cntbtn1++;
    }
  stareVechebtn1 = starebtn1;
  }//end btn1

//btn2
 if(starebtn2 != stareVechebtn2)
  {
    if(starebtn2 == HIGH)
    {

      cntbtn2 = cntbtn2+1;

    }
    stareVechebtn2 = starebtn2;
  }//endbtn2

//btn3
 if(starebtn3 != stareVechebtn3)
  {
    if(starebtn3 == HIGH)
    {
      cntbtn3 = cntbtn3+1;
    }
    stareVechebtn3 = starebtn3;
  }//endbtn3

//btn4
 if(starebtn4 != stareVechebtn4)
  {
    if(starebtn4 == HIGH)
    {
      cntbtn4 = cntbtn4+1;
    }
    stareVechebtn4 = starebtn4;
  }//endbtn4

//btn5
 if(starebtn5 != stareVechebtn5)
  {
    if(starebtn5 == HIGH)
    {
      cntbtn5 = cntbtn5+1;
    }
    stareVechebtn5 = starebtn5;
  }//endbtn5

//ecran1
     if(cntbtn1 == 1)
    {
     displayInteriorTempHum();
     //u8g.drawStr(23,58,temp.c_str());
    // u8g.drawStr(99,58,hum.c_str());
    }
//ecran2
     if(cntbtn1 == 2)
    {
     displayInteriorLights();
    }

//ecran3
      if(cntbtn1 == 3)
    {
     displayExteriorValues();
    }

     if(cntbtn1 == 4) cntbtn1 = 0;
     if(cntbtn2 == 3) cntbtn2 = 1;
     if(cntbtn2_1 == 3) cntbtn2_1 = 1;
     if(cntbtn3 == 3) cntbtn3 = 1;
} //end loop

void imagineSistemDomotic()
{
  u8g.firstPage();
  do{
    u8g.drawFrame(0,0,128,64);
    u8g.setFont(u8g_font_courB10);
    u8g.drawStr(0,30,"Sistem Domotic");
    }while(u8g.nextPage());
}

void imagineCasaWifi()
{
   u8g.firstPage();
   do{
    u8g.drawFrame(0,0,128,64);
    u8g.drawBitmapP( 0, 1, 16, 64, CasaDomoticaImage2);
     }while(u8g.nextPage());
}

void tempInterior()
{
   u8g.firstPage();
   do{
    u8g.setFont(u8g_font_courB10);
    u8g.drawStr(32,10,"Interior");
    u8g.drawFrame(0,15,128,49);
    u8g.setFont(u8g_font_5x7);
    u8g.drawStr(2,24,dateR.c_str());
    u8g.drawStr(101,24,houR.c_str());
    u8g.setFont(u8g_font_courB10);
    u8g.drawBitmapP( -3, 4, 16, 64, Temp1);
    u8g.drawCircle(40,46,1);
    u8g.drawStr(23,58,"26");
    u8g.setFont(u8g_font_10x20);
    u8g.drawStr(43,58,"C");
    u8g.setFont(u8g_font_courB10);
    u8g.drawBitmapP( 66, 10, 16, 64, UmidLogo);
    u8g.drawStr(99,58,"57");
    u8g.drawStr(117,58,"%");
     }while(u8g.nextPage());
}

void displayExteriorValues()
{
       frame1 = false;
       frame2 = true;
  u8g.firstPage();
      do{
        u8g.setFont(u8g_font_courB10);
        u8g.drawStr(32,10,"Exterior");
        u8g.drawFrame(0,12,128,51);
        u8g.drawLine(64,12,64,62);

       if(cntbtn2 == 1)
       {
        //u8g.drawBitmapP( 15, 30, 16, 64, robinetApaOprita);
        u8g.setFont(u8g_font_5x8);
        u8g.drawStr(78,23,"Irigare");
        u8g.drawStr(78,30,"pornita");
        u8g.drawBitmapP( 72, 8, 16, 64, robinetApaPornita);
        u8g.setPrintPos(15,40);
        u8g.setFont(u8g_font_courB10);
        u8g.print(procentajUmiditate());
        if(procentajUmiditate()<100)
        {
          u8g.setPrintPos(34,40);
          u8g.print("%");
        }
        else
        {
          u8g.setPrintPos(44,40);
          u8g.print("%");
        }

       }

  else{

      //u8g.drawBitmapP( 15, 30, 16, 64, robinetApaOprita);
      u8g.setFont(u8g_font_5x8);
      u8g.drawStr(78,23,"Irigare");
      u8g.drawStr(78,30,"pornita");
      u8g.drawBitmapP( 72, 8, 16, 64, robinetApaPornita);
     // u8g.drawBitmapP( 20, -20, 16, 64, LightOff);
    // valoare buna FanOffLOGO   u8g.drawStr(10,23,"Ventilatie");
   // valoare buna FanOffLOGO    u8g.drawStr(20,30,"oprita");
    //  u8g.drawBitmapP( -15, 24, 16, 64, fanOffLogo);
       u8g.drawStr(10,23,"Umid. Sol");
       u8g.drawBitmapP( 12, -1, 16, 64, UmiditateSol);
       }
       }while(u8g.nextPage());
    cntbtn2 = 0;
}

void displayInteriorLights()
{

   u8g.firstPage();
      do{
      u8g.setFont(u8g_font_courB10);
      u8g.drawStr(32,10,"Interior");
      u8g.drawFrame(0,12,128,51);
      u8g.drawLine(64,12,64,62);
      u8g.setFont(u8g_font_5x8);

      if(cntbtn2 == 1)
      {
      u8g.drawStr(73,23,"Dormitor");
      u8g.drawStr(75,60,"L.aprinsa");
      u8g.drawBitmapP( 78, 7, 16, 64, LightOn);
      }
      else if(cntbtn2 == 2)
      {
      u8g.drawStr(73,23,"Dormitor");
      u8g.drawStr(75,60,"L.stinsa");
      u8g.drawBitmapP( 78, 7, 16, 64, LightOff);
      }
      else{
      u8g.drawStr(73,23,"Dormitor");
      u8g.drawStr(75,60,"L.stinsa");
      u8g.drawBitmapP( 78, 7, 16, 64, LightOff);
      }

      if(cntbtn3 == 1)
      {
      u8g.drawStr(10,23,"Sufragerie");
      u8g.drawStr(15,60,"L.aprinsa");
      u8g.drawBitmapP( 20, 8, 16, 64, LightOn);
      }
      else if(cntbtn3 == 2)
      {
      u8g.drawStr(10,23,"Sufragerie");
      u8g.drawStr(15,60,"L.stinsa");
      u8g.drawBitmapP( 20, 8, 16, 64, LightOff);
      }
    //else if(digitalRead(relay)

    else{
      u8g.drawStr(10,23,"Sufragerie");
      u8g.drawStr(15,60,"L.stinsa");
      u8g.drawBitmapP( 20, 8, 16, 64, LightOff);
    }
      }while(u8g.nextPage());

}

void displayInteriorTempHum()
{
      u8g.firstPage();
      do{
      u8g.setFont(u8g_font_courB10);
      u8g.drawStr(32,10,"Interior");
      u8g.drawFrame(0,15,128,49);
      u8g.setFont(u8g_font_5x7);
      u8g.drawStr(2,24,dateR.c_str());
      u8g.drawStr(101,24,houR.c_str());
      u8g.setFont(u8g_font_courB10);
      u8g.drawBitmapP( -3, 4, 16, 64, Temp1);
      u8g.drawCircle(40,46,1);
      u8g.drawStr(23,58,temp.c_str());
      u8g.setFont(u8g_font_10x20);
      u8g.drawStr(43,58,"C");
      u8g.setFont(u8g_font_courB10);
      u8g.drawBitmapP( 66, 10, 16, 64, UmidLogo);
      u8g.drawStr(99,58,hum.c_str());
      u8g.drawStr(117,58,"%");
      digitalWrite(ledVerde,LOW);
        }while(u8g.nextPage());
}

```

# Answer
Difficult to advise without more clear information but here's a couple of ideas to play around with (currently typing on my phone, will edit later).

If using a physical menu and buttons then you need some way to track location. You could try adding proximity sensors to check physical location/proximity to the light source and let that be the deciding variable for which bulb gets activated. You could use a "universal remote" approach, using separate arduinos (per light) with IR receivers.

If using an app menu, like on a phone, try declaring a variable "room" and have the button pass the frame name or ID number based on the frame ("bedroom" or "kitchen", "1" or "2" etc) as that variable via your communication line to the arduino. On the arduino side, declare the same variable and process the received data from the app i.e. String room = your-room-ID. Ensure you have separate pinout declarations for each bulb you want to control i.e. #define kitchen 14 # define livingroom 15... setPin(output, kitchen), setPin(output, livingroom) then modify your bulb activation line to be pinout(room, HIGH);
> 1 votes

# Answer
It's really very simple, I think... If I understood properly...

```
global frame, lightRoom1, lightRoom2

function changeFrame ( ) {

// if frame == 1, change it to 2

    if ( frame == 1 ) {
        <commands to refresh display>;
        frame = 2;
    } else {
        <commands to refresh display>
        frame = 1;
    }

}

function switchLight ( ) {

// roomno = frameno.
// if light on, switch off; if off, switch on.

    if ( frame == 1 ) {

        if ( lightRoom1 == false ) {
            <code to switch light on >;
            lightRoom1 == true;
        } else {
            <code to switch light off >;
            lightRoom1 == false;
        }

    }

    if ( frame == 2 ) {

        // same as above but for room 2.

    }

}

if ( digitalRead ( framePin ) == LOW ) {
    changeFrame ( );
}

if ( digitalRead ( lightPin ) == LOW ) {
    switchLight ( );
}

```
> 1 votes

# Answer
The code you show is indeed too long. However, a cursory look seems to indicate that you are not using any debouncing library. This is then the first thing you should do. There are probably many options. I will suggest Bounce2 which, in addition to debouncing, handles the edge detection. Then you have the `fell()` method that tells you whether the input signal just fell since the last time it was tested, which is a way to detect the button press.

Then, within `loop()`, you would add something like this:

```
if (mainButton.update() && mainButton.fell()) {

    // Find the pin that controls the appropriate light.
    uint8_t lightPin;
    if (currentFrame == FRAME1) {
        lightPin = PIN_LIGHT_ROOM_1;
    } else {  // FRAME2
        lightPin = PIN_LIGHT_ROOM_2;
    }

    // Toggle the light.
    if (digitalRead(lightPin) == HIGH) {
        digitalWrite(lightPin, LOW);
    } else {
        digitalWrite(lightPin, HIGH);
    }
}

```

The assumptions I am making should be pretty obvious:

* `currentFrame` is a variable updated by your menu system. Its value can only be one of the constants `FRAME_1` or `FRAME_2`
* `PIN_LIGHT_ROOM_1` and `PIN_LIGHT_ROOM_2` are constants holding the pin numbers which control the corresponding lights.
> 0 votes

---
Tags: programming
---


title: 'myservo' does not name a type

text:
# Question
Title: 'myservo' does not name a type
I keep getting *'myservo' does not name a type* as an error message, I have already looked other solved questions like this one but I can´t find the mistake. I would be very glad for your help.

```
/*********************************************************
 * Bot control
 * By soleil_zero
 * Based on code by
 * MSc. Fausto M. Lagos S.
 * @piratax007
 * V2.0.0 - 2019
 * GNU GPLV3+
 *
 * Hardware:
 * Arduino Mega2560
 * Adafruit Motor Shield V1.2
 * Bluetooth module H6
 * 1 Servo
 * 2 DC Motor
 *********************************************************/

// Librería para Adafruit Motor Shield V1.2 y Servo
#include "AFMotor.h"
#include "Servo.h"

// Motores conectados en los puertos 1 y 2
AF_DCMotor leftMotor(1, MOTOR12_64KHZ);
AF_DCMotor rightMotor(2, MOTOR12_64KHZ);

Servo myservo;
myservo.attach(9);

// Variable para el paso de mensajes vía Bluetooth
char message;
//ángulo de rotación del servo
int angle = 0;

void setup() {
  // Velocidades en los motores
  leftMotor.setSpeed(150);
  rightMotor.setSpeed(150);

  /* Debido a que el Adafruit Motor Shield V1.2 ocupa los pines digitales 0 y 1 para la conexión del módulo HC05
     bluetooth deben utilizarse cualquiera de los otros disponibles: 14 (TX3) y 15 (RX3) o 16 (TX2) y 17 (RX2) o
     18 (TX1) Y 19 (RX1). De acuerdo a cuál de los cuatro pines se utilicen deben modificarse las líneas
     relacionadas a la comunicación Serial e.g si se utilizan los pines 18 y 19 la instrucción será Serial1 */
  Serial3.begin(9600);
  myservo.write(angle);
}

void loop() {
  // Verificación de mensaje en el puerto Serial
  if (Serial3.available() > 0) {
    message = Serial3.read();
  }

 if (message == 'F') {//Forward
    leftMotor.run(FORWARD);
    rightMotor.run(FORWARD);
  } else if (message == 'B') {//Backwards
    leftMotor.run(BACKWARD);
    rightMotor.run(BACKWARD);
  } else if (message == 'L') {//Left
    leftMotor.run(FORWARD);
    rightMotor.run(BACKWARD);
  } else if (message == 'R') {//right
    leftMotor.run(BACKWARD);
    rightMotor.run(FORWARD);
  } else if (message == 'S') {//stop
    leftMotor.run(RELEASE);
    rightMotor.run(RELEASE);
    Serial3.print("stop");
  }
  } else if (message == 'U') {//down
    angle = 0;
    servo1.write(angle);
  }else if (message == 'D') {//up
    angle = 90;
    servo1.write(angle);
  }
}

```

# Answer
> 1 votes
In C and C++ languages we write statements *inside functions*. That `myservo.attach(9);` is a *statement*. You can't just write it in the middle of the file. It has to reside inside a function.

In your code `myservo.attach(9);` just sits in the middle of nowhere. You had enough sense to put `leftMotor.setSpeed(150);` inside `setup()`. Why did you suddenly decide to place `myservo.attach(9);` outside of any functions?

Function `setup()` would be an appropriate place for this statement.

---
Tags: arduino-mega, servo
---


# Question
Title: Difference between these two relays (D1 Mini Relay Shield and Single 5V Relay)
I've setup my NodeMCU v3 with this relay and I got this:

* When using 3V to power the relay, I can hear coil when I turn on the board and I can only turn it on once. Then I can no longer hear the coil, but LED turns on and off.
* When using VU pin (5V) to power the relay, I get the same coil sounds (when turning on board and on first toggle), then nothing. But the LED stays on, just slightly dims itself when turning on. Barely noticeable.

Alright, but I had a D1 Mini relay shield* laying around and I decided to give it a try. And it worked when powering the shield with VU pin (5V).

So my question is what is the difference? Does the D1 Mini Relay Shield have a transistor to pull up pin voltage from 3V to 5V and the other relay doesn't? If I had a logic level converter 3V-5V between the NodeMCU GPIO and the relay IN, would it work?

Thanks in advance.

\*must say mine is a clone, but it works

# Answer
More than likely it is a faulty board.

The schematic for the D1 Mini relay shield can be found here.

I couldn't find a schematic for the relay that is having the problems but you can see from the picture below that it has 2 LEDs (power and relay signal), a flyback diode and a FET or transistor.

As you can see the circuits are pretty much the same. So my conclusion is that you have a faulty relay board.
> -1 votes

# Answer
Ok, so:

1. I've bought a logic level converter.
2. Bought another relay.

Now to the results:

* With the first relay, no joy with 5v or 3v in any combination (3v on VCC / 3v on IN; 5v VCC / 5V IN; 3V VCC / 5V IN; 5v VCC / 3V IN)
* With the second relay (the new one), funny enough.. **Didn't work with 5V on VCC and 5V on input. But it did work with 3v on both of them.**

I measured every output voltage to make sure everything was working fine and it wasn't a problem with power supply.

I guess it should work with 5v...? Right?

Anyway, it was indeed a faulty relay. And 3V on VCC and Input is what worked for me, even though it is a 5V relay. Thank you all for the assistance.
> 0 votes

---
Tags: esp8266, nodemcu, relay
---


title: Webpage values wont update

text:
# Question
Title: Webpage values wont update
I've been trying to run the following esp32 LED PWM code to change the LED's brightness, and show the current PWM duty on the webpage, but the PWM values on the webpage won't change until I hit the submit button twice.

```
#include <Arduino.h>
#include <WiFi.h>
#include <WebServer.h>
WebServer ser(80);
int s=0;
String k;

String iso()
{
  k="<p style=\"text-align: center;\"><strong><font size=\"9\">LED PWM</font></strong><font size=\"3\"></font><FORM action=\"/\" method=\"post\"><input type=\"text\" name=\"duty\"><br> <input type=\"submit\" value=\"Submit\">Cureent Duty=";
  k=k+s;
  k=k+"</p>";

  return k;
}

void root()
{
  iso();
  ser.send(200, "text/html", iso());

  if (ser.hasArg("duty"))
  {
      iso();
      s=ser.arg("duty").toInt();
      ledcWrite(4, s);
      iso();
      ser.send(200, "text/html", iso());
  }
}

void setup() {
  Serial.begin(9600);
  ledcAttachPin(33, 4);
  ledcSetup(4, 5000, 8);
  WiFi.begin("ssid", "pass");
  Serial.print("\nConnecting To WiFi");
  while (WiFi.status()!=WL_CONNECTED)
  {

    Serial.printf("\n.");
  }
  Serial.print("\nConnected");

  ser.on("/", root);
  ser.begin(80);
}

void loop() {
  ser.handleClient();
}

```

Here's a GIF addressing the issue

# Answer
> 3 votes
When the client sends you a request, you should answer *only once*. Your `root()` function attempts to answer twice whenever the request contains the argument “duty”. The client will not handle a duplicate response to a single request.

Here is your `root()` function:

```
void root()
{
  iso();
  ser.send(200, "text/html", iso());  // ← first response

  if (ser.hasArg("duty"))
  {
      iso();
      s=ser.arg("duty").toInt();
      ledcWrite(4, s);
      iso();
      ser.send(200, "text/html", iso());  // ← second response
  }
}

```

You may notice that the first response was sent *before* updating the duty cycle.

The proper way to handle the request is to first handle the request parameters, if any, *then* send the response:

```
void root()
{
  if (ser.hasArg("duty")) {
    s = ser.arg("duty").toInt();
    ledcWrite(4, s);
  }
  ser.send(200, "text/html", iso());  // ← only sent once
}

```

As a side note, there is absolutely no need to build the response five times (you have five calls to `iso()` within `root()`) when you only need it once!

---
Tags: web-server, esp32
---


# Question
Title: How does the dual 5V and 3.3V output on the Uno R3 work exactly?
I'm constructing a circuit that needs both voltage supplies (for 3.3V RFID and 5V relay, GPS and screen) but the Uno is physically too big so I need to use a nano or mini pro, both of which I can only get in 5V. I understand how to use a regulator to drop 5V to 3.3V for the RFID-IC power but I keep seeing instructions to use a level shifter between the IC outputs and arduino input pins. I was just wondering if the Uno has a built-in level shifter for all pins or some other method as the I/O pins do not have specified voltages or uses.

Thanks for your time.

# Answer
Pins of the UNO/Nano/Mini/Mega board are connected to GPIO pins of the MCU without any additional circuit. The ATmega MCU running at 5 V will sense 3.3 V as HIGH because of the threshold level to convert voltage to logic state.

ATmega will read the pin HIGH from 0.6 * Vcc, so at 5 V Vcc the threshold is 3 V.

Sources:
> 3 votes

# Answer
There are no built-in level shifters on the Uno; it doesn't need them. Uno's 3.3v pin is merely a convenience for supplying a low-current 3.3v device but there is no provision made for level shifting if/when that is necessary.

Genuine Uno's can deliver a *max* of 150mA to the 3.3v pin, so plan your current-budget conservatively. In my dual-voltage designs (2 voltage rails on a board with 3.3v & 5v parts), I reduce the "raw" 5v with a 3.3v regulator (typically an LM1117-3.3 part) rather than drawing it off of the regulated 5v power. (I put "raw" in quotes because I usually supply the board with a pre-regulated 5 volts (USB or wall-wart).

For I/O levels, a 3.3v part's HIGH level is within the range of what Uno will read as HIGH. In the other direction, Uno's HIGH level is too high for a 3.3v part and needs to be shifted down to 3.3v. If there are only one or two such signals (Uno -\> 3.3v device), a voltage divider circuit would be less expensive and use less board space than a level-shifter. The level-shifter board would be an extra purchase but it is a quick and dirty solution if you have the space for it.
> 2 votes

# Answer
You can get pro-mini in 3.3V, but this has little to do with your problem.

The nano runs on 5V, but has an on-board regulator which supplies 3.3V power, although the logic I/O is 5V.

Level shifters can be used to perform logic level translation, but are not always needed.

The output of a 3.3V logic circuit will drive the INPUT of a 5V logic circuit (technically this is marginal, but works in practice).

5V logic outputs can be connected to 3.3V inputs with a simple voltage divider (you can use level shifter or other methods). Without some means of limiting voltage there is a risk of damaging the 3.3V logic.

Without more detail of exactly what you are planning it is not possible to be more precise.
> 0 votes

---
Tags: arduino-uno, voltage-level
---


title: Esp and blynk app

text:
# Question
Title: Esp and blynk app
It is possible to control one relay using Blynk app and also using an atmega? To a better understanding think at a relay that will turn on a fan when you use the blynk app. but when you don;t have the phone around you, using a pushbutton, you can turn it on from there(the button will be connected to atmega)

---

```

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

  pinMode(relCh2,OUTPUT);

  pinMode(relCh3,OUTPUT);

  pinMode(relCh4,OUTPUT);
  digitalWrite(relCh1,HIGH);
  pinMode(EspReadPin, INPUT);
  digitalWrite(relCh3,HIGH);
}
void loop()
{
Serial.println(digitalRead(6));
delay(400);
  if(digitalRead(EspReadPin == 1))
  {
    digitalWrite(relCh3,LOW);
  }
  else if(digitalRead(EspReadPin == 0))
  {
    digitalWrite(relCh3,HIGH);
  }
}

```

# Answer
> 1 votes
Yes it is possible.

Use the Blynk example sketch to activate the pin of the esp8266. Read the pin of the esp8266 with the ATMega. Handle in ATmega sketch the esp8266 pin as a second button.

---
Tags: relay, blynk
---


title: Xbee S2C is resetting Arduino Uno

text:
# Question
Title: Xbee S2C is resetting Arduino Uno
I have a coordinator radio hooked up to a sparkfun xbee shield, hooked up to an Uno. This is then hooked up to my computer. This coordinator talks with a number of xbee routers/end devices and sends them 6 commands to change the digital pins high or low on the corresponding xbees. The commands are always frame ID = 0, then the last (6th) command I send a 0x2 to save all the digital pins high or low at once.

The issue is that occasionally when the xbee receives all of the commands and saves them, the Uno will reset itself. (I can tell by the blinking LED on 13).

I have looked into it, and the best suggestion so far is to disable D7 on the receiving Xbee via XCTU. This unfortunately has not helped. Is there another reason that the arduino is resetting every couple of times I change the pins on the xbee? It doesn't happen every time, just once out of every 3-5 times...

# Answer
Bleh, I figured it out. Not only do I have to turn D7 off, I also have to hook a jumper between 5V and RST as shown here. https://learn.sparkfun.com/tutorials/xbee-shield-hookup-guide/all
> 0 votes

---
Tags: xbee
---


title: Multiple dht11 on an wemos d1 r1

text:
# Question
Title: Multiple dht11 on an wemos d1 r1
I am trying to connect three separate DHT11 to my Wemos d1 r1. I have each sensor hooked to a power pin which turns on and off, the sensor pin and a common ground. Here is my code:

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

String apiKey = "xxxxxxxxxxxxxx";
const char* ssid = "xxxxxxxxxxx";
const char* password = "xxxxxxxxxxxx";
const char* server = "api.thingspeak.com";

DHTesp dht;
DHTesp dht2;
DHTesp dht3;
WiFiClient client;

void setup() {

  pinMode(D6,OUTPUT);
  pinMode(D8,OUTPUT);
  pinMode(D1,OUTPUT);

    Serial.begin(115200);
    dht.setup(D5, DHTesp::DHT11);
    dht2.setup(D7, DHTesp::DHT11);
    dht3.setup(D2, DHTesp::DHT11);
    WiFi.begin(ssid, password);

  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");
digitalWrite(D6,HIGH);

}

void loop() {
 digitalWrite(D6,HIGH);
  delay(8000);

    float t = dht.getTemperature();
    float f = (t*1.8) + 32;

    if (isnan(t))
  {
    Serial.println("Failed to read from DHT2 sensor!");
    return;
  }
    Serial.print(", \"maintemp\": ");
    Serial.print(f);
    Serial.print("}\n");

digitalWrite(D6,LOW);
digitalWrite(D8,HIGH);
delay(8000);

    float t2 = dht2.getTemperature();
    float f2 = (t2*1.8) + 32;

    if (isnan(t2))
  {
    Serial.println("Failed to read from DHT3 sensor!");
    return;
  }
    Serial.print(", \"lowtemp\": ");
    Serial.print(f2);
    Serial.print("}\n");

digitalWrite(D6,LOW);
digitalWrite(D1,HIGH);
delay(8000);

    float t3 = dht3.getTemperature();
    float f3 = (t3*1.8) + 32;

    if (isnan(t3))
  {
    Serial.println("Failed to read from DHT sensor!");
    return;
  }
    Serial.print(", \"uptemp\": ");
    Serial.print(f3);
    Serial.print("}\n");

    digitalWrite(D1,LOW);

    delay(2000);

    if (client.connect(server, 80)) {
    String postStr = apiKey;
    postStr += "&field3=";
    postStr += String(f);
    postStr += "&field4=";
    postStr += String(f2);
    postStr += "&field5=";
    postStr += String(f3);
    postStr += "\r\n\r\n\r\n\r\n";

    client.print("POST /update HTTP/1.1\n");
    client.print("Host: api.thingspeak.com\n");
    client.print("Connection: close\n");
    client.print("X-THINGSPEAKAPIKEY: " + apiKey + "\n");
    client.print("Content-Type: application/x-www-form-urlencoded\n");
    client.print("Content-Length: ");
    client.print(postStr.length());
    client.print("\n\n\n\n");
    client.print(postStr);

    Serial.print("Temperature: ");
    Serial.print(f);

    Serial.println("Sending data to Thingspeak");
  }
  client.stop();

  Serial.println("Waiting 20 secs");
  // thingspeak needs at least a 15 sec delay between updates
  // 20 seconds to be safe

  delay(53700);
}

```

As you can see I assign a separate DHT to each sensor pin and turn on and off the power pins to each sensor. They all have a common ground.

When I run the code the first sensor reads the temperature but the second one says "Failed to read from DHT3 sensor!".

It is not the sensor because if I swap the first and second sensor the first one always read and the second fails. If I eliminate the second sensor the third one fails. I have tried to power all of the sensor pins in SetUP but still the first one is the only one to work. Is there some kind of trick I have to use here.
I am using DHTESP.h since the regular DHT.h didn't work with the Wemos Pro Mini.

Has anyone had any experience with this to give me some guidance.

Thanks

# Answer
> 0 votes
You probably have to create an set up a new DHT object each time you turn the power on. My guess is that the sensor needs to be initialized by the Arduino before it is ready to take readings, and when you turn the power off and back on it loses its configuration.

---
Tags: esp8266, temperature-sensor
---


# Question
Title: Change css form color from esp32 if statement
I am fairly new to arduino and ESP though am very familiar with css and javascript.

I have an esp webserver that includes a button

```
client.print("<button style='background-color: #F30C0C; color:#000;'></button>");

```

but need it to change the css backbround-color when pin is reading HIGH

```
 if (c == '\n') {
          currentLineIsBlank = true;
          buffer = "";
        }
        else if (c == '\r') {
          if (buffer.indexOf("GET /?relay1") >= 0)
            relayPIN1read = digitalRead(relayPIN1);

          if (relayPIN1read == HIGH) {
            digitalWrite(relayPIN1, LOW);
          }
          if (relayPIN1read == LOW) {
            digitalWrite(relayPIN1, HIGH);
          }
        }
      }

```

Does any one know of any way to do this?

# Answer
First print everything up to the colour. Then print the colour, which you change depending on the state of the pin. Then print the rest.

```
client.print("<button style='background-color: ");

if (digitalRead(PIN) == HIGH) {
    client.print("#0CF30C");
} else {
    client.print("#F30C0C");
}

client.print("; color:#000;'></button>");

```
> 1 votes

---
Tags: arduino-ide, web-server, esp32
---


title: Nodemcu does not connect to phone wifi

text:
# Question
Title: Nodemcu does not connect to phone wifi
All welcome.

I'm trying to connect nodemcu to the phone's wifi.

And nodemcu can't do it. But sometimes after several reboots she does it. Also if i use my old phone - nodemcu connects perfectly! Why?

My "new" phone: Fly FS504 Cirrus 2

My old phone: Fly IQ4504 Quad.

My code:

```
#include <ESP8266WiFi.h>

const char *ssid =  "Just my SSID";

const char *pass =  "Some password";

WiFiClient client;

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

       Serial.println("Connecting to ");
       Serial.println(ssid);

       WiFi.begin(ssid, pass);
       while (WiFi.status() != WL_CONNECTED)
          {
            // stack here (only with new phone)
            delay(500);
            Serial.print(".");
          }
      Serial.println("");
      Serial.println("WiFi connected");
}

void loop()
{

}

```

# Answer
From my experience the esp8266's wifi is a little bit buggy sometimes. I'm not sure if it has something to do with the esp auto-connecting to known networks, but I managed to work-around this issue by explicitly `WiFi.disconnect()`ing from any potential network right before calling `WiFi.begin()`.

Another thing that I noticed several times is that the esp can be easily disturbed when connected to a breadboard, in special when wifi is in use (in this case the esp might even crash). There must be some bad interferences, I guess.
> 1 votes

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


title: New to arduino, help wiring relay

text:
# Question
Title: New to arduino, help wiring relay
I am new to arduino and need some help. I just baught light bars for my jeep and wiring harnesses with them, the harnesses come with buttons and I wanted to replace the button and have them controlled on my phone. The harnesses come with a relay and a fuse and a button all 12v, How would i go about using my raspberry pi or udoo x86(which has built in adruino) to basically replace the rocker switch so i can then turn things on and off without needing to have actual switches.

# Answer
> 1 votes
To drive a relay you'll need a transistor (a MOSFET is a good choice) and you'll need a diode across the relay coils to protect the transistor from the reverse current pulse when you remove power from the relay coils.

As Majenko says, if you Google "Arduino relay" you'll find lots of articles covering the topic. (And if you use a digital output line from your PI the exact same circuit will work.)

This MOSFET is a good option for switching high current loads with a 5V logic signal:

https://www.adafruit.com/product/355

The diode will need to be a power diode that can handle your voltage/current needs. You'll need to figure out how much current your light bar uses, and then I'd suggest a diode that can handle twice that much current (at 12V) for a margin of safety.

---
Tags: programming, relay, wires, switch
---


# Question
Title: All floats feedback a rounded down integer
So I am very confused at the results I am getting. It seems that floats aren't working properly, and I don't understand why.

I was trying to read a temp sensor and convert the reading to celsius. However, when I tried to divide the value (an int between 145-165) by 1024, and multiply by 5 I would get back a float value of 0.00 Here's the code I was using

```
    void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
  pinMode(A0, INPUT);

}

void loop() {
  int sensorVal = analogRead(A0);
    Serial.print("Sensor Value: ");
    Serial.println(sensorVal);

  float voltage = ((sensorVal/1024) * 5);
    Serial.print("Voltage Value: ");
    Serial.println(voltage);

}

```

This would only return values of 0.00 for voltage, even though the sensor itself is working fine, returning varying values between 146 and 165 based on how much heat I apply. This didn't make any sense, so I tried it with some other values, eg.

```
Serial.print(float (10 / 6));

```

and

```
Serial.print(float (5 / 2));

```

which should have returned 1.67 and 2.50 respectively, but instead returned 1.00 and 2.00

I think it might be a settings thing, where all floats round down to an int, but that seems really weird.

Any help would be great!

# Answer
You are doing integer arithmetic. Try adding .0 to the end of your values where you need the floating point results.

For example...

```

  float voltage = ((sensorVal/1024.0) * 5.0);

```

Remember the results of analog read is an integer. So the conversion to a float in you original code only happens when the "=" is being "executed". Another possibility is to cast it to a float straight away.

```

  float voltage = ((((float)sensorVal)/1024.0) * 5.0);

```

Or more simply

```

  float voltage = ((float)sensorVal)/1024.0 * 5.0;

```
> 1 votes

# Answer
You already got a couple of perfectly good answer. I will nevertheless suggest a slightly different idiom:

```
float voltage = sensorVal * (5.0 / 1024);

```

or, maybe better:

```
const float V_REF = 5.0;  // at the top of the sketch

float voltage = sensorVal * (V_REF / 1024);

```

The reason this is slightly better than the other options is because division – even integer division – is a very expensive operation on the smaller Arduinos. By writing the conversion as in the lines above, the ratio `V_REF / 1024` becomes a compile-time constant, which is evaluated by the compiler at build time. Then, only the much cheaper multiplication needs to be done by the Arduino itself, at run time. Not a big deal if you are not time constrained, but it's a low-hanging fruit in terms of optimization.

You may write `1024.0` instead of `1024` if it feels safer. I tend to keep the `.0` for the voltage only, because 1024 is an integer, whereas the “5” in “5 volts” is conceptually a real number (it's an *analog* voltage, and not even exactly 5 V if you bother to measure it). But this is just a personal preference at the end.
> 4 votes

# Answer
GMc explained what to do, but didn't explain in detail why your code fails to give floating point results.

Most languages evaluate expressions using order of operations. C and C++ are no exception to this.

In C/C++, while the expression is being evaluated, the compiler also decides what data types to use for each part. integer-integer expressions are evaluated using integer math. If either of the parts of an expression is a larger/floating point type, both values are "promoted" to the larger/more complex type before evaluating the expression.

in your code

```
float voltage = ((sensorVal/1024) * 5);

```

The `sensorVal/1024` bit is evaluate first. Since both `sensorVal` and `1024` are integers, the compiler uses integer math. That yields an int result, and so any fractional part is truncated and lost.

It then evaluates `result*5` (where `result` is the result of the first part, `sensorVal/1024`, which is an integer.) Both of those parts are integers, so the result of that expression is an int.

Finally, you ask the compiler to store the result into a float, `voltage`. The compiler then promotes the integer result of the whole expression to a float, but you've lost any floating point part of your calculations.

By rewriting your line as

```
float voltage = ((sensorVal/1024.0) * 5.0);

```

The compiler does what you want. The `sensorVal/1024.0` bit is now integer-float math, so the compiler "promotes" `sensorVal` to a float and then does float-float math. The second part is now float-float, so the result is also floating point.

```
float voltage = ((sensorVal/1024.0) * 5);

```

Would also work in this case (where `5` is an integer constant.) That works because `float_result*5` is float-integer math, and the compiler will promote `5` to a floating point value and do float-float math. to get the final result. However, it's safer to use all floating point constants so you don't accidentally do part of your calculations using integer math and truncate that part before converting to floating point.

As you say, making `sensorVal` a float also would be a good idea. (Again, to avoid accidentally doing integer math on part of your expression and getting wrong results in the process. In this case making `sensorVal` a float isn't needed, but with a different expression you might wind up with integer math for part of the calculation.)
> 2 votes

---
Tags: programming, arduino-ide, c++, float
---


# Question
Title: Windows 10 does not recognize Arduino Leonardo
Using Arduino Leonardo, IDE 1.8.9, Windows 10.

For a short time, when I first got the Leonardo, Windows 10 would recognize the board; I could see it in devices, Windows 10 would make a sound when plugged in, it would show listed in the ports of the IDE, and I could upload my code to the board (confirmed with blinking light sketch). ***It no longer does.***

The error I get in the IDE `avrdude: butterfly_recv(): programmer is not responding`.

I believe the main issues stems from I had selected Arduino UNO (I have a couple of those as well) in the IDE and Uploaded my sketch.

Ever since I did this, Windows 10 no longer recognizes the board when plugged in. It doesn't even show in "other devices" under device manager.

I have tried the following:

* The on-board reset trick that seems to be most of what other users experience and solves their issue. All variations. Holding the reset button, uploading, releasing, etc.
* Swapping cables. Confirmed with another device it was a data cable and working.
* Uninstalling and reinstalling the IDE
* Restarting numerous times
* Burning boot loader - since Windows 10 won't recognize the device, this fails immediately can't even communicate to the board.

I have seen similar questions about this, but none of them seem to specifically cover what I am encountering.

# Answer
> 1 votes
Sounds like you've bricked it. Your broken sketch (wrong MCU selected) means that it's not presenting a CDC/ACM port.

Your best bet is to use a hardware programmer (eg USBASP or another Arduino) to erase the chip and reload the bootloader.

---
Tags: arduino-ide, arduino-leonardo, windows
---


# Question
Title: Adafruit Micro-SD breakout not initializing on MEGA 2560
\] \[I am having quite a bit of trouble trying to get my Arduino MEGA 2560 to read my micro-SD card. My wiring is as follows:

```
Breakout    Arduino
5v            5v
Gnd           Gnd
CLK           52
DO            50
DI            51
CS            53
CD            Was not connected and then connected to 47 (neither worked)

```

Here is my code:

```
#include <Wire.h> //library necessary to use I2C communications bus
#include <Adafruit_Sensor.h>
#include <Adafruit_BME680.h>
#include <SD.h>
#include <SPI.h>

const uint8_t chipSelect = 53; //chipSelect pin for the SD card Reader
const uint8_t cardDetect = 47;

File CO2Data; //Data object you will write your sensor data to

void setup() {
Serial.begin(115200);//"begins" the serial monitor so you can print stuff out when connected to the computer (set baud rate to 115200)
Wire.begin ();//begins the I2C communications bus so it can talk to the K33

Serial.print("Initializing SD car...");
pinMode(53, OUTPUT);

if (!SD.begin(chipSelect)) {
Serial.println("Card failed, or not present");
// don't do anything more:
while (1) ;
}
Serial.println("card initialized.");
File CO2data = SD.open("datalog.txt", FILE_WRITE);
if (! CO2data) {
Serial.println("error opening datalog.txt");
// Wait forever since we cant write data
 while (1) ;
}}

```

The SD card is formatted to FAT32.

Thank you for any help!

# Answer
The non-analog ground line attached to the micro-SD was pulling down my voltage. Just hardwired to different ground and problem solved! (Check your voltages).

From what I could gather. the ground pin on the MEGA inline with the digital pins was a different ground source (digital ground). I literally took the ground lead from the SD board and just touched it to the housing of the USB connector on the MEGA and my voltage came back.
> 1 votes

---
Tags: spi, sd-card, adafruit, atmega2560
---


# Question
Title: Arduino timer to turn a serve at a certain time
i am working on a project for my school tech class. Our goal is to make a vehicle that will travel along a cable and drop an egg to a target while going down the cable. i am using an arduino to to open a trap door with a servo after a certain amount of time that is set by two push buttons, and a third push button will control when the timer starts. Here is my circuit

Here is the code:

```
#include <Servo.h>
#include <LiquidCrystal.h>

int b = 0;
int up = 0;
int down = 0;
int val = 100;

LiquidCrystal lcd(12, 11, 5, 4, 3, 2);

Servo myservo;

int pos = 0;

void setup()
{
  pinMode(b, INPUT);
  pinMode(up, INPUT);
  pinMode(down, INPUT);
  lcd.begin(16, 2);
  myservo.attach(9);  // attaches the servo on pin 9 to the servo object
}

void loop()
{
  digitalRead(down);
  digitalRead(up);
  digitalRead(b);
  lcd.setCursor(0, 0);
  lcd.print("milli seconds:");

  while (b == HIGH)
  {
    digitalRead(down);
    digitalRead(up);
    digitalRead(b);
    lcd.setCursor(0, 1);
    lcd.print(val);
    myservo.write(0);
    if (up == HIGH, down == LOW)
    {
      val + 1;
    }
    if (down == HIGH, up == LOW )
    {
      val - 1;
    }

    delay(val);
    myservo.write(100);
    delay(1000);
  }
}

```

# Answer
> 1 votes
in setup you are calling

```
pinMode(b, INPUT);
pinMode(up, INPUT);
pinMode(down, INPUT);

```

but b, up and down all equal 0 so this is what you are doing is :

```
pinMode(0, INPUT)
pinMode(0, INPUT)
pinMode(0, INPUT)

```

This doesn't do what you want at all, these need to be assigned to pins. All you are doing is repeatedly setting arduino digital pin 0 to INPUT 3 times.

secondly

```
while(b == HIGH)

```

will never fire since b is 0 and is never set to anything else. so it will never == HIGH

Finally,

```
digitalRead(down);

```

doesn't do anything useful; what it does is read from pin down which is set to 0, and then drops the return value on the floor

also, this,

```
if (up == HIGH, down == LOW)

```

is just very wrong, sholud be

```
if (up == HIGH && down == LOW)

```

anyway based on you scematic, fixing this code:

```
#include <Servo.h>
#include <LiquidCrystal.h>

const int B = 7;
const int UP = 8;
const int DOWN = 9;
int val = 100;

LiquidCrystal lcd(12, 11, 5, 4, 3, 2);

Servo myservo;

int pos = 0;

void setup()
{
  pinMode(B, INPUT);
  pinMode(UP, INPUT);
  pinMode(DOWN, INPUT);
  lcd.begin(16, 2);
  myservo.attach(9);  // attaches the servo on pin 9 to the servo object
  lcd.setCursor(0, 0);
  lcd.print("milli seconds:");
}

void loop()
{
  // todo: debounce the switches
  int up = digitalRead(UP);
  int down = digitalRead(DOWN);
  int b = digitalRead(B);

  if (up == HIGH && down == LOW)
  {
     val += 1  // todo: handle overflow
  }

  if (down == HIGH && up == LOW )
  {
     val -= 1
  }

  lcd.setCursor(0, 1);
  lcd.print(val);

  if(b == HIGH)
  {
    myservo.write(0);
    delay(val);
    myservo.write(100);
    delay(val);
  }

}

```

this will do what the origonal code was trying to do, more or less, but the proper way to do this would be (in psuedo-code):

```
// Setup pins etc.
// Setup(): pinMode(...) ... etc.
// Loop():
//   debounce buttons
//   handle up/down
//   record milliseconds when button is pressed
//   see how much time has passed
//   trigger servo when timer has passed

```

---
Tags: arduino-uno, timing
---