0
votes

I have an Arduino Mega 2560.

I want to connect it to ESP8266 aka ESP 01 module.

First i open and compile an empty sketch. When i start serial monitor, i write AT commands (like connect with WIFI) in serial monitor and i click on send button. In this case all works fine.

After I tested that the commands works properly , I want to write an Arduino sketch in which I implement the function to automatically send command without writing it in serial monitor.

For this purpose, i write this code:

#define SSID "test"
#define PASS "1111"

void connectWiFi() {
Serial.write(“AT+CWJAP=\"SSID\",\"PASS\""); 
}

void setup() {

Serial.begin(9600);

connectWiFi();

}

void loop() {
}

When i try to execute the code in Serial monitor, it is printed only the string but the command does not work.

Why when i write this command in serial monitor works and when i try the code above, the command does not work?

Is there a way to pass and execute a command from arduino sketch? What is the problem in my code if is wrong?

Thanks in advance for response.

Sorry for my English.

1
What exactly is this supposed to do? Most of the running code is commented out. And how is your module connected? To the software serial or hardware serial? You are not actually reading anything back. - gre_gor
I edit post. However it's connected to hardware serial. - Federico
Try to use the println function like Serial.println("YOUR AT COMMAND"); instead of the write function - Fruchtzwerg

1 Answers

2
votes

Serial.write(...) makes arduino write through its serial ports (i.e. USB or pins 0 and 1). A better way to make Arduino send instructions directly to ESP is by defining "software serial" pins to communicate with ESP.

You'll need to include SoftwareSerial.h and use SoftwareSerial esp8266(2,3); for example to make pins 2 and 3 communicate serially with ESP.

Your code should look something like this:

#include <SoftwareSerial.h>

#define SSID "test"
#define PASS "1111"

SoftwareSerial esp8266(2,3);
void setup(){
  Serial.begin(9600);
  esp8266.begin(9600); //ensure this baudrate is similar to your ESP's
  delay(500); //give it some time

  esp8266.println(“AT+CWJAP=\"SSID\",\"PASS\""); //send to ESP this way
}

void loop(){
  if(esp8266.available()){
    while(esp8266.available()){
      Serial.write(esp8266.read()); //make serial monitor print what ESP sends
    }  
  }
}

You can also refer to this example for further detail