text:
ESP8266 sends data to the website but doesn't return status
I have problem with my esp8266 it connects to my site and sends 89 bytes of data but does return a confirmation status all i get is SEND OK but i don't get any confirmation from my server
This is my code below
 #include <SoftwareSerial.h>
#include<time.h>

SoftwareSerial ESP8266(3, 2); // RX, TX
//DEFINE ALL GLOBAL VAARIABLES HERE
unsigned int timeout_start_val;
char scratch_data_from_ESP[20];//first byte is the length of bytes
char payload[150];
byte payload_size=0, counter=0;
char ip_address[16];
char youtube_subs[10];
char youtube_views[13];
char current_temp[5];
char hi_temp[5];
char lo_temp[5];

//MODES
const char CWMODE = '3';//CWMODE 1=STATION, 2=APMODE, 3=BOTH
const char CIPMUX = '1';//CIPMUX 0=Single Connection, 1=Multiple Connections
//PASS word

const char SSID_ESP[]="Xamel";//"AOTEA TZ";//from constant

const char SSID_KEY[]="cewu5103";//"wyrnC592";

//DEFINE KEYWORDS HERE
const char keyword_OK[]="OK";
const char keyword_FAIL[]="FAIL";
const char keyword_Ready[] = "Ready";
const char keyword_no_change[] = "no change";
const char keyword_blank[] = "#&";
const char keyword_ip[] = "192.";
const char keyword_rn[] = "\r\n";
const char keyword_quote[] = "\"";
const char keyword_carrot[] = ">";
const char keyword_sendok[] = "SEND OK";
const char keyword_linkdisc[] = "Unlink";
const char keyword_CHECKCWMODE[] = "+CWMODE:3";
const char keyword_URL_CONNECTION_ERROR[]="Link typ ERROR";
const char TEST_URL[]="";

const char GET_URL[]="GET /ESP8266_BackEnd/SaveDetail.php?Name=";
int str1=strlen(GET_URL);
const char Name[]="Alex ";
int str2=strlen(Name);

const char TRAILING_URL[]="HTTP/1.1 \\r\\nHost: www.pick2get.com\\r\\n\\r\\n";
int str3=strlen(TRAILING_URL);
int strTotal=str1+str2+str3;

const char AT_CIPSTART[]="AT+CIPSTART=4,\"TCP\",\"pick2get.com\",80 \r\n";
const char AT_CIPSEND[]="AT+CIPSEND=4,";
//function prototype
boolean read_until_ESP(const char keyword1[], int key_size, int timeout_val, byte mode);
void serial_dump_ESP();
boolean setup_ESP(const char SSID_ESP[],const char SSID_KEY);
String url="&School=4D616B6F6E676F";
void setup() {
  // Open serial communications and wait for port to open:
  Serial.begin(9600);
  while (!Serial) {
    ; // wait for serial port to connect. Needed for native USB port only
  }

  //.print("Total string length");Serial.println(strTotal);

  // set the data rate for the SoftwareSerial port
  ESP8266.begin(9600);
  //

  //Serial.println(read_until_ESP(keyword_URL_CONNECTION_ERROR,sizeof(keyword_URL_CONNECTION_ERROR),5000,0));
  setup_ESP(SSID_ESP,SSID_KEY);

  ESP8266.print(AT_CIPSTART);
  ESP8266.print("");
  delay(1000);

  ESP8266.print(AT_CIPSEND);
  ESP8266.print(strTotal);
  ESP8266.print("\r\n");
  delay(1000);
  ESP8266.print("");
  ESP8266.print(GET_URL);
  ESP8266.print(Name);
  ESP8266.print(TRAILING_URL);
  delay(1000);
  ESP8266.print("");
  //ESP8266.println("&Grade=466F726D204F6E65");
  //ESP8266.println("&DeviceIP=3139322E3136382E302E31");
  //ESP8266.println(TRAILING_URL);

}

void loop() { // run over and over
  byte buffer[300];
  if (ESP8266.available()) {
   Serial.write(ESP8266.read());
  }
  if (Serial.available()) {
    ESP8266.write(Serial.read());
  }
}

This is the output generated on the serial monitor
ESP CHECK OK
ESP RESET OK
ESP RESET OK
timeout
ESP CWMODE SET FAILED
CWMODE ALREADY SET
SETTING SSID_ESP: Xamel
SETTING SSID_KEY: cewu5103
ESP SSID SET OK DEVICE CONNECTED
CHECKING FOR AN IP ADDRESS
IP ADDRESS = 192.168.4.1
ESP CIPMUX SET
AT+CIPSTART=4,"TCP","pick2get.com",80

OK
Linked
AT+CIPSEND=4,89

> GET /ESP8266_BackEnd/SaveDetail.php?Name=Alex HTTP/1.1 \r\nHost: www.pick2get.com\r\n\r\n
SEND OK

OK
Unlink

Can any one please help here.
When adding ESP8266.print("+IPD\r\n"); this is the output i get
    ESP CHECK OK
ESP RESET OK
ESP RESET OK
timeout
ESP CWMODE SET FAILED
CWMODE ALREADY SET
SETTING SSID_ESP: Xamel
SETTING SSID_KEY: cewu5103
ESP SSID SET OK DEVICE CONNECTED
CHECKING FOR AN IP ADDRESS
IP ADDRESS = 192.168.4.1
ESP CIPMUX SET
AT+CIPSTART=4,"TCP","pick2get.com",80

AT+CIPSEND=4,89

busy p...

OK
Linked
GET /ESP8266_BackEnd/SaveDetail.php?Name=Alex HTTP/1.1 \r\nHost: www.pick2get.com\r\n\r\n

wrong syntax

ERROR
AT+IPD

ERROR

I have managed to fix the lack of server response by removing the \r\n \nd replacing them with regular \r\n\r\n
enter code here
const char TRAILING_URL[]="HTTP/1.1 \r\nHost: www.pick2get.com \r\n\r\n";
int str3=strlen(TRAILING_URL);
int strTotal=str1+str2+str3;

const char AT_CIPSTART[]="AT+CIPSTART=4,\"TCP\",\"pick2get.com\",80 \r\n";
const char AT_CIPSEND[]="AT+CIPSEND=4,";

At this lines and was able to get a server response
+IPD,4,392:HTTP/1.1 400 Bad Request
Date: Tue, 15 May 2018 12:07:08 GMT
Server: Apache
Content-Length: 226
Connection: close
Content-Type: text/html; charset=iso-8859-1

400 Bad Request
Bad Request
Your browser sent a request that this server could not understand.

finally i have debugged and fixed all the errors and the code works just fine
This and server returns a status 200
turns out it was just me pointing GET request in the wrong folder path with this line code at in the GET_URL variable
const char GET_URL[]="GET pick2get.com/ESP8266_BackEnd/SaveDetail.php?Name=";
I replaced with this
const char GET_URL[]="GET /ESP8266_BackEnd/SaveDetail.php?Name=";
And got the desired result
+IPD,4,166:HTTP/1.1 200 OK
Date: Tue, 15 May 2018 12:2249 GMT
Server: Apache
Upgrade: h2
Connection: Upgrade
Transfer-Encoding: chunked
Content-Type: text/html
2
OK
+IPD,4,191:16
Connected successfully
5c
 DATA TRANSMITTED SUCSSEFULLYSTUDENT NAME RECIVED: AlexSTUDENT SCHOOL NAME RECIVED:
3b
STUDENT GRADE RECIVED: DEVICE IP ADDREESS RECIVED:
OK
+IPD,4,42:1f
New record created successfully
0
Thanks a lot guys below is the complete working code
    /*
  Software serial multple serial test

 Receives from the hardware serial, sends to software serial.
 Receives from software serial, sends to hardware serial.

 The circuit:
 * RX is digital pin 10 (connect to TX of other device)
 * TX is digital pin 11 (connect to RX of other device)

 Note:
 Not all pins on the Mega and Mega 2560 support change interrupts,
 so only the following can be used for RX:
 10, 11, 12, 13, 50, 51, 52, 53, 62, 63, 64, 65, 66, 67, 68, 69

 Not all pins on the Leonardo and Micro support change interrupts,
 so only the following can be used for RX:
 8, 9, 10, 11, 14 (MISO), 15 (SCK), 16 (MOSI).

 created back in the mists of time
 modified 25 May 2012
 by Nolawi solomon

 */
#include <SoftwareSerial.h>
#include<time.h>

SoftwareSerial ESP8266(3, 2); // RX, TX
//DEFINE ALL GLOBAL VAARIABLES HERE
unsigned int timeout_start_val;
char scratch_data_from_ESP[20];//first byte is the length of bytes
char payload[150];
byte payload_size=0, counter=0;
char ip_address[16];

//MODES
const char CWMODE = '3';//CWMODE 1=STATION, 2=APMODE, 3=BOTH
const char CIPMUX = '1';//CIPMUX 0=Single Connection, 1=Multiple Connections
//PASS word

const char SSID_ESP[]="Xamel";//"AOTEA TZ";//from constant

const char SSID_KEY[]="cewu5103";//"wyrnC592";

//DEFINE KEYWORDS HERE
const char keyword_OK[]="OK";
const char keyword_FAIL[]="FAIL";
const char keyword_Ready[] = "Ready";
const char keyword_no_change[] = "no change";
const char keyword_blank[] = "#&";
const char keyword_ip[] = "192.";
const char keyword_rn[] = "\r\n";
const char keyword_quote[] = "\"";
const char keyword_carrot[] = ">";
const char keyword_sendok[] = "SEND OK";
const char keyword_linkdisc[] = "Unlink";
const char keyword_CHECKCWMODE[] = "+CWMODE:3";
const char keyword_URL_CONNECTION_ERROR[]="Link typ ERROR";
//const char TEST_URL[]="";

const char GET_URL[]="GET /ESP8266_BackEnd/SaveDetail.php?Name=";
int str1=strlen(GET_URL);
const char Name[]="Alex ";
int str2=strlen(Name);

const char TRAILING_URL[]="HTTP/1.1\r\nHost: www.pick2get.com \r\n\r\n";
int str3=strlen(TRAILING_URL);
int strTotal=str1+str2+str3;

const char AT_CIPSTART[]="AT+CIPSTART=4,\"TCP\",\"pick2get.com\",80 \r\n";
const char AT_CIPSEND[]="AT+CIPSEND=4,";
//function prototype
boolean read_until_ESP(const char keyword1[], int key_size, int timeout_val, byte mode);
void serial_dump_ESP();
boolean setup_ESP(const char SSID_ESP[],const char SSID_KEY);
//String url="&School=4D616B6F6E676F";
void setup() {
  // Open serial communications and wait for port to open:
  Serial.begin(9600);
  while (!Serial) {
    ; // wait for serial port to connect. Needed for native USB port only
  }

  //.print("Total string length");Serial.println(strTotal);

  // set the data rate for the SoftwareSerial port
  ESP8266.begin(9600);
  //

  //Serial.println(read_until_ESP(keyword_URL_CONNECTION_ERROR,sizeof(keyword_URL_CONNECTION_ERROR),5000,0));
  setup_ESP(SSID_ESP,SSID_KEY);

  ESP8266.print(AT_CIPSTART);
  ESP8266.print("");
  delay(1000);

  ESP8266.print(AT_CIPSEND);
  ESP8266.print(strTotal);
  ESP8266.print("\r\n");
  delay(1000);
  ESP8266.print("");
  ESP8266.print(GET_URL);
  ESP8266.print(Name);
  ESP8266.print(TRAILING_URL);
  //delay(3000);
  //ESP8266.print("");
  //delay(2000);
  //ESP8266.print("\r\n");
  //delay(2000);
  //ESP8266.print("");
  //ESP8266.print("AT+IPD\r\n");
  //ESP8266.println("&Grade=466F726D204F6E65");
  //ESP8266.println("&DeviceIP=3139322E3136382E302E31");
  //ESP8266.println(TRAILING_URL);

}

void loop() { // run over and over
  byte buffer[300];
  if (ESP8266.available()) {
   Serial.write(ESP8266.read());
  }
  if (Serial.available()) {
    ESP8266.write(Serial.read());
  }
}

boolean read_until_ESP(const char keyword1[], int key_size, int timeout_val, byte mode){
  timeout_start_val=millis();//for the timeout
  char data_in[20];//this is the buffer - if keyword is longer than 20, then increase this
  int scratch_length=1;//the length of the scratch data array
  key_size--;//since we're going to get an extra charachter from the sizeof()

 //FILL UP THE BUFFER
 for(byte i=0; i<key_size; i++){//we only need a buffer as long as the keyword

            //timing control
            while(!ESP8266.available()){//wait until a new byte is sent down from the ESP - good way to keep in lock-step with the serial port
              if((millis()-timeout_start_val)>timeout_val){//if nothing happens within the timeout period, get out of here
                Serial.println("timeout");
                return 0;//this will end the function
              }//timeout
            }// while !avail

    data_in[i]=ESP8266.read();// save the byte to the buffer 'data_in[]

    if(mode==1){//this will save all of the data to the scratch_data_from
      scratch_data_from_ESP[scratch_length]=data_in[i];//starts at 1
      scratch_data_from_ESP[0]=scratch_length;// [0] is used to hold the length of the array
      scratch_length++;//increment the length
    }//mode 1

  }//for i

//THE BUFFER IS FULL, SO START ROLLING NEW DATA IN AND OLD DATA OUT
  while(1){//stay in here until the keyword found or a timeout occurs

     //run through the entire buffer and look for the keyword
     //this check is here, just in case the first thing out of the ESP was the keyword, meaning the buffer was actually filled with the keyword
     for(byte i=0; i<key_size; i++){
       if(keyword1[i]!=data_in[i])//if it doesn't match, break out of the search now
       break;//get outta here
       if(i==(key_size-1)){//we got all the way through the keyword without breaking, must be a match!
       return 1; //return a 1 and get outta here!
       }//if
     }//for byte i

    //start rolling the buffer
    for(byte i=0; i<(key_size-1); i++){// keysize-1 because everthing is shifted over - see next line
      data_in[i]=data_in[i+1];// so the data at 0 becomes the data at 1, and so on.... the last value is where we'll put the new data
    }//for

           //timing control
            while(!ESP8266.available()){// same thing as done in the buffer
              if((millis()-timeout_start_val)>timeout_val){
                Serial.println("timeout");
                return 0;
              }//timeout
            }// while !avail

    data_in[key_size-1]=ESP8266.read();//save the new data in the last position in the buffer

      if(mode==1){//continue to save everything if thsi is set
      scratch_data_from_ESP[scratch_length]=data_in[key_size-1];
      scratch_data_from_ESP[0]=scratch_length;
      scratch_length++;
    }//mode 1

    /*  JUST FOR DEBUGGING
    if(ESP8266.overflow())
    Serial.println("*OVER");
    */

  }//while 1

}//read until ESP

boolean setup_ESP(const char SSID_ESP[],const char SSID_KEY[]){//returns a '1' if successful

  ESP8266.print("AT\r\n");// Send just 'AT' to make sure the ESP is responding
  //this read_until_... function is used to find a keyword in the ESP response - more on this later and in the function itself
  if(read_until_ESP(keyword_OK,sizeof(keyword_OK),5000,0))//go look for keyword "OK" with a 5sec timeout
    Serial.println("ESP CHECK OK");
  else
    Serial.println("ESP CHECK FAILED");
  serial_dump_ESP();//this just reads everything in the buffer and what's still coming from the ESP

   ESP8266.print("AT+RST\r\n");// Give it a reset - who knows what condition it was in, better to start fresh
  if(read_until_ESP(keyword_Ready,sizeof(keyword_Ready),5000,0))//go look for keyword "Ready" - takes a few seconds longer to complete
    Serial.println("ESP RESET OK");//depneding on the FW version on the ESP, sometimes the Ready is with a lowercase r - ready
  else
    Serial.println("ESP RESET FAILED");
  serial_dump_ESP();
  ESP8266.print("AT+RST\r\n");// Give it a reset - who knows what condition it was in, better to start fresh
  if(read_until_ESP(keyword_Ready,sizeof(keyword_Ready),5000,0))//go look for keyword "Ready" - takes a few seconds longer to complete
    Serial.println("ESP RESET OK");//depneding on the FW version on the ESP, sometimes the Ready is with a lowercase r - ready
  else
    Serial.println("ESP RESET FAILED");
  serial_dump_ESP();

   ESP8266.print("AT+CWMODE=");// set the CWMODE
   ESP8266.print(CWMODE);//just send what is set in the constant
   ESP8266.print("\r\n");
  if(read_until_ESP(keyword_OK,sizeof(keyword_OK),1000,0))//go look for keyword "OK"
    Serial.println("ESP CWMODE SET");
  else

    Serial.println("ESP CWMODE SET FAILED");//probably going to fail, since a 'no change' is returned if already set - would be nice to check for two words
    ESP8266.println("AT+CWMODE?");
    if(read_until_ESP(keyword_CHECKCWMODE,sizeof(keyword_CHECKCWMODE),1000,0))
    {
      Serial.println("CWMODE ALREADY SET");
      serial_dump_ESP();
    }
    serial_dump_ESP();

   //Here's where the SSID and PW are set
   Serial.print("SETTING SSID_ESP: ");
   Serial.println(SSID_ESP);
   Serial.print("SETTING SSID_KEY: ");
   Serial.println(SSID_KEY);
   //DEbug poin

   ESP8266.print("AT+CWJAP=");//
   ESP8266.print("\"");
   ESP8266.print(SSID_ESP);//
   ESP8266.print("\",\"");
   ESP8266.print(SSID_KEY);//
   ESP8266.print("\"\r\n");
  if(read_until_ESP(keyword_OK,sizeof(keyword_OK),5000,0)==1)//go look for keyword "OK"
    Serial.println("ESP SSID SET OK DEVICE CONNECTED");
  else if(read_until_ESP(keyword_FAIL,sizeof(keyword_FAIL),5000,0)==1)
    Serial.println("ESP SSID SET FAILED");
  serial_dump_ESP();

  //This checks for and stores the IP address
  Serial.println("CHECKING FOR AN IP ADDRESS");
  ESP8266.print("AT+CIFSR\r\n");//command to retrieve IP address from ESP
  if(read_until_ESP(keyword_rn,sizeof(keyword_rn),10000,0)){//look for first \r\n after AT+CIFSR echo - note mode is '0', the ip address is right after this
  if(read_until_ESP(keyword_rn,sizeof(keyword_rn),1000,1)){//look for second \r\n, and store everything it receives, mode='1'
    //store the ip adress in its variable, ip_address[]
    for(int i=1; i<=(scratch_data_from_ESP[0]-sizeof(keyword_rn)+1); i++)//that i<=... is going to take some explaining, see next lines
       ip_address[i] = scratch_data_from_ESP[i];//fill up ip_address with the scratch data received
//i=1 because i=0 is the length of the data found between the two keywords, BUT this includes the length of the second keyword, so i<= to the length minus
//size of teh keyword, but remember, sizeof() will return one extra, which is going to be subtracted, so I just added it back in +1
    ip_address[0] = (scratch_data_from_ESP[0]-sizeof(keyword_rn)+1);//store the length of ip_address in [0], same thing as before
    Serial.print("IP ADDRESS = ");//print it off to verify
    for(int i=1; i<=ip_address[0]; i++)//send out the ip address
    Serial.print(ip_address[i]);
    Serial.println("");
  }}//if first \r\n
  else
  Serial.print("IP ADDRESS FAIL");
  serial_dump_ESP();

   ESP8266.print("AT+CIPMUX=");// set the CIPMUX
   ESP8266.print(CIPMUX);//from constant
   ESP8266.print("\r\n");
  if(read_until_ESP(keyword_OK,sizeof(keyword_OK),5000,0))//go look for keyword "OK" or "no change
    Serial.println("ESP CIPMUX SET");
  else
    Serial.println("ESP CIPMUX SET FAILED");
  serial_dump_ESP();

 //that's it!  Could be done by nesting everything together, so if one thing fails, it returns '0', and if it gets all the way through it returns '1'...oh well

}//setup ESP

//pretty simple function - read everything out of the serial buffer and whats coming and get rid of it
void serial_dump_ESP(){
  char temp;
  while(ESP8266.available()){
    temp =ESP8266.read();
    delay(1);//could play around with this value if buffer overflows are occuring
  }//while

}//serial dump

What happens when you write +IPD\r\n as the next AT command? (https://github.com/espressif/ESP8266_AT/wiki/IPD)

@MaximilianGerhardt Can you elaborate more i am pretty much a beginner with the esp8266

I think you have to send this additional AT command to receive the data. Add ESP8266.print("+IPD\r\n"); as the last statement in your setup function. Refer to https://www.espressif.com/sites/default/files/documentation/4a-esp8266_at_instruction_set_en.pdf

I have added that AT command and it seems there is a syntax error

Edit your question with the updated code and the error then.

Can you try the command "+IPD,500\r\n". This should request 500 bytes from the conenction. Try to play around with the number.

\\r\\n; are you sure you need to double escape those newlines?

@Gerben thanks alot apparently by replacing \r\n with the regular \r\n worked i am getting a response back apparently it status 400 but its progress still :)

@Gerben have ever had a situation where esp8266 would just hang after sending get request

I haven’t really done anything with an ESP. Try figuring out where the program halts. Most of the times it’s just a software problem. If the program sporadically stops working, you could look into enabling the WatchDog.

You need to have "Connection: keep-alive" in your http header, default is "Connection: close" and that's why you never get anything in return from the server.
I have described it all together with a code sample in https://arduino.stackexchange.com/a/54558/48149
The code sample uses the library WifiEsp to connect to ESP8266.

Yeah thanks i fixed that along time ago but still much respect for your contribution


text:
Using a 3V latching relay to power up ESP8266
I'm trying to use a 2-Coil Latching Relay like TXS2SA-L2-3V for  powering up a ESP8266. My idea is to activate the relay by setting the first coil to high and deactivate the coil by setting the second coil to high. In my circuit i will set the second coil to high at the end of the code by the esp8266. I need the latching (holding the power) function of it. Because when somebody activtes the Deep Sleep function to early, I have no electricity to power the esp8266.
My question is:
What kind of circuit I must use? I have no idea where I can start.
I have a regulator that can be enabled via de EN signal.
Thanks in advance!

I've read your question twice, but it's still unclear to me what your actual question is.

My idea is to activate the relay by setting the first coil to high...? How?

deactivate the coil by setting the second coil to high. ...? How?

You control a latching relay of this sort in the exact same way as a normal relay. What is your problem?

You use a latching relay of this form in the exact same way as a normal relay - it's just there's two of them.
One coil you want to control with a button (power on) and the other with a transistor (and possibly an "off" button as well).

simulate this circuit – Schematic created using CircuitLab
Press ON to latch the relay into the ON position (NO -> COM). Activate M1 or press OFF to latch the relay into the OFF position (NC -> COM).

Excellent! Thank you for your help. What kind of transistor can I use? Both ESP8266 and the relay work with 3V3. Thanks in advance.

If use an n MOSFET with a VGS below 2v.

I have great luck with the IRLZ44N on 8266s; cheap w/low rds+vgsth

source: Stack Exchange

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

sort: votes


text:
ESP8266 WiFi Module disconnects from WiFi itself

#define id "qwerty"
#define password"123456789"
int relayPin= 4;
void setup()
{
  Serial.begin(115200);

  Serial.println("AT");
  pinMode(13, OUTPUT);
  pinMode(relayPin, OUTPUT);
  delay(3000);

  if (Serial.find("OK")) {
    Serial.println("AT+CWMODE=1");
    delay(2000);
    String connectionCommand= String("AT+CWJAP=\"") + id+ "\",\"" + password+ "\"";
    Serial.println(connectionCommand);
    delay(5000);
    Serial.println("AT+CIFSR");
    delay(50);
    Serial.println(Serial.read());
  }

  Serial.print("AT+CIPMUX=1\r\n");
  delay(200);
  Serial.print("AT+CIPSERVER=1,80\r\n");
  delay(1000);
}
void loop() {
  if (Serial.available() > 0) {
    if (Serial.find("+IPD,")) {
      String metin = " Hello World ";
      metin += "
<button type='button'>ON</button>";
      metin += "
<button type='button'>OFF</button>";
      String cipsend = "AT+CIPSEND=";
      cipsend += "0";
      cipsend += ",";
      cipsend += metin.length();
      cipsend += "\r\n";
      Serial.print(cipsend);
      delay(500);
      Serial.println(text);
      lock_open_close();
      //Serial.println("AT+CIPCLOSE=0");

    }
  }
}

void lock_open_close() {
  String coming= "";
  char readonserial;
  while (Serial.available() > 0) {
    readonserial= Serial.read();
    coming+= readonserial;

  }
  Serial.println(coming);
  if ((coming.indexOf(":GET /?pin=on") > 1)) {
    digitalWrite(13, HIGH);
    digitalWrite(relayPin, HIGH);
    delay(200);
  }
  if ((coming.indexOf(":GET /?pin=off") > 1)) {
    digitalWrite(13, LOW);
    digitalWrite(relayPin, LOW);
    delay(200);
  }
}

Here's my code. I connected ESP8266 with a relay and a solenoid lock, so that I am expecting to control the lock with the buttons. But ESP8266 disconnects itself. Any suggestions?
Thanks a lot.
Sincerely,
Y.

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


text:
Arduino SocketIO library not working over HTTPS
I am currently using this Socket.io library to be able to send data from the Adafruit Feather HUZZAH (based on ESP8266) to my NodeJS server. It works like a charm on my local webserver, never failing me. However, when I try the setup with the proper webapp hosted on Heroku, the command SocketIOClient::connect(host, port) fails and no connection is established with the webserver's SocketIO.
Since there is no mention of limitations with HTTPS connections, I assume that I might be doing something wrong. If the impossibility of having HTTPS connection is the case, however, is there any other way to send this kind of data through web sockets to a NodeJS server hosted on Heroku?

probably not an arduino question. But it is also hard to know what your doing when you don't post any code or error messages.   "Fails" can mean a lot of different things.

a lot of tls stuff doesn't work on the 8266 because of lack of power and the shared CPU

For anyone having the same issues with SocketIO and the ESP8266, this issue on Github explains how I solved it:

When specifying the host, avoid including the http:// or any other trailing slashes.
  So it became String host = "something.herokuapp.com";


text:
how to send data to 15 meters with KY-005
I am using the LED KY-005 as emitter and the KY-022 as a receiver, according to their specifications they reach 18 meters.
I have performed the tests and it supports more than ten meters, however after the 6 meters the data is not received correctly. For example, I send 0xa90 but any other value except the desired one arrives at the receiver.
Here I leave the connection diagram:

This is the code that I use to send data:
#include <IRremote.h>
IRsend irsend;

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

void loop()
{
   for (int i = 0; i < 50; i++) {
     irsend.sendSony(0xa90, 12); // Sony TV power code
     delay(40);
   }
}

the link to KY-022 is invalid

you only posted 1/2 the information

The link it's ok now.

I'm sure they've tested this in special conditions to better the results, with minimal external influences. Unless you know the testing procedure, there's no way of reproducing it.

Datasheet (http://www.datasheet4u.com/datasheet/T/L/1/TL1838-OpenImpulse.pdf.html) claims minimal 10m, typical 15m receiving distance with the "L5IR = 300MA" test signal. Now if we only knew what that was..

In the emitter breakout board there is only a LED, nothing more. Comments in the linked page of the supplier states, that the 5V pin of it is not connected to anything. This means you are driving the LED directly from the Arduinos pin, which cannot provide more than 40mA. The supplier states a forward current from 30 to 60mA. You can use a small MOSFET in combination with a resistor, that limits the current to maybe 55mA, to drive the LED indirectly.
With this you won't fry the pins hardware and can provide more current, which means the LED can shine brighter. If you can find out, what LED is actually used for this board, you can refer directly to its datasheet. I couldn't find a part number at the site.


text:
Connect one HC-05 "master" to two slaves at the same time
Does any one know what AT+CMODE=2 "slave loop" used for. As I try to connect one HC-05 master to two slaves using it, but it didn't work.
i donot know if AT+cmode=2 is used for connecting to multiple slaves or not as i want to know what is used for , i tried to understand what it do from the HC-05 datasheet but i didnot find anything useful about it excpet for what is this image

why do you think that AT+cmode=2 is used for connecting to multiple slaves? .... please provide a link to the source of your information

HC-05 CANNOT connect to more than one slave at a time. This wouldn't even make sense, since this is a bluetooth to serial/UART module. UART can only work between two devices, not more

AT+CMODEis mainly used for setting the address pairing purpose. What chrisl stated is exactly true, you cannot connect more than 1 slave to the master at a time. When you set the parameter as 2 you actually set a passive connection, a connection between master and slave to receive the remote Bluetooth master device data and send it back to the master device. It is like a feedback-loop, and is mainly related for testing the connectivity and other features of the PAN (Personal Area Network). So actually whatever is received from the master, is sent back again to the master by the slave.

Based on the documentation :
Slave (slave role)----Passive connection;
Slave-Loop----Passive connection, receive the remote Bluetooth master device data and send it back to the master device;
Master (master role)----Inquire the near SPP Bluetooth slave device, build connection with it positively, and build up the transparent data transmission between master and slave device.
More info here : http://www.linotux.ch/arduino/HC-0305_serial_module_AT_commamd_set_201104_revised.pdf
So if you want your HC-05 master send : AT+ROLE=1
If you want it to connect to a device safely send : AT+CMODE=0 but you have then to specify what address ( AT+BIND= )
If you want it to connect to all devices available send : AT+CMODE=1


text:
PWM should be applied to ENA or IN1/IN2 for L298N board for speed control
I am new to the Arduino stuff and I am using L298N to drive two DC motors. When I searched online for sample code, I noticed that there are two types of design.
One type uses analogWrite(pin, pwmOutput) to control PWM on IN1/IN2 pin to adjust speed, and the other uses digitalWrite(pin, HIGH/LOW) to control IN1/IN2 but use analogWrite(enA, pwmOutput) to control speed.
I guess probably both can work, but I just feel it is not right to apply PWM on the enable pin. Any suggestion from the experts?
One more thing, many people say L298N is obsolete. Would anyone please recommend a replacement motor drive module?

I'd use PWM on EN input. Motor will be driven in HIGH and left floating in LOW. The other method means it'll be shorted (= full on brake).
L298N is based on bipolar transistors. That means relatively big voltage drop between drivers Emitter and Collector (about 2V on each transistor), so there are big power losses (= heat).
Maybe something like LMD18200 could be used as unipolar replacement.

Thanks for your reply, but I don't think the other method means shorted. For examle, IN1 = LOW (one bridge lower arm ON) and IN2 is PWM (the other bridge upper arm PWM), or vice versa, is the common way used in discrete MOSFET H-bridge circuit.

So you have one pin connected to the 0V and second one is alternating between 0V and 12V (I've omitted voltage drops) - what happen, if your motor rotates and you connect both ends to the 0V? Well, with voltage drops that big as in L298N it's not such a big short, but still.

If both ends are connected to 0V, the motor terminals are temperarily connected together through the lower arms of the H-bridge. It is a short brake effect, but it shouldn't be a problem.

@roTor-roTor Except for lower efficiency, bigger losses on transistors... It might be interesting to measure RPMs vs current, minimal pulse width to start rotation from zero RPM ....


text:
Arduino Mega resets when DFPlayer speaker plugged into amp!
I have a MP3 DFPlayer Mini connected to a Mega2560. I'm using serial to control it. The Mega is powering/grounding the DFPlayer, and USB is powering the Mega. If I plug a small speaker directly to the DFPlayer speaker pins, I hear the audio as expected. Tracks play correctly, at the proper volume, etc.
I also have a 20w audio amplifier (MAX9744, and 20w speaker ofc), powered separately by a 12v DC wall plug. If I plug an iPod into that via the stereo jack, I hear nice loud audio, as expected. Everything is fine.
For months, I have had the DFPlayer speaker pins supplying audio into the headphone jack on the amplifier. It has been working perfectly. Until recently...
Now, for some reason, the Mega2560 instantly resets, and will continue to reset every couple of seconds while the speakers are plugged in to the amplifier. As soon as the line in stereo jack is removed from the amplifier, the Mega works again.
This has me completely stumped. This setup has previously been working perfectly, for several months. The amplifier is clearly affecting the Mega somehow (via the DFPlayer!), even when no audio is actively playing. But I'm stuffed if I can figure out where the problem is!
I appreciate any ideas and suggestions you may have.

Sounds as the ampifier is drawing too much current from the DFPlayer. Maybe try to add a resisitor between amplifier and DFPlayer to check for this. The resistor will reduce the possible current. So if I'm right the mega will then work as intended. I don't know why this would have happend though. Maybe some current rating exceeding

You should not connect the speaker outputs to an amplifier. There are separate outputs on the DFPlayer for doing that.

chrisl: The amp is drawing power from a totally separate source. The DFPlayer and Amplifier are connected in only one way - via stereo headphone jack.

majenko: which pins should I be using? The dac ones? If so, any ideas why it's been working just fine for months using the speaker out pins?

For externally amplified speakers, you should be feeding the DAC and GND pins to the amp's inputs.  Those DAC pins provide a signal that varies by a small number of volts and is shifted so that they're always positive.  This is in the range expected by small headphones (ear buds) and line level inputs to audio components like an amplifier.
The speaker pins on the DF Player mini are pre-amplified (a little tiny bit) to directly drive a very small speaker (like 2 Watts at 8 Ohms).  They are a differential signal that includes both positive and negative voltages (relative to GND).  Note that the two speaker outputs (SPK+ and SPK-) are not left and right, but two sides of a differential signal.  Based on the schematic on page 11 of the datasheet (Chinese), it's a mono output made from mixing the outputs of the left and right DACs.
I could see how you might have gotten away with sending those to the amp, since the pre-amped speaker outputs are low power, and a good amp probably has input protection.
I don't know enough about electronics to know why it's failing now when it seemed to be working before.  It could be sensitive to the amplifier's gain or a ground loop between the power sources, but I'm just shooting in the dark.  Somehow, I suspect the DF Player Mini struggled to provide enough current to your amp, and since the DF Player Mini was powered from your Arduino, the Arduino essentially browned out, triggering a reset.

As Adrian McCarthy pointed out, you don't want to be running the speaker outputs into an amp like that. Use a DAC pin and Ground. As to why its stopped working - I've had trouble powering an arduino plus dfplayer from USB. The combination can quite easily draw more current than USB is designed to give. It's a bit fuzzy because not all USB supplies work exactly to proper spec. and exactly how much current you need can depend on factors as unpredictable as how much bass there is in your piece of music. If definitely nothing at all has changed in your setup, I would check in case you've got a joint going bad and shorting in the connection from the dfplayer to the amp...


text:
How to digital read and send the data through serial to PC with speed around 2 MHz?
I would like to read analog data with frequency sampling around 2 MHz and send it to PC to be processed with python for digital oscilloscope. I use Arduino Nano. I have found ADC (AD9057, PDF) that can handle up to 40 MSPS into 8 bits parallel, but I still face some problems

How could I read digital pin data quickly around 2-4 MHz? I read that it is possible using direct port manipulation.

How could I send the data to PC with that sampling rate? I know that the maximum baud rate of arduino is around 2.000.000 or let say 2 MegaBytes/s, so for 2 MHz sampling, i could only send one character per micro second, could it be more faster?

Thank you

ad 2. With asynchronous serial interface it's actually 2Mega bits, not mega bytes. In synchronous it's possible.

Read this and this. Actually you might just want to write assembly code to read a specific PORT (e.g. PORTD) and push it into the UART registers. If that is not sufficient, get a better, faster microcontroller (ESP8266 / ESP32). Also this might interesting.

Do you want do read analog values (using the ADC) vor digital data using the PIN registers directly? This is a huge difference and write both is your question.

@MaximilianGerhardt thanks mate, i'll read it

@KIIV what is it means with synchronous serial?

@chrisl i would like to read the incoming digital signal from external ADC

Then how do you have connected the external ADC to the Nano? What external ADC do you use? Please provide a link to a datasheet

For USART / UART read http://ww1.microchip.com/downloads/en/DeviceDoc/Atmel-42735-8-bit-AVR-Microcontroller-ATmega328-328P_Datasheet.pdf Chapter 24. With USART you have to send an additional clock signal, but can achieve a much higher speed.

@chrisl edited, the datasheet added

In short? You can't.
To have a 2MHz transmission you need 2*Nbit MHz of serial clock to send it to the PC, where Nbit is the number of bits per sample. Since the minimum is 8, englecting the synchronization or additional bits the serial clock has to be at least 16MHz. Which is the system clock of the nano. So no way.
Now, with the alternatives. First question: what is your ADC's interface? I found the LTC2204. It is a parallel ADC, so you need something to convert it to anything readable by the PC.
I'm not sure about the feasibility of this, but a nano is not enough. I'd use an STM32 (because I have their Nucleo boards, but you can search for other 32-bit boards) and a high speed serial interface. Since even SPI can be slow, maybe ethernet needs to be used. I was not able to search for boards with native ethernet interface; anyway the STM32F4 microcontrollers should (see this article) have an ethernet interface and you will "only" need the PHY. I think that this is the only applicable way to follow..


text:
How to change the value within a variable using math?
I'm up to Lesson 11 in the TopTechBoy tutorial: https://www.youtube.com/watch?v=afurKLOqqSg
Lesson 11 : http://www.toptechboy.com/arduino/lesson-11-arduino-circuit-to-dim-led-with-potentiometer/
I can use the analogRead() to fill a variable with a value and Serial.printld it out, but I want to be able to increase that integer by × 4.887585533
int pinV; // This empty variable will be filled with an integer value between 0 and 1023.
int receiverPin=0; // This is the RX pin, a ‘receiver’ that connects to the USB to Serial interface.
int ResultsPerSec=500; // The Arduino reads and prints out a result every half second.
float printingValue; // Another empty variable that is given the pinV value to multiply and print.
void setup() {
  Serial.begin(9600);
  pinMode(receiverPin,INPUT);
}

void loop() {
  pinV=analogRead(receiverPin);
  // Each Volt has a value of 204.6 (4.88 mV per integer of the 1023 available)
  printingValue = (pinV *4.887585533);
  // 5,000 mV divided by 1023 possible values = is 4.887585533 mV per integer
  // The Arduino can count from 0 to 5 Volts in 4.887585533 mV increments.
  // 1,000 mV divided by 4.887585533 mV = 204.599999989 integers out of the 1023 available equal 1V
  // Each integer of the 1023 possible values that analogRead() outputs can be increased by 4.887585533
  // This shows the real Voltage in millivolts (mV).
  Serial.println(printingValue);
  delay(ResultsPerSec);
}

This is actually acceptable as far as the IDE is concerned, but it doesn't work as intended. I'm getting outputs in the thousands, when it should be printing 0 in the Serial monitor. How do I do this properly?

I just got a reply from someone from one of the threads on https://8ch.net/tech/catalog.html
It turns out that the Digital pins (0,1,2,3,4,5,6,7,8,9,10,11,12,13) are not capable of reading Analog voltages. Pins A0 to A5 need to be used instead. Also, if not voltage is supplied, the Arduino will print random numbers in the Serial Monitor.

0 as parameter of analogRead is A0. you used A0. if pin is not connected to a circuit or ground it is called 'floating'

The page you linked to clearly shows analogue pin A0 being used for the reading. You seem to have thought that pin 0 (on the other side of the board) would be an acceptable alternative.

Its great how I can turn my Arduino into a voltmeter (As long as its below 5V). You can touch two wires on either ends of an AA battery and and see its voltage. But I wonder if the math is correct? Its been said that the float can only hold up to 7 numbers after the decimal (4.887585533 counts nine).

The voltage you should print is 5e3/1024*analogRead(A0). Ignore the tutorial using 1023: the datasheet is the only authoritative reference. 2. Floats do not hold decimals: they are binary, whith a machine epsilon of 2^(−23) ≈ 1.19e-7. The ratio 5e3/1024 is an exact float. 5e3/1023 is not, and the compiler rounds it to the nearest float, namely 4.88758563995361328125. The rounding error is inconsequential given the low resolution of the measurement.

https://gph.is/1dogvB3


text:
My code isn't adjusting the speed of one of the motors and i'm not sure why
I'm trying to change the speed of motors depending on the amount of light hitting the LDRs. Here i'm trying to make it so that if the LDR has a high value than another, then the motor associated with that LDR slows down so it turns towards the light.
const int motorDirectionA = 9;
const int motorEnableA = 10;
const int motorDirectionB = 5;
const int motorEnableB = 6;

const int leftLDR = A0;
const int rightLDR = A1;

int motorSpeedA = 250;
int motorSpeedB = 250;

void setup()
{
  Serial.begin(9600);
  pinMode(motorDirectionA,OUTPUT);
  pinMode(motorEnableA, OUTPUT);
  pinMode(motorDirectionB,OUTPUT);
  pinMode(motorEnableB, OUTPUT);

  pinMode(leftLDR, INPUT);
  pinMode(rightLDR, INPUT);

}

void loop()
{
  int ldrReadL = analogRead(leftLDR);
  int ldrReadR = analogRead(rightLDR);
  int leftLDRread = ldrReadL;
  int rightLDRread = ldrReadR;

  digitalWrite(motorDirectionA, LOW);
  analogWrite(motorEnableA, motorSpeedA);
  digitalWrite(motorDirectionB, HIGH);
  analogWrite(motorEnableB, motorSpeedB);

  Serial.print("Left LDR reading: ");
  Serial.println(ldrReadL);
  Serial.print("Right LDR reading: ");
  Serial.println(ldrReadR);

  if (leftLDRread > rightLDRread)
  {
    motorSpeedA = 80;
    motorSpeedB = 210;
  }
     else
     {
        motorSpeedA = 210;
        motorSpeedB = 210;
     }

  if (leftLDRread < rightLDRread)
  {
    motorSpeedB = 80;
    motorSpeedA = 210;
  }
      else
     {
       motorSpeedA = 210;
       motorSpeedB = 210;
     }
}

@Maximillian Gerhardt If the left LDR is picking up more light than the right LDR, the left motor should be assigned a 'speed' of 80 whilst the right motor has a speed of 210. If the right one has more intensity, then the right motor should be assigned a speed of 80 and the left motor assigned a speed of 210.
If they're both equal each motor should have a speed of 210 (although I dont have that included in the code).

Let leftLDRread = a and rightLDRread = b.
The two ifs don't make logical sense -- you are already covering the case a > b and in the else case a <= b.
If a > b it will go into the code of the first if clause and in the else clause of the second if, causing both motors to have equal speed, which is probably what you see. Can you describe more clearly to what value the motor speeds should be set if leftLDRRead is greater or smaller than rightLDRread?

You can always edit your question to include clarifications and delete that 'answer'. Again, try to write down your wanted logic more clearly. If the light intensity on the left sensor is greater than that one of the left, what motor speeds should be assigned? What if the right one has a bigger intensity? What if they're both of equal? If you edit your question to include that wanted behaviour, you'll probably see what code you need to write.

If the left LDR is picking up more light than the right LDR, the left motor should be assigned a 'speed' of 80 whilst the right motor has a speed of 210. If the right one has more intensity, then the right motor should be assigned a speed of 80 and the left motor assigned a speed of 210.
If they're both equal each motor should have a speed of 210 (although I dont have that included in the code).

In code you would express this as
void loop()
{
    int ldrReadL = analogRead(leftLDR);
    int ldrReadR = analogRead(rightLDR);
    int leftLDRread = ldrReadL;
    int rightLDRread = ldrReadR;

    digitalWrite(motorDirectionA, LOW);
    analogWrite(motorEnableA, motorSpeedA);
    digitalWrite(motorDirectionB, HIGH);
    analogWrite(motorEnableB, motorSpeedB);

    Serial.print("Left LDR reading: ");
    Serial.println(ldrReadL);
    Serial.print("Right LDR reading: ");
    Serial.println(ldrReadR);

    //assuming motorSpeedA is the left motor
    // left > right
    if (leftLDRread > rightLDRread) {
        motorSpeedA = 80;
        motorSpeedB = 210;
    } else if( leftLDRread < rightLDRread ) {
        //left < right
        motorSpeedA = 210;
        motorSpeedB = 80;
    } else {
        // left == right
        motorSpeedA = 210;
        motorSpeedB = 210;
    }
}

Also note that this is a quite primitive form of a PID controller. You want to respond to environmental influences in some kind of way, for which a PID is for.
You might find these videos interesting:

https://www.youtube.com/watch?v=1pKJ-KcHZ8g
https://www.youtube.com/watch?v=VVOi2dbtxC0

Edit: The code was fixed, a wrong variable was used (the pin number vs the read value)

@mymotordude Retry again. Edit your question if you'd like to comment (or register an account?)


text:
FastLed LED Strip Output Checksum
I am wondering if anyone has ever connected the output of their LED strip back to the Arduino to read and make sure the strip is functioning correctly, kinda like checksum functionality.
I am using the FastLed library and it doesn't appear that this has been done.
The reason why I want to do this is because when an LED breaks on the strip, it causes all of the following LEDs to flicker wildly. I need to be able to shut the LED strip off immediately if it starts flickering because my device is being used as a visual therapy aid in a school.
I am using an Arduino Due with WS2812B LED strip.

here is the data sheet .... http://www.seeedstudio.com/document/pdf/WS2812B%20Datasheet.pdf .... if you have 20 LEDs, you have to start to load the 21st LED before you see the output from the last one (20th) .... i do not think that you actually have to send 24 bits to the non-existent 21st LED

the timings are very fast and might be hard to read to inspect for bugs. a CDS on the last LED could detect erratic flashing, ands easy to consume w/MCUs, or maybe even an IC like a 555 missing edge detector.

another thought .... maybe use this for the 21st LED (see my previous post).... https://cdn-shop.adafruit.com/datasheets/WS2811.pdf ..... use three optocouplers instead of LEDs .... always send black to the 21st LED ... if any other values other than zero are received, then one or more of the optocouplers will conduct and cause a reset ............. you could also use a microcontroller to monitor the output of the LED string

Maybe the simplest solution would be to always set the last LED to black and place a photo resistor on top of it. If there is ever light output, I will know that the LED strip is malfunctioning.

Look at timing on sheet 4 of the datasheet, and the times on sheet 3
A Low bit is 400 +/- 150nS wide Low followed by a 800 +/- 150nS wide High
A High bit is 850 +/- 150nS wide High follow by a 450nS wide Low.
To do what you suggest with a checksum, you'd have to send the checksum (minimum of 3 bytes to fake the data for an extra WS2812B for example) first, and see if the 24 bits were received correctly while at the same time the last 3 bytes were being sent out.
A Due might be fast enough to do that. I don't think a 16 MHz Arduino could.
Checking power level is not really feasible, as many strips get power attached to the beginning, middle, and end of a strip to ensure uniform brightness and to keep the strip's power traces from overheating from excess current flow.

I don't think LED strips support this feature, however, probably there is a voltage reduction depending on how many LEDs are on. So you could check the voltage at the end of the strip, based on the LEDs which are on (assuming you store this) and compare the values.

WS2812 strips have a data out pin that outputs a copy of every input bit past the (24×n)-th, where n is the number of LEDs in the strip.


text:
Can I simulate a clock without an RTC connected?
I want to program for a timer that works as set timer such as in an oven where user can set their own time. One of the way I know is using an IC(RTC) for the timer. However, I don't have the IC yet only the coding and Arduino.
Is it possible to simulate the Arduino code without having the RTC? Or is there any electrical component that I can use to replace the IC for the time being?
Thank you for your help and comment.I really appreciate that.

You can, by using millis(), if you can tolerate the mediocre frequency accuracy of the ceramic resonator clocking the Arduino.

Yes, if you don't mind if your cake cooks for 1 hour or 1 hour and 5 seconds. :)

Are you referring to a RTC (Real Time Clock) chip?

Reply to Majenko: Yes the RTC chip.

TimeLib.h has a virtual clock that can be updated and corrected from multiple sources, including an RTC chip or an NTP server on the internet (assuming an internet connection).
It doesn't need that clock source, though, but it will drift with time. Once you have set the clock correctly it will keep close to the right time (assuming no reset or power loss of the Arduino). Not perfect (because the Arduino's main clock isn't perfect) but close enough for many simple applications.

There are programs to simulate Arduino code, but they are very limited. To really simulate the circuit the program would have to also know about the IC you are using. You didn't told us what IC this is, so we can only speculate, that it might not be something, that these programs know (though you can try it). And sometimes Arduino Simulators have problems with simulating time sensitive code. If you want to try, just google for Arduino Simulator and check out the possibilities. I cannot suggest one, since I didn't use one until now.
At this point it might be the better option to write time-keeping code using the millis() function, which returns the number of milliseconds since the Arduino started. Save a timestamp from when you started and compare the difference between millis() and your timestamp to the wanted bake time.
You can pack this code in extra functions, that can later be replaced by code managing the "timer IC". With dividing your code this way you can write the rest of the logic without bothering about the timing part (after writing the millis() part as a "dummy").
For an oven timer the accuracy of the Arduinos clock should be ok, since it doesn't really matter, if it is a few seconds off. And for testing and writing the first code version it is also sufficient.

If the IC you are referring  to is a RTC (Real Time Clock) module, the code for it should be pretty simple to write. There are libraries for the most common RTCs. You might want to try the Arduino Time library.


text:
ESP8266 Led is not working
My led is not blinking, I have no idea why it's not working.
I am running it on "generic esp8266 module" plate.
 /*Blink

  Turns an LED on for one second, then off for one second, repeatedly.

  Most Arduinos have an on-board LED you can control. On the UNO, MEGA and ZERO
  it is attached to digital pin 13, on MKR1000 on pin 6. LED_BUILTIN is set to
  the correct LED pin independent of which board is used.
  If you want to know what pin the on-board LED is connected to on your Arduino
  model, check the Technical Specs of your board at:
  https://www.arduino.cc/en/Main/Products

  modified 8 May 2014
  by Scott Fitzgerald
  modified 2 Sep 2016
  by Arturo Guadalupi
  modified 8 Sep 2016
  by Colby Newman

  This example code is in the public domain.

  http://www.arduino.cc/en/Tutorial/Blink
*/

// the setup function runs once when you press reset or power the board
void setup() {
  // initialize digital pin LED_BUILTIN as an output.
  pinMode(13, OUTPUT);
}

// the loop function runs over and over again forever
void loop() {
  digitalWrite(13, HIGH);   // turn the LED on (HIGH is the voltage level)
  delay(1000);                       // wait for a second
  digitalWrite(13, LOW);    // turn the LED off by making the voltage LOW
  delay(1000);                       // wait for a second
}

My scheme

Wifi module is working fine, but led is not working at all.

Another sketch
#include <ESP8266WiFi.h>
#include <WiFiClientSecure.h>
#include <UniversalTelegramBot.h>
#include <Servo.h>
// Initialize Wifi connection to the router
char ssid[] = "---";     // your network SSID (name)
char password[] = "---"; // your network key
int tempsensorPin = 0;
int lightsensorPin = 1;
bool searchState = false;
bool starting = false;
bool lightState = false;
Servo servo_test;
// Initialize Telegram BOT
#define BOTtoken "----"  // your Bot Token (Get from Botfather)

WiFiClientSecure client;
UniversalTelegramBot bot(BOTtoken, client);

int Bot_mtbs = 1000; //mean time between scan messages
long Bot_lasttime;   //last time messages' scan has been done

void setup() {
  //servo_test.attach(8);
  Serial.begin(115200);

  // Set WiFi to station mode and disconnect from an AP if it was Previously
  // connected
  WiFi.mode(WIFI_STA);
  WiFi.disconnect();
  delay(100);

  // Attempt to connect to Wifi network:
  Serial.print("Connecting Wifi: ");
  Serial.println(ssid);
  WiFi.begin(ssid, password);

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

  Serial.println("");
  Serial.println("WiFi connected");
  Serial.print("IP address: ");
  Serial.println(WiFi.localIP());
  pinMode(13, OUTPUT);
}

void loop() {
 digitalWrite(13,lightState);
  if (millis() > Bot_lasttime + Bot_mtbs)  {
    int numNewMessages = bot.getUpdates(bot.last_message_received + 1);

    while(numNewMessages) {
      Serial.println("got response");
      for (int i=0; i<numNewMessages; i++) {
        String id = bot.messages[i].chat_id;
        String text = bot.messages[i].text;

       //bot.sendMessage(bot.messages[i].chat_id, bot.messages[i].text, "");
        if(searchState){
          searchState=false;
          bot.sendMessage(bot.messages[i].chat_id, "http://lmgtfy.com/?q="+text, "");
        }else{
          bot.sendMessage(bot.messages[i].chat_id, answerMe(text), "");
        }
      }
      numNewMessages = bot.getUpdates(bot.last_message_received + 1);
    }

    Bot_lasttime = millis();
  }
}
String answerMe(String request){
 int tempSensor = analogRead(tempsensorPin);
 int lightSensor = analogRead(lightsensorPin);
 float voltage = tempSensor * 5.0;
 voltage /= 1024.0;
 Serial.print(voltage); Serial.println(" volts");
   float temperatureC = (voltage - 0.5) * 20 ;
 Serial.print(temperatureC); Serial.println(" degrees C");
 float temperatureF = (temperatureC * 9.0 / 5.0) + 32.0;
 Serial.print(temperatureF); Serial.println(" degrees F");
 if(starting){
  if (request=="/temperatureF"){
    return "Current temperature is " + String(temperatureF) + " F";
  }
  if (request=="/temperatureC"){
    return "Current temperature is " + String(temperatureC) +" C";
  }
  if(request=="/lightIntensity"){
    return "Current light intensity is " + String(lightSensor);
  }
  if(request=="/lightON"){
    lightState=true;
    return "Current light state is true!";
  }
  if(request=="/lightOFF"){
    lightState=false;
    return "Current light state is false!";
  }
  if(request=="/lightDepend"){
    analogWrite(13,lightSensor);
    return "Here we go!";
  }
  if(request=="/google"){
    searchState=true;
    return "What you want to google?";
  }
  if(request=="close"){
    starting=false;
    servo_test.write(0);
    return "Bye bye!";
  }
}else if(request=="/open"){
    starting=true;
    servo_test.write(90);
    return "What's next?";
}else
    return "Open the box first!";

}

You are uploading ESP8266 code to the Arduino???

or his uploading Blink with pin 13 to esp8266 and expects the led on Arduino to blink

I think he's compiling for the ESP8266 (I am running it on "generic esp8266 module" plate.) but uploading it to the Arduino. Maybe. It's a common mistake that you select the ESP8266 as your target when it's a mere peripheral to the Arduino that you are actully programming.

the upload would fail, or not? 250+ kb? if I see it right RX is to RX and TX to TX

yep it's rx to rx and tx to tx and it works

So you're running code on the ESP8266 and expecting it to magically blink the LED on the Arduino?

@Juraj updated, i've changed tx to rx and tx to rx now led is blinking while code compile but upload fails warning: espcomm_sync failed
error: espcomm_open failed
error: espcomm_upload_mem failed
error: espcomm_upload_mem failed

The esp8266 will not blink the LED on pin 13 or any other pin of the Uno. It has no access to pins of Uno. And your analogRead calls return some random values.
The RX to RX, TX to TX connection reduces the Uno to an "USB to Serial" adapter for the esp8266. You upload the Blink to esp8266. If the Blink sketch would have the original LED_BUILTIN pin number, then the LED on the esp8266 module would perhaps blink.
After you changed the connection RX to TX and TX to RX, you can't upload to esp8266 because the esp8266 is not anymore connected to PC over USB.
If you want to read and write the pins of Uno from esp8266, use ConfigurableFirmata sketch in Uno and FirmataMaster library in esp8266.
Other option is to write your own sketch for Uno and handle the communication between esp8266 and Uno over Serial.
Or you can use the esp8266 as network adapter with some firmware (AT firmware or WiFi Link) and port your sketch to Uno.

So it's impossible to make this light blink even if i change pin to 11? sorry for being dumb

you can blink any pin on Uno with a sketch in Uno. but for what you want to use the esp8266 module?

i am using it to connect to the telegram bot and by its commands getting different sensor outputs such as light sensor and temperature sensor, i also want to blink   light but it's not working, i spent like 2 days to solve this problem but its not working at all

you plan to send commands or you have a working sketch?

i have working sketch, but i can't make my led working on it other modules working well

updated pls check it out

your analogRead calls return some random values from esp8266 pins. If you want to read and write the pins of Uno from esp8266, use ConfigurableFirmata sketch in Uno and FirmataMaster library in esp8266. Answer updated.

Probably you are not uploading the code to ESP8266. Instead the code is getting uploaded to the Arduino. You should Ground the GPIO1 and connect ESP8266 Reset to Arduino Reset. Then go to the Sketch and see if you have changed the Board from ARduino to ESP8266.

how could a 250kb big esp sketch be successful uploaded to Uno?


text:
attiny85: ISR not triggering for PCINT2?
I am using an attiny85 to read the fan speed reported by a pair of 4-wire fans. I had planned to attach the TACH output from the fans to pins 1 and 2, but I ran into a problem: I was able to handle interrupts on pin 1 without a problem, but I can't get the ISR to trigger for changes on pin 2.  Code demonstrating the problem looks like this:
#define PIN_LED 0
#define PIN_TACH2 2

void setup() {
  cli();
  pinMode(PIN_TACH2, INPUT_PULLUP);
  pinMode(PIN_LED, OUTPUT);

  GIMSK |= _BV(PCIE);
  PCMSK |= _BV(digitalPinToPCMSKbit(PIN_TACH2));
  sei();
}

void loop() {
  digitalWrite(PIN_LED, 1);
  delay(2000);
}

ISR(PCINT0_vect) {
  byte tach2;

  tach2 = (PINB & _BV(PIN_TACH2));

  if (! tach2) {
    digitalWrite(PIN_LED, 0);
  }
}

If I replace the definitions of PIN_TACH2 and PIN_TACH2_INT with
pin 1, such as...
#define PIN_TACH2 1
#define PIN_TACH2_INT PCINT1

...it works just fine (interrupts also works for pins 0 and 3).
Why can't I handle pin change interrupts for pin 2?
for @chrisl
This is just testing code. The LED remains on until the ISR fires, at which point it will go out for up to 2 seconds.  With interrupts attached to pins 1 or 3, it works as expected: a falling edge on the pin causes the LED to go off.
On pin 2, the ISR never triggers.

I don't quite understand, what your code should do. You are only turning the LED on every 2s. Explain further what you expect, what happens instead and what can you see using pins 1 or 3

PCINT should turn LED off. Within 2 seconds it will come on again. Simple testing code. With PCINT1/3 it apparently works (LED can be turned off) but not with PCINT2. Looks to me like it should work, but what do I know?

I assume there is a 1:1 mapping between pin numbers and PORTB bits?

@majenko it looks like it based on the datasheet.

You won't find that in the datasheet. You'll only find it in the source code or documentation for whatever core / board definition you are using.

The PCINT* constants are straight from the data sheet and refer to bits in the PCMSK register.  Looking at the board definition, it appears to follow the same pin numbering as the datasheet.

Ok, that all looks fine then. I must say I don't know why it's not working.

Do you have another attiny chip? The one you’re using could be damaged.

@Gerben I see the same behavior with a second attiny chip.

So, it turns out that it was a really stupid problem and entirely my fault, but I'm going to leave this question here in the hopes that it will prevent someone else from running into the same issue.
The answer is...
DISCONNECT THE PROGRAMMER BEFORE TESTING YOUR SKETCH
That's it.  With the programmer disconnected, it all behaves as expected.

Since this is the solution for your problem, please accept your answer as the correct one, so that others can see, that this was right

@chrisl, you have to wait for two days to accept your own answer.

I think 2 days passed already, its time


text:
Can I switch from Serial to SoftwareSerial at runtime with the same baud?
I'm trying to use a GPS and the Adafruit thermal printer module with an Arduino Nano in the same project (both use baud 9600) and was wondering if I could do something like in the code below? Basically, in the example I made, I'm getting the time from the GPS and when it's on the minute, it will call the printTime() method.
What I'm wondering is if it's okay to do what I did in my disableGPS, enablePrinter methods by ending the serial connection for GPS and starting it for my printer? I feel like this should work, but I don't fully understand serial connections.
If this doesn't work, is there an alternative I could do? I never need to read from GPS and write to the printer at the same time in code.
#include <Adafruit_Thermal.h>
#include <TinyGPS++.h>
#include <SoftwareSerial.h>
#define PrinterTXPin 6 // Arduino transmit  YELLOW WIRE  labeled RX on printer
#define PrinterRXPin 5 // Arduino receive   GREEN WIRE   labeled TX on printer

static const uint32_t baud = 9600;
//Printer
SoftwareSerial PrinterSerial(PrinterRXPin, PrinterTXPin);
Adafruit_Thermal printer(&PrinterSerial);
//we only want to print on the minute
boolean havePrinted = false;

//GPS
TinyGPSPlus gps;
TinyGPSDate lastDate;

void setup() {
  enableGPS();
}

void loop()
{
  if(gps.time.isValid() && checkDate(gps.time)){
    printTime(gps.time);
  }
}

boolean checkDate(TinyGPSTime theTime)
{
 if(theTime.second() == 0 && !havePrinted)
 {
    havePrinted = true;
    return true;
 }
 if(theTime.second() == 1){
    havePrinted = false;
 }
}

void printTime(TinyGPSTime theTime)
{
  //Disable since we can only have 1 serial connection per baud
  disableGPS();
  enablePrinter();

  printer.doubleHeightOn();
  printer.println(theTime.hour() + ":" + theTime.minute());
  printer.feed(1);

  disablePrinter();
  enableGPS();
}

void enablePrinter()
{

  PrinterSerial.begin();
  printer.begin();
  printer.wake();
}

void disablePrinter()
{
  printer.sleep();
  PrinterSerial.end();
}

void disableGPS()
{
  Serial.end();
}

void enableGPS()
{
  Serial.begin(baud);
}

your description is not completely clear ... are you connecting the printer and the GPS to the same serial pins?

Serial.end() does not take any parameters. So Serial.end(baud) is wrong

Hey jsotola, hardware serial Serial is done through the serial pins on the nano 0 and 1 while SoftwareSerial can use any digital pins (In this case PrinterTXPin and PrinterRXPin).
chrisl - noted.

I think you are missing what the baud rate is.  It is the speed at which the data is transmitted.   So the fact that your two devices are the same is not an issue.   It looks like from the code that your gps is connected to the hardware serial(pins 0,1 on uno) and the printer is on a software serial( pins 5,6)   If this is the case, there is no reason to turn off either of them, they can both work. In the case of using multiple SOFTWARE serial connections, only one can be 'listening' at any time, so you must switch between them. This is not the case in your code, as there is only one software serial connection.

Ohhh. Thank you so much! For some reason, I assumed all Serial transmissions were pooled into the same I/O and the baud had to be unique for each Serial device!


text:
Power consumption for arduino
I am using an Arduino SMD UNO r3 board ,and connecting thermal sensor MLX 90614 , wifi modem ESP 8266 , a buzzer and an arduino based sound sensor .
How much power distribution will it require ?
What should be the capacity of the battery ?

You need to create a power budget. This means pouring through the datasheets of each component and finding the max and nominal current consumption info and then summing it up. From this, you should be able to come up with a battery capacity value.
There is a great article called "What is a Power Budget" written by Chris Gammell (from The Amp Hour) that goes into power budgets in more detail. Here are the key items from that page:

So what is a power budget? Much like a budget you might have for your personal finances, a power budget shows where all the possible power will be used by a device to by breaking it down into components and categories.
As you can see, not much more is required than your datasheets and a spreadsheet type program. ... The first two columns (A&B) are simply identifiers to allow you to recognize which components correspond to which set of data. The next two columns (C&D) determine the multiplicative factor. If you have 5 components that contain 4 op amps per, then that will consume 20x the power of a device that has the same supply current needs but only one op amp per and there is only one on the board.  The next two columns (E&F) show how much current each individual component contributes and then the sum of all the components of that type contribute. Note that this parameter on a data sheet would be listed as “supply current” or “active current”. The “quiescient” number is when the device is in a resting state and will likely be much less than the active number (and not relevant for this example). Finally, the supply voltage is listed (in column G) to calculate power (using the formula P=I*V) which is listed in column I per device. All of these contributors are summed, an efficiency is estimated (I assumed a poor efficiency linear type supply) and the total power required input to the device is given. Further calculations could result from much of this initial data.


text:
Will Nodemcu support 4AAA
Will Nodemcu support 4AAA batteries which is 6v approx, or should i go with 3AAA batteries which is 4.5V approx. And one more question , is it ok to use AA instead of AAA ?

Yes, yes and yes.

Will Nodemcu support 4AAA batteries which is 6v approx

Yes, it will. However there is no back-powering protection on the USB, so having that connected whilst the board is connected to your computer could potentially damage your computer's USB port. That's why VIN's label was changed to 5V on the newer boards.

or should i go with 3AAA batteries which is 4.5V approx.

Yes, you should. Not only does that mean your USB port won't die, but you're not wasting as much power. The NodeMCU employs a linear "LDO" regulator to get 3.3V from the incoming power source. That means that the voltage difference between incoming power and 3.3V is thrown away as heat. The higher the incoming voltage the more heat is generated to discard that voltage.  Using a lower voltage, therefore, means that you don't waste as much. That fourth battery is doing absolutely nothing towards powering your project and is just being used to generate more heat.  One thing to note though is that 5V coming in from USB could try and charge your 3xAAA batteries. If they're not rechargeable then they could cause problems (overheat, leak, cause a fire, etc).  Adding a schottky diode in series with them would protect them from that.

is it ok to use AA instead of AAA ?

Yes. Your project will last longer before you need to replace the batteries, since AA batteries have a higher mAh capacity than AAA.

Thanks. How long do you think 3 AAA battery can last before replacing, approximately? Im connecting only one soil moisture sensor to the nodemcu.

I can't tell you that.

Can you suggest me someway , that the board gets power for atleast a month? I tried 9V battery, and conncted the positive and negative to Vin and Gnd. The board started working abnormally. I guess 9V battery is overloading the board

It is impossible to give any value. It all depends on your code and your hardware. To get that kind of length of operation of AAA batteries you will need to use some very aggressive power saving techniques (deep sleep modes, high efficiency regulators, isolated power domains, etc).

And 9V batteries are complete junk.

Not sure I can agree with the 3 cell recommendation.  While there are indeed risks in using 4, with 3 (especially if they are NiMH not alkaline) they will probably fail to meet the regulator minimum input voltage midway through what should be their usable life, ie, to get 3.3v out you need more the 4.3v in, and most people would not consider an AA measuring 1.4 volts "dead".   Going into regulator dropout does not automatically mean the board complete fails, but it's not really a good idea.  The truth of the matter is that the NodeMCU is not designed for battery power.

The ESP8255 can operate happily right down to 2.5V. LDOs really don't care if you go below the regulation threshold - especially if they are part of a family that has versions right down to say 0.8V (as most families do), since all that differs between them is the internal feedback network. You just get a (few) diode drop(s) worth of voltage reduction.

You don't have to connect any UART. This is done through USB serial communication. So, just copy the uf2 file to pico. Let it reboot. Then you should see a ttyS* or ttyACM* device shows up in /dev/ if PX4 is running fine. Then you can connect to it using putty or minicom.

What do uf2 files and the pico have to do with a nodemcu device?


text:
PCM library - Timer0
I would need a quick help if possible because I have a project with the deadline tomorrow night.
On my Uno (atmega328p in fact), I need to communicate with a SPI flash to transfer music and then, take this music (part by part) to play with the PCM library.
But, both libraries are using pin 11 (MOSI and speakPin) to work.
That's why I tried to change the source code in PCM.c https://github.com/damellis/PCM/blob/master/PCM.c, I just changed the timer 2 in timer 0.
That works but only for one song. With the timer 2 you can use several times the startPlayback() function but with the timer 0 it will work with only song.... I guess it's because timer 2 is asynchronous but not the timer 0.
I found this website : http://www.renar.net/?p=73&lang=en, that's why I hope it's possible with a synchronous timer and several song.
I hope you'll have some clues for me !
Here below my new code in PCM.c :
int speakerPin = 6;
volatile unsigned char *sounddata_data;
int sounddata_length=0;
volatile uint16_t sample;
byte lastSample;
volatile boolean counterReady;

// This is called at 8000 Hz to load the next sample.
ISR(TIMER1_COMPA_vect) {
if (sample >= sounddata_length) {
   if (sample == sounddata_length + lastSample) {
    stopPlayback();
    counterReady = true;
   }
   else {
    // Ramp down to zero to reduce the click at the end of playback.
    OCR0A = sounddata_length + lastSample - sample;
   }
 }
 else {
    OCR0A = pgm_read_byte(&sounddata_data[sample]);
 }

 ++sample;
}

void startPlayback(unsigned char *data, int length)
{
   sounddata_data = data;
   sounddata_length = length;

   pinMode(speakerPin, OUTPUT);

   // Set up Timer 2 to do pulse width modulation on the speaker
   // pin.

  // Use internal clock (datasheet p.160)
  ASSR &= ~(_BV(EXCLK) | _BV(AS2));

  // Set fast PWM mode  (p.157)
   TCCR0A |= _BV(WGM01) | _BV(WGM00);
   TCCR0B &= ~_BV(WGM02);

   // Do non-inverting PWM on pin OC2A (p.155)
   // On the Arduino this is pin 11.
   TCCR0A = (TCCR0A | _BV(COM0A1)) & ~_BV(COM0A0);
   TCCR0A &= ~(_BV(COM0B1) | _BV(COM0B0));

   // No prescaler (p.158)
   TCCR0B = (TCCR0B & ~(_BV(CS12) | _BV(CS11))) | _BV(CS10);

   // Set initial pulse width to the first sample.
   OCR0A = pgm_read_byte(&sounddata_data[0]);

   // Set up Timer 1 to send a sample every interrupt.

   cli();

   // Set CTC mode (Clear Timer on Compare Match) (p.133)
   // Have to set OCR1A *after*, otherwise it gets reset to 0!
   TCCR1B = (TCCR1B & ~_BV(WGM13)) | _BV(WGM12);
   TCCR1A = TCCR1A & ~(_BV(WGM11) | _BV(WGM10));

   // No prescaler (p.134)
   TCCR1B = (TCCR1B & ~(_BV(CS12) | _BV(CS11))) | _BV(CS10);

   // Set the compare register (OCR1A).
   // OCR1A is a 16-bit register, so we have to do this with
   // interrupts disabled to be safe.
   OCR1A = F_CPU / SAMPLE_RATE;    // 16e6 / 8000 = 2000

  // Enable interrupt when TCNT1 == OCR1A (p.136)
  TIMSK1 |= _BV(OCIE1A);

   lastSample = pgm_read_byte(&sounddata_data[sounddata_length-1]);
   sample = 0;
   sei();
}

void stopPlayback()
{
    // Disable playback per-sample interrupt.
    TIMSK1 &= ~_BV(OCIE1A);

   // Disable the per-sample timer completely.
   TCCR1B &= ~_BV(CS10);

   // Disable the PWM timer.
   TCCR0B &= ~_BV(CS10);

   digitalWrite(speakerPin, LOW);
}

Or is it maybe cause the Timer0 remapping destryys millis and delay, causing hickups in your SPI driver? If you do load the music data chunkwise via SPI (from an SD card I presume), does it play the entire song correctly or only the first chunk?

I guess it's because timer 2 is asynchronous but not the timer 0 - what do you mean by that? I don't think the timers differ in asynchronousity (if that is a word, which I gather it isn't).

@NickGammon: Unlike Timer 0, Timer 2 can be operated in asynchronous mode (independent of the main clock). But this mode is not used here, so this is not relevant.

Try keeping Timer 2, but switchin to pin OC2B (Arduino pin 3). Just replace in the original code OCR2A → OCR2B, and swap COM2A0 ↔ COM2B0, COM2A1 ↔ COM2B1.

@NickGammon synchronicity is a word. Not sure about its opposite though...  (asynchronicity ... yes, Grammarly likes it. )

@EdgarBonet Oh yeah, good point.


text:
General confusion about how to start
I want to test around with my ESP32 and an E-Paper display - yet i am stuck at uploading sketches via Arduino IDE. I get those kind of errors:
avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x48

and looking into tools,i dont even see my board there - i bought it on amazon and the article just says "ILS - LOLIN32 Lite V1.0.0 Wifi and Bluetooth Board with ESP-32 Rev1 MicroPython 4MB FLASH".
What am i missing here? I am 99% sure i got the pins correct (finally), i got the USB-Serial driver, i got the right port - yet even a simple test sketch i found on the internet didnt work.

Uh.. have you installed ESP32 support in the Arduino IDE and have the correct board selected? Can you include a screenshot of your Arduino IDE when you try to upload the code?

what do you mean, "installed ESP32 support"? and i highly doubt i have the correct board selected i tried uploading multiple times on different board - but i dont know how to find out what board exactly i have in the IDE that. here is a screenshot: https://ibb.co/crQQLd

In the lower right corner you can see you have selected "Arduino Uno" board on COM3 as your target device. That's not what you want. You need to install the ESP32 Core for the Arduino IDE to be able to use the ESP32 boards and select it under Werkzeuge -> Board. Try to follow these instructions and check back if it worked: https://github.com/espressif/arduino-esp32/blob/master/docs/arduino-ide/windows.md or https://www.smart-prototyping.com/blog/How%20to%20Install-ESP32-Core-Arduino-IDE

aah, i never heard of such thing being required to install - i always thought that ESP32 is just a generic name for those dev boards and that arduino boards are ESP32 with different specs. thanks, i will try to get that working for now

Clarification: "Arduino" is a framework / core. It is a set of functions (like millis(), digitalWrite(), digitalRead(), so to say. There are very different Arduino-Compatible boards (most famous: Arduino Uno / Nano / Mega, ESP8266, ESP32, STM32..). But since these boards are all from entirely different architecture (AVR vs XTensa vs ARM ..), they all need a different implementation of the Arduino Core. Thus you need to extend your Arduino IDE with more Cores for different board types to use them with the Arduino Framework.

Now i understand - i guess its a little like a driver for Arduino running on my LOLIN32?

alright, everything set up, now it seems to be working (at least more than before) - but i get this error: (it appears twice, the first two words mean "invalid library"):
Ungültige Bibliothek C:\Program Files (x86)\Arduino\hardware\espressif\esp32\libraries\BLE in C:\Program Files (x86)\Arduino\hardware\espressif\esp32\libraries\BLE gefunden

You must execute a recursive git pull in Arduino/hardware/esp32: https://github.com/espressif/arduino-esp32/issues/766 . Did you install it by the downloaded ZIP file or via a git pull? Seems like you need the git pull, because the github ZIP doesn't contain sub-gits.

i downloaded the ZIP and i think i got all files i need via the python script that was included - i get a lot more feedback from the IDE now, it seems to be working, after pressing "upload" it ends with "leaving" and "hard resetting via RTS pin" - dont know if thats a good thing yet, i couldnt see any results on the board or on the display yet

I'd need a full log / screenshot for that. What exact sketch are you running? Can you try running the sketch https://github.com/espressif/arduino-esp32/blob/master/libraries/WiFi/examples/WiFiScan/WiFiScan.ino and look at the serial monitor at 115200 baud?

yes! i can see entries using the sketch you provided - i was using a LED  blinking sketch i found online and that did not blink the big blue LED on the board - the next step i want to take is using the example sketch for a 7.5" e-paper display that i got from the arduino folder, but uploading that never did anything even with (i suppose) correct pin mapping

You should be able to blink the LED if you remove LED_BUILTIN for 22 in the example blink sketch (see schematics here and here. However, connecting an E-Paper display should be posted as a different question with more information (code, wireup, ..).

i am confused - i used this sketch: http://www.arduino.cc/en/Tutorial/Blink
on my LOLIN32 but i only see a small, red LED blinking - i suppose that is not the right one, and it doesnt blink every 1 second aswell. what is that "LED_BUILTIN for 22" that you are talking about? excuse me if i am overlooking something obvious here

In the code, LED_BUILTIN appears 3 times. Replace every LED_BUILTIN by the number 22. The LED is on pin number 22 as I've shown you in the schematic diagram. Very likely LED_BUILTIN is just wrongly set by default. You're probably seeing that "CHARGE" LED flicker, not the one labeled "22"?

that might be true, now i understand - the sketch comments say that the LED_BUILTIN is set to the right pin by default - and yes, the 22 fixed it, thanks a lot - now i can finally move to the e-paper after fiddling around for more than a week!

The Arduino IDE does not have a core for the ESP32 installed by default.
The problem was solved by explicitly installing the ESP32-Arduino Core in the Arduino IDE according to their manuals

https://github.com/espressif/arduino-esp32/blob/master/docs/arduino-ide/windows.md
https://www.smart-prototyping.com/blog/How%20to%20Install-ESP32-Core-Arduino-IDE


text:
Share I2C pins with other device when lacking GPIOs
We're Using ESP12E as our MCU and we have three functionality :

SIM800 connected to TX(GPIO1), RX(GPIO3)
Matrix Keypad connected to GPIOs: 14,13,2,10,0,4,5,16
GLCD connected to GPIOs: 15,12

And we also need to communicate with an RTC(DS3231) module via I2C bus!
So i'm wonder how we could do this?
Is it possible to share I2C pins with any other pins ?
And BTW for some reason we can't use IO expander such as PCF8574

Why can't you use a IO expander? It'll save you those 8 pins needed for the matrix keypad. Can you use any other external IC?

Yeah i know, that's a great IC but for now we've some restriction on PCB and some other issue on supply

GLCD (graphical LCD) connected via two wires? How is that possible, it usually requires far more wires? If this is already an I2C bus device, just put the RTC module on the exact same lines? I2C is a bus after all..

@MaximilianGerhardt  It's a ST7920 GLCD with 3 Wire software SPI using this nice lib:https://github.com/olikraus/u8g2 , also we're in serial mode so cs is chip enable and is connected to logic 1

Then if you used another display with same characteriscs (columns, lines, ..) but with a I2C interface, wouldn't your problems be solved? Then you have still 2 wires but with 2 devices on the I2C bus. Or throw in an I2C to SPI converter chip like NXP SC18IS602B.

Since you already want to use I2C it makes sense to move other things onto that same I2C bus to save IO pins.  And even off-load processing.
For instance, you could move your keypad to a dedicated matrix keypad interface chip, such as the MAX7365 (probably overkill for a small keypad), or a general I2C GPIO IO expander, such as the MCP23017.

We found 74C922 at long last! without any other choices.
A cheap, available, reliable and easy setup IC.
The simple schematic we use:

here is a good topic to start with


text:
HC-SR04 systematically finding a weird value
I have a HC-SR04 connected to my Arduino. its all working very nice. Yet with a constant interval a weird value appears (see the Serial Plot picture). I am wondering what causes this. I will soon upload my Sketch (Making it bit more readable).
Or are there to many possible factors that could influence the HC-SR04 behaviour that it is impossible to determine the cause?

Y-axis shows distance in cm, x-axis shows iteration (once a second)
Thanks in advance!
Kind Regards, a fellower Arduino User

It's probably less likely the HC-SR04 and more likely Arduino interrupts and micros() jitter.

Yes I am using millis() ! To make my distance sensor not lockup the remaining of the sketch

I am thinking more with the pulseIn() function that is commonly used for reading the HC-SR04. That uses micros() for the timing, and if that gets interrupted (by the timer0 millis() interrupt, or a serial interrupt, for instance) it could skew the results.

Sounds logic, aswell as I do use PulseIn and serial connection. Is there a way I can Predict when it occurs?

For absolute precision, you should be using one of the timer Input Compare peripherals, though I don't know of an Arduino library offhand that does it.


text:
How to set sampling rate for digital pin input?
I have an ADC that have sampling rate up to 40 MSPS, but i use 8 MHz clock so it will be 8 MSPS. The board used is arduino nano. The problem is i have to sampling it just 2 MHz (because the capacity of array variable in arduino Nano, which is around 10.000 elements in array variable). I know that using direct port reading will increase the speed of the digital read, but how can i set the direct port reading to just read every 0.5 us? Micros function cannot do the job of course
Thank you

On what board...?

@Majenko edited, Arduino Nano

You don't set the sampling rate for a digital pin. You sample it in software by readinging the appropiate PORTX register (C,D,..). 500 nanoseconds is pretty on the edge. Only reading the PORT will cost you 125ns (and that's NOT doing any SPI logic -- if you bitbang SPI then this will be ONE BIT!) (https://github.com/NicksonYap/digitalWriteFast/blob/master/NOTES/NOTES.md)

@MaximilianGerhardt how can i set it in the software? AFAIK, using timer wont work because there is no timer with resolution 500ns

You can sample a digital port at 2 MHz, or even as fast as F_CPU/3, while storing the data in an array, but: 1. This needs assembly programming and, 2. It is very likely not what you want to achieve.

Of course, sampling too quickly will not allow the internal capacitor to stabilize at the input voltage.  I agree with @MaximilianGerhardt that 500 ms is a reasonable speed, determined by delay().

You need:

A timer
A board that is capable of running fast enough to do what you want.

The Nano fits the first criteria, but not the second.
At 16MHz you get a clock period of 63ns.  That means you get a mere 8 clock ticks (actually gives you 504ns) per interruption from the timer. That's at most 8 assembly instructions that can be executed within that time.
Since an interrupt service routine's preamble is longer than 7 instructions you can see there would be a slight problem there.  No time for actually reading a digital IO port - and if you are using a serial protocol to communicate with your ADC you can multiply the reading time by the double the number of bits you need to read. That's a long time compared to 500ns.
So no. Think again. Use a more suitable board. Maybe an ARM based board (like the Teensy 3.x) would be a better fit.

Note: this is an attempt to answer the question as asked. This
answer is unlikely to be of any use to the original poster, who
presumably asked the wrong question. I am writing this only as a way to
explore the limits on how fast a modest AVR can sample a port. For an
answer that genuinely attempts to address the OP’s problem, see
Majenko’s answer.
I read the question as follows: can we sample a digital port at
2 MHz on an Arduino Nano clocked at 8 MHz? Can we do so while
storing the values in a RAM-based buffer?
The answer is yes, but it is non trivial, and it requires some assembly.
To see the problem, let’s start by trying to do it in C++:
uint8_t buffer[1024];

void fill_buffer()
{
    cli();
    for (size_t i = 0; i < sizeof buffer; i++)
        buffer[i] = PINB;
    sei();
}

Note that the loop runs with interrupts disabled, otherwise the timer
interrupt would wreak havoc with the loop timing. This is translated by
gcc into an assembly equivalent to this:
    cli
    ldi  r30, lo8(buffer)      ; load the buffer address into pointer Z
    ldi  r31, hi8(buffer)      ; ditto
0:  in   r24, 0x03             ; read the port
    st   Z+,  r24              ; store into buffer, increment the pointer
    ldi  r24, hi8(buffer+1024) ; save (buffer+1024)>>8 in r24
    cpi  r30, lo8(buffer+1024) ; compare the pointer with buffer+1024
    cpc  r31, r24              ; ditto
    brne 0b                    ; loop back
    sei
    ret

The loop takes 8 cycles per iteration. With an 8 MHz clock, that
would be one reading per microsecond. Too slow by a factor two.
One could save one cycle by using a different register for the port data
and for the end-of-loop condition, and by moving the third ldi out of
the loop. Another cycle could be saved by testing only the high byte of
the Z pointer, but that would require aligning the buffer to
256 byte boundaries. With those two optimizations, we still need
6 CPU cycles per iteration, i.e. 0.75 µs at 8 MHz.
In order to make this faster, the only solution is to unroll the loop.
This can be done in assembly by using the .rept (meaning “repeat”)
directive:
void fill_buffer()
{
    cli();
    asm volatile(
        ".rept %[count]\n"  // repeat (count) times:
        "in r0, %[pin]\n"   //   read the port input register
        "st Z+, r0\n"       //   store in RAM
        "nop\n"             //   1 cycle delay
        ".endr"
        ::      "z" (buffer),
        [count] "i" (sizeof buffer),
        [pin]   "I" (_SFR_IO_ADDR(PINB))
        : "r0"
    );
    sei();
}

This takes 4 cycles, or 0.5 µs per iteration. Note that a
delay cycle had to be introduced, otherwise the sampling would be too
fast : 3 cycles, or 0.375 µs, per iteration.
This is not the fastest one can get. It is possible to take one sample
per CPU cycle with something like this:
    in r0, 0x03
    in r1, 0x03
    in r2, 0x03
    ...

However this technique is limited to burst readings of at most
32 samples.


text:
Arduino HTTPClient passing string to variable
For some reason I can't seem to pass a simple string from one variable to another. Below is my code:
  HTTPClient http; // Declare an object of class HTTPClient
  http.begin(address); // Specify request destination
  int httpCode = http.GET(); // Send the request

  Serial.println("String: " + http.getString());

  String prp = http.getString();
  Serial.println("temp string: " + prp);

It prints out:

String: < ! DOCTYPE HTML>
  26
temp string:

Why doesnt my string get correctly passed on to my temporary string variable?
Tom

The getString() method calls writeToStream which is documented write all  message body / payload to Stream. It writes all the data of the http response to he output and doesn't store them internally. The next call has nothing to read because the first call to getString() put everything out.

Is there a way I can adapt my code so that it will still work?

isn't it obvious? read into variable and then print the value of the variable. remove the redundant println

Isn't that what I do? The first println works fine, it's the second one that's the problem!

you throw away the String used in first println. but the response was only in that String. call to getString put the received bytes into that String.