I am using ESP32, but I assume the question is applicable to esp8266 or Arduino WIFI. That is why I extended my tags. Please let me know if I am wrong.
I have a working sketch that uses WIFI to send http requests.
My current code includes SSID and password in clear text:
const char *ssid = "my_secure_router";
const char *password = "clear_text_password_is_bad";
void initWifi(){
WiFi.mode(WIFI_STA);
WiFi.begin(ssid, password);
Serial.println("");
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.println(WiFi.status());
Serial.print("*");
}
Serial.print("WiFi connected with IP: ");
Serial.println(WiFi.localIP());
}
While the code is working, I am not able to push the code to a git repository since it includes the password in clear text.
Is there any easy option to eliminate the clear text password from the above code?
People often do this by using a second file that's not checked into the repository. They'll often name the file secrets.h or config.h.
Then you'd change your code to look like:
#include "secrets.h"
void initWifi(){
WiFi.mode(WIFI_STA);
WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
Serial.println("");
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.println(WiFi.status());
Serial.print("*");
}
Serial.print("WiFi connected with IP: ");
Serial.println(WiFi.localIP());
}
and put this in secrets.h:
#pragma once
#define WIFI_SSID "my_secure_router";
#define WIFI_PASSWORD "clear_text_password_is_bad";
The #pragma line stops the file from being processed if it's included twice, which avoids errors from WIFI_SSID and WIFI_PASSWORD being defined multiple times.
Then add secrets.h to .gitignore so that git won't check it in.
As a bonus, you might create a secrets.h-example file that has dummy strings for all the secrets that are stored in it.
Note that I changed the two strings from being C++ character array variables to preprocessor constants. There's really no benefit in this case to storing the strings in variables, and using preprocessor constants simplifies their use.
Related
My WeMos D1 Mini is running a script that is supposed to perform certain actions if it receives certain strings in udp packets.
It works most of the time, but sometimes it just doesn't respond to anything.
Usually it's enough to just wait a few minutes or send the packet a couple of times. My guess is that it might go into some kind of deep sleep. Sometimes the only thing that helps is to restart it.
I tried implementing a watchdog but that didn't really work (but that's a separate issue) and i'm not sure if it would even solve the problem.
I'm sending the packets through Netcat and the WiFi strength is ok (but not great).
Everything is on the local network.
Please take a look at my code and check it for mistakes/improvements.
#include <ESP8266WiFi.h>
#include <WiFiUDP.h>
#define SSID "XXX"
#define PASSWORD "XXX"
#define PORT XXX
WiFiUDP udpServer;
char MESSAGE[] = "message";
void setup() {
Serial.begin(9600);
WiFi.mode(WIFI_STA);
WiFi.begin(SSID, PASSWORD);
wifiStrength();
udpServer.begin(PORT);
delay(100);
}
void wifiStrength(){
if (WiFi.status() != WL_CONNECTED) {
Serial.println("no wifi, reconnecting...");
delay(3000);
WiFi.begin(SSID, PASSWORD);
}
long rssi = WiFi.RSSI();
Serial.print("connected, RSSI:");
Serial.println(rssi);
}
void loop() {
if (udpServer.parsePacket()) {
char receiveBuffer[WIFICLIENT_MAX_PACKET_SIZE + 1];
udpServer.read(receiveBuffer, sizeof(receiveBuffer) - 1);
if (strstr(receiveBuffer, MESSAGE)) {
Serial.println("do stuff...");
}
}
}
I'm really in need of help with this problem and as most commonly advised, I have researched and researched and researched for days and I can't figure out what's wrong...
With that being said, I'm working on a project that uses an ESP-32S (pinout) and an A6 GSM module. (pinout) I'm attempting to get them connected to have the A6 send data to ThingSpeak... My problem is that I can't get it to work... I have the exact same configuration between the two using an ESP8266 and it connects and works but with the ESP32S it just doesn't seem to work...
Below is the code I have used to connect the 32 to the A6 and everything says success and pass but it won't change any ThingSpeak values using any methods...
#define TINY_GSM_MODEM_A6
#include "TinyGsmClient.h"
#include "ThingSpeak.h"
#define SerialMon Serial
HardwareSerial SerialAT(1);
bool modemConeted;
// Your GPRS credentials
// Leave empty, if missing user or pass
const char apn[] = "wireless.twilio.com";
const char user[] = "";
const char pass[] = "";
bool dataSent = false;
TinyGsm modem(SerialAT);
TinyGsmClient client(modem);
void setup(){
SerialMon.begin(9600);
delay(1000);
gsmModSetup();
}
void gsmModSetup() {
// Set GSM module baud rate
SerialAT.begin(9600, SERIAL_8N1, 27, 26, false); //27 and 26 are the pins on the ESP32S connected to the U_Rxd/U_Txd pins of A6
delay(3000);
SerialMon.println("Initializing modem...");
modem.init();
delay(3000);
String modemInfo = modem.getModemInfo();
SerialMon.print("Modem: ");
SerialMon.println(modemInfo);
SerialMon.print("Waiting for network...");
if (!modem.waitForNetwork()) {
SerialMon.println(" fail");
delay(10000);
return;
}
SerialMon.println(" OK");
SerialMon.print("Connecting to ");
SerialMon.print(apn);
if (!modem.gprsConnect(apn, user, pass)) {
SerialMon.println(" fail");
delay(5000);
return;
}
SerialMon.println(" OK");
}
void loop(){
}
I'm using a Twilo Sim card that's loaded with data (as said above it works with esp8266 so not the SIM and not the board) The only part of this code that doesn't pass is the part that says GPRS connect. it never says pass or fail. It just sits for like five minutes then continues.
After this, I try and post to ThingSpeak and it gives ThingSpeak ERROR-307 which means failed to connect to ThingSpeak...
I have tried 2 different ways
The what I find the easy and normal way
ThingSpeak.setField(1, temp);
ThingSpeak.setField(2, h);
ThingSpeak.setField(3, p);
ThingSpeak.setField(4, pt);
ThingSpeak.writeFields(myChannelNumber, myWriteAPIKey);
and the more complicated way of connecting to the server then sends a GET command with all the values put together with strings.
if (client.connect(thingSpeakAddress, 80))
{
client.print("POST /update HTTP/1.1\n");
client.print("Host: api.thingspeak.com\n");
client.print("Connection: close\n");
client.print("X-THINGSPEAKAPIKEY: " + WriteAPIKey + "\n");
client.print("Content-Type: application/x-www-form-urlencoded\n");
client.print("Content-Length: ");
client.print(thingSpeakData.length());
client.print("\n\n");
client.print(thingSpeakData);
}
client.stop();
Yet neither work and I don't know what to do... My A6 is connected to the 32 using GPIO26 & 27 they're connected to the A6 U_Rxd/U_Txd pins. All boards share common ground as they should.
Any more guides to read or code to change or libraries to try would be extremely helpful as my days of digging has yielded nothing but frustration as one attempt after another fails. the readers of this really are my last hope in solving this problem that's hindering my farther progression.
(Any questions about anything on my end, please ask. -Thank you)
The enclose documentation shows ESP32S pins for HW Serial 0 RX/TX on pin GIPO01/GIPO03, HW Serial 1 RX/TX on pin GIPO09/GIPO10 Given you have attached no oter HW at the moment, why not try with the basic config with serial1Read about this: https://github.com/G6EJD/ESP32-Using-Hardware-Serial-Ports and use the latest core ESP32 package (as of today 23.3.2020 is 1.04, previous releases had issues with serial. Do notforget to setup the serial a given in the article its different to esp8266 (!) so much about code compability. If you use the code on both platforms, you have to work with
#ifdef ESP32
//configure serial for esp32
#elif ESP8266
//configure serial for esp8266
#else
#error "Hardware not supported"
#endif
Here a small test routine for just the serial communication. If you type something in the input line of serial monitor it should be mirrored in the output window
#include <HardwareSerial.h>
void setup() {
Serial.begin(9600);
// set the data rate for the HardwareSerial port
Serial2.begin(9600);
}
void loop() {
if (Serial2.available()) {
Serial.write(Serial2.read());
}
if (Serial.available()) {
Serial2.write(Serial.read());
}
}
You can then expand the serial2 to your settings. If it fails it may be dueto: U1UXD is unused and can be used for your projects. Some boards use this port for SPI Flash access though - so try Serial3.
I want to send my microphone data wirelessly to labview and then I want to do some post processing over that data like FFT, amplification and stuffs like that.
How should I proceed exactly?
I have researched a lot about this but didn't find any sufficient answer to this.
I have setup my microcontroller and the microphone module and i am able to get values on the serial monitor.
I have also connected my nodemcu to my AP and thought to use esp8266 as a web-server so that I can send the data to labview but cant possibly do it.
This is my current code:
#include <ESP8266WebServer.h>
#include <ESP8266WiFi.h>
int val=0;
ESP8266WebServer server(80);
void setup() {
// put your setup code here, to run once:
Serial.begin(115200);
const char* id = "****";
const char* pass = "****";
WiFi.begin(id,pass);
while(WiFi.status()!=WL_CONNECTED)
{
delay(500);
Serial.print(".");
}
Serial.print("Connected successfully to: ");
Serial.println(id);
Serial.print("The IP address is: ");
Serial.println(WiFi.localIP());
server.begin();
}
void loop() {
// put your main code here, to run repeatedly:
server.handleClient();
int val= analogRead(0);
Serial.println(val);
server.send(200,"text/html",String(val));
}
I am trying to develop an IoT device that should provide some functionality using a HTTP/REST API. I decided to use the ESP32 chip (on "ESP32 dev board").
Now I want to implement an easy-to-use WLAN configuration. I don't want to store credentials in my source code like many other samples do; so I decided to use WPS.
I tried to implement a basic web server using the sources here:
https://randomnerdtutorials.com/esp32-web-server-arduino-ide/ - and then I added the WPS functionality from the Wifi/WPS samples shipped with the EPS32 extensions for Arduino IDE.
Now the WPS already works, i.e. when the dev-board gets powered it is in WPS connection mode and waits for the router to accept the WPS connection. It successfully gets the SSID and connects to the WLAN.
But when I power-off the ESP32, and power-on again, I have to do the WPS reconnection procedure again. I'd expect a reconnection, that stores the credentials and is able to connect to the same WLAN again when the ESP32 device is powered-on at any time later. I guess I have to store some credentials and use them to re-establish the connection - but where do I get the credentials, and how do I reconnect?
I did search the web for "ESP32 WLAN WPS reconnect" and similar terms, but did find only reconnect strategies for non-wps (SSID + password) connections. I did also check the WiFi library documentation and the esp_wps library documentation, but didn't find anything suitable.
That's the WLAN WPS connection source:
#include <WiFi.h>
#include "esp_wps.h"
#define ESP_WPS_MODE WPS_TYPE_PBC
esp_wps_config_t config = WPS_CONFIG_INIT_DEFAULT(ESP_WPS_MODE);
String wpspin2string(uint8_t a[]){
//...
}
void WiFiEvent(WiFiEvent_t event, system_event_info_t info){
switch(event){
case SYSTEM_EVENT_STA_START:
Serial.println("Station Mode Started");
break;
case SYSTEM_EVENT_STA_GOT_IP:
Serial.println("Connected to :" + String(WiFi.SSID()));
Serial.print("Got IP: ");
Serial.println(WiFi.localIP());
break;
case SYSTEM_EVENT_STA_DISCONNECTED:
Serial.println("Disconnected from station, attempting reconnection");
WiFi.reconnect();
break;
case SYSTEM_EVENT_STA_WPS_ER_SUCCESS:
Serial.println("WPS Successfull, stopping WPS and connecting to: " + String(WiFi.SSID()));
esp_wifi_wps_disable();
delay(10);
WiFi.begin();
break;
case SYSTEM_EVENT_STA_WPS_ER_FAILED:
Serial.println("WPS Failed, retrying");
esp_wifi_wps_disable();
esp_wifi_wps_enable(&config);
esp_wifi_wps_start(0);
break;
case SYSTEM_EVENT_STA_WPS_ER_TIMEOUT:
Serial.println("WPS Timedout, retrying");
esp_wifi_wps_disable();
esp_wifi_wps_enable(&config);
esp_wifi_wps_start(0);
break;
case SYSTEM_EVENT_STA_WPS_ER_PIN:
Serial.println("WPS_PIN = " + wpspin2string(info.sta_er_pin.pin_code));
break;
default:
break;
}
}
// some GPIO stuff, removed for SO question
void setup() {
// initialize some GPIO for status etc. - removed for SO
//Initialize serial and wait for port to open:
Serial.begin(115200);
while(!Serial) {
; // wait for serial port to connect. Needed for native USB port only
}
// We start by connecting to a WiFi network
WiFi.onEvent(WiFiEvent);
WiFi.mode(WIFI_MODE_STA);
Serial.println("Starting WPS");
esp_wifi_wps_enable(&config);
esp_wifi_wps_start(0);
// attempt to connect to Wifi network:
while(WiFi.status() != WL_CONNECTED) {
// Connect to WPA/WPA2 network. Change this line if using open or WEP network:
delay(700);
Serial.print(".");
}
Serial.println("WiFi connected");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
server.begin();
}
void loop() {
//irrelevant for SO question
}
The ESP, both 32 and 8266, remember the last AP it was connected to. So simple call WiFi.begin(); without any credentials will make it connect to that last AP. Then in your while(WiFi.status() != WL_CONNECTED) loop you could make it timeout and then call the esp_wifi_wps_start(0); if it does not connect.
you can find the answer here https://www.esp32.com/viewtopic.php?f=19&t=27004
the SSID and password are stored in the config and given to esp_wifi_set_config, after WPS has finished, you can just use the getter function again by calling:
wifi_config_t config;
esp_err_t err = esp_wifi_get_config(WIFI_IF_STA, &config);
if (err == ESP_OK) {
printf("SSID: %s, PW: %s\n", (char*) config.sta.ssid, (char*) config.sta.password);
} else {
printf("Couldn't get config: %d\n", (int) err);
}
and you can then find the SSID and password in that struct again.
The problem is that I want to execute the code below, but when ESP8266 is shut down, then I start it again, everything is gone.
So, is there a solution that I can make this ESP8266 work the same controlled by my Arduino Uno.
My program blow is to control the GPIO2 through web browser.
Thanks a lot to all of you!!
My Codes:
#include <ESP8266WiFi.h>
#include <aREST.h>
// Create aREST instance
aREST rest = aREST();
// WiFi parameters
const char* ssid = "Protect Big Dragon 4";
const char* password = "18717772056";
// The port to listen for incoming TCP connections
#define LISTEN_PORT 80
// Create an instance of the server
WiFiServer server(LISTEN_PORT);
void setup(void)
{
// Start Serial
Serial.begin(115200);
// Give name and ID to device
rest.set_id("2");
rest.set_name("lamp_control");
// Connect to WiFi
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("WiFi connected");
// Start the server
server.begin();
Serial.println("Server started");
// Print the IP address
Serial.println(WiFi.localIP());
}
void loop() {
// Handle REST calls
WiFiClient client = server.available();
if (!client) {
return;
}
while(!client.available()){
delay(1);
}
rest.handle(client);
}
So your ESP8266 loses your code when it is rebooted.
Sounds like the memory is faulty.
Try a different ESP8266 and let us know what occurs.