text:
Detecting the presence of a specific smartphone
I would like you to give me some clues about a projet I have: I want to make sure that my little brother's smartphone stays in a shelf overnight and during school hours in order to monitor the time he spends with it.
In order to fulfill my needs, I thought of using an Arduino to detect that the smartphone stays in proximity at certain hours.
Since this is my first Arduino project, I'm not quite sure what I could do, and what is possible to do.
Hence I've got a lot of questions:

Can I easily detect that a specific smartphone is in range?
Can I use the smartphone's NFC (RFID) to do so?
What kind of output could I possibly get from an Arduino? I would like to make statistics, so it must be stored somewhere, and I know Arduino doesn't have a lot of memory.
Is it possible to write on a USB key?
Which Arduino is best suited for my needs Should I consider buying an Arduino with Ethernet in order to send emails?

Thanks a lot!

I'd suggest looking into the apps that exist, that will let you schedule phone/app usages. Something like e.g. http://ourpact.com/ .

Can I easily detect that a specific smartphone is in proximity ?

It can be done, yes. How "easily" depends on how much money and expertise you have to throw at it.

Can I use the smartphone's NFC (RFID) to do so ?

It is possible to use that, yes - if you add the right hardware and software to the Arduino.

How long can an Arduino run on battery using a 9V battery from the market ?

A couple of hours if you're lucky. They are useless batteries.

What kind of output could I possibly get from an Arduino ? I would like to make statistics, so it must be stored somewhere, and I know Arduino has not a lot of memory.

Whatever you want. Again, it's SMOP / SMOH.

Is it possible to write on an USB key ?

Sure, if you get the right hardware for that.

Which Arduino is best suited for my needs ? Should I consider buying an Arduino with Ethernet in order so send email ?

The Arduino that provides the facilities your project requires - and that depends on how you are going to decide on how to do it. Remember: the Arduino is just the "brain" of the operation. You need to decide what "organs" the brain needs to control and in what way.
There's a million and one ways of achieving what you want. You could even do it 100% in the phone in software (there's probably an app for that...) without need of an Arduino...


text:
ESP8266 wifi mesh
I'm using 3 ESP8266 for my project: one ESP8266 is a server and controls any action.
I want to be able to connect to any ESP8266 with a phone and if that ESP8266 is a client, send data to the server.
I'm using TCP/IP for communication between ESP8266 models and ESP8266 with PC or phone.
My problem is with the number of clients. In ESP8266, a maximum of 5 TCP clients can connect to a server, and my master ESP8266 is using 2 (to connect to the other ESP8266), so that just leaves 3 clients (PC or phone) that can connect to the master ESP8266.
Is there any way to increase the number of clients?
Is there any alternative for communicating between ESP8266 models other than TCP/IP and leave 5 clients in ESP8266 for the user to connect?

Can I just clarify.  You have set one ESP8266 as an access point and you want to be able to connect more than 5 clients to it?

master model is AP

others AP and station

just buy a cheap router and connect them all to that.

@LookAlterno: connection persistence was unclear, but clearly, that's going to be a HW limit if applicable, i was referring to the AP mode incoming station limit. with polling instead of always-on, a router would lets dozens and dozens of clients talk to one ESP.

Have a look at e.g. this and use your favorite find-o-magic to locate more ESP mesh solutions.

If I understand correctly the problem is only 5 clients can connect to an ESP8266 at any one time.  This is an early morning solution to the problem and to be honest I haven't though it through that much, but hopefully its a starting point.
Rather than having all the clients in the mesh connect to the Master node, run an aggregation service on the slaves.  One slave will accept connections fro up to 4 other slaves and it will forward the data to the master.  If you ever wanted more than 5 slave nodes you would need to have the aggregator nodes feeding into another aggregator (like a tree structure). Its quite easy to do statically, but could be tricky if you wanted to do it dynamically.  These aggregators might need to be dedicated nodes, it depends on traffic.
That leaves the master 4 connections for clients.  If that isn't enough then you could send the data from the master to additional ESP8266s acting as dedicated webservers and get the clients to connect to them instead.  There may even be a method of sharing the load between these two web servers in the same way as proper servers do.

i get that. evry esp8266 get 5 client so i can have 15 client  but problem is connection between esp8266 models if i us tcp for connection, my master esp lost 2 space of clients. master model is in center of my place and most clients using that

I think you got half of it.  The master ONLY talks to one ESP, (lets call it slave1) Slave1 is a sensor and server, it forwards data from Slave2, Slave3, etc to the Master and from the master back to the Slaves.  I'm not sure if Slave2 will be able to be a sensor and a server, so it might need to be an extra ESP.  Another plan might be to look at ESP32, it will cost about 5x what a 8266 costs (~£5), but it might support more clients (Its dual core and has more RAM)

tnx fo your try to help. i'am thinking about beter slution

i read some where that max client can up to 255 i think about this

You don't need a separate socket for every client. A client connects to server, sends data or gets data and disconnects. Then the next client connects. One server and one client at the time plus one client connection to PC.

i need clients be conected

whats the difference? why is the keep alive of the connection important for you?

It depends on the frequency of the packets you are sending, to often and the connection overhead will be ridiculous.   Also there is no guarantee that you won't have a situation where all the available connections are used, because all devices and clients are connected.

i want send online status to clients so i need cients be alive

source: Stack Exchange

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/

sort: votes


text:
Is it possible to read-write the memory of a Gikfun ISD1820 voice recording module?
I just got a Gikfun ISD1820 voice recording module for an Arduino project that I'm working on. I want to be able to record a few seconds message and then send the message over wifi to another Arduino Mega 2560, which will then play back the message.
The ISD1820 module can record and play back short messages and can be controlled from the Arduino, but I want to know if it is possible to access the memory / read-write the memory of the ISD1820 module to accomplish my goal. And how would I do it?
If it is impossible, what hardware should I get instead? Do I need a wave shield with a SD card or a wifi shield with an SD card?
Thanks!

No. You can't. That module can only record and play.
The only possible thing you could do is record onto the chip then play it back recording it on to the Arduino (at ridiculously low quality) - in which case, what would the point of the chip be?
If you want some quality to your recordings you need a powerful microcontroller with an I2S interface and a CODEC chip.  However any powerful MCU (such as the ARM chip on the Due, or the Teensy, or the PIC32 chip on the chipKIT boards) can sample at a reasonable quality through the ADC inputs.
The Arduino Uno can record very short bursts at very low quality (due to lack of memory) without any external hardware (except a suitable microphone preamplifier). The Mega can record slightly more, but the quality will still be very low.

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/


text:
SPI - Apparently Random pulses on CS/SS line
I'm trying to figure out why my SPI device isn't responding as expected. So I hooked up my logic analyzer and am a bit confused by the results.
I'm seeing what appears to be random pulses on the chip select/slave select line (CS in the images below). The pulses happen in random locations with random counts. Always matching either a falling edge or rising edge in the CLK line.

The code I'm running is part of a library, but I've pulled it all out for a minimum functional example:
#include <SPI.h>

#define DC_PIN          9
#define CS_PIN          10
#define BUSY_PIN        7

int IfInit(void) {
    pinMode(CS_PIN, OUTPUT);
    SPI.begin();
    SPI.beginTransaction(SPISettings(2000000, MSBFIRST, SPI_MODE0));
    return 0;
}

void SpiTransfer(unsigned char data) {
    digitalWrite(CS_PIN, LOW);
    SPI.transfer(data);
    digitalWrite(CS_PIN, HIGH);
}

int Init() {

    if (IfInit() != 0) {
        return -1;
    }

    SendCommand(0x01); //POWER_SETTING
    SendData(0x03);                  // VDS_EN, VDG_EN
    SendData(0x00);                  // VCOM_HV, VGHL_LV[1], VGHL_LV[0]
    SendData(0x2b);                  // VDH
    SendData(0x2b);                  // VDL
    SendData(0xff);                  // VDHR
    SendCommand(0x06); //BOOSTER_SOFT_START
    SendData(0x17);
    SendData(0x17);
    SendData(0x17);                  //07 0f 17 1f 27 2F 37 2f
    SendCommand(0x04); //POWER_ON
    WaitUntilIdle();
    SendCommand(0x00); //PANEL_SETTING
    SendData(0xbf);    // KW-BF   KWR-AF  BWROTP 0f
    SendData(0x0b);
    SendCommand(0x30); //PLL_CONTROL
    SendData(0x3c);        // 3A 100HZ   29 150Hz 39 200HZ  31 171HZ

    return 0;
}

void SendCommand(unsigned char command) {
//    digitalWrite(DC_PIN, LOW);
    SpiTransfer(command);
}

void SendData(unsigned char data) {
//    digitalWrite(DC_PIN, HIGH);
    SpiTransfer(data);
}

void WaitUntilIdle(void) {
    while(digitalRead(BUSY_PIN) == 0) {      //0: busy, 1: idle
        delay(100);
    }
}

void setup() {

  pinMode(CS_PIN, OUTPUT);
  digitalWrite(CS_PIN, HIGH);

  Serial.begin(9600);
  Serial.println("Start");

  if (Init() != 0) {
    Serial.println("init failed");
    return;
  }

  Serial.print("init success");

}

void loop() {

}

I've tried on two different ATMEGA chips (same Arduino Uno board), same results. I've also tried with the device disconnected. Again same results. I've also tried changing the pin used for the CS, still didn't change anything.
Anyone have some insight as to what might be causing this, and/or what can be done to stop it?

ground is connected?

What processor (Arduino board) are you using?

Doing SPI.begin() after SPI.beginTransaction is the wrong order to do things. SPI.begin() should be done first.

Yes each test line of the logic analyzer is grounded.

@NickGammon That is how the library had it, nonetheless I believe you are correct. I have updated the code, re-ran the test, however the issue persists.

@NickGammon Running on Arudino Uno (Official)

The leads from arduino to device are about 15 inches. Is that long enough to be affected by RF?

ground between Uno and the device is connected?

I shortened the leads between my arduino board and the device from 15 inches down to ~5 inches and the issue disappeared.
I would have to guess that it was some RF interference.

Interesting. A possible alternative would have been to slow down SPI. However that doesn't totally explain the glitches on SS.

See my page about SPI.

Pin 10 of the Arduino is the SS line - so does this mean you have to use it for the peripheral SS line? Or should it be kept high? The answer (from the Atmega documentation) is that the SS line (pin 10) must be configured as an output (regardless of what value is on it). If configured as an output the Arduino ignores the value on that line, and thus the SPI hardware will not be put into slave mode.
Since the value on pin 10 is ignored, providing it is set as an output, then it can also be used as the SS line for your first, or only, slave. You could then use other pins (eg. 5, 6, 7, 8, 9) to control other slaves.

For you to successfully make an SPI master then pin 10 on your Uno must be configured as an output, regardless of whether or not you actually use pin 10 for SS. Under the circumstances, you may as well use pin 10 for SS if you are going to make it an output anyway.

This issue persists when using pin 10 as the SS.

I tried your code with my Uno (no device connected) and had no such problems. Sounds like an electrical issue to me.

This issue persists when using pin 10 as the SS.

See amended reply. I cannot reproduce that issue with your code.

Interesting. That definitely suggests it's an issue specific to my setup. Thanks.


text:
How to reset the arduino uno after 5 seconds?
I am using this code.. But everytime after one rfid tag is read by the reader, I have to manually press the reset button on the arduino before scanning the next tag. I want to do this operation after every 10 or 20 seconds from one tag scanning without manually pressing the reset button. What changes I have to make to this code??
/*
* source: http://www.electroschematics.com/11301/arduino-rfid-reader-rc522-access-control-system/
* Read a card using a mfrc522 reader on your SPI interface
* Pin layout should be as follows (on Arduino Uno):
* MOSI: Pin 11 / ICSP-4
* MISO: Pin 12 / ICSP-1
* SCK: Pin 13 / ISCP-3
* SS: Pin 10
* RST: Pin 9
*/

#include <SPI.h>
#include <RFID.h>
#include <Wire.h>
#include <LiquidCrystal_I2C.h>

LiquidCrystal_I2C lcd(0x27, 2, 1, 0, 4, 5, 6, 7, 3, POSITIVE);  // Set the LCD I2C address----------------------------------------------

#define SS_PIN 10
#define RST_PIN 9

RFID rfid(SS_PIN,RST_PIN);

int startAlarm = false;
int resetAlarm = 2;
int relay = 6;
int alarm = 8;

int serNum[5];

int cards[][5] = {
  {00,162,227,135,198} // card 1

};

bool access = false;

void setup()
{
  // Setup size of LCD 20 characters and 2 lines
  lcd.begin(20,2);    //------------------------------------------------------
  // Back light on
  lcd.backlight();  //---------------------------------------------------------

  lcd.setCursor(0,0);         //----------------------------------------------
  lcd.print("SCAN your ID");   //------------------------------------------------

    Serial.begin(9600);
    SPI.begin();
    rfid.init();
    pinMode(resetAlarm, INPUT);
    pinMode(relay, OUTPUT);
    pinMode(alarm, OUTPUT);
    digitalWrite(relay, HIGH); // or LOW if you have a regular relay------------------------------(ALREADY CHANGED)
    attachInterrupt(0, reset_alarm, LOW);
}

void loop()
{

    if(rfid.isCard()){

        if(rfid.readCardSerial()){
            Serial.print(rfid.serNum[0]);
            Serial.print(",");
            Serial.print(rfid.serNum[1]);
            Serial.print(",");
            Serial.print(rfid.serNum[2]);
            Serial.print(",");
            Serial.print(rfid.serNum[3]);
            Serial.print(",");
            Serial.print(rfid.serNum[4]);
            Serial.println("");

            for(int x = 0; x < sizeof(cards); x++){
              for(int i = 0; i < sizeof(rfid.serNum); i++ ){
                  if(rfid.serNum[i] != cards[x][i]) {
                      access = false;
                      break;
                  } else {
                      access = true;
                  }
              }
              if(access) break;
            }

        }

       if(access){
          Serial.println("Welcome!");
          startAlarm = false;
          digitalWrite(relay, LOW); // HIGH with regular relay (I have already changed the code)  //------------------------------
          lcd.setCursor(0,0);   //----------------------------------------------------------------------------------------------
          lcd.print("Access Granted");  //-------------------------------------------------------------------------------------------
          delay(3000);
          lcd.clear();
          lcd.setCursor(0,0);         //----------------------------------------------
          lcd.print("SCAN your ID");   //------------------------------------------------
             //---------------------------------------------------------------
       } else {
           Serial.println("Not allowed!");
           startAlarm = true;
           digitalWrite(relay, HIGH);  // LOW with regular relay (I have already changed the code)----------------------------------
           lcd.setCursor(0,0);         //------------------------------------------------------------------------------------
           lcd.print("Invalid Access ");        //------------------------------------------------------------------------------------
           delay(3000);
           lcd.clear();                            //--------------------------------------------
           lcd.setCursor(0,0);         //----------------------------------------------
           lcd.print("SCAN your ID");   //------------------------------------------------

       }
    }

    if(startAlarm) {
       digitalWrite(alarm, HIGH);
    } else {
      digitalWrite(alarm, LOW);
    }

    rfid.halt();

}

void reset_alarm(){
    startAlarm = false;
}

Sound like you are having a software problem. I'd suggest trying to fix that, instead of this hackish workaround. My first instinct is that, because you call rfid.halt();, the RFID reader will no longer read any further cards, which would explain why you need to reset the Arduino.

XY problem.

This may not be your only issue, but I think you are using sizeof() wrongly.  This 'function' returns the number of bytes occupied by a variable or type OR the number of bytes occupied by an array.
So
1 == sizeof(char)
6 == sizeof ("Hello")  // Because of the trailing null
2 == sizeof(int)
int cards[][5] = {
                  {00,162,227,135,198} // card 1
                 };
10 == sizeof (cards)

So you line that says for(int x = 0; x < sizeof(cards); x++){ is happening 10 times, not once.
Personally I would never use sizeof to measure the size of an array, but if you have to then you need to do this:
size = sizeof (cards) / sizeof (int)

You mean 10 == sizeof(cards).

Yes I do, I wasn't sure when I wrote it, but just tested and corrected it.

As you may know, sizeof is an operator rather than a function.  So one can say, equivalently,  sizeof (cards) / sizeof (cards[0]) or   sizeof cards/ sizeof  cards[0].  Note, per §6.5.3.4.2 of ISO/IEC 9899:201x N1570 C++ std, "The sizeof operator yields the size (in bytes) of its operand, which may be an expression or the parenthesized name of a type."  That is, sizeof (int) is ok,  but malformed sizeof int is not ok

I would think the rfid library would be able to read multiple cards in a row... however I'm not familiar with it.
Here is an answer from a similar question about how to initiate a hardware reset with software using the watchdog timer - https://arduino.stackexchange.com/a/1478/31106 :

The SoftReset library makes it easy. Although it is not difficult to
  implement directly. Shown below..
#include <avr/wdt.h>
...
setup() {

  ...
  MCUSR = 0;  // clear out any flags of prior resets.
  ...

then when desired...
...
wdt_enable(WDTO_15MS); // turn on the WatchDog and don't stroke it.
for(;;) {
  // do nothing and wait for the eventual...
}
...

This would certainly force a system restart which is what the OP said he wanted. It is, however, a drastic solution for what is almost certainly a simple coding problem which may be better handled by a timeout or some similar mechanism in the application program.

100% agree. Finding a solution that didn't require a reset would be ideal.


text:
i am unable to make a correct program using the pushbutton to toggle LED on/off?
I want to toggle the the LED on on my first complete click(i.e. pushing and even releasing the pushbutton) and i want to make my LED off at my second click.
This is the program :-
int led = 13;
int buttonpin = 8;
boolean lastbuttonstate = LOW;
boolean ledon = LOW;

void setup ()
{
  digitalWrite(buttonpin,HIGH);
  pinMode(buttonpin,INPUT);
  pinMode(led,OUTPUT);
}

void loop ()
{
  if( digitalRead(buttonpin) == HIGH && lastbuttonstate == LOW && ledon = !digitalRead(buttonpin))
  {
    digitalWrite(led,HIGH);
  }
  else if (digitalRead(buttonpin) == LOW && lastbuttonstate == HIGH && ledon =!digitalRead(buttonpin))
  {
    digitalWrite(led,HIGH);
  }
   if( digitalRead(buttonpin) == HIGH && lastbuttonstate == LOW && ledon =digitalRead(buttonpin))
  {
    digitalWrite(led,LOW);
  }
  else if (digitalRead(buttonpin) == LOW && lastbuttonstate == HIGH && ledon =digitalRead(buttonpin))
  {
    digitalWrite(led,LOW);
  }
}

I have connected all the connections on my breadboard according to schematic but there is something wrong in the program itself.

Edit your question and format the code. Select the code and click the {} button in the editor.

First off, did you use pullup or pulldown resistors for your button?

Second, what's the purpose of ledon variable, in its current usage, it is just useless.

Nothing will happen as lastbuttonstate is never changed.

so i got to change the last buttonstate according to the led state ??

I'd add a delay(100); at the end of the loop to have to very basic debouncing of the button.

I would use a different approach
int led = 13;
int buttonpin = 8;
boolean waspressed = false;

void setup (){
    pinMode(buttonpin,INPUT);
    pinMode(led,OUTPUT);
    digitalWrite(led,LOW);
}

void loop(){
    if(digitalRead(buttonpin) == HIGH){
        waspressed = true;
    }else{
        if(waspressed == true){
            digitalWrite(led, !digitalRead(led));
            waspressed = false;
        }
    }
}

We can understand it better if we just take a step by step view. When the controller is started, it first executes the setup(), setting the led pin as output, buttonpin as input and setting the led pin value to low. The led pin is set to LOW because it needs to have an initial value once it is an output. The initial value can also be HIGH without changing the behavior of the circuit. Always remember to set an initial value to all your output pins. This prevent them to float, which may lead no unpredictable results.
The loop() can be a little more tricky.
State 1 - button not pressed
The first interaction tries the value of buttonpin:if(digitalRead(buttonpin) == HIGH). Once the button is not pressed (buttonpin is LOW), the interpreter moves to the else element. At this element, there is another conditional - i.e, another if. This conditional looks for the value of waspressed. This is false, as set at the begging of the code. Because of this, the information inside the conditional is not executed and the loop() is executed over and over with no change until the button is pressed.
Stage 2 - button is pressed
When the button is pressed, the next iteraction of loop() will catch this action when trying the first conditional if(digitalRead(buttonpin) == HIGH). Once buttonpin is high if the button is pressed, waspressed will be set to true. This will repeat as long as the button remain pressed.
Stage 3 - button is released
After being released, the first conditional will read buttonpin as LOW, and the interpretor will move the the else element. At that element, it will try the second conditional if(waspressed == true). Until now, there is no difference from what was executed at the first stage, however this time, waspressed is true because it was set true when the button was pressed. This leads the interpreter inside the conditional and execute the lines
digitalWrite(led, !digitalRead(led));
waspressed = false;

The first one set the led pin to the opposite value it has. I.e, if the led pin is HIGH, it becames LOW, if it is LOW, it becames HIGH. This happens because !digitalRead(led) outputs the complement of the value of digitalRead(led) - without the !.
The second one set waspressed to false again. With this, the next iteration will be back to stage one and wait for another press on the button.

Can  u plz explain me how u r using the variable waspressed here ?

At every loop, it reads the variable buttonpin for its value. In case it is HIGH, it sets waspressed to true. This means that by the time you are holding the button, the value of waspressed will always be true. At the time you release the button, the next loop will read buttonpin as false and will check if waspressed is true. In case it is true, this means that the button has just being released. In this case it changes the value of the led pin and set waspressed to false again so you go back to the initial state.

I can explain it in a slower rhythm if necessary. Just ask me if you need it. :)

I edited the answer to provide a more detailed explanation

thanx for the elaboration.....now i'm completely  able to understand this program.....it was easier than a complex program that i was unable to understand from youtube.

can you help me in one more question? I had posted it it 1 year ago which is related on this same concept of push button, integrating fading effect with push button. P.S. :- I have made some changes in the program after learning this concept. plz help me out !!

This appears to be the classic "how to debounce a mechanical button" problem.
You can either denounce a button using external hardware.  Or you can denounce a button using software.
Using Hardware:
Normally a Set Reset or SR Latch is used to debounce mechanical buttons.  It is common to use a single poll double throw (break before make) type switch to accomplish this.

Using Software:
When solving this in software, one needs to create a state machine with 4 states.  Two of which are the normally expected ON and OFF state.  The other two are the state where we are not sure if the button is pressed or not. As the button is in motion or is "bouncing".  These 2 extra states have a time component much longer then the expected time it takes the switch to stop "bouncing".  But much shorter then to be noticeable to the operator of the button.
For a really good explanation of using state machines for debouncing switches specifically for an Arduino refer to the "denounce a button using software" link at the top of this answer.


text:
Arduino and 2 MOSFETs
I want to turn on 2 bulbs using 2 MOSFETs. The problem is that they both turn on when it should turn up just one light.
Code:
void setup() {
  pinMode(13, OUTPUT);
  pinMode(7, OUTPUT);
}

void loop() {
  digitalWrite(13,1);
  digitalWrite(13,0);
}

See circuit below:

What sort of MOSFETs are they? (part numbers)

Try adding a delay into your loop. In your code pin 13 will toggle very rapidly, much too fast to see it. For example:
void loop() {
  digitalWrite(13,HIGH);
  delay (1000);
  digitalWrite(13,LOW);
  delay (1000);
}

It doesn't look wired correctly. For an N-channel MOSFET the Source should go to ground, like this:

The following circuit diagram works perfectly.

i prefer you to use relay to control any ac appliance with arduino it very much safe...
Just follow this circuit diagram and use 5v relay in your project it will always work fine.....

I fail to see how this can help. OP is not attempting to control an A.C. appliance, the diagram clearly shows that they are D.C. Also, the OP has no button in their circuit, so that is completely superfluous.


text:
How to use #define in a library I'm trying to write?
I have written simple code to enable toggling of serial.print debug data.
  #define DEBUG
  #ifdef  DEBUG
    #define DEBUG3(x,y,z) Serial.print(x);Serial.print(" ");Serial.print(y);
     Serial.print(" "); Serial.println (z)
    #define DEBUG2(y,z) Serial.print(y);Serial.print(" ");Serial.println
     (z)
    #define DEBUG(z) Serial.println(z)
    #define DEBUGln  Serial.println("");
  #else
    #define DEBUG3(x,y,z)
    #define DEBUG2(x,y)
    #define DEBUG(x)
    #define DEBUGln
  #endif

Then I can just call DEBUG3("words",value,"words"); anywhere in the sketch and it will automatically print out the text, int, strings, etc with a single space between and automatically go to next line etc etc.
Just define the correct number of fields to print and separate using commas.
If I want to turn off debug then I just comment out #define DEBUG at the top.
Now the issue is I don't want to copy in this code every time I want to use it, so it makes sense to make it a library so that I can just call something like:
#include <SERIAL_DEBUG.h>
#define DEBUG     (or //#define DEBUG) //to enable or disable

The reason being that sometimes I might want to print up to 10 things on a single line (not very often but it could happen).
This is my first library attempt and I'm having a hard time finding any information on how I would go about setting up the .h and .cpp files for this type of #define DEBUG(x) Serial.println(x) and the #define DEBUG (from sketch) parts.

I wouldn't use DEBUG if I was you, some compilers define it.  You might want to look at printf which may solve you needs.

Have you tried copying someone elses library and renaming the folders and files as appropriate.  You might have an issue because the source file has no substance, so the compiler won't actually generate an object it can link against.  You could stick a dummy function in there if this becomes an issue.  In this case another solution would be to just define a header file and store it in a central location and do a 'include "..\DebugFile.h"` - dirty but effective.

yea i have been tossing up what exact command to call it. i want something simple and DEBUG() was working sofar but i might change it.. easy enough..
no substance yes good thinking ill keep it in mind.
so you mean just a .h and not do much if anything with .cpp?
because that would be oh so much less to think about

Anything in a header file that is included with #include is literally pasted into the file at the point of the #include.
So anything in your sketch you want to place into a header file you can just place it in a header file and include that file at the same location where the original code was.
So you can have a header file debug.h:
  #ifdef  DEBUG
    #define DEBUG3(x,y,z) Serial.print(x);Serial.print(" ");Serial.print(y);
     Serial.print(" "); Serial.println (z)
    #define DEBUG2(y,z) Serial.print(y);Serial.print(" ");Serial.println
     (z)
    #define DEBUG(z) Serial.println(z)
    #define DEBUGln  Serial.println("");
  #else
    #define DEBUG3(x,y,z)
    #define DEBUG2(x,y)
    #define DEBUG(x)
    #define DEBUGln
  #endif

And include that in your sketch at the right location:
#define DEBUG
#include "debug.h"

Note that the #define DEBUG must come before the #include. Remember: the #include is replaced by the content of the included file, so after preprocessing you end up with exactly what you had before in your sketch:
  #define DEBUG
  #ifdef  DEBUG
    #define DEBUG3(x,y,z) Serial.print(x);Serial.print(" ");Serial.print(y);
     Serial.print(" "); Serial.println (z)
    #define DEBUG2(y,z) Serial.print(y);Serial.print(" ");Serial.println
     (z)
    #define DEBUG(z) Serial.println(z)
    #define DEBUGln  Serial.println("");
  #else
    #define DEBUG3(x,y,z)
    #define DEBUG2(x,y)
    #define DEBUG(x)
    #define DEBUGln
  #endif

The file can be in the same location as the sketch (in which case you should use #include "debug.h" or in a library folder (Arduino/libraries/debug/debug.h) in which case you should include it with #include <debug.h>. In the Arduino IDE it actually makes little or no difference which type of #include you use, but it does serve as a visual reminder that this is either a header included with the sketch ("") or an external library or system header (<>).

thank you sir . this worked and solved the issue.. i was thinking it would be more complicated to do from all the content out there about libraries and not realzing what exactly a the #include and .h file actually do cheers

Not a direct answer to your question, but I would suggest a different
approach based on streaming output, as described in the Arduino
Playground: Adding Streaming (insertion-style) Output. In
a nutshell, you define the << operator for Serial (and any other
object that inherits from Print) in a way that allows you to write
things like:
Serial << "My name is " << name << " and I am " << age << " years old.";

Now you can define a Debug object which would be, depending on whether
you want debugging output or not:

an alias to Serial
a dummy object that just discards its input.

Example:
#define DEBUG_ON

// From https://playground.arduino.cc/Main/StreamingOutput
template<class T> inline Print& operator<<(Print &obj, T arg)
{ obj.print(arg); return obj; }

#ifdef DEBUG_ON
# define Debug Serial
#else
class DummyStream {
public:
    template<class T> DummyStream& operator<<(T arg)
    { (void) arg; return *this; }
} Debug;
#endif

void setup()
{
    const unsigned long BAUDRATE = 9600;
    Serial.begin(BAUDRATE);
    Debug << "Serial port open at " << BAUDRATE << " bps\r\n";
}

thanks both of you. Alterno i agree haha. i had a look at a few of the other ways to go about toggling serial debug lines @COMPILE TIME. all of which seem really long winded and overly complicated. {{{continue on next}}}

my approach seems to work a lot better than i had expected.  being simple to implement a long chain of serial data and with ZERO change in overhead compared to Serial.print  when DEBUG enabled(extra spaces aside..),  and also ZERO overhead (as if all Serial.print was // commented out..) when disabled. it literally turns it all on or completely eliminates it.             i discovered if i put all the #define DEBUG#(X) into an otherwise enpty sketch and #include <DIR\sketch.ino> that works  its not a proper library but i guess it'l do if i cant make the library work


text:
How to vibrate Adafruit Feather 32u4 Bluefruit LE device?
I have 11 Adafruit Feather 32u4 Bluefruit LE devices. I want to vibrate my devices using a signal through an app. Is there any signal (Code from app like 0x56-NeoPixel checking, 0x43-clear color) or any sketch? Please provide me.

I can't find any device called "adafeuit feature 32u bluefeature le". Did you mean "Adafruit Feather 32u4 Bluefruit"?

If it is that Feather device how do you expect it to "vibrate"? What have you added to it that can vibrate?

If you can't even spell the board name correctly you have no hope of success with Arduino. Either start using your brain or give up.


text:
Urgent need of help splitting a JSON formatted string received by UDP
I guess that my problems are because I'm new to C, but after spending three evenings without success I thought I'd give it a try to ask here!
I receive a JSON-formatted string in a UDP message. It contains several values that I would like to catch and convert to variables. The string format is like this:
{
  "U1": 224,
  "U2": 227,
  "U3": 224,
  "I1": 0,
  "I2": 0,
  "I3": 0,
  "P": 0,
  "PF": 0,
  "E pres": 639,
  "E total": 69901578,
  "Serial": "16889379",
  "Sec": 393833
}

Actually I really only need to get values U1, U2, U3 and I1, I2, I3. I'm grateful for all the help I can get solving this!
Best regards
Per

Have you tried iterating over the string?

Two possible approaches:

Tokenize the string using strtok(), probably a few levels deep.
This may require you learning quite a bit more about C++, pointers, and character arrays as strings.
An excellent opportunity to use an existing library, such as ArduinoJSON, which abstracts out the difficulties you may encounter if the fields in your JSON string arrive in a different order, etc.

An example of using ArduinoJSON for your case is shown in the documentation (excerpted/adapted from Decoding JSON)
#include <ArduinoJson.h>

// [...] other code

char json[] = "{ \"U1\": 224, \"U2\": 227, \"U3\": 224, \"I1\": 0, \"I2\": 0, \"I3\": 0, \"P\": 0, \"PF\": 0, \"E pres\": 639, \"E total\": 69901578, \"Serial\": "16889379", \"Sec\": 393833 }";

//
// Step 1: Reserve memory space
//
StaticJsonBuffer<200> jsonBuffer;

//
// Step 2: Deserialize the JSON string
//
JsonObject& root = jsonBuffer.parseObject(json);

if (!root.success())
{
  Serial.println("parseObject() failed");
  return;
}

//
// Step 3: Retrieve the values
//
uint16_t    u1 = root["U1"];
uint16_t    u2 = root["U2"];
uint16_t    u3 = root["U3"];
uint16_t    i1 = root["I1"];
uint16_t    i2 = root["I2"];
uint16_t    i3 = root["I3"];


text:
SIM900A A6 module Arduino +CME error 58
I've recently bought a SIM900A A6 GSM module. Whenever I send a command it gives an error: +CME error 58.
Does anybody know what this means and how to solve it?

I am also working on A6 and receiving the same error. I suspect it has something to do with the power supply. Will post my final answer once I have finished. Hassan (hassan.uh@gmail.com)

Which commands are you sending? From my experience it seems the command isn't supported. What happens if you issue just AT or ATZ?

Your sim card is probably protected by a PIN. Easiest way to get it working is to put the SIM into a normal phone and remove the PIN protection.

I've already done that it is receiving text messages and calls but its still giving this error

I had the same error.  My error was using the incorrect baud rate.  Set the baud rate to 115200.  Also, ensure that "Both NL & CR" option is selected for new line options.  After changing those settings, I had to reboot the A7, and wait for all the status messages to complete before I could send the AT command.


text:
Any advice you can give me on my step motor code?
I'm very new to Arduino, currently undertaking a uni project in which my team wish to create a sort of slot machine-esque device that uses a step motor to rotate a drum (like one of the cylinders in a slot machine).
What I've currently tried to do is merge some code that uses a counter variable and button to enable a servo to rotate round multiple times with a single button, with code I found that i think is used to test a step motor? In my mind the code I have should allow me to rotate my stepper by 45 degrees after each button press, but I have no idea if my code makes any sense. Could you guys tell me if im close or is it a load of rubbish. if it does work ok, id look to set the speed higher and have the motor perform multiple full rotations before each stop, to make it work more like an actual slot machine spinner. any advice you could offer would be great, apologies in advance if i don't quite understand certain things  you may explain as I am new to coding, as I mentioned.
Here's the code:

#include <Stepper.h>

//variables
int counter = 0;
const int buttonPin = 8;
const int stepsPerRevolution = 90;

Stepper myStepper(stepsPerRevolution,1,2,3,4);

void setup() {

 pinMode(buttonPin, INPUT);
 myStepper.setSpeed(60);

}

void loop() {

  int buttonState;

  buttonState = digitalRead(buttonPin);

   if (buttonState == LOW)
  {
    counter++;

 delay(150);
  }

if(counter == 0)
   myStepper.step(0);

 else if(counter == 1)
   myStepper.step(45);

 else if(counter == 2)
  myStepper.step(90);

 else if(counter == 3)
    myStepper.step(135);

else if(counter == 4)
   myStepper.step(180);

 else if(counter == 5)
  myStepper.step(225);

else if(counter == 6)
    myStepper.step(270);

else if(counter == 7)
  myStepper.step(315);

else if(counter == 8)
    myStepper.step(360);

  else
   counter = 0;

}

The event of a button press is not deterministic in your case. Generally, your delay()-approach combined with reading the current button state is not how sth. like this works.
Instead, you have to detect when a button is pressed/released.
One way to do that is the following:
#define buttonPin 8
bool last_state=false;

void loop(){
  if(!digitalRead(buttonPin)) {
    if(last_state) {
      //button has been released
      //increment your counter here
    }
    last_state=false;
  } else {
    last_state=true;
  }
}

First understand that myStepper.step(x) method is relative steps not absolute. So if you want the motor to do two rotations of 45 steps back to back you should write
myStepper.step(45);
myStepper.step(45);    /// NOT myStepper.step(90)  <-- that's 90 MORE steps

Second, it looks like your code will increase steps taken by 45 while HOLDING the button down but should also rotate the motor 45 steps for each button press as long as the subsequent presses do not occur while the motor is in mid rotation.
Furthermore, your can delete the following extra else if statements and it should still work.
else if(counter == 2)
  myStepper.step(90);

 else if(counter == 3)
    myStepper.step(135);

else if(counter == 4)
   myStepper.step(180);

 else if(counter == 5)
  myStepper.step(225);

else if(counter == 6)
    myStepper.step(270);

else if(counter == 7)
  myStepper.step(315);

else if(counter == 8)
    myStepper.step(360);

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/


text:
Time counting using millis
I am trying to write a code where photoresistors (a or b) sense blinking of the light, and lights LED (k and d) simultaneosly with that blinking. And I want that when both photoresistors sense dark for more than 3 secs, the LEDs would light up and stay until one of them again gets lighting. But I cannot understand in which part should I put millis time count?

int k = 2;
int d = 3;
int fk = A0;
int fd = A1;
int a = 0;
int b = 0;

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

void loop()
{
  a = analogRead (fk);
  b = analogRead (fd);
  while (a < 1000 && b < 1000)
  {
    digitalWrite(2, HIGH);
    digitalWrite(3, HIGH);
    a = analogRead (fk);
    b = analogRead (fd);
  }
  if (a > 1000)
    digitalWrite(2, HIGH);
  else
    digitalWrite(2, LOW);
  if (b > 1000)
    digitalWrite(3, HIGH);
  else
    digitalWrite(3, LOW);
}

Did you say photo resistors & blinking lights??  Keep in mind that photo resistors have an odd valance band.  Specifically, photo resistors will conduct current when lights go on and will continue to conduct current after lights go off for perhaps a second or more.  So if you lights are blinking fast enough, you will never detect the lights going off with photo resistors.

Bilnks are in 1sec interval, I have already tested that, everything works, I'm just stuck with that timing.

What type of light are you blinking to activate the photoresistors?

This is one of those cases where the solution is simply to implement a
finite state machine. Consider a state machine with these three
states:

LIGH: light has been detected by at least one of the sensors, the
LEDs follow the light sensors
SHORT_DARK: neither sensor sees light, both LEDs are off
LONG_DARK: it has been at least three seconds since neither sensor
saw light, both LEDs are on.

The transitions between those states can be depicted by the following
state diagram:

where “darkness detected” means that no sensor sees light, and “light
detected” means that at least one sensor sees light.
As a general rule, it is a good practice to always draw a state diagram
before you start writing code. Once you are sure your diagram describes
the desired behavior, it is almost trivial to translate it into code.
Here is how I would code it:
void loop()
{
    bool light_k = analogRead(IN_K) >= 1000;
    bool light_d = analogRead(IN_D) >= 1000;

    static enum { LIGHT, SHORT_DARK, LONG_DARK } state;
    static uint32_t darkness_start;
    switch (state) {
    case LIGHT:
        digitalWrite(OUT_K, light_k ? HIGH : LOW);
        digitalWrite(OUT_D, light_d ? HIGH : LOW);
        if (!light_k && !light_d) {
            darkness_start = millis();
            state = SHORT_DARK;
        }
        break;
    case SHORT_DARK:
        if (light_k || light_d) {
            state = LIGHT;
        } else if (millis() - darkness_start >= 3000) {
            digitalWrite(OUT_K, HIGH);
            digitalWrite(OUT_D, HIGH);
            state = LONG_DARK;
        }
        break;
    case LONG_DARK:
        if (light_k || light_d) {
            state = LIGHT;
        }
        break;
    }
}

Millis gives you a measure of time.  You can store that measure and compare to it later.  I don't know what in your code represents a sense of dark/light in your code (resistors can be used to raise or lower the measured input depending on your circuit) so you will have to work the following in by replacing stuff in <>
unsigned long lastlight;
void loop()
{
    if (<isLitSensorA>) lastlight = millis();
    if (<isLitSensorB>) lastlight = millis();
    if(millis() - lastlight > 3000){ //3 sec since lastlight
        <LightsAlwaysOn>
    }
    else{
        <BlinkWithLights>
    }
}

Here is a more elegant way to do this. This program doesn't require you to actually count it has been dark, instead it just remembers the time it has last seen the light (how poetic ;). I also added some commentary alongside the code.
// All the variables
int k = 2;        // LED 1
int d = 3;        // LED 2
int fk = A0;      // photoresistor 1
int fd = A1;      // photoresistor 2
int lastLight = 0;

// Set up the LEDs
void setup() {
  pinMode(k, OUTPUT);
  pinMode(d, OUTPUT);
}

void loop()
{
  // Check the photoresitors
  int a = analogRead (fk);
  int b = analogRead (fd);
  if (a > 1000 || b > 1000)
  {
    // Turn LEDs on if one photoresitor senses light
    digitalWrite(k, HIGH);
    digitalWrite(d, HIGH);
    // Also set the last time it was bright to the current time
    lastLight = millis();
  }
  else if (abs(millis() - lastLight) > 3000)
  {
    // Turn LEDs on if it has been dark for more than 3 seconds (that is 3000 milliseconds)
    digitalWrite(k, HIGH);
    digitalWrite(d, HIGH);
  }
  else
  {
    // Turn LEDs off
    digitalWrite(k, LOW);
    digitalWrite(d, LOW);
  }
}

Re “if (lastLight < millis() - 3000)”: here you have a millis-rollover bug. It can be somehow mitigated by if (millis() - lastLight > 3000), but it will still fail if it stays dark for longer than the rollover period. Adding lastLight = millis() - 9000 within the if, or some kind of state variable, can fix that.

Good point, I updated the answer to match that. However, using if (millis() - lastLight > 3000) will not change that. You can bypass the problem by using the absolute value of the difference (this way the LEDs stay dark even if a rollover occurs). I don't understand your suggestion though for the case that it stays dark for longer than 49.5 days.

abs() won't help, but you have to make lastLight an unsigned long. See millis() overflow ... a bad thing? and How can I handle the millis() rollover?. If it stays dark for longer than 49.7 days, millis() will get very close to lastLight, and this code will turn the LEDs off. That won't happen if you repeatedly change lastLight to stay a few seconds behind millis().


text:
Why does my code treat my sound sensor as if it's always HIGH
I have a sound sensor that was working perfectly fine as I was using it as a clap sensor to turn lights on and off. However, I tried to change the code to make it work a little smoother and for whatever reason it stopped working. I then tried to write a very simple script to allow it to turn on and off using just one clap but now it treats the sound sensor as if it's always inputting HIGH. Any ideas why this might be happening?
note: I've turned up the sensitivity and can see that the sound sensor isn't always HIGH. Even when it's too high to hear me clap it still turns the LED on and off as if the if statement below was always true.
int SENSOR = 2;
int LED = 13;

void setup() {
  // put your setup code here, to run once:
  pinMode(LED, OUTPUT);
  pinMode(SENSOR, INPUT);
}

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

  if(digitalRead(SENSOR) == HIGH){
    digitalWrite(LED, (digitalRead(LED) == HIGH ? LOW : HIGH));
    delay(100);
  }
}

This is the sound sensor module I am using: Robojax Sound Detection Microphone Module

sensors don't output HIGH or LOW, their output is numbers...

revert your code to where it worked and start rewriting the code again

The issue is that I can't revert back to my old code so I need to rewrite.

Also, even if I use 1 or 0 I have the same issue

What is your "sound sensor"?

Im sorry about all the confusion, I just read up on how it works and apparently it outputs low when it senses a sound, weird because it was working before when I was checking for a HIGH input. Anyways my problem's solved thank you for the suggestions.

one thing that may help you in future code writing ... treat my sound sensor as if it's always HIGH .... this is absolutely not true ..... it is just that your code does not do anything when the sensor is LOW

@jsotola Not really. It toggles the LED when the sensor is reads HIGH, with a delay of 100 ms between each toggle. When the sensor does not read HIGH it doesn't toggle the LED. Thus it does something different when the sensor is HIGH compared to LOW.

The robojax microphone switch I was using outputs LOW when it senses a sound rather than outputting HIGH as I assumed. The solution was just to replace all the if statements testing for a HIGH input with LOW.
note: sorry about not looking into the microphone earlier.


text:
ADC with better performance
I need to sample voltage at a very high rate (say for like 10000 Hz) and with a very good precision(at least 10-12 bit ADC will do). So I am in need of an Analog-to-Digital Converter(ADC) which has a very high sampling rate (sampling rate has to be constant and known), can be interfaced with Arduino Mega or Raspberry Pi and noise should be neligible to minimum level of voltage magnitude that it can count. Can anyone suggests me with any ADC that follows these characteristics?

You mean like an external ADC chip?  What about a TeensyLC or Teensy3.6 instead?  About 100KHz 12-bit ADC, if that's accurate enough.  You could edit your question and say what "very good precision" actually means.

Define "very good precision". Define "high sampling rate". Define "negligible noise". What is the maximum voltage you need to measure? Your idea of "very good precision" and mine might vary by a considerable amount. You know that the chip vendors (like DigiKey) have search parameters that let you type in the things you want and it returns the chips that meet those requirements?

What are you planning to do with these figures? At 10000 samples per second, where are you going to store them? RAM? Disk? If in RAM you will soon run out of RAM on most microcontrollers after a second or so. If on disk, the speed of writing to disk will slow you down. So another question is: How many samples are you planning to capture?

I am trying to calculate total harmonic distortion of line voltage. I've already tried with Arduino Mega. I can store 3200 number of sample data into it's storage. The ADC captures data for like only 0.4 second but that's sufficient for me. The problem is, Arduinos ADC sampling rate can't be easlity determined and it adds some noise to obtained data I guess.Besides Arduino can't transmit data over serial port at a fast rate.

So now I'm thingking of using another ADC and interfacing it directly with Raspberry Pi and transmit sampled data directly to the Pi(if possible). Maximum volatge doesn't matter beacuse I'll have it stepped down and shifted within ADC voltage range.@NickGammon

If you change the prescaler you can get something like 76000 conversions per second on the AVR chip at (slightly less than) 10 bit resolution. See http://www.gammon.com.au/adc

The problem is,  using Ann external ADC solves none of those problems for you.

ADS7835 from Texas Instrument.

can be interfaced with Arduino Mega or Raspberry Pi

It is interfaced through SPI, 12 bit data, and up to 500kHz throughput rate.

I need to sample voltage at a very high rate (say for like 10000 Hz) and with a very good precision(at least 10-12 bit ADC will do).

10Ksps and 12bit-resolution adcs are fairly common for onboard ADC. you should be able to find lots of mcus that have adc modules that can do that.
even for an external adc, that's not difficult at all. because of the speed, you are likely looking at a spi adc module.
precision is another matter.


text:
Arduino Uno with ESP8266-01 with AT
Here is the schematic I followed:

Here also the link: https://www.circuito.io/app?components=10167,11021,12083,13678,13959
#include "DHT.h"
#include "NewPing.h"
#include <SoftwareSerial.h>
#define DEBUG true

SoftwareSerial esp8266(11,10);

#define DHTPIN 2       // DHT-11 Output Pin connection
#define DHTTYPE DHT11   // DHT Type is DHT 11 (AM2302)
#define TRIGGER_PIN 4
#define ECHO_PIN 3
#define MAX_DISTANCE 400

NewPing sonar(TRIGGER_PIN,ECHO_PIN,MAX_DISTANCE);

float hum;
float temp;

DHT dht(DHTPIN, DHTTYPE);

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

  pinMode(TRIGGER_PIN, OUTPUT);
  pinMode(ECHO_PIN, INPUT);

  sendData("AT+RST\r\n",2000,DEBUG);
  sendData("AT+CWMODE=2\r\n",1000,DEBUG);
  sendData("AT+CIFSR\r\n",1000,DEBUG);
  sendData("AT+CIPMUX=1\r\n",1000,DEBUG);
  sendData("AT+CIPSERVER=1,80\r\n",1000,DEBUG);
}

void loop()
{
  delay(2000);  // Delay so DHT-11 sensor can stabalize

  hum = dht.readHumidity();  // Get Humidity value
  temp= dht.readTemperature();  // Get Temperature value

  digitalWrite(TRIGGER_PIN, LOW);
  delayMicroseconds(2);
  digitalWrite(TRIGGER_PIN, HIGH);
  delayMicroseconds(10);
  digitalWrite(TRIGGER_PIN, LOW);

  long duration,distance;
  duration = pulseIn(ECHO_PIN,HIGH);

  distance = duration/58.2;

  Serial.print("Humid: ");
  Serial.print(hum);
  Serial.print(" %, Temp: ");
  Serial.print(temp);
  Serial.print(" C, ");
  Serial.print("Distance: ");
  Serial.print(distance);
  Serial.println(" cm");
  delay(50);

  if(esp8266.available())
  is sending a message
  {
    if(esp8266.find("+IPD,"))
    {
      delay(1000);
      int connectionId = esp8266.read()-48;
      /* We are subtracting 48 from the
         output because the read() function returns
         the ASCII decimal value and the
         first decimal number which is 0 starts at 48 */
      String webpage = "
IOT Garbage Monitoring System
";
      webpage += "

";
      if (distance<5)
      {
        webpage+= " Trash can is Full";
      }
      else{
        webpage+= " Trash can is Empty";
      }
      webpage += "

";
      String cipSend = "AT+CIPSEND=";
      cipSend += connectionId;
      cipSend += ",";
      cipSend +=webpage.length();
      cipSend +="\r\n";

      sendData(cipSend,1000,DEBUG);
      sendData(webpage,1000,DEBUG);
      String closeCommand = "AT+CIPCLOSE=";
      closeCommand+=connectionId;
      closeCommand+="\r\n";
      sendData(closeCommand,3000,DEBUG);
    }
  }
}

String sendData(String command, const int timeout, boolean debug)
{
  String response = "";
  esp8266.print(command);
  long int time = millis();
  while( (time+timeout) > millis())
  {
    while(esp8266.available())
    {
      char c = esp8266.read();
      response+=c;
    }
  }
  if(debug)
  {
    Serial.print(response);
  }
  return response;
}

I've been trying to solve this problem for almost a week.

Comments are not for extended discussion; this conversation has been moved to chat.

This is not a forum. Questions should stand on their own, and comments under questions should seek clarification which is edited into the question. If there is more information which would help answer this question it should be edited into the question by the asker of the question (the OP, namely Xiaomy).

@NickGammon, that is what we did. only it took many clarification questions. clarifications were edited into Question

@Juraj need your assistance

related in this topic see the chat thank you sir @Juraj

@Juraj https://chat.stackexchange.com/rooms/85432/discussion-on-question-by-xiaomy-arduino-uno-with-esp8266-01-with-at

If you want to use esp-01 over SoftwareSerial, you must set the AT firmware's default baud rate to 9600 baud. The default baud rate of AT firmware is 115200 baud. SoftwareSerial can't work at this speed.
To change the baud rate you must have a way to communicate with AT firmware at the default baud rate of 115200 baud. You can use the USB adapter of the Uno. Upload BareMinimal sketch from Examples to Uno to make it silent and connect the esp-01 to RX and TX pins of the Uno.
Connect RX to RX and TX to TX to have the cross connection to USB of the Uno. Then connect from Serial Monitor to esp-01 at 115200 with "Both line end characters" set. Try some basic AT commands and then still at 115200 baud send the command to change the default baud rate AT+UART_DEF=9600,8,1,0,0

In setup() in sketch begin for SoftwareSerial is missing. Add  esp8266.begin(9600);

Uno pin 11 is RX of software serial, pin 10 is TX. The RX pin 11 must connect to TX pin of esp-01. Same applies for TX pin 10. It must connect to RX pin of the esp-01.
On the Fritzing schema on Uno pin 11 is green wire and on esp-01 TX is green wire. But the green wire is on sides of the level converter not on the same position. The conclusion is that you have RX connected to RX not to TX. Switch wires on best at level converter.

The 3.3 V pin of some Uno clones can't supply enough current for WiFi operations of the esp8266. You need to convert to 3.3 V from Uno 5 V pin or use a separate 3.3 V power source for the esp-01.

This guy is a genius and very kind! :)

details are in chat https://chat.stackexchange.com/transcript/85432

sir @Juraj need your help sir


text:
String Comparison
I am trying to compare two string but each time i am getting awkward results. When i use Equals() function i always get the wrong answer and never satisfy the IF statement. When i use compareTo() function i always get the right answer (which is btw not correct) but it always just satisfy the IF statement.
String input;
String Answer = "cat";

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

void loop()
{
  while (Serial.available() == 0)
  {
    Serial.readStringUntil('\n');
    if (input.equals(Answer))
    {
      Serial.println(input + ", Correct");
    }
    else
    {
      Serial.println(input + ", wrong");
    }
  }
}

Above is the code i am using to learn the string Comparison.

You have defined a variable named input, but you never assign a value
to it. It should thus always have its initial value, which is an empty
string.
Here:
Serial.readStringUntil('\n');

you probably meant
input = Serial.readStringUntil('\n');

Edgar Bonet thanks. I have initialised the input as you mentioned. But results are same. I don't know what's getting wrong here.

@ASADALI, add input.trim() after input = Serial.readStringUntil('\n'); to remove \r


text:
How fast does the Arduino execute code?
I am using the Arduino Nano every. Take this example where I am measuring two things A and B.
Loop{// this loop runs once every second
    //Read A,B
    //Change something using analogueWrite which would effect A,B values
    //Read A,B
}

Would the analogueWrite values have changed fast enough such that the third line would read the new and changed A,B values?

yes the data should be able to change if you are using the analog write function it will change the waves immediately so you will see a change immediately  .

The Arduino Nano Every does not have analog outputs. The function
analogWrite() uses PWM as an ersatz of analog output. As soon as the
function returns, you know that the timer registers controlling the PWM
feature have been set to the proper duty cycle. The timer, however, will
complete the current PWM cycle using the previous settings. Only when
this cycle is over will it use the updated settings for the next one.
Completing the current cycle can take up to 2 ms.
Now, I wonder how the PWM cycle can have any effect on what you are
measuring. If you expect to measure something that depends on the
apparent “analog” value you are outputting, this can only work if your
circuit contains (or behaves like) a low-pass filter. In order to
convert the PWM to an analog value, the filter's time constant has to be
significantly longer than the PWM period. This in turn will cause a
corresponding lag, so your readings will take roughly one filter's time
constant to catch up with the value you are outputting.
Note that all this has absolutely nothing to do with how fast the
Arduino executes code.

the PWM sets the duty cycle on an SMPS device, this in turn would effect the voltage and currents I am measuring. I am worried that the duty cycle would not change in time and hence this means the third line of the code there would not read the changed current and voltage values( A,B)

I am unable to find timing information to be able to investigate this or find anything to draw an accurate conclusion.


text:
subroutine with if else does not work
Everything in this code seems to work as expected except the subroutine speedcw at the bottom. It should change the time_delay variable.
#define ENA 2 //pin 2 on chip
#define in_A 0 //pin 0 on chip IN2
#define in_B 1 //pin 1 on chip IN1
#define in_C 3 //pin 3 on chip AUX
#define in_D 4 //pin 4 on chip AUX

byte PWM_PIN = 5;  //pin 5 on chip

int pwm_value = 1500;

int time_delay = 7;

void setup() {
    pinMode(ENA, OUTPUT);
    pinMode(in_A, OUTPUT);
    pinMode(in_B, OUTPUT);
    pinMode(in_C, OUTPUT);
    pinMode(in_D, OUTPUT);
    pinMode(PWM_PIN, INPUT);
}

void step1(){
    //A+,B+
    digitalWrite(in_A, 1);
    digitalWrite(in_B, 1);
    delay(time_delay);
}

void step2(){
    //A+,B-
    digitalWrite(in_A, 1);
    digitalWrite(in_B, 0);
    delay(time_delay);
}

void step3(){
    //A-,B-
    digitalWrite(in_A, 0);
    digitalWrite(in_B, 0);
    delay(time_delay);
}

void step4(){
    //A-,B+
    digitalWrite(in_A, 0);
    digitalWrite(in_B, 1);
    delay(time_delay);
}

void clockwise(long st){
    long i = 0;
    while( i < st ){
        //step1
        step1();
        //step2
        step2();
        //step3
        step3();
        //step4
        step4();
        i++;
    }
}

void counter_clockwise(long st){
    long i = 0;
    while( i < st ){
        //step1
        step4();
        //step4
        step3();
        //step3
        step2();
        //step2
        step1();
        i++;
    }
}

void loop() {
    pwm_value = pulseIn(PWM_PIN, HIGH);
    time_delay = 7;

    while (pwm_value <= 1450) {//red LED
        pwm_value = pulseIn(PWM_PIN, HIGH);
        digitalWrite(ENA, 1);
        //    digitalWrite(in_C, 1); //red LED
        //    digitalWrite(in_D, 0); //green LED
        // time_delay = 1;
        speedcw();
        clockwise(2);
    }

    while (pwm_value >= 1550) {//green LED
        pwm_value = pulseIn(PWM_PIN, HIGH);
        digitalWrite(ENA, 1);
        //    digitalWrite(in_C, 0); //red LED
        //    digitalWrite(in_D, 1); //green LED
        time_delay = 1;
        // speedccw();
        counter_clockwise(2);
    }

    while ((pwm_value >= 1451)&&(pwm_value <= 1549)) {
        pwm_value = pulseIn(PWM_PIN, HIGH);
        digitalWrite(ENA, 0);
        digitalWrite(in_C, 0);
        digitalWrite(in_D, 0);
    }
}

void speedcw(){
    if (pwm_value <= 900){
        time_delay = 1;
    }
    else if (pwm_value <= 1000){
        time_delay = 2;
    }
    else if (pwm_value <= 1100){
        time_delay = 3;
    }
    else if (pwm_value <= 1200){
        time_delay = 4;
    }
    else if (pwm_value <= 1300){
        time_delay = 5;
    }
    else if (pwm_value <= 1400){
        time_delay = 6;
    }
}

void speedccw(){
}

Are you sure that 'pwm_value <= 1450' is ever true? If not, then the code would just skip that while loop and not even call speedcw().

thank you, you were correct i made and error with the pwm i was feeding my code, 1300 was the lowest received.  im new to the arduino.


text:
Reading a string from the serial port and comparing to another string
I'm using an Arduino Mega 2560 and writing a really simple piece of code that doesn't work.
String a, letra;
#define led 13

void setup() {
  Serial.begin(9600); // opens serial port, sets data rate to 9600 bps
  pinMode(led, OUTPUT);
}

void loop() {
  while(Serial.available()) {
    letra= Serial.readStringUntil('\n');
    letra.trim();
    Serial.println(letra);

    if(letra.equals("aa\r\n")){
      Serial.println("ABRE 1");
    }
    if(letra == "aa\r\n"){
      Serial.println("ABRE 2");
    }
    if(letra.compareTo("aa\r\n") == 0){
      Serial.println("ABRE 3");
    }
  }
}

It's returning what I typed, but it's not entering any of the if conditions...
Can someone help me with that ?

there can be no \r\n in the string after trim()

Additionally, the terminating \n is removed from the input buffer, but excluded from the returned result, even without trim.

Trim removes whitespace, and you are comparing for \r and \n to be there. Since they are whitespace naturally the compare fails.
See here for one definition of whitespace for C.


text:
Can't upload the program to Arduino Uno
My Arduino Uno R3 is not detected by any laptop (I tried 3 laptops). Under devices there is no Arduino port or other devices option. It does not make sound on inserting USB cable. On plugging the USB LED 13 doesn't blink. I is just continuously on. Reset also didn't blink LED 13. Even on external power also it's not resetting.
I checked the USB cable but it's working for my friend's Arduino in my laptop too.
5V Pin giving voltage around 4.96 v, and 3.3 also giving voltage around 3.27 v.
Now I don't have access to any other Arduino for testing. Is there any way to figure out whether the ATmega chip is fried or whether it's a bootloader problem? And how to fix them? Thanks in advance.

Consider swapping socketed Arduino processors to see if the problem follows the processor.  Be careful about not bending pins.  Also avoid static electricity.

Genuine Arduino or cheap oriental clone?

Please check the answer at https://arduino.stackexchange.com/questions/44957/arduino-port-grayed-out-for-arduino-uno/

While installing the Arduino software,
there are several window pop ups which occur to install the  drivers needed for the operating system to communicate with the device.
Click install to all of them.

If you have access to a linux computer, what does lsusb say when it is plugged in over USB? Compare that output to lsusb with no Arduino plugged in. If you don't, does the arduino show up as a device to your OS at all?
You could also use your friend's arduino to reflash your bootloader. If that still doesn't work, or if your arduino doesn't show up as a device, you can try reflashing the atmega16u4 ( the USB <-> serial chip ). It is the chip responsible for telling the computer that it is an arduino serial port, so if things are still getting power, but not showing up, I would check that chip.
If it is neither of those things, there may be something wrong with one of the passive USB components, maybe one of the varistors died and is now shorted to ground, for instance. I could give more help if you share the schematic for your specific board.. is it an official Arduino, or a clone?

Can't upload the program to Arduino Uno

if your trouble is limited to just "the program", then the issues must be specific to that program.
if you cannot upload "any program", then the issues must be hardware or host related.

It is probably not a problem with the Atmega328p chip or its bootloader; the Uno has a separate processor to handle USB - an Atmega 32U4, which is the flat, surface-mount chip right behind the USB connector on the board. If that or its firmware is damaged, your PC won't recognize the device when you plug it in. If that chip is up and running, your PC will see it.


text:
Wiring diagram for Arduino to prevent relay firing on reboot
I'm starting to explore using an Arduino to control a couple of switches programatically. I have read somewhere about relays firing during reboot due to floating inputs/outputs during the reboot phase.
What is the best way to ensure that a relay will not fire on a reboot?
Is there a simple wiring diagram to explain it? I am using an Arduino Uno and a Relay Module.
Any assistance would be greatly appreciated.

Two things:

If that relay uses a FET input with no pulldown then you should add your own. If it uses an opto-isolator there is no floating problem to deal with.
Don't use pin 13 for a relay - that is connected to the LED which blinks during reset and will "flash" your relay.

You can add a pull down/up resistor between the wire and ground/vcc so that when the arduino pin is set to high impedance during reboot the wire is pulled low/high as desired.

What is the best way to ensure that a relay will not fire on a reboot?

put pull-up/down, as appropriate, on those pins.


text:
Arduino & NodeMCU, one server and multiple clients
I have seen another similar question and I followed the answer, but I cannot get my code to work for a single client properly.
In short, one NodeMCU provides AP and a WiFi server to multiple clients. The clients are supposed to stay connected. I am testing just a single client and it succeeds to connect and server reads just the first message, whereas all the subsequent messages are not received.
The server code:
#include <ESP8266WiFi.h>

#define MAX_CLIENTS 10

IPAddress    apIP(42, 42, 42, 42);
const char *ssid = "ESP8266";
const char *password = "ESP8266Test";
WiFiServer server(80);
WiFiClient *clients[MAX_CLIENTS] = { NULL };

void setup() {
  Serial.begin(115200);
  WiFi.mode(WIFI_AP_STA);
  WiFi.softAPConfig(apIP, apIP, IPAddress(255, 255, 255, 0));
  WiFi.softAP(ssid, password);
  IPAddress myIP = WiFi.softAPIP();
  Serial.print("AP IP address: ");
  Serial.println(myIP);
  server.begin();
}

void loop () {
  WiFiClient newClient = server.available();
  if (newClient) {
    Serial.println("new client");
    // Find the first unused space
    for (int i=0 ; i<MAX_CLIENTS ; ++i) {
      if (NULL == clients[i]) {
        clients[i] = new WiFiClient(newClient);
        break;
      }
    }
  } else {
    // Check whether each client has some data
    for (int i=0 ; i<MAX_CLIENTS ; ++i) {
      if (NULL != clients[i]) //ako ima taj client {
        if (clients[i]->available()) {
          Serial.print("client "); Serial.print(i);
          Serial.println("data received");
          digitalWrite(ledPin, LOW);
          String request = clients[i]->readStringUntil('\r');
          Serial.println(request);
        }
      }
    }
  }
}

As one can see, I'm checking incoming connections with server.available(), whereas I check if there is some data over the existing connection with clients[i]->available.
What happens is that I get only the first message from the client. The client code follows:
#include <ESP8266WiFi.h>

char ssid[] = "ESP8266";
char pass[] = "ESP8266Test";
WiFiClient client;

void setup() {
  Serial.begin(115200);
  WiFi.begin(ssid, pass);
  while (WiFi.status() != WL_CONNECTED) {
    Serial.println("W");
    delay(500);
  }
  client.connect(WiFi.gatewayIP(), 80); // Connection to the server
}

void loop () {
  client.println("0.00"");
  Serial.println("0.00"");
  delay(3000);
}

I suspect that I do not understand well the Server and Client classes from ESP8266WiFi Library, but it seems poorly documented.
Please advise.

i would just use the http examples if you only need 1/3Hz updates.

I believe it should work this way somehow, as http is more complex, and introduces unnecessary data and processing overhead. Maybe the problem is because the server node is also an AP?

I tried the both server and client nodeMCU's to be stations on another router's wireless network. Surprisingly, it works now.
Is this an issue with the library? Thank you

I presume you are not flushing the first data that's why only the first time your communication is happening but not after the subsequent time


text:
How can I log data to a thumb drive?
I am working on a project where I need to log data, but I was wondering if it is possible to log that data to a thumb drive? I know that I can log data to an SD card, but I thought a thumb drive would be more accessible to users who wish to obtain the data. And if it is possible to log to a thumb drive, could it be done in CSV format?
The data is just sensor data.

they make tiny readers that convert sd/microsd into usb drives, in about the same form factor as a thumb drive. not exactly the same thing, but way easier and cheaper to interface with an MCU.

In principle you can log to a thumb drive any data you want, binary and text (thus also CSV).
However, the Arduino Uno does not support connecting a USB stick directly. If you want to connect a USB stick, you need a so called USB Host shield (for Arduino).
More information can be read on the Arduino site at this page:
https://docs.arduino.cc/retired/shields/arduino-usb-host-shield

[Updated]
As an alternative to a Uno host shield, changing to a different Arduino MCU may also assist. USB host capabilty is needed for communicating with thumb drives.
Some Arduino models have a native USB port (e.g., Arduino Due, Arduino Leonardo, Arduino Micro, Arduino Nano 33 IOT, Arduino Zero, Arduino MKR Zero, Arduino MKR1000 ... ) which will work as a USB client device role.
A smaller set of MCU can act as either a USB client or host (e.g., Arduino Due, Arduino Portenta, ...). There is a USBHost library for Arduino Due listed in the Arduino Reference. Documentation for Arduino Portenta in USB host mode is here.
Here is a discussion (and reference to an alternative library) regarding using a Due to write files to a thumb drive.
Of course an adapter cable or a thumb drive with a physical connector matching the native USB port on the selected MCU is required. Both are commonly available.
See also Can the Arduino interface with USB devices without the USB host shield?

For the Micro and Leonardo, the datasheet of the ATmega32U4 says its USB controller “Supports full-speed and low-speed Device role”. I see no mention of support for the host role. Are you sure they can act as a host?

Hi Edgar, no my experience has been with the Due, and so I relied on the linked discussion for the list of other MCU with native USB. I’ll edit my answer. Thanks. Do you know of a list of MCU with host capable native USB?

No, sorry. My experience with USB-capable Arduinos is limited to playing with the Keyboard library on a Micro. I just learned that the Due is host-capable, thanks to your answer.

Thanks for the help!


text:
A beginner lost at sea, Arduino looking at the sun
I am working on trying to make a LED strip respond to natural Light levels for a sculpture. I have reached a problem in trying to get the code to work when sending PWM to the light strip. Thank you for any suggestions!
const int analogInPin = A0;
const int analogOutPin = 9;

int sensorValue = 0;
int outputValue = 0;

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

void loop() {
  sensorValue = analogRead(analogInPin);
  outputValue = map(sensorValue, 0, 1023, 0, 500);
  analogWrite(analogOutPin, outputValue);
  Serial.print("sensor = ");
  Serial.print(sensorValue);
  Serial.print("\t output = ");
  Serial.println(outputValue);
  delay(2);
}

I am using an NTE 2908 N-channel.

The LED strip won't respond to the Photocell, I apologize for being unclear haha.

Narrow it down: Print the values read from the LDR to serial. Is that the problem?  Make the LED strip blink: is that the problem? If you can do each individually then the problem is joining it together in code. If one fails by itself then there is something wrong with that bit, obviously.  BTW, analogWrite() takes values from 0-255 not 0-500.

I guess my problem is making it blink. Thank you.

What do you mean you "guess the problem is making it blink".   Firstly, why are you guessing?  Don't you know what your problem is?  Secondly, blinking wasn't mentioned anywhere in your post and nothing in your code even attempts to do anything like blinking.  Can you please describe what you actually want this thing to do?

I'm voting to close this question as off-topic because it has been abandoned for months without ever stating a specific answerable question.

@ChrisStratton why off-topic all the time? It seems like "unclear what you're asking" would be the obvious choice here.

You'd better post also the schematic, but I'm pretty sure you just messed up the circuit.
I think you just put the ground connection for the LED strip in the wrong pin (AREF). If you look, the top-most blue wire goes to the third pin from above in the right connector (which is AREF) instead of the fourth one (which is GND). Move this and it should work
Otherwise, put the schematic on the question

How about pinMode (analogOutPin, OUTPUT); ?

It isn't needed if you're going to use analogWrite.  If you'll look at the first few lines for the source for analogWrite you'll see exactly why that is true (analogWrite sets the pinMode itself.)

That still doesn't make it relate in any way to the OP's problem.  And I could turn that argument the other way, there's just as likely to be a hypothetical change where pinMode would break an analogWrite.  I would think that more likely even since the documentation says you don't need it they wouldn't worry about breaking code that did.  Point being, you need to know details about your platform before writing code. Don't assume this might happen or that might happen.  Don't assume anything in this game.  Assumption is the mother of all screw ups.  Always read instead of assuming.


text:
How to connect Arduino Nano with ESP8266 and BMP180?
I have an issue with my application.
Hardware used:

ESP8266 Serial Wi-Fi Wireless Transceiver Module for IOT
Robodyn Micro USB Compatible for Arduino Nano V3.0 ATmega168 CH340G
SENSOR: BMP180

Connections:

Arduino Nano to ESP8266
CH-PD to Vcc
GPIO0 to GND
Rx to Rx
Tx to Tx
3.3v to 3.3v
Reset to GND
GND to GND

Arduino Nano to BMP180

3.3v to VIN
GND to GND
A5 to SCL
A4 to SDA

Sketch used (uploaded in Generic ESP8266 Board):
#include <DHT.h> //  DHT.h library
#include <ESP8266WiFi.h> // ESP8266WiFi.h library
#include <SFE_BMP180.h>
#include <Wire.h>

SFE_BMP180 pressure;

const char* ssid     = "GOPI-LAPTOP";
const char* password = "kcejava123";
const char* host = "api.thingspeak.com";
const char* writeAPIKey = "CQSHDFP4EZFCDWKO";

void setup() {
  // Initialize sensor
  Serial.begin(9600);
  delay(1000);
  if (pressure.begin())
    Serial.println("BMP180 init success");
  else {
    Serial.println("BMP180 init fail\n\n");
  }
  //  Connect to WiFi network
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
  }
}

void loop() {
  char status;
  double T, P, p0, a;
  status = pressure.startTemperature();
  if (status != 0) {
    // Wait for the measurement to complete:
    delay(status);
    status = pressure.getTemperature(T);
    if (status != 0) {
      // Print out the measurement:
      Serial.print("temperature: ");
      Serial.print(T,2);
      Serial.print(" deg C, ");
      Serial.print((9.0/5.0)*T+32.0,2);
      Serial.println(" deg F");
    } else
      Serial.println("error retrieving pressure measurement\n");
  }
  status = pressure.startPressure(3);
  if (status != 0) {
    delay(status);
    status = pressure.getPressure(P, T);
    if (status != 0) {
      // Print out the measurement:
      Serial.print("absolute pressure: ");
      Serial.print(P, 2);
      Serial.print(" mb, ");
      Serial.print(P*0.0295333727, 2);
      Serial.println(" inHg");
      p0 = 1013.25; // we're at 1655 meters (Boulder, CO)
      Serial.print("relative (sea-level) pressure: ");
      Serial.print(p0, 2);
      Serial.print(" mb, ");
      Serial.print(p0*0.0295333727, 2);
      Serial.println(" inHg");
      a = pressure.altitude(P, p0);
      Serial.print("computed altitude: ");
      Serial.print(a, 0);
      Serial.print(" meters, ");
      Serial.print(a*3.28084, 0);
      Serial.println(" feet");
    }
  }
  // make TCP connections
  WiFiClient client;
  const int httpPort = 80;
  if (!client.connect(host, httpPort)) {
    return;
  }
  String url = "/update?key=";
  url+=writeAPIKey;
  url+="&field1=";
  url+=String(T);
  url+="&field2=";
  url+=String(P);
  url+="\r\n";
  // Request to the server
  client.print(String("GET ") + url + " HTTP/1.1\r\n" +
    "Host: " + host + "\r\n" +
    "Connection: close\r\n\r\n");
  Serial.print(String("GET ") + url + " HTTP/1.1\r\n" +
    "Host: " + host + "\r\n" +
    "Connection: close\r\n\r\n");
  delay(30000);
}

Serial Output:
BMP180 init fail

GET /update?key=CQSHDFP4EZFCDWKO&field1=8.04&field2=8.08
 HTTP/1.1
Host: api.thingspeak.com
Connection: close

GET /update?key=CQSHDFP4EZFCDWKO&field1=8.04&field2=8.08
 HTTP/1.1
Host: api.thingspeak.com
Connection: close

Queries:
• How to enable BMP180 to sense? When I configure BMP180 with Arduino (without ESP8266), I get the output in the serial terminal.
• How to send data to Thingspeak.com from BMP180 using the specified hardware?

I get the feeling you are getting a little confused about what is doing what. It looks like you are using the Arduino as a USB to UART converter, and programming the ESP8266 - and then connecting the BMP180 to the Arduino which you aren't programming and isn't even running.

why not just run the BMP from the ESP?

For I2C to work you must have pull up resistors.  Normally 4.7K connected between SCL and VIN and SDA and VIN make thinks work.
You probably should use a logic level convertor to convert 3.3 to 5V (not a resistor divider, not sharp enough edges for digital signals).  If I remember correctly the ESP can take 7V on its pins before you kill it (its in the chip spec) but that doesn't mean its a good idea to do it.
As mentioned above you need to cross the serial leads to make the connection.  The Nano's Rx lead needs to be connected to the ESP's Tx lead and vice versa.

Connections:
[...]

Rx to Rx
Tx to Tx

That's not gonna fix your problem with initializing the BMP180, but you have to cross the lines, Rx to Tx and Tx to Rx, if you want to get anything on the serial terminal... Besides, your Nano is 5V, your ESP 3.3V. Connecting directly the Nano's Rx/Tx lines at 5V to the ESP's Rx/Tx 3.3V lines might not be very safe.
As for the BMP180, is it rated for 3.3V, or only 5V? If it is 5V only, it might not work on the ESP. Hence the init fail.


text:
White screen when I perform grapicstest in ili9341
I get a white screen when I perform grapicstest in ili9341. I used the below code:
#include "SPI.h"
#include "Adafruit_GFX.h"
#include "Adafruit_ILI9341.h"

// For the Adafruit shield, these are the default.
#define TFT_DC 9
#define TFT_CS 10

// Use hardware SPI (on Uno, #13, #12, #11) and the above for CS/DC
Adafruit_ILI9341 tft = Adafruit_ILI9341(TFT_CS, TFT_DC);
// If using the breakout, change pins as desired
//Adafruit_ILI9341 tft = Adafruit_ILI9341(TFT_CS, TFT_DC, TFT_MOSI, TFT_CLK, TFT_RST, TFT_MISO);

void setup() {
  Serial.begin(9600);
  Serial.println("ILI9341 Test!");

  tft.begin();

  // read diagnostics (optional but can help debug problems)
  uint8_t x = tft.readcommand8(ILI9341_RDMODE);
  Serial.print("Display Power Mode: 0x"); Serial.println(x, HEX);
  x = tft.readcommand8(ILI9341_RDMADCTL);
  Serial.print("MADCTL Mode: 0x"); Serial.println(x, HEX);
  x = tft.readcommand8(ILI9341_RDPIXFMT);
  Serial.print("Pixel Format: 0x"); Serial.println(x, HEX);
  x = tft.readcommand8(ILI9341_RDIMGFMT);
  Serial.print("Image Format: 0x"); Serial.println(x, HEX);
  x = tft.readcommand8(ILI9341_RDSELFDIAG);
  Serial.print("Self Diagnostic: 0x"); Serial.println(x, HEX);

  Serial.println(F("Benchmark                Time (microseconds)"));
  delay(10);
  Serial.print(F("Screen fill              "));
  Serial.println(testFillScreen());
  delay(500);

  Serial.print(F("Text                     "));
  Serial.println(testText());
  delay(3000);

  Serial.print(F("Lines                    "));
  Serial.println(testLines(ILI9341_CYAN));
  delay(500);

  Serial.print(F("Horiz/Vert Lines         "));
  Serial.println(testFastLines(ILI9341_RED, ILI9341_BLUE));
  delay(500);

  Serial.print(F("Rectangles (outline)     "));
  Serial.println(testRects(ILI9341_GREEN));
  delay(500);

  Serial.print(F("Rectangles (filled)      "));
  Serial.println(testFilledRects(ILI9341_YELLOW, ILI9341_MAGENTA));
  delay(500);

  Serial.print(F("Circles (filled)         "));
  Serial.println(testFilledCircles(10, ILI9341_MAGENTA));

  Serial.print(F("Circles (outline)        "));
  Serial.println(testCircles(10, ILI9341_WHITE));
  delay(500);

  Serial.print(F("Triangles (outline)      "));
  Serial.println(testTriangles());
  delay(500);

  Serial.print(F("Triangles (filled)       "));
  Serial.println(testFilledTriangles());
  delay(500);

  Serial.print(F("Rounded rects (outline)  "));
  Serial.println(testRoundRects());
  delay(500);

  Serial.print(F("Rounded rects (filled)   "));
  Serial.println(testFilledRoundRects());
  delay(500);

  Serial.println(F("Done!"));

}

void loop(void) {
  for(uint8_t rotation=0; rotation<4; rotation++) {
    tft.setRotation(rotation);
    testText();
    delay(1000);
  }
}

unsigned long testFillScreen() {
  unsigned long start = micros();
  tft.fillScreen(ILI9341_BLACK);
  yield();
  tft.fillScreen(ILI9341_RED);
  yield();
  tft.fillScreen(ILI9341_GREEN);
  yield();
  tft.fillScreen(ILI9341_BLUE);
  yield();
  tft.fillScreen(ILI9341_BLACK);
  yield();
  return micros() - start;
}

unsigned long testText() {
  tft.fillScreen(ILI9341_BLACK);
  unsigned long start = micros();
  tft.setCursor(0, 0);
  tft.setTextColor(ILI9341_WHITE);  tft.setTextSize(1);
  tft.println("Hello World!");
  tft.setTextColor(ILI9341_YELLOW); tft.setTextSize(2);
  tft.println(1234.56);
  tft.setTextColor(ILI9341_RED);    tft.setTextSize(3);
  tft.println(0xDEADBEEF, HEX);
  tft.println();
  tft.setTextColor(ILI9341_GREEN);
  tft.setTextSize(5);
  tft.println("Groop");
  tft.setTextSize(2);
  tft.println("I implore thee,");
  tft.setTextSize(1);
  tft.println("my foonting turlingdromes.");
  tft.println("And hooptiously drangle me");
  tft.println("with crinkly bindlewurdles,");
  tft.println("Or I will rend thee");
  tft.println("in the gobberwarts");
  tft.println("with my blurglecruncheon,");
  tft.println("see if I don't!");
  return micros() - start;
}

unsigned long testLines(uint16_t color) {
  unsigned long start, t;
  int           x1, y1, x2, y2,
                w = tft.width(),
                h = tft.height();

  tft.fillScreen(ILI9341_BLACK);
  yield();

  x1 = y1 = 0;
  y2    = h - 1;
  start = micros();
  for(x2=0; x2<w; x2+=6) tft.drawLine(x1, y1, x2, y2, color);
  x2    = w - 1;
  for(y2=0; y2<h; y2+=6) tft.drawLine(x1, y1, x2, y2, color);
  t     = micros() - start; // fillScreen doesn't count against timing

  yield();
  tft.fillScreen(ILI9341_BLACK);
  yield();

  x1    = w - 1;
  y1    = 0;
  y2    = h - 1;
  start = micros();
  for(x2=0; x2<w; x2+=6) tft.drawLine(x1, y1, x2, y2, color);
  x2    = 0;
  for(y2=0; y2<h; y2+=6) tft.drawLine(x1, y1, x2, y2, color);
  t    += micros() - start;

  yield();
  tft.fillScreen(ILI9341_BLACK);
  yield();

  x1    = 0;
  y1    = h - 1;
  y2    = 0;
  start = micros();
  for(x2=0; x2<w; x2+=6) tft.drawLine(x1, y1, x2, y2, color);
  x2    = w - 1;
  for(y2=0; y2<h; y2+=6) tft.drawLine(x1, y1, x2, y2, color);
  t    += micros() - start;

  yield();
  tft.fillScreen(ILI9341_BLACK);
  yield();

  x1    = w - 1;
  y1    = h - 1;
  y2    = 0;
  start = micros();
  for(x2=0; x2<w; x2+=6) tft.drawLine(x1, y1, x2, y2, color);
  x2    = 0;
  for(y2=0; y2<h; y2+=6) tft.drawLine(x1, y1, x2, y2, color);

  yield();
  return micros() - start;
}

unsigned long testFastLines(uint16_t color1, uint16_t color2) {
  unsigned long start;
  int           x, y, w = tft.width(), h = tft.height();

  tft.fillScreen(ILI9341_BLACK);
  start = micros();
  for(y=0; y<h; y+=5) tft.drawFastHLine(0, y, w, color1);
  for(x=0; x<w; x+=5) tft.drawFastVLine(x, 0, h, color2);

  return micros() - start;
}

unsigned long testRects(uint16_t color) {
  unsigned long start;
  int           n, i, i2,
                cx = tft.width()  / 2,
                cy = tft.height() / 2;

  tft.fillScreen(ILI9341_BLACK);
  n     = min(tft.width(), tft.height());
  start = micros();
  for(i=2; i<n; i+=6) {
    i2 = i / 2;
    tft.drawRect(cx-i2, cy-i2, i, i, color);
  }

  return micros() - start;
}

unsigned long testFilledRects(uint16_t color1, uint16_t color2) {
  unsigned long start, t = 0;
  int           n, i, i2,
                cx = tft.width()  / 2 - 1,
                cy = tft.height() / 2 - 1;

  tft.fillScreen(ILI9341_BLACK);
  n = min(tft.width(), tft.height());
  for(i=n; i>0; i-=6) {
    i2    = i / 2;
    start = micros();
    tft.fillRect(cx-i2, cy-i2, i, i, color1);
    t    += micros() - start;
    // Outlines are not included in timing results
    tft.drawRect(cx-i2, cy-i2, i, i, color2);
    yield();
  }

  return t;
}

unsigned long testFilledCircles(uint8_t radius, uint16_t color) {
  unsigned long start;
  int x, y, w = tft.width(), h = tft.height(), r2 = radius * 2;

  tft.fillScreen(ILI9341_BLACK);
  start = micros();
  for(x=radius; x<w; x+=r2) {
    for(y=radius; y<h; y+=r2) {
      tft.fillCircle(x, y, radius, color);
    }
  }

  return micros() - start;
}

unsigned long testCircles(uint8_t radius, uint16_t color) {
  unsigned long start;
  int           x, y, r2 = radius * 2,
                w = tft.width()  + radius,
                h = tft.height() + radius;

  // Screen is not cleared for this one -- this is
  // intentional and does not affect the reported time.
  start = micros();
  for(x=0; x<w; x+=r2) {
    for(y=0; y<h; y+=r2) {
      tft.drawCircle(x, y, radius, color);
    }
  }

  return micros() - start;
}

unsigned long testTriangles() {
  unsigned long start;
  int           n, i, cx = tft.width()  / 2 - 1,
                      cy = tft.height() / 2 - 1;

  tft.fillScreen(ILI9341_BLACK);
  n     = min(cx, cy);
  start = micros();
  for(i=0; i<n; i+=5) {
    tft.drawTriangle(
      cx    , cy - i, // peak
      cx - i, cy + i, // bottom left
      cx + i, cy + i, // bottom right
      tft.color565(i, i, i));
  }

  return micros() - start;
}

unsigned long testFilledTriangles() {
  unsigned long start, t = 0;
  int           i, cx = tft.width()  / 2 - 1,
                   cy = tft.height() / 2 - 1;

  tft.fillScreen(ILI9341_BLACK);
  start = micros();
  for(i=min(cx,cy); i>10; i-=5) {
    start = micros();
    tft.fillTriangle(cx, cy - i, cx - i, cy + i, cx + i, cy + i,
      tft.color565(0, i*10, i*10));
    t += micros() - start;
    tft.drawTriangle(cx, cy - i, cx - i, cy + i, cx + i, cy + i,
      tft.color565(i*10, i*10, 0));
    yield();
  }

  return t;
}

unsigned long testRoundRects() {
  unsigned long start;
  int           w, i, i2,
                cx = tft.width()  / 2 - 1,
                cy = tft.height() / 2 - 1;

  tft.fillScreen(ILI9341_BLACK);
  w     = min(tft.width(), tft.height());
  start = micros();
  for(i=0; i<w; i+=6) {
    i2 = i / 2;
    tft.drawRoundRect(cx-i2, cy-i2, i, i, i/8, tft.color565(i, 0, 0));
  }

  return micros() - start;
}

unsigned long testFilledRoundRects() {
  unsigned long start;
  int           i, i2,
                cx = tft.width()  / 2 - 1,
                cy = tft.height() / 2 - 1;

  tft.fillScreen(ILI9341_BLACK);
  start = micros();
  for(i=min(tft.width(), tft.height()); i>20; i-=6) {
    i2 = i / 2;
    tft.fillRoundRect(cx-i2, cy-i2, i, i, i/8, tft.color565(0, i, 0));
    yield();
  }

  return micros() - start;
}

Please pare down your code to the absolute minimum. There is lots of code in there that is obviously superfluous.

Are you sure you have wired everything correctly? In particular:

In most cases I have seen, the source of the problem was incorrect wiring of MOSI and SCLK. Do not trust the default constructor, better use the constructor that specifies the values of those pins.
Check that the reset pin on your 9341 board is wired correctly.
Power the 9341 with 5V; if you feed it 3.3V, the voltage regulator will not be able to supply a high enough voltage for the controller to work correctly.

You also haven't mentioned what you are running this on!

yes m using 5V only and my wiring is proper also i changed the position in breadboard so many times to make sure if the problem is coming from breadboard but still nothing happened please help