# Question
Title: How to control continuous rotation servo via HC-12 rf module
I am working on a project to wirelessly control a continuous rotation servo...something like a wireless vending machine. The problem I am having is controlling how many revolutions the servo is making. During testing I used a button and had no issues getting the delay to work properly. Now that it's connected to the HC-12 RF module I can't get the delay to control how many rotations the servo makes. The servo I'm using is the FS90R.

```
#include <SoftwareSerial.h>
#include <Servo.h>
SoftwareSerial mySerial(2, 3); // RX, TX
Servo badservo;

int pos = 92;
unsigned long last = millis();

void setup() {
  mySerial.begin(9600);
  badservo.attach(9);
  badservo.write(pos);
}

void loop() {
  if(mySerial.available() > 1){
    int input = mySerial.parseInt();//read serial input and convert to integer (-32,768 to 32,767)
    int servpos = badservo.read();
    if(millis() - last > 250){
      if(servpos == 92 && input == 1234){
        badservo.write(0);
        delay(470);
        //mySerial.println(8894);
      }
      else{
        badservo.write(pos);
        //mySerial.println(8894);
      }
    }
  mySerial.flush();//clear the serial buffer for unwanted inputs
  last = millis();
  }
  delay(20);//delay little for better serial communication
}

```

With the servo that I'm using has a stop position of 92, meaning when I do servo.write(92); it will stop the servo. Also, the 470 delay was tested with a button and was a single full rotation.

Now, with the HC-12 module, I can't get the servo to rotate less than 2.5 times. Anyone have any idea what I'm doing wrong? The goal is to get the servo to rotate only once when the RF module receives the proper signal.

# Answer
> 0 votes
You can't rely on a specific delay being one rotation - especially when you are using SoftwareSerial. SoftwareSerial breaks many things, and anything that uses interrupts (such as the Servo library) gets broken by it. It's a real interrupt hog.

The proper way of doing it is to use a rotary encoder on the servo to report the position (or *change* in position) so that you know where the servo is. That's really the only reliable method of getting the servo to perform precise operations.

By the way:

```
mySerial.flush();//clear the serial buffer for unwanted inputs

```

does absolutely nothing. The operation of `flush()` changed when the Arduino API turned one. It is now supposed to wait until both the TX circular buffer and the UART TX FIFO are empty. It has nothing to do with emptying any inputs. Instead you want:

```
while (mySerial.read() != -1);

```

---
Tags: rf, continuous-servo
---


# Question
Title: Arduino serial plotter with independent Y axis, is it possible?
The Arduino IDE has a built in functionality that allows the user to plot a value (such as temperature) over time.

I would like to plot two variables with different ranges on the y-axis (pressure in the range of thousands and temperature which varies from 20°C to 40°C).

I could make it work to have both being plotted, but the range differences does not allow me to see small changes in one/both quantities. Is there a way to two, or more, Y axis each one with its own scale?

# Answer
> 5 votes
No. The Arduino Serial Plotter only supports one Y axis.

An alternative would be to capture the data into a file as CSV data and use some other software to plot it - you could import the data into Excel / LibreOffice, or (as I prefer for quick graphing) use something like GnuPlot (or whatever is similar for your chosen OS).

For instance, this is a GnuPlot configuration for plotting two independent axis datasets and the results:

```
set datafile separator ","
set terminal png enhanced size 1360,768
set output 'testCharge.png'
set ytics nomirror
set ylabel "Current (A)"
set y2label "Voltage (V)"
set y2tics nomirror
plot "testCharge.csv" using 3 smooth bezier title "Current" w l, \
     "testCharge.csv" using 4 title "Cutoff" w l dashtype 2, \
     "testCharge.csv" using 2 smooth bezier title "Voltage" w l axes x1y2

```

The data I use is formatted thus:

```
Phase,Voltage,Current,Cutoff
0,3.58,1.098,0.033
0,3.59,1.098,0.033
0,3.59,1.098,0.033
0,3.59,1.098,0.033
0,3.6,1.098,0.033
0,3.6,1.098,0.033
0,3.6,1.098,0.033
0,3.61,1.098,0.033
0,3.61,1.098,0.033
... etc ...

```

And the results:

Incidentally, that's me charging a Li-Ion battery and monitoring the voltage and current.

# Answer
> 1 votes
The Serial Plotter from within the Arduino IDE is quite limited. Not to mention the lack of documentation on the Arduino website. So, no the Serial Plotter cannot do what you require.

However, there is a very good selection of serial data plotter programs over at this question: Serial data plotting programs

---
Tags: serial, arduino-ide
---


title: HX711 sporadic wrong values

text:
# Question
Title: HX711 sporadic wrong values
Am interfacing HX711 with arduino to measure the load of something. However, in my project, I need to continuously monitor the load.

I get fairly accurate values most of the time however, at times I suddenly get a junk value. For example, I call the weight function every 3 seconds and I have placed a 10kg weight, this is what I get. 17.25 is the concern.

10.04, 10.03, 17.25, 10.04, 10.03, 10.03

Am using HX711 library and my process function is a simple call as shown below.

```
float Processweight()
{
  Serial.print(scale.get_units(40), 2);

  scale.power_down();              // put the ADC in sleep mode
  delay(500);
  scale.power_up();
}

```

is there something that am missing? What could cause the wrong values?

# Answer
> 2 votes
> I get fairly accurate values most of the time however, at times I suddenly get a junk value.

if you use the ebay board, it has the incorrect grounding, which may contribute to the sporadic values you saw.

> For example, I call the weight function every 3 seconds

poor quality libraries could be another possibility.

I have used the board quite extensively and aside from its tempco, it is fairly reliable. you can see here: https://dannyelectronics.wordpress.com/2015/10/25/a-hx711-based-milliohm-meter/

when everything is done right (and in a constant temperature environment), it has very good consistency.

# Answer
> 1 votes
Finally I got this right by adding a code to check if 5 consecutive values are fairly close enough and only then respond. That way I was able to flush out sudden changes. However, I still am not sure as to what is causing that jump.

---
Tags: arduino-uno
---


title: Arduino Human Infrared Sensor

text:
# Question
Title: Arduino Human Infrared Sensor
I started out again with Arduino (beginner), but I wanted to know if I could connect another human infrared sensor like this to the Arduino Uno. I know how to connect a simple pir like this one, but I dont know for sure how to connect the 12V one (if its possible). Guess the red wire goes to a seperate 12V power supply, brown goes to ground and blue then goes to a digital pin on the arduino arduino? I didnt really understand the description that was available for the 12V sensor, so thats why I am asking (I want to be entirely sure before buying).

Thanks

# Answer
Blue - Ground, connect to Arduino GND
Brown - Power, connect to external 12V source.
Red - 12 V output. Connect via a diode to arduino input pin. Enable pullup on arduino pin.

This way when the sensor output is low it will pull the arduino pin low. When the output is high the diode blocks the 12V from frying the arduino while the internal pullup ensures the input pin goes to a safe voltage for a high pin.

Don't put the diode the wrong way around or things will go bang.

simulate this circuit – Schematic created using CircuitLab
> 1 votes

# Answer
I think it should be compatible with Arduino with a bit of support. Now the first issue is this that we don't really know that what sensor is this detaily. So we can't really find a datasheet that could say it's pinout or its electrical characteristics. Now assuming those pinouts are similar to those of the any sensor that are **VCC Data Out GND** Then you could probably use it but according to that page it says it needs 12V So according to that Data Out also must be fluctuating with voltage near 12V. So the solution would be to use a voltage divider circuit. Now you could find the resistor values from the Google. I think that setup should be ***Okay*** but I can't tell anything up to you provide us with any data sheet.
> 0 votes

---
Tags: arduino-uno, sensors, infrared
---


title: Arduino open door (outdoor) tonemelody

text:
# Question
Title: Arduino open door (outdoor) tonemelody
My problem lies in the fact that I can not stop the "void loop" function and more accurately "StatInDoor". I have to make sure that the "ButtonOpenDoor" works independently of "ButtonCall". If someone presses the "ButtonCall" button then the "ButtonOpenDoor" button must work in progress, and if the "ButtonCall" button is pressed, the "ButtonOpenDoor" button must stop playing the melody.

My idea for this this:

```
int StatOutDoor = digitalRead(ButtonCall && ButtonOpenDoor);

```

or:

```
if(StatOutDoor == LOW && StatInDoor = LOW){
   PlayMelody();
}

```

But it does not work :(

Full code:

```
#include "pitches.h"

int melody[] = {
  NOTE_C4, NOTE_G3, NOTE_G3, NOTE_A3, NOTE_G3, 0, NOTE_B3, NOTE_C4
};
int noteDurations[] = {
  4, 8, 8, 4, 4, 4, 4, 4
};
int ButtonCall = 4;
int buzzer = 8;
int ButtonOpenDoor = 7;
int RelayModule = 12;

void PlayMelody() {
  for (int thisNote = 0; thisNote < 8; thisNote++) {
    int noteDuration = 1000 / noteDurations[thisNote];
    tone(buzzer, melody[thisNote], noteDuration);
    int pauseBetweenNotes = noteDuration * 1.30;
    delay(pauseBetweenNotes);
    noTone(buzzer);
  }
}

void setup(){
  pinMode(ButtonCall, INPUT);
  pinMode(buzzer, OUTPUT);
  pinMode(ButtonOpenDoor,INPUT);
  pinMode(RelayModule,OUTPUT);
}

void loop() {
  int StatOutDoor = digitalRead(ButtonCall);
  if(StatOutDoor == LOW){
    PlayMelody();
  }
  int StatInDoor = digitalRead(ButtonOpenDoor);
  if (StatInDoor == HIGH) {
    digitalWrite(RelayModule, HIGH);
  } else {
    digitalWrite(RelayModule, LOW);
    delay(3300);
  }
}

```

Can someone help with this? (Sorry for my bad English).

# Answer
I'm not quite sure I understand the logic of what you're asking. Your description is a little vague. Maybe if you provided more information about what the signals are, what they mean, and where they come from, it may help.

However - if you want the melody to play when both inputs are LOW you should change:

```
if(StatOutDoor == LOW && StatInDoor = LOW){
      PlayMelody();
}

```

to:

```
if(StatOutDoor == LOW && StatInDoor == LOW){
      PlayMelody();
}

```

Note the use of `==` not `=` to denote equality (`=` is assignment).

Also the use of a 3.3 second delay in your `else` will show everything down to a crawl when `StatInDoor` is `HIGH`.
> 1 votes

# Answer
The Arduino doesn't multitask. So when you execute `PlayMelody()` the `loop()` function can't do anything else until the song ends.

You could use interrupts to play the song, but to keep things simple, here's a way to do it without interrupts.

```
// Struct to hold the song data (simpler than 2 arrays)
struct note {
    int pitch;
    int duration;
};

// Class to play songs
class song_player {
protected:
    note *melody;   // Array of all the notes
    int note_count;  // How many notes in song
    int current_note;
    bool am_playing;  // Playing song?
    unsigned long last_event;  // Time of last note
    unsigned long next_event;  // Time to play next note
    byte speaker_pin;

    // is it time to play the next note?
    bool elapsed()
    {
        unsigned long m = millis();
        if (m >= next_event) {
            last_event = m;
            return true;
        }
        return false;
    }

    // play one note
    void play_next_note() {
        if (elapsed()) {
            // Play next note unless at end of song
            if (current_note < note_count) {
                unsigned long duration = 1000 / melody[current_note].duration;
                tone(speaker_pin, melody[current_note].pitch, duration);
                next_event = millis() +  1.3 * duration;
                current_note += 1;
            }
            else {
                // Finished...
                noTone(speaker_pin);
                am_playing = false;
            }
        }
    }
public:
    // ctor
    song_player(byte speaker_pin, note *melody, int note_count) :
        am_playing(false),
        speaker_pin(speaker_pin),
        note_count(note_count),
        melody(melody)
    {
        // Note: does not make local copy, so array should be
        // valid for lifetime of this object
    }

    // Start the song
    void start() {
        // Initialize
        current_note = 0;
        am_playing = true;
        last_event = millis();
    }

    // Call this every loop()
    void loop() {
        if (am_playing) {
            play_next_note();
        }
    }
};

```

Then you would change the rest of the program to something like:

```
// Song data
note the_song[] = {
  {NOTE_C4, 4},
  {NOTE_G3, 8},
  {NOTE_G3, 8},
  {NOTE_A3, 4},
  {NOTE_G3, 4},
  {0, 4},
  {NOTE_B3, 4},
  {NOTE_C4, 4}
};
// Create a player object
song_player player(9, the_song, sizeof(the_song) / sizeof(the_song[0]));

//....

void loop()
{
    // other stuff .....

    if(StatOutDoor == LOW && StatInDoor == LOW) {
        // Start the song
        player.start();
    }
    // Important: Call this every time
    player.loop();

    // Other stuff here....
}

```
> 0 votes

---
Tags: button, relay, speaker
---


# Question
Title: What is importance of the reflow profile?
I was reading the MPU6050 datasheet to understand all the type of errors that affect the accelerometer, after finding information on the Reflow Profile i look up on wikipedia the Reflow Soldering Definition

As a noob i can't understand the importance, initially i though it was correlated with the temperature effect on the accelerometer bias, but i was wrong.

**Why is important?**

**How do you read this values?(or when you use this data)**

# Answer
> 2 votes
Reflow soldering is an assembly process for printed circuit boards (PCBs) in which surface-mount parts are placed on a PCB prepared with solder paste. The solder is melted by heating in a temperature-controlled oven, which then electrically connects component leads to pads on the PCB. ICs can be damaged by high temperatures/rapid changes in temperatures, so the thermal profile defines the acceptable limits on the temperature of the reflow to avoid damaging the component.

---
Tags: mpu6050
---


# Question
Title: Connect Arduino to an external microSD card reader
I have a camera with a microSd card reader that is the only output type. I want to read the microSd when the camera makes a photo. How can I read it with an Arduino? Duplicating the reader connections and join it to my Arduino microSd reader? Or I can try to connect to the circuit (its very very small)? Do you think I can put an ESP8266 to the camera?

Thanks for all!!!

# Answer
> 3 votes
**You cannot**

SD cards cannot be shared between masters in operation, and it is unsafe to disconnect the card from the camera with an electronic switch when the camera is not expecting that.

Nor is an ordinary Arduino fast enough to passively snoop the data being written to the card by the camera (while a card will let an Arduino write to it quite slowly, any camera would do so far, far faster)

Nor is an ordinary Arduino able to do much of anything meaningful with the image files produced by a typical camera in real time.

Nor can an ESP8266 while running Arduino-based software; it apparently does have some high-speed I/O capabilities but that would require low-level rather than Arduino-port-based programming.

For all practical purposes, you'd need to power off the camera, remove the card, and place it in the Arduino reader.

---
Tags: sd-card, sd
---


title: Drawing specific RGB on touch screen

text:
# Question
Title: Drawing specific RGB on touch screen
I have the Arduino MEGA and an adafruit touch screen 2.8 inches.

**My goal is to draw a pixel given a specific RGB**

I am using the `ILI9341`, `GFX`, and `TFT.h` libraries to draw and control the touch screen. I noticed the `drawPixel` function given, in which it takes in three parameters and draws the pixel:

```
tft.drawPixel(4,4,ILI9341_BLUE);

```

But, I am trying to draw a pixel with specific a RGB. So instead, the function would ideally need 5 parameters instead of 3, x, y, and then R, G, and B:

```
tft.idealDrawPixel(5,6,89,234,76);

```

I tried putting in a number as the third parameter and not `ILI9341_COLOR`, and the screen just prints blue:

```
tft.drawPixel(45,67,255);

```

Is there a function that allows me to draw RGB pixels specifically? Thanks for any help!

# Answer
As noted in the second paragraph on Adafruit's Graphics Library webpage,

> First thing to note is that color is 16-bit, and that includes Red, Green and Blue in a 16-bit variable. The way the color is packed in is the top 5 bits are red, the middle 6 bits are green and the bottom 5 bits are blue.

If you want to specify 8-bit color components, you could write an intermediary routine to translate from that form to the 565 form. For example:

```
#define rgbDrawPixel(x,y,r,g,b) drawPixel(x,y,(((r)&0b11111000)<<8)|(((g)&0b11111100)<<3)|(((b)&0b11111000)>>3))

```

Note, this assumes the TFT library you're using has the same specs as Adafruit's. That might or might not be; I don't know how to account for a 255 color number showing up as blue rather than white.
> 2 votes

---
Tags: arduino-mega, display, tft
---


title: Arduino uno and 1602A I2C not working

text:
# Question
Title: Arduino uno and 1602A I2C not working
I'm a newbie in engineering.

I bought this with arduino learning kit.

It's simply not working.

There are several possible problems:

* The display is not working due to a hardware problem. It could need to be repaired or soldered better.
* The library that I chose could be buggy (software problem)

How can I check this? Thanks!

PS Build-in led is blinking as expected.

Here is the code:

```
#include <Wire.h>
#include <LiquidCrystal_I2C.h>

LiquidCrystal_I2C lcd(0x27, 16, 2);

void setup()
{
  lcd.init();
  lcd.begin(8,2);

  pinMode(LED_BUILTIN, OUTPUT);
}

void loop()
{
  digitalWrite(LED_BUILTIN, HIGH);
  lcd.setCursor(0, 0);
  lcd.print("TEST");
  delay(1000);
  digitalWrite(LED_BUILTIN, LOW);
  lcd.setCursor(0, 0);
  lcd.print("   ");
  delay(1000);
}

```

# Answer
Try with this address 0x3F or 0x27

```
#include <LiquidCrystal_I2C.h>
LiquidCrystal_I2C lcd(0x3F, 2, 1, 0, 4, 5, 6, 7, 3, POSITIVE); // or 0x27
void setup() {
lcd.begin(16, 2);
}
void loop()
{
  digitalWrite(LED_BUILTIN, HIGH);
  lcd.setCursor(0, 0);
  lcd.print("TEST");
  delay(1000);
  digitalWrite(LED_BUILTIN, LOW);
  lcd.setCursor(0, 0);
  lcd.print("   ");
  delay(1000);
}

```
> 0 votes

---
Tags: display
---


# Question
Title: Powering a DC motor with an external battery
I'm working on a project where i need to control a 6 volt motor with an Arduino. The motor that I'm using requires 6 volts so I'm using a 9 volt with a voltage divider to get those 6 volts. My problem is that when I use the external power, the motor keeps spinning and ignores the input from the Arduino. If I use a 5 V battery and draw the 5 V from the Arduino, it works fine. I made sure that the voltage divider sends out 6 volts and the current code should have the motor not spinning. Here is the circuit: Motor Schematic.

What could I do to make the motor take the input from the Arduino?

Note: The schematic isn't like my actual circuit. In reality I have 6 V power supply instead of a 9 V and a voltage divider. I also am using a motor that requires 6 volts, while the one in the schematic requires 5 V.

# Answer
Your schematic is bad - the motor is connected betveen base and power, emitor is connected to ground.That keeps the transistor open, and B-E voltage is like 0.7V, rest is for the motor to rotate. More over the transistor is open, so if you send pulses from pin 3, they are shortcuted to ground thru the transistor, not affecting the motor at all.

Switch the wires to Base and to Colector (lines 48 and 49) and it should work better.

(Still I would not use divider 9-\>6 volts, losing a lot of power constantly, I would rather change the PWM little down (and have it relatively fast, 1kHz or more) and the motor should be OK, if effective voltage ther would be under 6V - so the PWM under like 66% HIGH. Also shortcutting pin3 to ground with resistor is not optimal, the resistor should be between pin3 and Base.)
> 1 votes

# Answer
In power application like motor driver you can not use voltage divider for step down the voltage because resistor drop the voltage when current flowing from the resistor increase. You can used voltage regulator or buck converter. The motor will work fine. Even you can use 9V battery and control the speed of dc motor using PWM. you use the following schematic both will work fine. The 2n2222 is the general purpose npn transistor which is used for power amplification. The arduino board can not provide large current at output pins to drive motors directly having a current rating more than 250mA.

In above schematic the LM2596 buck converter is used which current rating is about 3A. and you can adjust the desired output voltage.

The second option which shows in schematic is to use 6V battery.
> 0 votes

---
Tags: arduino-uno, motor, transistor, voltage
---


title: analogWrite mosfet problem

text:
# Question
Title: analogWrite mosfet problem
i have a custom atmega328p board which have connected to pin 9 the gate of a MOSFET. If i run a simple sketch like:

```
void setup() {

}
void loop() {
  analogWrite(9,70);
}

```

The motor connected to the mosfet works just fine, from 70pwm to 255pwm.

On the other sketch i'm receiving serial data from an android app via bluetooth. Ive 2 Servo motors and a DC motor connected to the mosfet. The 2 servos works like expected, the DC motor doesn't spin unless i use a 255pwm.

```
void loop() {
  if(Serial.available() > 0){
      state = Serial.read();
  }
  if (state == 'S') {
      servoONE.write(90);
      servoTWO.write(90);
      analogWrite(MOSFET,MOSFET_LOW);
  }
  else if (state == 'F') {
      analogWrite(9,70);
      servoONE.write(90);
      servoTWO.write(90);
  }
  else if (state == 'L') {
      servoONE.write(MAX_SERVO);
      servoTWO.write(MIN_SERVO);
  }
  else if (state == 'R') {
      servoONE.write(MIN_SERVO);
      servoTWO.write(MAX_SERVO);
  }
  else if (state == 'Q') {
      analogWrite(MOSFET,MOSFET_HIGH);
      servoONE.write(MAX_SERVO);
      servoTWO.write(MIN_SERVO);
  }
  else if (state == 'E') {
      analogWrite(MOSFET,MOSFET_HIGH);
      servoONE.write(MIN_SERVO);
      servoTWO.write(MAX_SERVO);
  }
}

```

Do you know why the same motor works on the first sketch with any pwm above 70 and on the second sketch it only works at 255?

# Answer
You have a timer conflict.

Pin 9 is OC1A which is the Output Compare Channel A pin of Timer 1. However the Servo.h library also uses timer 1.

So you can't use servos and still use pins 9 (OC1A) and 10 (OC1B) as PWM.

However, you can still use pins 3, 5, 6 and 11 as PWM since they are on other timers.
> 3 votes

---
Tags: pwm, analogwrite, mosfet
---


# Question
Title: Serial.Write(buf,Len) how to read Serial sended array of byte
hello i'm trying to send array of byte with `Serial.Write(buf,Len)` but don't know hot to read this code with receiver.

SENDER code:

```
byte buf[4]={1,2,3,4};
void setup(){
Serial.begin(250000);
}

void loop(){
Serial.write(buf,4);
}

```

RECEIVER code (WRONG)

```
byte buf[4];

void setup() {
  Serial.begin(250000); // how suggest

}

void loop() {
  int i = 0;

  if (Serial.available()) {
    Serial.readBytes(buf,4);
    Serial.print(buf[0]);
    Serial.print(buf[1]);
    Serial.print(buf[2]);
    Serial.print(buf[3]);
  }
}

```

How to receive this ??

# Answer
You have two issues:

Firstly the transmitter is set to 250000 baud (a non-standard rate) while the receiver is set to 9600 baud. Both need to be set to the same rate.

Secondly the transmitter is constantly sending data and the receiver is constantly reading it, there is no way to ensure the two are synchronized. So your receive buffer could well end up being the end of one set of data and then the start of the next e.g. 3,4,1,2. If all you are sending is the same loop over and over this doesn't matter but for real world data it's an issue. If you have a value which you know will never be in your data (e.g. 0 or 0xff) then you can use that as a start of data marker, if not then things get a little more tricky.
> 1 votes

---
Tags: serial, serial-data
---


# Question
Title: Can I use NodeMCU 12E (ESP8266) as wifi shield for arduino Nano?
Update: Point 1- I don't want to program ESP, I just want to use it as a wifi shiled. cause I'm not familiar with flashing or writing sketch for ESP, so still feel comfortable with arduino. beside my existing projects need to upgrade to wifi version. Not possible to turn everying into esp instead of arduino. Point 2- If anyone can provide me a complete working sketch, where arduino sending a value to ESP, ESP receiving it and then sending to some data server (even sparkfun type will do).

I was working on Arduino based project for last couple of months, where I had to read several sesor data (e.g. temp, humidity, light, sound, motion etc) and save these data to a remote mysql server. I was doing well with Arduino Uno and Ethernet shield, where I connect through RJ45 cable to make my Arduino UNO able using internet. here is the code for that:

```
#include <SPI.h>
#include <Ethernet.h>
#include <MySQL_Connection.h>
#include <MySQL_Cursor.h>

byte mac_addr[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };

IPAddress server_addr(1.1.10.);  // IP of the MySQL *server* here
char user[] = "root";              // MySQL user login username
char password[] = "007";        // MySQL user login password

// Sample query
char INSERT_DATA[] = "INSERT INTO database (message, sensor_num, value) VALUES ('%s',%d,%s)";
char query[128];
//char temperature[10];

int potPin = 4;
float temperature = 0;
long val=0;

EthernetClient client;
MySQL_Connection conn((Client *)&client);

void setup() {
  Serial.begin(115200);
  while (!Serial); // wait for serial port to connect
  Ethernet.begin(mac_addr);
  Serial.println("Connecting...");
  if (conn.connect(server_addr, 3306, user, password)) {
    delay(200);
    // Initiate the query class instance
    MySQL_Cursor *cur_mem = new MySQL_Cursor(&conn);
    // Save
    //dtostrf(50.125, 1, 1, temperature);
    sprintf(query, INSERT_DATA, "test sensor", 24, temperature);
    // Execute the query
    cur_mem->execute(query);
    // Note: since there are no results, we do not need to read any data
    // Deleting the cursor also frees up memory used
    delete cur_mem;
    Serial.println("Data recorded.");
  }
  else
    Serial.println("Connection failed.");
  conn.close();
}

void loop() {
  val = analogRead(potPin);
    temperature = (val*0.0048828125*1000);
    delay(2000);
}

```

Later, I found it's not convenient to use a whole bunch of cable around, so I was thinking to make it wireless. At beginning I was thinking of RF24OL but it also can't connect internet directly. Then I found ESP8266 module which can directly connect to wifi. Now, I bought some ESP8266 12e (not ESP-01), which got one USB port to connect with computer, which made things way more sipmle comparing previous versions of ESP. I also installed ESP supporting files on my Arduino IDE, tested and it's working fine. But, the problem is, whenever I upload the code only for ESP(like connectiong to wifi), it compile and upload proerply.

Like this code works:

```
void setup() {
  pinMode(BUILTIN_LED, OUTPUT);

}

void loop() {
  digitalWrite(BUILTIN_LED, LOW);

  delay(500);
  digitalWrite(BUILTIN_LED,HIGH);
  delay(300);

}

```

this also works fine,

```
/*
 *  This sketch trys to Connect to the best AP based on a given list
 *
 */

#include <ESP8266WiFi.h>
#include <ESP8266WiFiMulti.h>

ESP8266WiFiMulti wifiMulti;

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

    wifiMulti.addAP("ssid_from_AP_1", "your_password_for_AP_1");
    wifiMulti.addAP("ssid_from_AP_2", "your_password_for_AP_2");
    wifiMulti.addAP("ssid_from_AP_3", "your_password_for_AP_3");

    Serial.println("Connecting Wifi...");
    if(wifiMulti.run() == WL_CONNECTED) {
        Serial.println("");
        Serial.println("WiFi connected");
        Serial.println("IP address: ");
        Serial.println(WiFi.localIP());
    }
}

void loop() {
    if(wifiMulti.run() != WL_CONNECTED) {
        Serial.println("WiFi not connected!");
        delay(1000);
    }
}

```

That means, my Arduino IDE, ESP8266 12e all got no problems. But whenever I add something more, like DHT11 library, it shows error compiling.

this code doesnt compile:

```
#define SSID       "Itead_1(Public)"                //type your own SSID name
    #define PASSWORD   "27955416"                                //type your own WIFI password

#include "uartWIFI.h"
#include <SoftwareSerial.h>
WIFI wifi;

extern int chlID;        //client id(0-4)

// for yeelink api
#define APIKEY         "3a362e99d6f1daf974561163a8c99a85" // replace your yeelink api key here

//replace the device ID and sensor ID for temperature sensor.
#define DEVICEID0       15483 // replace your device ID
#define SENSORID0       26660 // replace your sensor ID

//replace the device ID and sensor ID for humidity sensor.
#define DEVICEID1       15483 // replace your device ID
#define SENSORID1       26661 // replace your sensor ID

char server[] = "api.yeelink.net";   // name address for yeelink API

unsigned long lastConnectionTime = 0;          // last time you connected to the server, in milliseconds
boolean lastConnected = false;                 // state of the connection last time through the main loop
const unsigned long postingInterval = 5*1000; // delay between 2 datapoints, 5s
String returnValue = "";
boolean ResponseBegin = false;

int DHT11PIN=25;                        //Connect D25 to data pin of DHT11

int humidity;
int temperature;

int post_number;

void setup()
{

  wifi.begin();
  bool b = wifi.Initialize(STA, SSID, PASSWORD);
  if(!b)
  {
    DebugSerial.println("Init error");
  }
  delay(8000);  //make sure the module can have enough time to get an IP address
  String ipstring  = wifi.showIP();
  DebugSerial.println(ipstring);                //show the ip address of module

}
void loop()
{
  char message[400];
   // if you're not connected, and ten seconds have passed since
  // your last connection, then connect again and send data:
  if((millis() - lastConnectionTime > postingInterval)) {

  //read dht11
  int chk = dht11_read(DHT11PIN);
  if(chk==0)
  {
        if(post_number==0)
        {
                sendData(DEVICEID0,SENSORID0,temperature);
                post_number++;
        }
        else
        {
                post_number = 0;
                sendData(DEVICEID1,SENSORID1,humidity);
        }

  }

  }

  // if there's incoming data from the net connection.
  // send it out the serial port.  This is for debugging
  // purposes only:
  if(wifi.ReceiveMessage(message))
  {
      DebugSerial.println(message);
  }

  delay(10);

}

// this method makes a HTTP connection to the server:
void sendData(int device_id,int sensor_id,int thisData) {
  // if there's a successful connection:
  if (wifi.ipConfig(TCP,server, 80)) {
    DebugSerial.println("connecting...");
    // send the HTTP PUT request:
    String cmd;
        cmd = "POST /v1.0/device/";
        cmd += String(device_id);
        cmd += "/sensor/";
        cmd += String(sensor_id);
        cmd += "/datapoints";
        cmd += " HTTP/1.1\r\n";
        cmd += "Host: api.yeelink.net\r\n";
        cmd += "Accept: *";
        cmd += "/";
        cmd += "*\r\n";
        cmd += "U-ApiKey: ";
        cmd += APIKEY;
        cmd += "\r\n";
        cmd += "Content-Length: ";
        int thisLength = 10 + getLength(thisData);
    cmd += String(thisLength);
        cmd += "\r\n";
        cmd += "Content-Type: application/x-www-form-urlencoded\r\n";
        cmd += "Connection: close\r\n";
        cmd += "\r\n";
        cmd += "{"value":";
        cmd += String(thisData);
        cmd += "}\r\n";

        DebugSerial.println(cmd);

    wifi.Send(cmd);
    // note the time that the connection was made:
    lastConnectionTime = millis();
  }
  else {
    // if you couldn't make a connection:
    DebugSerial.println("connection failed");
    DebugSerial.println("disconnecting.");
    wifi.closeMux();
  }
}

int getLength(int someValue) {
  // there's at least one byte:
  int digits = 1;
  // continually divide the value by ten,
  // adding one to the digit count for each
  // time you divide, until you're at 0:
  int dividend = someValue /10;
  while (dividend > 0) {
    dividend = dividend /10;
    digits++;
  }
  // return the number of digits:
  return digits;
}

int dht11_read(int pin)
{
        // BUFFER TO RECEIVE
        int bits[5];
        int cnt = 7;
        int idx = 0;

        // EMPTY BUFFER
        for (int i=0; i< 5; i++)
        {bits[i]= 0;}[/i]

[i]        // REQUEST SAMPLE[/i]
[i]        pinMode(pin, OUTPUT);[/i]
[i]        digitalWrite(pin, LOW);[/i]
[i]        delay(18);[/i]
[i]        digitalWrite(pin, HIGH);[/i]
[i]        delayMicroseconds(40);[/i]
[i]        pinMode(pin, INPUT);[/i]

[i]        // ACKNOWLEDGE or TIMEOUT[/i]
[i]        unsigned int loopCnt = 10000;[/i]
[i]        while(digitalRead(pin) == LOW)[/i]
[i]                if (loopCnt-- == 0) return -2;[/i]

[i]        loopCnt = 10000;[/i]
[i]        while(digitalRead(pin) == HIGH)[/i]
[i]                if (loopCnt-- == 0) return -2;[/i]

[i]        // READ OUTPUT - 40 BITS => 5 BYTES or TIMEOUT[/i]
[i]        for (int i=0; i<40; i++)[/i]
[i]        {[/i]
[i]                loopCnt = 10000;[/i]
[i]                while(digitalRead(pin) == LOW)[/i]
[i]                        if (loopCnt-- == 0) return -2;[/i]

[i]                unsigned long t = micros();[/i]

[i]                loopCnt = 10000;[/i]
[i]                while(digitalRead(pin) == HIGH)[/i]
[i]                        if (loopCnt-- == 0) return -2;[/i]

[i]                if ((micros() - t) > 40) bits[idx] |= (1 << cnt);[/i]
[i]                if (cnt == 0)   // next byte?[/i]
[i]                {[/i]
[i]                        cnt = 7;    // restart at MSB[/i]
[i]                        idx++;      // next byte![/i]
[i]                }[/i]
[i]                else cnt--;[/i]
[i]        }[/i]

[i]        // WRITE TO RIGHT VARS[/i]
[i]        // as bits[1] and bits[3] are allways zero they are omitted in formulas.[/i]
[i]        humidity    = bits[0]; [/i]
[i]        temperature = bits[2]; [/i]

[i]        int sum = bits[0] + bits[2];  [/i]

[i]        if (bits[4] != sum) return -1;[/i]
[i]        return 0;[/i]

```

So, I decided to use ESP and arduino nano together. so that, ESP will work as wifi shiled to connect to internet, like ethernet shield was doing before, arduino will handle parts of sensors data reading and so on. I tried to connect to internet through connecting RX-TX and TX-RX between Arduino-ESP, but it doesn't work. I uploaded wifi connecting script to ESP and it connects to wifi properly, then i uploaded sensor data reading and saving to mysql script to arduino, then conneted arduino tx & rx to esp rx & tx. but arduino can't connect to internet. Now, my problem is, how I can use ESP8266 12e NodeMCU only as ethernet shield so that my arduino can connect to internet and upload data to my sql server? My ESP will only act as a wifi shield, i don't want to configure esp to read sensor data, cuase it got lack of GPIO pins, most importantly it doesn't work as smoothly as arduino does. So please don't suggest me to use only esp with sensors, because i also wanted to upgrade my existing projects to wifi which done with ethernet shields. Thanks in advance

# Answer
> 0 votes
OK you have made it very clear that, you want to use the ESP as a serial to WIFI bridge. You have a Node-MCU ESP12 board, which is normally configured for programming using Luna.

1. You need to have the correct firmware for this "AI Thinker AT Firmware" and you need to find the correct tool chain for loading this on your board. It would be easier to but an ESP7 (or lower) to be honest that already comes with the correct firmware.
2. You want to communicate with the ESP from the Nano. To do this you will need to use Software Serial on the Nano and cross connect the software serial port to the ESPs serial port. You must not connect to the nano's serial port, you need this to program the nano.
3. To configure the ESP to talk to a wireless network you will need to send it AT commands (from the nano) these will need to be part of the setup of you program. Technically this is programming the ESP, but I'm guessing you'll be OK with this.
4. Now you can add in your DHT-11 sensor and library and it will work.

**However**

You would find it so much easier to download the board support package for the ESP, take one of the Web server/client examples and add the DHT-11 code to that. You'll find, since it is all written in the same dialect of C++ as the Arduino uses, very easy. In fact the biggest problem you will have is finding something to weight the USB cable down to stop it from rolling the Node-MCU over.

BTW your code doesn't compile because you have left the italic mark-up tags in when you copied it off the website. Try removing all the \[i\] and \[/i\] tags.

---
Tags: esp8266, arduino-nano, nodemcu
---


# Question
Title: How to pass variables to custom callback functions
I want to use the Ticker library of the ESP8266 Arduino core to (asynchronously) delay the switch of a pin to a desired state like below. I am not sure about the "here is" function definitions and I am having a hard time to find some documentation. Please have a look at what I tried so far:

```
#include <Ticker.h>

Ticker change_pin;

...

    uint8_t desired_state = 1;
    ...
    change_pin.attach_ms(100, [](uint8_t state_to_change_to){
        if( digitalRead(PIN) != state_to_change_to ) {
            digitalWrite(PIN, state_to_change_to);
        }
        else {
            change_pin.detach();
        }
    }, desired_state);

```

But the compiler's yelling:

```
espIKEA:145: error: no matching function for call to 'Ticker::attach_ms(int, toogle_light(uint8_t)::__lambda0, uint8_t&)'

   }, des_state);

               ^

...

C:\Users\USER\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.3.0\libraries\Ticker/Ticker.h:45:7: note:   candidate expects 2 arguments, 3 provided

C:\Users\USER\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.3.0\libraries\Ticker/Ticker.h:62:7: note: template<class TArg> void Ticker::attach_ms(uint32_t, void (*)(TArg), TArg)

  void attach_ms(uint32_t milliseconds, void (*callback)(TArg), TArg arg)

       ^

C:\Users\USER\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.3.0\libraries\Ticker/Ticker.h:62:7: note:   template argument deduction/substitution failed:

C:\Users\USER\Documents\Arduino\Scratch\pintest\pintest.ino:145:15: note:   mismatched types 'void (*)(TArg)' and 'toogle_light(u8)::__lambda0'

   }, des_state);

               ^

```

So, I am having too few knowledge to understand what to do about it. I really would like to avoid having a separate function for the callback body.

PS: Important source file can be found here: Ticker.h

# Answer
The function you are trying to call is a template function:

```
template<typename TArg>
void attach_ms(uint32_t milliseconds, void (*callback)(TArg), TArg arg)
{
    ....
}

```

So, you need to tell it what type of parameter you are passing:

```
change_pin.attach_ms<uint8_t>(100, [](uint8_t state_to_change_to) {
//                     ^- tell the compiler about the parameter
    ....
}, desired_state);

```

---

To pass more than one parameter: Since the library only allows one parameter, I would create a `struct` and pass a pointer to it.

```
struct callback_parameter {
    int i;
    char *p;
};

```

Then create one of these structs and pass the address of it. You just have to make sure the struct is valid the entire time the timer is running. So either use `new`, `static`, or make it global.

```
callback_parameter param; // global variable

...

change_pin.attach_ms<callback_parameter *>(100, [](callback_parameter * state_to_change_to) {
    ....
}, &param);

```
> 2 votes

# Answer
It looks like you are trying to do a lambda function and that's a bit too modern for the Arduino compiler.

So you have:

```
change_pin.attach_ms(100, ????, desired_state);

```

Its just the ???? we need to sort, which you have:

```
void DoStuff (state_to_change_to)
{
    if( digitalRead(PIN) != state_to_change_to )
    {
        digitalWrite(PIN, state_to_change_to);
    }
    else
    {
        change_pin.detach();
    }
}

```

Now you can't just define your own function signature, it has to be either callback\_t or callback\_with\_arg\_t. So to make your "DoSTuff" function comply with callback\_with\_arg\_t you have to define it as:

```
void DoStuff (void* argument);

```

Which means inside you function you will have to do this:

```
void DoStuff (void* argument)
{
    if (argument != NULL)
    {
       const uint8_t state_to_change_to = *argument;
       if( digitalRead(PIN) != state_to_change_to )
       .... As above.

```

Does that make sense?

The library defines the signature of the function that acts as the call back, it has to otherwise it wouldn't be able to provide all the parameters. void\* gets around any pretence at type safe behaviour and is fine as long as you are careful to control what can get passed through those parameters. Always remember if you are working asynchronously there is no guarantee that data will still exist when you process it, if its dynamic memory it could have been freed/deleted or variables can go out of scope.
> 1 votes

---
Tags: esp8266, variables, core-libraries, callbacks
---


# Question
Title: Specify F_CPU in arduino to use 8MHz clock
I am using a custom made AVR board with Atmege-328p on it and it doesn't have a 16MHz crystal on it. I would like to use the internal 8MHz as clock. I have set the appropriate Fuses but now I am unable to tell the programs that F\_CPU is 8000000UL. One way of doing it is to add another variant to the boards. I would like to if there is another way to set F\_CPU ?

# Answer
No, the boards.txt file is where it is defined and the only place it is (or can be) defined. Making a new board variant is the proper way of adding a new board with new settings.
> 2 votes

---
Tags: oscillator-clock
---


# Question
Title: I have problem in sketch compiling error message is 'printNormalModeMessage' is not declared so what I can do
```
/* a,rduino door look project */
#include <SPI.h>
#include <MFRC522.h>
#include <LiquidCrystal.h>
#include <Servo.h>

#define RST_PIN  9
#define SS_PIN 10

byte readCard[4];
char* myTags[100] = {};
int tagsCount = 0;
String tagID = "";
boolean successRead = false;
boolean correctTag = false;
int proximitySensor;
boolean doorOpened = false;

//Creat instance
MFRC522 mfrc522(SS_PIN, RST_PIN);
LiquidCrystal lcd(2, 3, 4, 5, 6, 7);
//Parameters : (rs, enable, d4, d5, d6, d7)
Servo myServo;

void setup() {
  //Initiating
  SPI.begin();
  mfrc522.PCD_Init();
  lcd.begin(16,2);
  myServo.attach(8);

  myServo.write(10);

  lcd.print("-No Master Tag!-");
  lcd.setCursor(0,1);
  lcd.print("   SCAN NOW");

  while (!successRead) {
    successRead = getID();
    if (successRead == true) {
      myTags[tagsCount] = strdup(tagID.c_str());
      lcd.clear();
      lcd.setCursor(0,0);
      lcd.print("-Master  Tag Set!-");
      tagsCount++;
    }
  }
  successRead = false;
  printNormalModeMessage();
}
void loop() {
  int proximitySensor = analogRead(A0);
  // if door closed
  if (proximitySensor > 200) {
    if ( ! mfrc522.PICC_IsNewCardPresent()) {
      return;
    }
    if ( ! mfrc522.PICC_ReadCardSerial()) {
      return;
    }
    tagID = "";
    for ( unit8_t i = 0; i < 4; i++) {
      readCard[i]  = mfrc522.uid.uidByte[i];
      tagID.concat(String(mfrc522.uid.uidByte[i],HEX));
    }
    tagID.toUpperCase();
    mfrc522.PICC_HaltA();

    correctTag = false;
    if (tagID == myTags[0]) {
      lcd.clear();
      lcd.print("Program mode:");
      lcd.setCursor (1,0);
      lcd.print("Add/ Remove Tag");
      while (!successRead) {
        successRead = getID();
        if (successRead == true) {
          for (int i = 0; i < 100; i++) {
            if (tagID == myTags[i]) {
              myTags[i] = "";
              lcd.clear();
              lcd.setCursor(0,0);
              lcd.print("   Tag Removed!");
              printNormalModwMessage();
              tagsCount++;
              return:
            }
          }
        myTags[tagsCount] = strdup(tagID.c_str());
        lcd.clear();
        lcd.setCursor(0,0);
        lcd.print(" Tag Added!");
        printNormalModeMessage();
        return;
        }
      }
    }
    successRead = false;
    for (int i = 0; i < 100; i++) {
      if (tagID == myTags[i] ) {
        lcd.clear();
        lcd.setCursor(0,0);
        lcd.print( "Access Granted!");
        myServo.write(170);
        printNormalModeMessage();
        correctTag = true;
      }
    }
    if (correctTag == false) {
      lcd.clear();
      lcd.setCursor(0,0);
      lcd.print(" Access Denide!");
      printNormalModeMessags();
    }
  }
  else {
    lcd.clear();
    lcd.setCursor(0,0);
    lcd.print(" Door opeded!");
    while (!doorOpened) {
      proximitySensor = analogRead(A0);
      if (proximitySensor > 200)  {
        doorOpened = true ;
      }
    }
    doorOpened = false;
    delay(500);
    myServo.write(10);
    printNormalModeMessage();
  }
}
uint8_t getID() {
  if ( ! mfrc522.PICC_IsNewCardPresent()) {
    return 0;
  }
  if ( ! mfrc522.PICC_ReadCardSerial()) {
     return 0;
  }
  tagID = "";
  for ( unit_8 i = 0; i < 4; i++) {
    readCard[i] = mfrc522.uid.uidByte[i];
    tagID.concat(String(mfrc522.uid.uidByte[i],HEX));
  }
  tagID.toUpperCase();
  mfrc522.PICC_HaltA();
  return 1;
}
void printNoramalModeMessage() {
  delay(1500);
  lcd.clear();
  lcd.print("-Access Control-");
  lcd.setCorsor(0,1);
  lcd.print( " Scan Your Tag!");
}

```

```
Arduino: 1.8.2 (Windows 7), Board: "Arduino/Genuino Uno"

C:\Program Files\Arduino\arduino-builder -dump-prefs -logger=machine -hardware C:\Program Files\Arduino\hardware -tools C:\Program Files\Arduino\tools-builder -tools C:\Program Files\Arduino\hardware\tools\avr -built-in-libraries C:\Program Files\Arduino\libraries -libraries D:\arduino\libraries -fqbn=arduino:avr:uno -ide-version=10802 -build-path C:\Users\pc\AppData\Local\Temp\arduino_build_303473 -warnings=none -build-cache C:\Users\pc\AppData\Local\Temp\arduino_cache_499902 -prefs=build.warn_data_percentage=75 -prefs=runtime.tools.arduinoOTA.path=C:\Program Files\Arduino\hardware\tools\avr -prefs=runtime.tools.avrdude.path=C:\Program Files\Arduino\hardware\tools\avr -prefs=runtime.tools.avr-gcc.path=C:\Program Files\Arduino\hardware\tools\avr -verbose D:\Arduino\dooropened.ino\dooropened.ino.ino
C:\Program Files\Arduino\arduino-builder -compile -logger=machine -hardware C:\Program Files\Arduino\hardware -tools C:\Program Files\Arduino\tools-builder -tools C:\Program Files\Arduino\hardware\tools\avr -built-in-libraries C:\Program Files\Arduino\libraries -libraries D:\arduino\libraries -fqbn=arduino:avr:uno -ide-version=10802 -build-path C:\Users\pc\AppData\Local\Temp\arduino_build_303473 -warnings=none -build-cache C:\Users\pc\AppData\Local\Temp\arduino_cache_499902 -prefs=build.warn_data_percentage=75 -prefs=runtime.tools.arduinoOTA.path=C:\Program Files\Arduino\hardware\tools\avr -prefs=runtime.tools.avrdude.path=C:\Program Files\Arduino\hardware\tools\avr -prefs=runtime.tools.avr-gcc.path=C:\Program Files\Arduino\hardware\tools\avr -verbose D:\Arduino\dooropened.ino\dooropened.ino.ino
Using board 'uno' from platform in folder: C:\Program Files\Arduino\hardware\arduino\avr
Using core 'arduino' from platform in folder: C:\Program Files\Arduino\hardware\arduino\avr
Detecting libraries used...
"C:\Program Files\Arduino\hardware\tools\avr/bin/avr-g++" -c -g -Os -w -std=gnu++11 -fpermissive -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics  -flto -w -x c++ -E -CC -mmcu=atmega328p -DF_CPU=16000000L -DARDUINO=10802 -DARDUINO_AVR_UNO -DARDUINO_ARCH_AVR   "-IC:\Program Files\Arduino\hardware\arduino\avr\cores\arduino" "-IC:\Program Files\Arduino\hardware\arduino\avr\variants\standard" "C:\Users\pc\AppData\Local\Temp\arduino_build_303473\sketch\dooropened.ino.ino.cpp" -o "nul"
"C:\Program Files\Arduino\hardware\tools\avr/bin/avr-g++" -c -g -Os -w -std=gnu++11 -fpermissive -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics  -flto -w -x c++ -E -CC -mmcu=atmega328p -DF_CPU=16000000L -DARDUINO=10802 -DARDUINO_AVR_UNO -DARDUINO_ARCH_AVR   "-IC:\Program Files\Arduino\hardware\arduino\avr\cores\arduino" "-IC:\Program Files\Arduino\hardware\arduino\avr\variants\standard" "-IC:\Program Files\Arduino\hardware\arduino\avr\libraries\SPI\src" "C:\Users\pc\AppData\Local\Temp\arduino_build_303473\sketch\dooropened.ino.ino.cpp" -o "nul"
"C:\Program Files\Arduino\hardware\tools\avr/bin/avr-g++" -c -g -Os -w -std=gnu++11 -fpermissive -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics  -flto -w -x c++ -E -CC -mmcu=atmega328p -DF_CPU=16000000L -DARDUINO=10802 -DARDUINO_AVR_UNO -DARDUINO_ARCH_AVR   "-IC:\Program Files\Arduino\hardware\arduino\avr\cores\arduino" "-IC:\Program Files\Arduino\hardware\arduino\avr\variants\standard" "-IC:\Program Files\Arduino\hardware\arduino\avr\libraries\SPI\src" "-IC:\Program Files\Arduino\libraries\rfid-master\src" "C:\Users\pc\AppData\Local\Temp\arduino_build_303473\sketch\dooropened.ino.ino.cpp" -o "nul"
"C:\Program Files\Arduino\hardware\tools\avr/bin/avr-g++" -c -g -Os -w -std=gnu++11 -fpermissive -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics  -flto -w -x c++ -E -CC -mmcu=atmega328p -DF_CPU=16000000L -DARDUINO=10802 -DARDUINO_AVR_UNO -DARDUINO_ARCH_AVR   "-IC:\Program Files\Arduino\hardware\arduino\avr\cores\arduino" "-IC:\Program Files\Arduino\hardware\arduino\avr\variants\standard" "-IC:\Program Files\Arduino\hardware\arduino\avr\libraries\SPI\src" "-IC:\Program Files\Arduino\libraries\rfid-master\src" "-IC:\Program Files\Arduino\libraries\LiquidCrystal\src" "C:\Users\pc\AppData\Local\Temp\arduino_build_303473\sketch\dooropened.ino.ino.cpp" -o "nul"
"C:\Program Files\Arduino\hardware\tools\avr/bin/avr-g++" -c -g -Os -w -std=gnu++11 -fpermissive -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics  -flto -w -x c++ -E -CC -mmcu=atmega328p -DF_CPU=16000000L -DARDUINO=10802 -DARDUINO_AVR_UNO -DARDUINO_ARCH_AVR   "-IC:\Program Files\Arduino\hardware\arduino\avr\cores\arduino" "-IC:\Program Files\Arduino\hardware\arduino\avr\variants\standard" "-IC:\Program Files\Arduino\hardware\arduino\avr\libraries\SPI\src" "-IC:\Program Files\Arduino\libraries\rfid-master\src" "-IC:\Program Files\Arduino\libraries\LiquidCrystal\src" "-IC:\Program Files\Arduino\libraries\Servo\src" "C:\Users\pc\AppData\Local\Temp\arduino_build_303473\sketch\dooropened.ino.ino.cpp" -o "nul"
"C:\Program Files\Arduino\hardware\tools\avr/bin/avr-g++" -c -g -Os -w -std=gnu++11 -fpermissive -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics  -flto -w -x c++ -E -CC -mmcu=atmega328p -DF_CPU=16000000L -DARDUINO=10802 -DARDUINO_AVR_UNO -DARDUINO_ARCH_AVR   "-IC:\Program Files\Arduino\hardware\arduino\avr\cores\arduino" "-IC:\Program Files\Arduino\hardware\arduino\avr\variants\standard" "-IC:\Program Files\Arduino\hardware\arduino\avr\libraries\SPI\src" "-IC:\Program Files\Arduino\libraries\rfid-master\src" "-IC:\Program Files\Arduino\libraries\LiquidCrystal\src" "-IC:\Program Files\Arduino\libraries\Servo\src" "C:\Program Files\Arduino\hardware\arduino\avr\libraries\SPI\src\SPI.cpp" -o "nul"
"C:\Program Files\Arduino\hardware\tools\avr/bin/avr-g++" -c -g -Os -w -std=gnu++11 -fpermissive -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics  -flto -w -x c++ -E -CC -mmcu=atmega328p -DF_CPU=16000000L -DARDUINO=10802 -DARDUINO_AVR_UNO -DARDUINO_ARCH_AVR   "-IC:\Program Files\Arduino\hardware\arduino\avr\cores\arduino" "-IC:\Program Files\Arduino\hardware\arduino\avr\variants\standard" "-IC:\Program Files\Arduino\hardware\arduino\avr\libraries\SPI\src" "-IC:\Program Files\Arduino\libraries\rfid-master\src" "-IC:\Program Files\Arduino\libraries\LiquidCrystal\src" "-IC:\Program Files\Arduino\libraries\Servo\src" "C:\Program Files\Arduino\libraries\rfid-master\src\MFRC522.cpp" -o "nul"
"C:\Program Files\Arduino\hardware\tools\avr/bin/avr-g++" -c -g -Os -w -std=gnu++11 -fpermissive -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics  -flto -w -x c++ -E -CC -mmcu=atmega328p -DF_CPU=16000000L -DARDUINO=10802 -DARDUINO_AVR_UNO -DARDUINO_ARCH_AVR   "-IC:\Program Files\Arduino\hardware\arduino\avr\cores\arduino" "-IC:\Program Files\Arduino\hardware\arduino\avr\variants\standard" "-IC:\Program Files\Arduino\hardware\arduino\avr\libraries\SPI\src" "-IC:\Program Files\Arduino\libraries\rfid-master\src" "-IC:\Program Files\Arduino\libraries\LiquidCrystal\src" "-IC:\Program Files\Arduino\libraries\Servo\src" "C:\Program Files\Arduino\libraries\rfid-master\src\MFRC522Debug.cpp" -o "nul"
"C:\Program Files\Arduino\hardware\tools\avr/bin/avr-g++" -c -g -Os -w -std=gnu++11 -fpermissive -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics  -flto -w -x c++ -E -CC -mmcu=atmega328p -DF_CPU=16000000L -DARDUINO=10802 -DARDUINO_AVR_UNO -DARDUINO_ARCH_AVR   "-IC:\Program Files\Arduino\hardware\arduino\avr\cores\arduino" "-IC:\Program Files\Arduino\hardware\arduino\avr\variants\standard" "-IC:\Program Files\Arduino\hardware\arduino\avr\libraries\SPI\src" "-IC:\Program Files\Arduino\libraries\rfid-master\src" "-IC:\Program Files\Arduino\libraries\LiquidCrystal\src" "-IC:\Program Files\Arduino\libraries\Servo\src" "C:\Program Files\Arduino\libraries\rfid-master\src\MFRC522Extended.cpp" -o "nul"
"C:\Program Files\Arduino\hardware\tools\avr/bin/avr-g++" -c -g -Os -w -std=gnu++11 -fpermissive -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics  -flto -w -x c++ -E -CC -mmcu=atmega328p -DF_CPU=16000000L -DARDUINO=10802 -DARDUINO_AVR_UNO -DARDUINO_ARCH_AVR   "-IC:\Program Files\Arduino\hardware\arduino\avr\cores\arduino" "-IC:\Program Files\Arduino\hardware\arduino\avr\variants\standard" "-IC:\Program Files\Arduino\hardware\arduino\avr\libraries\SPI\src" "-IC:\Program Files\Arduino\libraries\rfid-master\src" "-IC:\Program Files\Arduino\libraries\LiquidCrystal\src" "-IC:\Program Files\Arduino\libraries\Servo\src" "C:\Program Files\Arduino\libraries\rfid-master\src\MFRC522Hack.cpp" -o "nul"
"C:\Program Files\Arduino\hardware\tools\avr/bin/avr-g++" -c -g -Os -w -std=gnu++11 -fpermissive -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics  -flto -w -x c++ -E -CC -mmcu=atmega328p -DF_CPU=16000000L -DARDUINO=10802 -DARDUINO_AVR_UNO -DARDUINO_ARCH_AVR   "-IC:\Program Files\Arduino\hardware\arduino\avr\cores\arduino" "-IC:\Program Files\Arduino\hardware\arduino\avr\variants\standard" "-IC:\Program Files\Arduino\hardware\arduino\avr\libraries\SPI\src" "-IC:\Program Files\Arduino\libraries\rfid-master\src" "-IC:\Program Files\Arduino\libraries\LiquidCrystal\src" "-IC:\Program Files\Arduino\libraries\Servo\src" "C:\Program Files\Arduino\libraries\LiquidCrystal\src\LiquidCrystal.cpp" -o "nul"
"C:\Program Files\Arduino\hardware\tools\avr/bin/avr-g++" -c -g -Os -w -std=gnu++11 -fpermissive -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics  -flto -w -x c++ -E -CC -mmcu=atmega328p -DF_CPU=16000000L -DARDUINO=10802 -DARDUINO_AVR_UNO -DARDUINO_ARCH_AVR   "-IC:\Program Files\Arduino\hardware\arduino\avr\cores\arduino" "-IC:\Program Files\Arduino\hardware\arduino\avr\variants\standard" "-IC:\Program Files\Arduino\hardware\arduino\avr\libraries\SPI\src" "-IC:\Program Files\Arduino\libraries\rfid-master\src" "-IC:\Program Files\Arduino\libraries\LiquidCrystal\src" "-IC:\Program Files\Arduino\libraries\Servo\src" "C:\Program Files\Arduino\libraries\Servo\src\avr\Servo.cpp" -o "nul"
"C:\Program Files\Arduino\hardware\tools\avr/bin/avr-g++" -c -g -Os -w -std=gnu++11 -fpermissive -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics  -flto -w -x c++ -E -CC -mmcu=atmega328p -DF_CPU=16000000L -DARDUINO=10802 -DARDUINO_AVR_UNO -DARDUINO_ARCH_AVR   "-IC:\Program Files\Arduino\hardware\arduino\avr\cores\arduino" "-IC:\Program Files\Arduino\hardware\arduino\avr\variants\standard" "-IC:\Program Files\Arduino\hardware\arduino\avr\libraries\SPI\src" "-IC:\Program Files\Arduino\libraries\rfid-master\src" "-IC:\Program Files\Arduino\libraries\LiquidCrystal\src" "-IC:\Program Files\Arduino\libraries\Servo\src" "C:\Program Files\Arduino\libraries\Servo\src\nrf52\Servo.cpp" -o "nul"
"C:\Program Files\Arduino\hardware\tools\avr/bin/avr-g++" -c -g -Os -w -std=gnu++11 -fpermissive -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics  -flto -w -x c++ -E -CC -mmcu=atmega328p -DF_CPU=16000000L -DARDUINO=10802 -DARDUINO_AVR_UNO -DARDUINO_ARCH_AVR   "-IC:\Program Files\Arduino\hardware\arduino\avr\cores\arduino" "-IC:\Program Files\Arduino\hardware\arduino\avr\variants\standard" "-IC:\Program Files\Arduino\hardware\arduino\avr\libraries\SPI\src" "-IC:\Program Files\Arduino\libraries\rfid-master\src" "-IC:\Program Files\Arduino\libraries\LiquidCrystal\src" "-IC:\Program Files\Arduino\libraries\Servo\src" "C:\Program Files\Arduino\libraries\Servo\src\sam\Servo.cpp" -o "nul"
"C:\Program Files\Arduino\hardware\tools\avr/bin/avr-g++" -c -g -Os -w -std=gnu++11 -fpermissive -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics  -flto -w -x c++ -E -CC -mmcu=atmega328p -DF_CPU=16000000L -DARDUINO=10802 -DARDUINO_AVR_UNO -DARDUINO_ARCH_AVR   "-IC:\Program Files\Arduino\hardware\arduino\avr\cores\arduino" "-IC:\Program Files\Arduino\hardware\arduino\avr\variants\standard" "-IC:\Program Files\Arduino\hardware\arduino\avr\libraries\SPI\src" "-IC:\Program Files\Arduino\libraries\rfid-master\src" "-IC:\Program Files\Arduino\libraries\LiquidCrystal\src" "-IC:\Program Files\Arduino\libraries\Servo\src" "C:\Program Files\Arduino\libraries\Servo\src\samd\Servo.cpp" -o "nul"
"C:\Program Files\Arduino\hardware\tools\avr/bin/avr-g++" -c -g -Os -w -std=gnu++11 -fpermissive -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics  -flto -w -x c++ -E -CC -mmcu=atmega328p -DF_CPU=16000000L -DARDUINO=10802 -DARDUINO_AVR_UNO -DARDUINO_ARCH_AVR   "-IC:\Program Files\Arduino\hardware\arduino\avr\cores\arduino" "-IC:\Program Files\Arduino\hardware\arduino\avr\variants\standard" "-IC:\Program Files\Arduino\hardware\arduino\avr\libraries\SPI\src" "-IC:\Program Files\Arduino\libraries\rfid-master\src" "-IC:\Program Files\Arduino\libraries\LiquidCrystal\src" "-IC:\Program Files\Arduino\libraries\Servo\src" "C:\Program Files\Arduino\libraries\Servo\src\stm32f4\Servo.cpp" -o "nul"
Generating function prototypes...
"C:\Program Files\Arduino\hardware\tools\avr/bin/avr-g++" -c -g -Os -w -std=gnu++11 -fpermissive -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics  -flto -w -x c++ -E -CC -mmcu=atmega328p -DF_CPU=16000000L -DARDUINO=10802 -DARDUINO_AVR_UNO -DARDUINO_ARCH_AVR   "-IC:\Program Files\Arduino\hardware\arduino\avr\cores\arduino" "-IC:\Program Files\Arduino\hardware\arduino\avr\variants\standard" "-IC:\Program Files\Arduino\hardware\arduino\avr\libraries\SPI\src" "-IC:\Program Files\Arduino\libraries\rfid-master\src" "-IC:\Program Files\Arduino\libraries\LiquidCrystal\src" "-IC:\Program Files\Arduino\libraries\Servo\src" "C:\Users\pc\AppData\Local\Temp\arduino_build_303473\sketch\dooropened.ino.ino.cpp" -o "C:\Users\pc\AppData\Local\Temp\arduino_build_303473\preproc\ctags_target_for_gcc_minus_e.cpp"
"C:\Program Files\Arduino\tools-builder\ctags\5.8-arduino11/ctags" -u --language-force=c++ -f - --c++-kinds=svpf --fields=KSTtzns --line-directives "C:\Users\pc\AppData\Local\Temp\arduino_build_303473\preproc\ctags_target_for_gcc_minus_e.cpp"
Compiling sketch...
"C:\Program Files\Arduino\hardware\tools\avr/bin/avr-g++" -c -g -Os -w -std=gnu++11 -fpermissive -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics -MMD -flto -mmcu=atmega328p -DF_CPU=16000000L -DARDUINO=10802 -DARDUINO_AVR_UNO -DARDUINO_ARCH_AVR   "-IC:\Program Files\Arduino\hardware\arduino\avr\cores\arduino" "-IC:\Program Files\Arduino\hardware\arduino\avr\variants\standard" "-IC:\Program Files\Arduino\hardware\arduino\avr\libraries\SPI\src" "-IC:\Program Files\Arduino\libraries\rfid-master\src" "-IC:\Program Files\Arduino\libraries\LiquidCrystal\src" "-IC:\Program Files\Arduino\libraries\Servo\src" "C:\Users\pc\AppData\Local\Temp\arduino_build_303473\sketch\dooropened.ino.ino.cpp" -o "C:\Users\pc\AppData\Local\Temp\arduino_build_303473\sketch\dooropened.ino.ino.cpp.o"
D:\Arduino\dooropened.ino\dooropened.ino.ino: In function 'void setup()':

dooropened.ino:49: error: 'printNormalModeMessage' was not declared in this scope

   printNormalModeMessage();

                          ^

D:\Arduino\dooropened.ino\dooropened.ino.ino: In function 'void loop()':

dooropened.ino:62: error: 'unit8_t' was not declared in this scope

     for ( unit8_t i = 0; i < 4; i++) {

           ^

dooropened.ino:62: error: 'i' was not declared in this scope

     for ( unit8_t i = 0; i < 4; i++) {

                          ^

dooropened.ino:84: error: 'printNormalModwMessage' was not declared in this scope

               printNormalModwMessage();

                                      ^

dooropened.ino:86: error: expected primary-expression before ':' token

               return:

                     ^

dooropened.ino:86: error: expected ';' before ':' token

dooropened.ino:86: error: expected primary-expression before ':' token

dooropened.ino:93: error: 'printNormalModeMessage' was not declared in this scope

         printNormalModeMessage();

                                ^

dooropened.ino:105: error: 'printNormalModeMessage' was not declared in this scope

         printNormalModeMessage();

                                ^

dooropened.ino:113: error: 'printNormalModeMessags' was not declared in this scope

       printNormalModeMessags();

                              ^

dooropened.ino:129: error: 'printNormalModeMessage' was not declared in this scope

     printNormalModeMessage();

                            ^

D:\Arduino\dooropened.ino\dooropened.ino.ino: In function 'uint8_t getID()':

dooropened.ino:140: error: 'unit_8' was not declared in this scope

   for ( unit_8 i = 0; i < 4; i++) {

         ^

dooropened.ino:140: error: 'i' was not declared in this scope

   for ( unit_8 i = 0; i < 4; i++) {

                       ^

D:\Arduino\dooropened.ino\dooropened.ino.ino: In function 'void printNoramalModeMessage()':

dooropened.ino:152: error: 'class LiquidCrystal' has no member named 'setCorsor'

   lcd.setCorsor(0,1);

       ^

Using library SPI at version 1.0 in folder: C:\Program Files\Arduino\hardware\arduino\avr\libraries\SPI
Using library rfid-master at version 1.3.6 in folder: C:\Program Files\Arduino\libraries\rfid-master
Using library LiquidCrystal at version 1.0.5 in folder: C:\Program Files\Arduino\libraries\LiquidCrystal
Using library Servo at version 1.1.2 in folder: C:\Program Files\Arduino\libraries\Servo
exit status 1
'printNormalModeMessage' was not declared in this scope

```

# Answer
> 2 votes
```
void printNoramalModeMessage() {
  delay(1500);
  lcd.clear();
  lcd.print("-Access Control-");
  lcd.setCorsor(0,1);
  lcd.print( " Scan Your Tag!");
}

```

You can't spell "Normal".

# Answer
> 0 votes
See :

```
dooropened.ino:49: error: 'printNormalModeMessage' was not declared in this scope

```

printNormalModeMessage();

You didn't implement this function.

(please align your code correctly to make it readable)

---
Tags: arduino-uno
---


title: WiFiClient::connected() not working

text:
# Question
Title: WiFiClient::connected() not working
I use an ESP32 to open an access point and listen for TCP connections over a WiFiServer object.

When I get a client on the server I want to know when it has disconnected.

Currently I have a simple piece of code on both the client and the server side. I connect using a TcpClient in C#.

When I call `client.close()` on the client side, the `client.connected()` loop on the server just continues forever.

Here is the ESP code:

```
void setup()
{
   WiFi.mode(WIFI_AP);

   WiFi.softAP("test");

   WiFi.softAPConfig(IPAddress(192, 168, 4, 1), IPAddress(192, 168, 4, 1), IPAddress(255, 255, 255, 0));

   Serial.println(WiFi.localIP());

   server.begin();
}

void loop()
{
    while (!client)
    {
        client = server.available();

        delay(10);
    }

    while (client.connected())
    {
        Serial.println("ok");

        delay(1000);

        client.read();
    }
}

```

C# code:

```
static void Main(string[] args)
{
     TcpClient client = new TcpClient("192.168.4.1", 222);

     client.Close();
}

```

# Answer
This is a bug in a previous version of the library as mentioned on https://github.com/bportaluri/WiFiEsp/issues/14

You can alternatively use WiFi.softAPgetStationNum() to get the count of stations connected to the AP interface.
> 1 votes

# Answer
**My actual answer**

You can try to inquire `client.status()` as a workaround. When no one is connected it should return 0.

**Context**

What are you building on? I tried to reproduce your problem but everything works as expected, the serial stops printing "ok" when I disconnect.

Also, what libraries are you using exactly? I included `ESP8266WiFi.h` and `WiFiClient.h`.

I used platformio v3.4 on an ESP8266-01 module and a simple Android netcat app as client.
> 1 votes

---
Tags: esp8266, wifi, esp32
---


title: Arduino Due unable to access library

text:
# Question
Title: Arduino Due unable to access library
I am unable to run code on Arduino Due that I earlier ran on an Arduino Uno. The error indicates it is unable to recognize the library. Could this library access problem be due to difference of the micro-controllers of the 2 boards?

# Answer
Quite possibly. The modern library format contains a list of board types it runs on (in `library.properties`). If the Due (SAM) isn't listed then it won't be included in the list of libraries.

For instance the SD library has:

```
name=SD
version=1.1.1
author=Arduino, SparkFun
maintainer=Arduino <info@arduino.cc>
sentence=Enables reading and writing on SD cards.
paragraph=Once an SD memory card is connected to the SPI interface of the Arduino or Genuino board you can create files and read/write on them. You can also move through directories on the SD card.
category=Data Storage
url=http://www.arduino.cc/en/Reference/SD
architectures=*

```

However the AVR specific SPI library has:

```
name=SPI
version=1.0
author=Arduino
maintainer=Arduino <info@arduino.cc>
sentence=Enables the communication with devices that use the Serial Peripheral Interface (SPI) Bus.
paragraph=SPI is a synchronous serial data protocol used by microcontrollers for communicating with one or more peripheral devices quickly over short distances. It uses three lines common to all devices (MISO, MOSI and SCK) and one specific for each device.
category=Communication
url=http://www.arduino.cc/en/Reference/SPI
architectures=avr

```

Note the last line of each - `architectures=...` \- that defines what the library can work with. If your (unspecified) library doesn't have `*` or include `sam` in that parameter then there is no way that library will work with the Due.
> 1 votes

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


title: Powering leds from arduino with adapter

text:
# Question
Title: Powering leds from arduino with adapter
Sorry for having (again) a beginners question, but I was wondering something.

If I would want to drive like 20-30 LEDs from an Arduino (Uno), and I want to use an external adapter (12V, 1A), going into the Arduino, in what way I should drive the LEDs?

Problems I see:

* I cannot connect too many LEDs per pin (max 20mA per pin)
* I cannot connect too many LEDs per 'group' (I have to find out which pins are connected to what groups)
* I cannot connect too many LEDS in total because of the max. 200 mA per VCC/GND (there are 2 or 3 GNDs, so that should be ok)
* Using a relay/transistor etc, but how do I get the power? (there are also only 2 VCCs for 200 mA max)

So my basic question: how can I use the 1A from my adapter?

# Answer
> 1 votes
The simplest thing you can do is group the LEDs together into chains that *almost* add up to the voltage of the power supply.

If you have LEDs with a 2V forward voltage (typical red LEDs) you could have up to say 5 per chain.

Each chain, since it only has 20mA or so maximum, can be driven with a simple small transistor.

simulate this circuit – Schematic created using CircuitLab

Connect the 12V to either VIN or the barrel jack, and also drive the LED chain through a suitable resistor (R=V/I = (12 - (Num LEDs * Forward Voltage)) / 0.02). You can have as many chains as your supply can provide current for.

---
Tags: arduino-uno, power, led, current, adapter
---


# Question
Title: How to store u-blox coordinates (lat, lng) values in doubles? [TinyGps++]
I use a u-blox gps with my arduino. I can successfully write out the value of a coordinate (lat, lng) like this: `Serial.println (gps.location.lat(), 8);` but when I try to store the value with all the decimals it returns `8.00` instead of the correct coordinate + all of the 8 decimals.

This is my code:

```
#include "TinyGPS++.h"
#include <SoftwareSerial.h>
SoftwareSerial gpsconnection (4,3);
TinyGPSPlus gps;

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

void loop()
{
 while (gpsconnection.available())
 {
   gps.encode(gpsconnection.read());
 }

 //this works and returns 8 decimals
 Serial.println (gps.location.lat(), 8);
 Serial.println (gps.location.lng(), 8);

 //but if i try to store it like this:
 double latcord = (gps.location.lat(), 8);
 double lngcord = (gps.location.lng(), 8);

 //it returns 8.00 on both the "latcord" and "lngcord" which is the wrong coordinate and also it doesnt return 8 decimals
 Serial.println (latcord);
 Serial.println (lngcord);

 //if i try to convert the value to a string and then back to a double like this:
 double lat = gps.location.lat();
 String msgLat =  String(lat, 8);

 double thelat = atof(msgLat.c_str());

 //with this i get the correct first two numbers out but only 2 decimals after, not 8 decimals as it should be.
 Serial.println (thelat);

}

```

# Answer
> 3 votes
You forgot the `, 8` from your println that specifies that it should print 8 decimal places. Instead you seem to have added it to the end of an assignment which makes absolutely no sense whatsoever.

```
double latcord = gps.location.lat();
double lngcord = gps.location.lng();

Serial.println(latcord, 8);
Serial.println(lngcord, 8);

```

---
Tags: arduino-pro-mini, gps, tinygps
---


# Question
Title: PIR sensor code logic works on Mega but not on Yún
I am trying to use this example(it works on Arduino Mega): `millis() - lowIn` comes greater than `5000`when motion ends.

```
/////////////////////////////
//VARS
//the time we give the sensor to calibrate (10-60 secs according to the datasheet)
int calibrationTime = 30;

//the time when the sensor outputs a low impulse
long unsigned int lowIn;

//the amount of milliseconds the sensor has to be low
//before we assume all motion has stopped
long unsigned int pause = 5000;

boolean lockLow = true;
boolean takeLowTime;

int pirPin = 3; //the digital pin connected to the PIR sensor's output
int ledPin = 13;

/////////////////////////////
//SETUP
void setup() {
  Serial.begin(9600);
  pinMode(pirPin, INPUT);
  pinMode(ledPin, OUTPUT);
  digitalWrite(pirPin, LOW);

  //give the sensor some time to calibrate
  Serial.print("calibrating sensor ");
  for (int i = 0; i < calibrationTime; i++) {
    Serial.print(".");
    delay(1000);
  }
  Serial.println(" done");
  Serial.println("SENSOR ACTIVE");
  delay(50);
}

////////////////////////////
//LOOP
void loop() {
  if (digitalRead(pirPin) == HIGH) {
    digitalWrite(ledPin, HIGH);
    //the led visualizes the sensor's output pin state
    if (lockLow) {
      // makes sure we wait for a transition to LOW before any further output is made:
      lockLow = false;
      Serial.println("---");
      Serial.print("motion detected at ");
      Serial.print(millis() / 1000);
      Serial.println(" sec");
      delay(50);
    }
    takeLowTime = true;
  }

  if (digitalRead(pirPin) == LOW) {
    digitalWrite(ledPin, LOW);
    //the led visualizes the sensors output pin state
    if (takeLowTime) {
      lowIn = millis();
      //save the time of the transition from high to LOW
      takeLowTime = false;
      //make sure this is only done at the start of a LOW phase
    }
    //if the sensor is low for more than the given pause,
    //we assume that no more motion is going to happen
    Serial.print(millis() - lowIn);
    Serial.print("    ");
    Serial.print(lockLow);
    Serial.print("    ");
    Serial.println(pause);
    if (!lockLow && millis() - lowIn > pause) {
      //makes sure this block of code is only executed again after
      //a new motion sequence has been detected
      lockLow = true;
      Serial.print("motion ended at "); //output
      Serial.print((millis() - pause) / 1000);
      Serial.println(" sec");
      delay(50);
    }
  }
}

```

But it doesn't work on a Yún shield mounted on an Arduino Leonardo. The difference of `millis() - lowIn` always comes out to be lower than pause.

# Answer
> 0 votes
The Arduino Leonardo uses the ATmega32U4 microcontroller which uses lower logic levels for the digital inputs. Perhaps that is not compatible with the PIR sensor. You can simulate the PIR sensor with a piece of wire and connect it to 5V or GND.

For the Leonardo, sometimes "SerialUSB" is used instead of "Serial". But if see a message on the serial monitor then "Serial" is okay.

If you can't make it work, then try to reduce the number of variables. In this case, remove the Yun shield and try it with the Leonardo board.

The Arduino Mega 2560 and Arduino Leonardo have both a 8-bit microcontroller and 'millis' works on both in exactly the same way. Therefor 'millis' itself or the variables can't be the problem.

---
Tags: arduino-mega, arduino-yun, millis
---


# Question
Title: Power ON/OFF a car using Arduino with IR remote control
I'm trying somehow to power OFF the car when the song plays using Arduino using Infrared (IR) Remote. I decided to play a song (SuperMario) using a Buzzer and when I press the Power ON button works fine and the song plays.

The problem is when I press Power OFF, I have to wait until the song ends to Power off the car.

I was thinking that maybe I need threads or something, but I'm not sure, or maybe there is a better way to fix this.

Here is a Demo program:

```
#include "IRremote.h"

#define NOTE_B0  31
#define NOTE_C1  33
#define NOTE_CS1 35
#define NOTE_D1  37
#define NOTE_DS1 39
#define NOTE_E1  41
#define NOTE_F1  44
#define NOTE_FS1 46
#define NOTE_G1  49
#define NOTE_GS1 52
#define NOTE_A1  55
#define NOTE_AS1 58
#define NOTE_B1  62
#define NOTE_C2  65
#define NOTE_CS2 69
#define NOTE_D2  73
#define NOTE_DS2 78
#define NOTE_E2  82
#define NOTE_F2  87
#define NOTE_FS2 93
#define NOTE_G2  98
#define NOTE_GS2 104
#define NOTE_A2  110
#define NOTE_AS2 117
#define NOTE_B2  123
#define NOTE_C3  131
#define NOTE_CS3 139
#define NOTE_D3  147
#define NOTE_DS3 156
#define NOTE_E3  165
#define NOTE_F3  175
#define NOTE_FS3 185
#define NOTE_G3  196
#define NOTE_GS3 208
#define NOTE_A3  220
#define NOTE_AS3 233
#define NOTE_B3  247
#define NOTE_C4  262
#define NOTE_CS4 277
#define NOTE_D4  294
#define NOTE_DS4 311
#define NOTE_E4  330
#define NOTE_F4  349
#define NOTE_FS4 370
#define NOTE_G4  392
#define NOTE_GS4 415
#define NOTE_A4  440
#define NOTE_AS4 466
#define NOTE_B4  494
#define NOTE_C5  523
#define NOTE_CS5 554
#define NOTE_D5  587
#define NOTE_DS5 622
#define NOTE_E5  659
#define NOTE_F5  698
#define NOTE_FS5 740
#define NOTE_G5  784
#define NOTE_GS5 831
#define NOTE_A5  880
#define NOTE_AS5 932
#define NOTE_B5  988
#define NOTE_C6  1047
#define NOTE_CS6 1109
#define NOTE_D6  1175
#define NOTE_DS6 1245
#define NOTE_E6  1319
#define NOTE_F6  1397
#define NOTE_FS6 1480
#define NOTE_G6  1568
#define NOTE_GS6 1661
#define NOTE_A6  1760
#define NOTE_AS6 1865
#define NOTE_B6  1976
#define NOTE_C7  2093
#define NOTE_CS7 2217
#define NOTE_D7  2349
#define NOTE_DS7 2489
#define NOTE_E7  2637
#define NOTE_F7  2794
#define NOTE_FS7 2960
#define NOTE_G7  3136
#define NOTE_GS7 3322
#define NOTE_A7  3520
#define NOTE_AS7 3729
#define NOTE_B7  3951
#define NOTE_C8  4186
#define NOTE_CS8 4435
#define NOTE_D8  4699
#define NOTE_DS8 4978

#define powerLedRed    2
#define powerLedGreen  3
#define receiver       5
#define buzzer         7

void translateIR( void );
void powerON( void );;
void powerOFF( void );
void swap( int *x, int *y );
void playSuperMario( void );
void buzz( int targetPin, long frequency, long length );

int power           = 2;
int switchOFF       = 0;
int switchON        = 1;

int melody[] = {
  NOTE_E7, NOTE_E7, 0, NOTE_E7,  0, NOTE_C7, NOTE_E7, 0,
  NOTE_G7, 0, 0,  0,  NOTE_G6, 0, 0, 0,
  NOTE_C7, 0, 0, NOTE_G6,  0, 0, NOTE_E6, 0, 0,
  NOTE_A6, 0, NOTE_B6,  0, NOTE_AS6, NOTE_A6, 0,
  NOTE_G6, NOTE_E7, NOTE_G7,  NOTE_A7, 0, NOTE_F7, NOTE_G7, 0,
  NOTE_E7, 0, NOTE_C7,  NOTE_D7, NOTE_B6, 0, 0,
  NOTE_C7, 0, 0, NOTE_G6,  0, 0, NOTE_E6, 0, 0,
  NOTE_A6, 0, NOTE_B6,  0, NOTE_AS6, NOTE_A6, 0,
  NOTE_G6, NOTE_E7, NOTE_G7,  NOTE_A7, 0, NOTE_F7, NOTE_G7, 0,
  NOTE_E7, 0, NOTE_C7,  NOTE_D7, NOTE_B6, 0, 0
};

int tempo[] = {
  12, 12, 12, 12,  12, 12, 12, 12,  12, 12, 12, 12,  12, 12, 12, 12,
  12, 12, 12, 12,  12, 12, 12, 12,  12, 12, 12, 12,  12, 12, 12, 12,
  9, 9, 9,  12, 12, 12, 12,  12, 12, 12, 12,  12, 12, 12, 12,
  12, 12, 12, 12,  12, 12, 12, 12,  12, 12, 12, 12,  12, 12, 12, 12,
  9, 9, 9,  12, 12, 12, 12,  12, 12, 12, 12,  12, 12, 12, 12,
};

int underworld_melody[] = {
  NOTE_C4, NOTE_C5, NOTE_A3, NOTE_A4,  NOTE_AS3, NOTE_AS4, 0,  0,
  NOTE_C4, NOTE_C5, NOTE_A3, NOTE_A4,  NOTE_AS3, NOTE_AS4, 0,  0,
  NOTE_F3, NOTE_F4, NOTE_D3, NOTE_D4,  NOTE_DS3, NOTE_DS4, 0,  0,
  NOTE_F3, NOTE_F4, NOTE_D3, NOTE_D4,  NOTE_DS3, NOTE_DS4, 0,  0,
  NOTE_DS4, NOTE_CS4, NOTE_D4, NOTE_CS4, NOTE_DS4, NOTE_DS4, NOTE_GS3,
  NOTE_G3, NOTE_CS4, NOTE_C4, NOTE_FS4, NOTE_F4, NOTE_E3, NOTE_AS4, NOTE_A4,
  NOTE_GS4, NOTE_DS4, NOTE_B3, NOTE_AS3, NOTE_A3, NOTE_GS3, 0, 0, 0
};

int underworld_tempo[] = {
  12, 12, 12, 12,  12, 12, 6,  3,
  12, 12, 12, 12,  12, 12, 6,  3,
  12, 12, 12, 12,  12, 12, 6,  3,
  12, 12, 12, 12,  12, 12, 6,
  6, 18, 18, 18,  6, 6,  6, 6,  6, 6,
  18, 18, 18, 18, 18, 18,  10, 10, 10,
  10, 10, 10, 3, 3, 3
};

IRrecv irrecv(receiver);
decode_results results;

void setup( void )
{
  pinMode(buzzer, OUTPUT);
  pinMode(powerLedGreen, OUTPUT);
  pinMode(powerLedRed,   OUTPUT);
  Serial.begin(9600);
  Serial.println("IR Receiver Button Decode");
  irrecv.enableIRIn();
}

void loop( void )
{
  if ( power == 2 ) {
    powerOFF();
  }

  if (irrecv.decode(&results)) {
    translateIR();
    irrecv.resume();
  }
}

void playSuperMario( void ) {
  Serial.println(" 'Mario Theme'");
  int size = sizeof(melody) / sizeof(int);
  for (int thisNote = 0; thisNote < size; thisNote++) {
    int noteDuration = 1000 / tempo[thisNote];
    buzz(buzzer, melody[thisNote], noteDuration);

    int pauseBetweenNotes = noteDuration * 1.30;
    delay(pauseBetweenNotes);

    buzz(buzzer, 0, noteDuration);
  }
}

void buzz( int targetPin, long frequency, long length ) {
  digitalWrite(13, HIGH);
  long delayValue = 1000000 / frequency / 2; // calculate the delay value between transitions
  long numCycles = frequency * length / 1000; // calculate the number of cycles for proper timing

  for (long i = 0; i < numCycles; i++) { // for the calculated length of time...
    digitalWrite(targetPin, HIGH); // write the buzzer pin high to push out the diaphram
    delayMicroseconds(delayValue); // wait for the calculated delay value
    digitalWrite(targetPin, LOW); // write the buzzer pin low to pull back the diaphram
    delayMicroseconds(delayValue); // wait again or the calculated delay value
  }

  digitalWrite(13, LOW);
}

void translateIR( void ) {
  switch (results.value) {
    case 0xFF02FD:
      Serial.println(" -OK-");

      swap(&switchON, &switchOFF);

      if (switchON == 0 )
      {
        powerON();
        playSuperMario();
      }
      else
      {
        powerOFF();
      }
      break;
    default:
      Serial.println(" other button   ");
      power = 0;
  }
  //delay(500);
}

void powerOFF( void ) {
  digitalWrite(powerLedRed,   HIGH);
  digitalWrite(powerLedGreen, LOW);
  power = 0;
}

void powerON( void ) {
  digitalWrite(powerLedRed,   LOW);
  digitalWrite(powerLedGreen, HIGH);
}

void swap( int *x, int *y ) {
  if (*x != *y) {
    *x ^= *y;
    *y ^= *x;
    *x ^= *y;
  }
}

```

inside the `translateIR` function I have this:

```
void translateIR( void ) {
  switch (results.value) {
    case 0xFF02FD:
      Serial.println(" -OK-");

      swap(&switchON, &switchOFF);

      if (switchON == 0 )
      {
        powerON();
        playSuperMario();
      }
      else
      {
        powerOFF();
      }
      break;
    default:
      Serial.println(" other button   ");
      power = 0;
  }
  //delay(500);
}

```

Here is a VIDEO Demo. How to fix this?

# Answer
> 2 votes
There are two ways you can accomplish this. FYI, my buzzer is connected to pin 11 which is a PWM pin on the Arduino UNO.

1. Get a DFPlayer mini which can play the song and all you do is press the stop function to stop the music just like in your code. (Recommended)
2. Use MelodyWithoutDelay(Okay, but it works just as well and is less expensive)

For this answer, I will explain the MelodyWithoutDelay method.

As you have heard before, the delay function is a terrible way to stall the Arduino. This is because the Arduino can not be aware, or multitask, while it is staring at its own clock. I dealt with the same issue when I tried to "multitask" my Arduino to play music while receiving commands via Bluetooth.

For this reason, I created code a bit similar to the ToneMelody example given by Arduino. I called it MelodyWithoutDelay. It's a pretty swag name :)

Anyway, all you have to do replace my melody\[\] and noteDuration\[\] code with your melody\[\] and tempo\[\] code. And you have to change lengthOfSong to the number of notes in your melody from start to finish. You might have to include the pitches.h file from the toneMelody example code given by Arduino.

But the bare meat you should be looking at is the void melodyWithoutDelay().

Instead of creating the code applicable to you, I will create the most basic form, which is the one I show below. I need to show the MelodyWithoutDelay example to some viewers out there for their own projects too!.

Just marinate your head in the code and it should give you a good understanding on how to attack your mission.

**If you want to test my code, Upload it and all you have to do is type 'g' in the Serial monitor and you should be able to pause and play the song.**

If you're wondering where I used the code check out my Instructable.

Good Luck!

Here is the code:

```
    //Invented by Nathan Ramanathan
#include "pitches.h"  //File with all the music notes in the known universe
#define buzzer 11

unsigned long songMillis = 0;
bool check = false;
int thisNote = -1;
// notes in the melody:
//int melody[] = {
//  NOTE_E4, NOTE_F4, NOTE_FS4, NOTE_G4, NOTE_A4, NOTE_B4, NOTE_C5
//};

int melody[] = {//The FINAL COUNTDOWN song
  NOTE_B4, NOTE_A4, NOTE_B4, NOTE_E4, 0, NOTE_C5, NOTE_B4, NOTE_C5, NOTE_B4, NOTE_A4, 0, NOTE_C5, NOTE_B4, NOTE_C5, NOTE_E4, NOTE_FS4, 0, NOTE_A4, NOTE_G4, NOTE_A4, NOTE_G4, NOTE_FS4, NOTE_A4,   NOTE_G4,0,NOTE_B4,NOTE_A4,NOTE_B4,NOTE_E4,0,NOTE_C5,NOTE_B4,NOTE_C5,NOTE_B4,NOTE_A4,0,NOTE_B4,NOTE_A4,NOTE_B4,NOTE_E4,NOTE_FS4,0,NOTE_A4,NOTE_G4,NOTE_A4,NOTE_G4,NOTE_FS4,NOTE_A4,   NOTE_G4,NOTE_FS4,NOTE_G4,NOTE_A4,NOTE_G4,NOTE_A4,NOTE_B4,NOTE_A4,NOTE_G4,NOTE_FS4,NOTE_E4,NOTE_B4,NOTE_C5,NOTE_G4,0,NOTE_B4,NOTE_A4,NOTE_B4,NOTE_E4,0,NOTE_C5,NOTE_B4,NOTE_C5,NOTE_B4,NOTE_A4,    0,NOTE_C5,NOTE_B4,NOTE_C5,NOTE_E4,NOTE_FS4,0,NOTE_A4, NOTE_G4, NOTE_A4, NOTE_G4, NOTE_FS4, NOTE_A4,NOTE_G4,0,NOTE_B4,NOTE_A4,NOTE_B4,NOTE_E4,0,NOTE_C5, NOTE_B4, NOTE_C5, NOTE_B4, NOTE_A4,0, NOTE_C5,NOTE_B4,NOTE_C5,NOTE_E4,   NOTE_FS4,0,NOTE_A4, NOTE_G4, NOTE_A4, NOTE_G4, NOTE_FS4, NOTE_A4,NOTE_G4
};

// note durations: 4 = quarter note, 8 = eighth note, etc.:
int noteDurations[] = {
  16, 16, 4, 4, 2, 16, 16, 8, 8, 4, 2, 16, 16, 4, 4, 4, 4, 16, 16, 8, 8, 8, 8,  4,8,16,16,4,4,2,16,16,8,8,4,2,16,16,4,4,4,6,16,16,8,8,8,8,  2,16,16,3,16,16,8,8,8,8,4,8,1,4,8,16,16,4,4,2,16,16,8,8,8,  2,16,16,4,4,4,8,16,16,8,8,8,8,4,6,16,16,4,4,2,16,16,8,8,4,2,16,16,4,4,  4,6,16,16,8,8,8,8,4
};

const int lengthOfSong = 23+25+25+30+9; //For some reason the millis() doesn't like calculating array size.
//////////////////////////////////////////////////////////////////////
void setup() {
  Serial.begin(115200);
  Serial.println("Type 'g' to hear a melody.");
}

void loop() {
  // no need to repeat the melody.
  unsigned long currentMillis = millis();
  if (Serial.available()) {
    int c = Serial.read();
    if (c == 'g') {               //type 'g' to start song
      check = !(check);
    }
    if (c == 'h') {               //type 'h' in the serial monitor to confirm that the arduino listens to you while it plays music!
       Serial.println("Hello");
    }
  }
  else {
    if (check) {
      MelodyWithoutDelay(currentMillis);
    }
  }
}

void MelodyWithoutDelay(long cMillis) {
  int noteDuration = 1700 / noteDurations[thisNote];
  int pauseBetweenNotes = noteDuration * 1.2;

  if ((cMillis - songMillis <= pauseBetweenNotes / 4)) {
  }
  else if ((cMillis - songMillis <= pauseBetweenNotes)) {
    tone(buzzer, melody[thisNote], noteDuration);
  }
  else {
    if (thisNote >= lengthOfSong) {
      thisNote = -2;
      check = false;
    }
    thisNote++;
    noTone(buzzer);
    songMillis = cMillis;
  }
}

```

# Answer
> 0 votes
What you have to is in the for loop within function playSuperMario to check for the Off button. If so, stop the loop.

This is assuming the delay for waiting until the note is finished is ok.\

Maybe a better 'design' is not to use playSuperMario as one function, but within the loop function, to keep a boolean that defines if the song is playing or not. If playing, call a function: playNextNoteOfSuperMario. You also need to keep the index of the next to play note.

Something like:

```
bool CurrentlyPlaying = false;

```

Maybe you can skip this variable CurrentlyPlaying since it is probably the same as (power == 2) ??. 2 means something, so use an enumeration for that.

```
void powerOFF( void ) {
  digitalWrite(powerLedRed,   HIGH);
  digitalWrite(powerLedGreen, LOW);
  power = 0;
  CurrentlyPlaying = false;
}

void powerON( void ) {
  digitalWrite(powerLedRed,   LOW);
  digitalWrite(powerLedGreen, HIGH);
  I would expect power also to be assigned here.
  CurrentlyPlaying = true;
}

int CurrentNote = 0;

```

Set this variable again to 0 when Power On button pressed

```
void loop( void )
{
  if (songPlaying)
  {
      playNextNoteOfSuperMario();
  }

  if ( power == 2 ) {
    powerOFF();
  }

  if (irrecv.decode(&results)) {
    translateIR();
    irrecv.resume();
  }
}

void playNextNoteOfSuperMario( void ) {
  Serial.println(" 'Mario Theme'");
  int size = sizeof(melody) / sizeof(int);

  int noteDuration = 1000 / tempo[CurrentNote];
  buzz(buzzer, melody[CurrentNote], noteDuration);

  int pauseBetweenNotes = noteDuration * 1.30;
  delay(pauseBetweenNotes);

  buzz(buzzer, 0, noteDuration);
}

```

---
Tags: arduino-uno, c
---


# Question
Title: Multiple definition of "..." Compiler Error
I am creating a simple library to test how multiple files in an Arduino program works. I have three files. MotorController.ino:

```
#include <motor.h>

void setup() {
   motorInitialize();
}

void loop() {

}

```

motor.cpp:

```
#include "motor.h"

void motorInitialize() {

  for (int i = 0; i < 4; i++) {
     motorArray[i].writeMicroseconds(2000);
     delay(1500);
     motorArray[i].writeMicroseconds(2000);
     delay(1500);
  }
  delay(1000);

}

```

and motor.h:

```
#ifndef _motor_h_
#define _motor_h_

#include "Arduino.h"
#include <Servo.h>

Servo motor1, motor2, motor3, motor4;
Servo motorArray[4] = {motor1, motor2, motor3, motor4};

void motorInitialize();
#endif

```

When I try to compile the program, I get the error:

```
libraries/motorLibrary/motor.cpp.o (symbol from plugin): In function `motor1':
(.text+0x0): multiple definition of `motor1'
sketch/test.ino.cpp.o (symbol from plugin):(.text+0x0): first defined here
libraries/motorLibrary/motor.cpp.o (symbol from plugin): In function `motor1':
(.text+0x0): multiple definition of `motor2'
sketch/test.ino.cpp.o (symbol from plugin):(.text+0x0): first defined here
libraries/motorLibrary/motor.cpp.o (symbol from plugin): In function `motor1':
(.text+0x0): multiple definition of `motor3'
sketch/test.ino.cpp.o (symbol from plugin):(.text+0x0): first defined here
libraries/motorLibrary/motor.cpp.o (symbol from plugin): In function `motor1':
(.text+0x0): multiple definition of `motor4'
sketch/test.ino.cpp.o (symbol from plugin):(.text+0x0): first defined here
libraries/motorLibrary/motor.cpp.o (symbol from plugin): In function `motor1':
(.text+0x0): multiple definition of `motorArray'
sketch/test.ino.cpp.o (symbol from plugin):(.text+0x0): first defined here

```

I have read similar posts on this issue, but none of the solutions seem to work for me. I've followed the instructions on the Arduino website on how to create a library, and that doesn't seem to resolve this issue.

# Answer
> 6 votes
Although the motor (global) variables are defined in a header files, they are included in both cpp files, thus defined twice.

Make them extern, and than define them in the motor.cpp file.

In motor.h, change

```
Servo motor1, motor2, motor3, motor4;
Servo motorArray[4] = {motor1, motor2, motor3, motor4};

```

to

```
extern Servo motor1, motor2, motor3, motor4;
extern Servo motorArray[4];

```

In motor.cpp, add:

```
Servo motor1, motor2, motor3, motor4;
Servo motorArray[4] = {motor1, motor2, motor3, motor4};

```

As a side note, use consts for values 4 and 2000.

---
Tags: library, compiler
---


title: Serial monitor showing extra data

text:
# Question
Title: Serial monitor showing extra data
I am trying to communicate NODEMCU and Arduino Uno using Serial Communication (RX,TX) using SoftwareSerial library.

Here is my code

```
int count;
char reqst[] = " ";

void setup() {

  Serial.begin(115200);
  Serial.println("Ready");

}

void loop() {

 while ( Serial.available() > 0 )  {

  char inChar = Serial.read();
  reqst[count] = inChar;
  count++;

     if (inChar == '\n') {

        Serial.print("String: ");
        Serial.println(reqst);
        count = 0;
        delay(1000);

     }

 }

}

```

here my output in serial monitor is showing ;

String: aj 779

String: am 779

I have checked that from NODEMCU i am sending correct string but in Arduino Uno the number "779" is coming from nowhere.

So my problem is i am not be able to execute my function according to the desired string. Can anyone tell why the number is coming below the string ?.

# Answer
```
char reqst[] = " ";

```

Here you created an array two chars in length. But one of those characters must be used for the null terminator so actually it can only hold a string that's a single character long. If you write past the end of the array that will cause undefined behavior. This is likely to be the cause of the strange results you encountered. You need to size reqst\[\] large enough to contain any string you may receive, including the null terminator. You should add code to ensure that you never write off the end of the array and that it will always end in a null terminator.

I realize it may only be a simplified minimal example, but in the code you posted there is no need to store the incoming characters. Instead you could just print them as they are received.
> 2 votes

---
Tags: arduino-uno, serial, softwareserial
---


title: Interfacing with SPI

text:
# Question
Title: Interfacing with SPI
I am attempting to program an Arduino to interface with a DAC, specifically the AD7390 made by Analog Devices.

I have tried using the SPI library as a means of realising the interface but am confused by the PIN layout of the DAC. It provides me with SCK, SDI, CLR and LD pins.

The LD (Load Strobe) PIN is used to transfer buffers from the chip's on-board shift register to its DAC register.

The CLR PIN is used to forcibly clear the DAC register.

The documentation claims that the device is SPI compatible but, using these PINs with the Arduino Mega2560 as a micro-controller, only partially works and I am concerned that the circuit requirements of the SPI library are not being satisfied. In SPI documentation, a SS (slave select) PIN is universally mentioned but is not present with my device.

As I have managed to get the CLR PIN working, consistently and as expected, I wonder if a manual approach - i.e. using shiftIn() instead of the SPI library - is the way to go.

Any suggestions or advice would be appreciated.

# Answer
> 1 votes
The AD7390 data sheet timing diagrams show that /LD is in effect a slave select, but an *active high* one.

Specifically, it says that while /LD is high, each rising clock edge causes "Shift-Register-Data Advanced One-Bit", while when it is low, the shift register data is transferred to the DAC.

So basically you would need to use SPI in a mode where the slave select is controlled by software and asserted with the opposite of the usual polarity, but the actual shifting of the data can be accomplished with the hardware SPI engine.

It does not seem that you are always required to use the /CLR input - if you don't want to use it, wire it high. Otherwise, you can connect it to a GPIO, take it low, and then raise it so that the rising edge causes an asynchronous clear.

---
Tags: serial, arduino-mega, spi
---


# Question
Title: Cannot find COM port for Arduino after replacing Atmega328p
I had mistakenly burnt my ATmega328p that was there on the Arduino UNO R3 board. So I bought a new ATmega328p-pu with Arduino UNO bootloader installed and a sample blinking LED program pre-flashed.

However when I replaced it and plugged in to the PC using the provided Arduino programmer cable, I could not find the COM port in the device manager in Windows and neither in the Arduino IDE.

I should also mention that when I put the new Atmega328p-pu into the Arduino UNO board, the LED at 13 or L did start blinking. So I am inclined to think that both the bootloader and the sample program are there. But I cannot find the required COM port.

How do I fix this?

# Answer
Generally the IDE will detect one it can use, so you shouldn't need to use the Device Manager.

When you select the board type, so far, so good.

Then when you ask it to pick the port, it will present a list of ports that it has discovered that are registered in the Device Manager.

One thing you will notice is that if you have a Genuine Uno, for instance, it will list that next to the port name.

But if you are using a board (of any type) that have the CH340-type port it will show just the COM9 or whatever it finds.

If it doesn't find any ports (My laptop always detects the COM1 port on the back that I never use so in my case if that is all it finds then it is not finding any USB ports) then jump ahead to the arrow below.

So by trying each one you will find a port that works with your board. Or not.

I am sure you have already seen the errors it throws when you use a port that won't work for you.

-----\> If you have tried all the ports listed and none works, then you are left with only a couple of possibilities: Either the cable is bad, or the board is not responding.

Ultimately, it doesn't matter what it says in Device Manager if the IDE won't use it.

So if you can find another board and see if the cable works that would eliminate the cable as being a problem.

But if it simply will not respond then look above in the comments at what @Majenko said.

Good luck.
> 1 votes

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