ESP-32 Camera only capture's once then re-sends the same frame buffer, or bugs - tcp

I've setup an ESP-32 Camera, specifically the: Freenove ESP32-WROVER CAM Board
The TCP connection is fine. -
The issue is the ESP32 captures the image only once, and seems to continuously send the same buffer over and over again.
I've tried to set the fb (frame buffer) to NULL and try to re-initialize it, with the esp_camera_fb_get() function, however despite this, the Camera seems to be sending the same buffer over and over again (The capture that seems to happen only once at the beginning)
I've tried to re-initialize the ESP sensor settings aswell upon each loop iteration, didn't work either.
I've tried commenting out the esp_camera_fb_return(fb) function and putting it back, it breaks if this function isn't included. It's weird tho, it should just re-capture the img and reset the buffer. Even tried to pass it the pointer instead...
ESP 32 CODE , the pins.h header has all the pin definitions ( I think those are fine since the camera's image capture is working fine, it's to re-capture that the issue)
/*
* This sketch sends a message to a TCP server
*
*/
#include "esp_camera.h"
#include <WiFi.h>
#include <WiFiMulti.h>
//Pin definitions from header file `pins.h`
#include "pins.h"
#include "camera_handle.cpp"
WiFiMulti WiFiMulti;
camera_config_t config;
void config_init();
//static camera_fb_t get_img();
const char *ssid_Router = "OMITTED"; //input your wifi name
const char *password_Router = "OMITTED"; //input your wifi passwords
void setup()
{
Serial.begin(115200);
delay(10);
config_init(); //This function sets the `camera_config_t config` global var to the pins needed (defined in `pins.h`)
// camera init
esp_err_t err = esp_camera_init(&config);
if (err != ESP_OK) {
Serial.printf("Camera init failed with error 0x%x", err);
return;
}
sensor_t * s = esp_camera_sensor_get();
s->set_vflip(s, 0); //1-Upside down, 0-No operation
s->set_hmirror(s, 0); //1-Reverse left and right, 0-No operation
s->set_brightness(s, 1); //up the brightness just a bit
s->set_saturation(s, -1); //lower the saturation
// We start by connecting to a WiFi network
WiFiMulti.addAP(ssid_Router, password_Router);
Serial.println();
Serial.println();
Serial.print("Waiting for WiFi... ");
while(WiFiMulti.run() != WL_CONNECTED) {
Serial.print(".");
delay(500);
}
Serial.println("");
Serial.println("WiFi connected");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
delay(500);
}
void loop()
{
// const uint16_t port = 80;
// const char * host = "192.168.1.1"; // ip or dns
const uint16_t port = 8887;
const char *host = "10.0.0.160"; // ip or dns
Serial.print("Connecting to :");
Serial.println(host);
// Use WiFiClient class to create TCP connections
WiFiClient client;
int TCP_Connect = client.connect(host,port);
delay(20);
if (!TCP_Connect) {
Serial.println("Connection failed.");
Serial.println("Waiting 5 seconds before retrying...");
delay(5000);
return;
}
Serial.println("Connected to server ! ( OK )");
// This will send a request to the server
//uncomment this line to send an arbitrary string to the server
// for(int i = 0; i < 10; i++){
// client.print("Send this data to the server ");
// }
//camera_fb_t x = get_img();
camera_fb_t *fb = NULL;
fb = esp_camera_fb_get();
if(!fb) {
Serial.println("Camera capture failed...");
return;
} else {
Serial.println("Camera Captured ( OK )");
}
const char *data = (const char*)fb->buf; // ??? Lol
// Image metadata. Yes it should be cleaned up to use printf if the function is available
Serial.print("Size of image:");
Serial.println(fb->len);
Serial.print("Shape->width:");
Serial.print(fb->width);
Serial.print("height:");
Serial.println(fb->height);
client.write((char*)&(fb->width),sizeof(fb->width)); //Character Buffer for Width (bytes)
client.write((char*)&(fb->height),sizeof(fb->height)); //Character Buffer for Height (bytes)
// Give the server a chance to receive the information before sending an acknowledgement.
delay(1000);
//getResponse(client);
Serial.print(data);
client.write(data, fb->len);
esp_camera_fb_return(fb);
Serial.println("bottom of loop...");
// client.stop();
delay(2000);
}
void getResponse(WiFiClient client) {
byte buffer[8] = { NULL };
while (client.available() > 0 || buffer[0] == NULL) {
int len = client.available();
Serial.println("Len" + len);
if (len > 8) len = 8;
client.read(buffer, len);
}
}
void config_init() {
config.ledc_channel = LEDC_CHANNEL_0;
config.ledc_timer = LEDC_TIMER_0;
config.pin_d0 = Y2_GPIO_NUM;
config.pin_d1 = Y3_GPIO_NUM;
config.pin_d2 = Y4_GPIO_NUM;
config.pin_d3 = Y5_GPIO_NUM;
config.pin_d4 = Y6_GPIO_NUM;
config.pin_d5 = Y7_GPIO_NUM;
config.pin_d6 = Y8_GPIO_NUM;
config.pin_d7 = Y9_GPIO_NUM;
config.pin_xclk = XCLK_GPIO_NUM;
config.pin_pclk = PCLK_GPIO_NUM;
config.pin_vsync = VSYNC_GPIO_NUM;
config.pin_href = HREF_GPIO_NUM;
config.pin_sscb_sda = SIOD_GPIO_NUM;
config.pin_sscb_scl = SIOC_GPIO_NUM;
config.pin_pwdn = PWDN_GPIO_NUM;
config.pin_reset = RESET_GPIO_NUM;
config.xclk_freq_hz = 20000000;
config.frame_size = FRAMESIZE_QVGA;
config.pixel_format = PIXFORMAT_JPEG; // for streaming
//config.pixel_format = PIXFORMAT_RGB565; // for face detection/recognition
config.grab_mode = CAMERA_GRAB_WHEN_EMPTY;
config.fb_location = CAMERA_FB_IN_PSRAM;
config.jpeg_quality = 12;
config.fb_count = 1;
}

Related

ESP32: Add micro sd card reader on 2nd SPI bus

I am trying to create a music box for my son, but i am having some trouble getting the SD card to work.
The idea is that when we scan a RFID tag we should get the corresponding mp3 file from the SD card.
I am using:
a ESP32 DOIT DEVKIT V1
RFID reader is a RFID-RC522
Micro SD card reader has no brand or model number on it. It just says "Micro sd card adapter" on the back and has 6 pins: cs, sck, mosi, miso, vcc, gnd
My problem is that both the RFID reader and the Micro SD Card reader should use SPI.
With the following code the RFID Card is working well. I just have no idea on how to add the SD Card reader (i have tried using the same pins as the rfid reader and also the HSPI pins, but without success!)
Any help is much appreciated!
#include <SPI.h>
#include <MFRC522.h>
#include <WiFi.h>
#include <ESPAsyncWebServer.h>
#include <WebSocketsServer.h>
#include <ArduinoJson.h>
#include "web_index.h"
// Constants
const char *ssid = "****";
const char *password = "****";
const int dns_port = 53;
const int http_port = 80;
const int ws_port = 1337;
// Globals
AsyncWebServer server(80);
WebSocketsServer webSocket = WebSocketsServer(1337);
char msg_buf[10];
// Tag reader variables
#define RFID_RC522_RST_PIN 27
#define RFID_RC522_SDA_PIN 5
MFRC522 mfrc522(RFID_RC522_SDA_PIN, RFID_RC522_RST_PIN);
bool rfid_tag_present_prev = false;
bool rfid_tag_present = false;
int _rfid_error_counter = 0;
bool _tag_found = false;
// Volume Variables
int VOLUME = 15;
int VOLUME_NORMAL_MAX = 30;
int VOLUME_LIMIT_MAX = 15;
int VOLUME_MAX = VOLUME_NORMAL_MAX;
int VOLUME_MIN = 0;
int VOLUME_CHANGE_AMOUNT = 1;
bool VOLUME_IS_LIMITED = false;
// Player variables
bool IS_PLAYING = false;
String TRACK_NAME = "-";
String ARTIST_NAME = "-";
// Button variables
const int BUTTON_VOL_DOWN_PIN = 34;
bool BUTTON_VOL_DOWN_STATE = HIGH;
bool BUTTON_VOL_DOWN_PREV_STATE = HIGH;
const int BUTTON_VOL_UP_PIN = 35;
bool BUTTON_VOL_UP_STATE = HIGH;
bool BUTTON_VOL_UP_PREV_STATE = HIGH;
const int BUTTON_STOP_PIN = 32;
bool BUTTON_STOP_STATE = HIGH;
bool BUTTON_STOP_PREV_STATE = HIGH;
const int BUTTON_NEXT_PIN = 33;
bool BUTTON_NEXT_STATE = HIGH;
bool BUTTON_NEXT_PREV_STATE = HIGH;
// Tag IDs
String TAG_TEST = "93 44 5C 92";
String TAG_BACH = "9C CD 69 0F";
/***********************************************************
Functions
*/
void volumeDecrease() {
if (VOLUME > VOLUME_MIN) {
VOLUME = VOLUME - VOLUME_CHANGE_AMOUNT;
broadcastUpdate();
}
}
void volumeIncrease() {
if (VOLUME < VOLUME_MAX) {
VOLUME = VOLUME + VOLUME_CHANGE_AMOUNT;
broadcastUpdate();
} else {
VOLUME = VOLUME_MAX;
broadcastUpdate();
}
}
void updateVolumeLimitState(bool state) {
VOLUME_IS_LIMITED = state;
broadcastUpdate();
}
void broadcastUpdate() {
DynamicJsonDocument doc(1024);
doc["volume"] = VOLUME;
doc["volume_min"] = VOLUME_MIN;
doc["volume_max"] = VOLUME_MAX;
doc["volume_is_limited"] = VOLUME_IS_LIMITED;
doc["is_playing"] = IS_PLAYING;
doc["track_name"] = TRACK_NAME;
doc["artist_name"] = ARTIST_NAME;
char json_string[1024];
serializeJson(doc, json_string);
webSocket.broadcastTXT(json_string);
}
void handleWsTextMessage(uint8_t client_num, uint8_t * payload) {
if ( strcmp((char *)payload, "getValues") == 0 ) {
broadcastUpdate();
} else if ( strcmp((char *)payload, "volume_down_button_click") == 0 ) {
volumeDecrease();
} else if ( strcmp((char *)payload, "volume_up_button_click") == 0 ) {
volumeIncrease();
} else if ( strcmp((char *)payload, "volume_limit_checkbox_on") == 0 ) {
updateVolumeLimitState(true);
} else if ( strcmp((char *)payload, "volume_limit_checkbox_off") == 0 ) {
updateVolumeLimitState(false);
} else { // Message not recognized
Serial.println("[%u] Message not recognized");
}
}
// Callback: receiving any WebSocket message
void onWebSocketEvent(uint8_t client_num, WStype_t type, uint8_t * payload, size_t length) {
// Figure out the type of WebSocket event
switch (type) {
// Client has disconnected
case WStype_DISCONNECTED:
Serial.printf("[%u] Disconnected!\n", client_num);
break;
// New client has connected
case WStype_CONNECTED:
{
IPAddress ip = webSocket.remoteIP(client_num);
Serial.printf("[%u] Connection from ", client_num);
Serial.println(ip.toString());
}
break;
// Handle text messages from client
case WStype_TEXT:
// Print out raw message
Serial.printf("[%u] Received text: %s\n", client_num, payload);
handleWsTextMessage(client_num, payload);
break;
// For everything else: do nothing
case WStype_BIN:
case WStype_ERROR:
case WStype_FRAGMENT_TEXT_START:
case WStype_FRAGMENT_BIN_START:
case WStype_FRAGMENT:
case WStype_FRAGMENT_FIN:
default:
break;
}
}
// Callback: send homepage
void onIndexRequest(AsyncWebServerRequest *request) {
const char* dataType = "text/html";
IPAddress remote_ip = request->client()->remoteIP();
Serial.println("[" + remote_ip.toString() +
"] HTTP GET request of " + request->url());
// request->send(SPIFFS, "/index.html", "text/html");
AsyncWebServerResponse *response = request->beginResponse_P(200, dataType, index_html_gz, index_html_gz_len);
response->addHeader("Content-Encoding", "gzip");
request->send(response);
}
// Callback: send 404 if requested file does not exist
void onPageNotFound(AsyncWebServerRequest *request) {
IPAddress remote_ip = request->client()->remoteIP();
Serial.println("[" + remote_ip.toString() +
"] HTTP GET request of " + request->url());
request->send(404, "text/plain", "Not found");
}
/***********************************************************
Main
*/
void handleButtons() {
// VOLUME DOWN BUTTON
bool buttonVolDownState = digitalRead(BUTTON_VOL_DOWN_PIN);
if (buttonVolDownState == LOW && BUTTON_VOL_DOWN_PREV_STATE == HIGH) {
Serial.println("button down pressed");
volumeDecrease();
BUTTON_VOL_DOWN_PREV_STATE = LOW;
} else if (buttonVolDownState == HIGH && BUTTON_VOL_DOWN_PREV_STATE == LOW) {
BUTTON_VOL_DOWN_PREV_STATE = HIGH;
}
// VOLUME UP BUTTON
bool buttonVolUpState = digitalRead(BUTTON_VOL_UP_PIN);
if (buttonVolUpState == LOW && BUTTON_VOL_UP_PREV_STATE == HIGH) {
Serial.println("button up pressed");
volumeIncrease();
BUTTON_VOL_UP_PREV_STATE = LOW;
} else if (buttonVolUpState == HIGH && BUTTON_VOL_UP_PREV_STATE == LOW) {
BUTTON_VOL_UP_PREV_STATE = HIGH;
}
// STOP BUTTON
bool buttonStopState = digitalRead(BUTTON_STOP_PIN);
if (buttonStopState == LOW && BUTTON_STOP_PREV_STATE == HIGH) {
Serial.println("button stop pressed");
volumeIncrease();
BUTTON_STOP_PREV_STATE = LOW;
} else if (buttonStopState == HIGH && BUTTON_STOP_PREV_STATE == LOW) {
BUTTON_STOP_PREV_STATE = HIGH;
}
// NEXT BUTTON
bool buttonNextState = digitalRead(BUTTON_NEXT_PIN);
if (buttonNextState == LOW && BUTTON_NEXT_PREV_STATE == HIGH) {
Serial.println("button next pressed");
volumeIncrease();
BUTTON_NEXT_PREV_STATE = LOW;
} else if (buttonNextState == HIGH && BUTTON_NEXT_PREV_STATE == LOW) {
BUTTON_NEXT_PREV_STATE = HIGH;
}
}
String getTagUid() {
String content = "";
byte letter;
for (byte i = 0; i < mfrc522.uid.size; i++) {
content.concat(String(mfrc522.uid.uidByte[i] < 0x10 ? " 0" : " "));
content.concat(String(mfrc522.uid.uidByte[i], HEX));
}
content.toUpperCase();
String tag_uid = content.substring(1);
Serial.println("Getting tag uid");
Serial.println(content.substring(1));
return content.substring(1);
}
void checkTagValidity(String tag_uid) {
if (tag_uid == TAG_TEST) {
Serial.println("BLUE TAG");
ARTIST_NAME = "Blue Tag";
TRACK_NAME = "Super Track name";
IS_PLAYING = true;
broadcastUpdate();
} else if (tag_uid == TAG_BACH) {
Serial.println("BACH");
} else {
Serial.println("UNKNOWN CARD: ");
Serial.print(tag_uid);
}
}
void setup() {
// Init buttons
pinMode(BUTTON_VOL_DOWN_PIN, INPUT_PULLUP);
pinMode(BUTTON_VOL_UP_PIN, INPUT_PULLUP);
pinMode(BUTTON_STOP_PIN, INPUT_PULLUP);
pinMode(BUTTON_NEXT_PIN, INPUT_PULLUP);
// Start Serial port
Serial.begin(115200);
// Init SPI bus (for the tag reader)
SPI.begin();
// Init the tag reader
mfrc522.PCD_Init();
// Start access point
WiFi.softAP(ssid, password);
// Print our IP address
Serial.println();
Serial.println("AP running");
Serial.print("My IP address: ");
Serial.println(WiFi.softAPIP());
// On HTTP request for root, provide index.html file
server.on("/", HTTP_GET, onIndexRequest);
// 404 page
server.onNotFound(onPageNotFound);
// Start web server
server.begin();
// Start WebSocket server and assign callback
webSocket.begin();
webSocket.onEvent(onWebSocketEvent);
}
void loop() {
// Check for button clicks
handleButtons();
// Look for and handle WebSocket data
webSocket.loop();
rfid_tag_present_prev = rfid_tag_present;
_rfid_error_counter += 1;
if (_rfid_error_counter > 2) {
_tag_found = false;
}
// Detect Tag without looking for collisions
byte bufferATQA[2];
byte bufferSize = sizeof(bufferATQA);
// Reset baud rates
mfrc522.PCD_WriteRegister(mfrc522.TxModeReg, 0x00);
mfrc522.PCD_WriteRegister(mfrc522.RxModeReg, 0x00);
// Reset ModWidthReg
mfrc522.PCD_WriteRegister(mfrc522.ModWidthReg, 0x26);
MFRC522::StatusCode result = mfrc522.PICC_RequestA(bufferATQA, &bufferSize);
if (result == mfrc522.STATUS_OK) {
if ( ! mfrc522.PICC_ReadCardSerial()) { //Since a PICC placed get Serial and continue
return;
}
_rfid_error_counter = 0;
_tag_found = true;
}
rfid_tag_present = _tag_found;
// rising edge
if (rfid_tag_present && !rfid_tag_present_prev) {
Serial.println("Tag found");
// Get tag uid
String tag_uid = getTagUid();
// Check if valid tag
checkTagValidity(tag_uid);
}
// falling edge
if (!rfid_tag_present && rfid_tag_present_prev) {
Serial.println("Tag gone");
ARTIST_NAME = "-";
TRACK_NAME = "-";
IS_PLAYING = false;
broadcastUpdate();
}
}
Thanks to the comments from #romkey and #RamyHx i got it to work using the same SPI pins.
My problem was that i was using the same pin for the CS of both devices. Once i change it to different CS pins for the rfid and sd card reader it started working.
For the RFID i have used the pin D2, and for the sd card reader i have used the pin D5.
For the rfid i have change #define RFID_RC522_SDA_PIN 5 into #define RFID_RC522_SDA_PIN 2.
For the sd card i have used the code here, which assumes we are using the default pins (with CS connected to pin D5).

ESP12F, cant get a relay to work with data from dht11

i've been trying to build a system that detects in one room of the house the temperature using an esp8266 and a dht11 sensor, this esp sends the data to a webserver while the ESP12F grabs this data and should turn the relay on when a certain value is reached, however i can't get the relay to work, as soon as i upload the code, the led on the module turns but not at its full power, i tried with another code to see if it was just a faulty relay, but it works perfectly with the same connections. The code from the client side of the system is below:
#include "ESP8266WiFi.h"
#include "ESP8266HTTPClient.h"
#include "WiFiClient.h"
#include "ESP8266WiFiMulti.h"
ESP8266WiFiMulti WiFiMulti;
const char* ssid = "*******";
const char* password = "********";
//Your IP address or domain name with URL path
const char* serverNameTemp = "http://192.168.1.188/temperature";
const char* serverNameHumi = "http://192.168.1.188/humidity";
const char* serverNamePres = "http://192.168.1.188/pressure";
#include "Wire.h"
#include "Adafruit_GFX.h"
#include "Adafruit_SSD1306.h"
#define SCREEN_WIDTH 128 // OLED display width, in pixels
#define SCREEN_HEIGHT 64 // OLED display height, in pixels
// Declaration for an SSD1306 display connected to I2C (SDA, SCL pins)
#define OLED_RESET -1 // Reset pin # (or -1 if sharing Arduino reset pin)
Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, OLED_RESET);
String temperature;
String humidity;
String pressure;
const int relay = 5;
float temp_int = temperature.toFloat();
unsigned long previousMillis = 0;
const long interval = 2000;
void setup() {
Serial.begin(115200);
Serial.println();
pinMode(relay,OUTPUT);
digitalWrite(relay,LOW);
// Address 0x3C for 128x64, you might need to change this value (use an I2C scanner)
if(!display.begin(SSD1306_SWITCHCAPVCC, 0x3C)) {
Serial.println(F("SSD1306 allocation failed"));
for(;;); // Don't proceed, loop forever
}
display.clearDisplay();
display.setTextColor(WHITE);
int int_temp = temperature.toFloat();
WiFi.mode(WIFI_STA);
WiFiMulti.addAP(ssid, password);
while((WiFiMulti.run() == WL_CONNECTED)) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("Connected to WiFi");
}
void loop() {
unsigned long currentMillis = millis();
if(currentMillis - previousMillis >= interval) {
// Check WiFi connection status
if ((WiFiMulti.run() == WL_CONNECTED)) {
int int_temp = temperature.toFloat();
temperature = httpGETRequest(serverNameTemp);
humidity = httpGETRequest(serverNameHumi);
pressure = httpGETRequest(serverNamePres);
if(int_temp < 26){
digitalWrite(relay,LOW);
}
else if (int_temp > 26){
digitalWrite(relay,HIGH);
}
Serial.println("Temperature: " + temperature + " *C - Humidity: " + humidity + " % - Pressure: " + pressure + " hPa");
Serial.println(int_temp);
Serial.println(temperature.toFloat());
display.clearDisplay();
// display temperature
display.setTextSize(2);
display.setCursor(0,0);
display.print("T: ");
display.print(temperature);
display.print(" ");
display.setTextSize(1);
display.cp437(true);
display.write(248);
display.setTextSize(2);
display.print("C");
// display humidity
display.setTextSize(2);
display.setCursor(0, 25);
display.print("H: ");
display.print(humidity);
display.print(" %");
// display pressure
display.setTextSize(2);
display.setCursor(0, 50);
display.print("P:");
display.print(pressure);
display.setTextSize(1);
display.setCursor(110, 56);
display.print("hPa");
display.display();
// save the last HTTP GET Request
previousMillis = currentMillis;
}
else {
Serial.println("WiFi Disconnected");
}
}
}
String httpGETRequest(const char* serverName) {
WiFiClient client;
HTTPClient http;
// Your IP address with path or Domain name with URL path
http.begin(client, serverName);
// Send HTTP POST request
int httpResponseCode = http.GET();
String payload = "--";
if (httpResponseCode>0) {
Serial.print("HTTP Response code: ");
Serial.println(httpResponseCode);
payload = http.getString();
}
else {
Serial.print("Error code: ");
Serial.println(httpResponseCode);
}
// Free resources
http.end();
return payload;
}

Error using thingspeak talk back to control arduino led

The error I'm facing is about using talkback function of thingspeak to control my Arduino LED. it cannot execute the talkback command to off the led. The error is in my void get talkback. Please help me
#include "ThingSpeak.h"
#include <Ethernet.h>
#define redLED 8
byte mac[] = {0x90, 0xA2, 0xDA, 0x10, 0x40, 0x4F};
const String channelsAPIKey = "";
const String talkBackAPIKey = "";
const String talkBackID = "";
const String talkCommandID = "";
const unsigned int getTalkBackInterval = 10 * 1000;
const unsigned int updateChannelsInterval = 15 * 1000;
String talkBackCommand;
long lastConnectionTimeChannels = 0;
boolean lastConnectedChannels = false;
int failedCounterChannels = 0;
long lastConnectionTimeTalkBack = 0;
boolean lastConnectedTalkBack = false;
int failedCounterTalkBack = 0;
char charIn;
// Arduino Ethernet Client is initialized
EthernetClient client;
void setup()
{
Ethernet.init(10); // Most Arduino Ethernet hardware
Serial.begin(9600); //Initialize serial
// start the Ethernet connection:
pinMode(redLED, OUTPUT);
digitalWrite(redLED, HIGH);
}
void loop()
{
getTalkBack();
}
void getTalkBack()
{
String tsData;
tsData = talkBackID + "/commands/execute?api_key=" + talkBackAPIKey;
if ((!client.connected() && (millis() - lastConnectionTimeTalkBack > getTalkBackInterval)))
{
if (client.connect("api.thingspeak.com", 80))
{
client.println("GET /talkbacks/" + tsData + " HTTP/1.0");
client.println();
lastConnectionTimeTalkBack = millis();
if (client.connected())
{
Serial.println("---------------------------------------");
Serial.println("GET TalkBack command");
Serial.println();
Serial.println("Connecting to ThingSpeak");
Serial.println();
Serial.println();
Serial.println("Server response");
Serial.println();
failedCounterTalkBack = 0;
while (client.connected() && !client.available()) delay(2000); //waits for data
while (client.connected() || client.available())
{
charIn = client.read();
talkBackCommand += charIn;
Serial.print(charIn);
if (talkBackCommand == "LED_ON")
{
digitalWrite(redLED, HIGH);
}
if (talkBackCommand == "LED_OFF")
{
digitalWrite(redLED, LOW);
}
}
if (talkBackCommand = talkBackCommand.substring(talkBackCommand.indexOf("_CMD_") + 5));
{
Serial.println();
Serial.println();
Serial.println("Disconnected");
Serial.println();
Serial.println("--------");
Serial.println();
Serial.println("talkback command was");
Serial.println();
Serial.println("--------");
Serial.println();
Serial.println(talkBackCommand);
Serial.println("--------");
Serial.println();
}
}
else
{
failedCounterTalkBack++;
Serial.println("Connection to ThingSpeak failed (" + String(failedCounterTalkBack, DEC) + ")");
Serial.println();
lastConnectionTimeChannels = millis();
}
}
}
if (failedCounterTalkBack > 3 )
{
startEthernet();
}
client.stop();
Serial.flush();
}
The below is a image from my serial monitor. It shows that I can capture the command but couldn't execute it.
Looks like you are reading and appending all the received bytes to talkBackCommand. So, talkBackCommand is "HTTP/1.1 200 OK Date...." and if (talkBackCommand == "LED_ON") would never be true.
I think you wanted to see if the received data contain your commands LED_ON or LED_OFF. You can do something like this:
if (talkBackCommand.indexOf("LED_ON") != -1)
indexOf() locates a String in a String and returns index or -1 if not found.
See more info about indexOf() here: https://www.arduino.cc/reference/en/language/variables/data-types/string/functions/indexof/

Sending a HTTP request to Google Script in Arduino

I am using the following code which sends and receives a HTTP request to the custom website with no problem. However when I try to change the host to following I get a failure message. You can simply put this address into browser to see the actual response.
I need to change const char* host = "djxmmx.net"; to const char* host = "https://script.google.com/macros/s/AKfycby72HRgl874tst5e0FBHDa_VR6luqofn-ojiYF8KUBPmC2E3aiB/exec";
#include <ESP8266WiFi.h>
const char* ssid = "Phone";
const char* password = "aa";
const char* host = "djxmmx.net";
const uint16_t port = 17;
void setup() {
Serial.begin(115200);
delay(10);
// We start by connecting to a WiFi networkre
Serial.println();
Serial.println();
Serial.print("Connecting to ");
Serial.println(ssid);
/* Explicitly set the ESP8266 to be a WiFi-client, otherwise, it by default,
would try to act as both a client and an access-point and could cause
network-issues with your other WiFi-devices on your WiFi-network. */
WiFi.mode(WIFI_STA);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("WiFi connected");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
}
void loop() {
Serial.print("connecting to ");
Serial.print(host);
Serial.print(':');
Serial.println(port);
// Use WiFiClient class to create TCP connections
WiFiClient client;
if (!client.connect(host, port)) {
Serial.println("connection failed");
delay(5000);
return;
}
// This will send a string to the server
Serial.println("sending data to server");
client.println("hello from ESP8266");
unsigned long timeout = millis();
while (client.available() == 0) {
if (millis() - timeout > 5000) {
Serial.println(">>> Client Timeout !");
client.stop();
delay(60000);
return;
}
}
// Read all the lines of the reply from server and print them to Serial
Serial.println("receiving from remote server");
while (client.available()) {
char ch = static_cast<char>(client.read());
Serial.print(ch);
}
// Close the connection
//Serial.println();
//Serial.println("closing connection");
// client.stop();
//delay(300000); // execute once every 5 minutes, don't flood remote service
}
You can do it this way using some help as mentioned. This requires a data server setup in Google app in this link GoogleSheetScript. Note how "name=Amir" transfer your data.
/* HTTPS on ESP8266 with follow redirects, chunked encoding support
* Version 2.1
* Author: Sujay Phadke
* Github: #electronicsguy
* Copyright (C) 2017 Sujay Phadke <electronicsguy123#gmail.com>
* All rights reserved.
*
* Example Arduino program
*/
#include <ESP8266WiFi.h>
#include "HTTPSRedirect.h"
#include "DebugMacros.h"
// Fill ssid and password with your network credentials
const char* ssid = "AmirPhone";
const char* password = "aa112233";
const char* host = "script.google.com";
// Replace with your own script id to make server side changes
const char *GScriptId = "AKfycby72HRgl874tst5e0FBHDa_VR6luqofn-ojiYF8KUBPmC2E3aiB";
const int httpsPort = 443;
// echo | openssl s_client -connect script.google.com:443 |& openssl x509 -fingerprint -noout
const char* fingerprint = "";
// Write to Google Spreadsheet
String url = String("/macros/s/") + GScriptId + "/exec?name=Amir";
// Fetch Google Calendar events for 1 week ahead
String url2 = String("/macros/s/") + GScriptId + "/exec?cal";
// Read from Google Spreadsheet
String url3 = String("/macros/s/") + GScriptId + "/exec?read";
String payload_base = "";
String payload = "";
HTTPSRedirect* client = nullptr;
// used to store the values of free stack and heap
// before the HTTPSRedirect object is instantiated
// so that they can be written to Google sheets
// upon instantiation
unsigned int free_heap_before = 0;
unsigned int free_stack_before = 0;
void setup() {
Serial.begin(115200);
Serial.flush();
//free_heap_before = ESP.getFreeHeap();
//free_stack_before = cont_get_free_stack(&g_cont);
Serial.printf("Free heap before: %u\n", free_heap_before);
Serial.printf("unmodified stack = %4d\n", free_stack_before);
Serial.println();
Serial.print("Connecting to wifi: ");
Serial.println(ssid);
// flush() is needed to print the above (connecting...) message reliably,
// in case the wireless connection doesn't go through
Serial.flush();
WiFi.mode(WIFI_STA);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("WiFi connected");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
// Use HTTPSRedirect class to create a new TLS connection
client = new HTTPSRedirect(httpsPort);
client->setPrintResponseBody(true);
client->setContentTypeHeader("application/json");
Serial.print("Connecting to ");
Serial.println(host);
// Try to connect for a maximum of 5 times
bool flag = false;
for (int i=0; i<5; i++){
int retval = client->connect(host, httpsPort);
if (retval == 1) {
flag = true;
break;
}
else
Serial.println("Connection failed. Retrying...");
}
if (!flag){
Serial.print("Could not connect to server: ");
Serial.println(host);
Serial.println("Exiting...");
return;
}
if (client->verify(fingerprint, host)) {
Serial.println("Certificate match.");
} else {
Serial.println("Certificate mis-match");
}
// Send memory data to Google Sheets
payload = payload_base + "\"" + free_heap_before + "," + free_stack_before + "\"}";
client->POST(url2, host, payload, false);
payload = payload_base;// + "\"" + ESP.getFreeHeap() + "," + cont_get_free_stack(&g_cont) + "\"}";
client->POST(url2, host, payload, false);
// Note: setup() must finish within approx. 1s, or the the watchdog timer
// will reset the chip. Hence don't put too many requests in setup()
// ref: https://github.com/esp8266/Arduino/issues/34
Serial.println("\nGET: Write into cell 'A1'");
Serial.println("=========================");
// fetch spreadsheet data
client->GET(url, host);
// Send memory data to Google Sheets
payload = payload_base;// + "\"" + ESP.getFreeHeap() + "," + cont_get_free_stack(&g_cont) + "\"}";
client->POST(url2, host, payload, false);
Serial.println("\nGET: Fetch Google Calendar Data:");
Serial.println("================================");
// fetch spreadsheet data
client->GET(url2, host);
// Send memory data to Google Sheets
payload = payload_base;// + "\"" + ESP.getFreeHeap() + "," + cont_get_free_stack(&g_cont) + "\"}";
client->POST(url2, host, payload, false);
Serial.println("\nSeries of GET and POST requests");
Serial.println("===============================");
Serial.printf("Free heap: %u\n", ESP.getFreeHeap());
Serial.printf("unmodified stack = %4d\n");//, cont_get_free_stack(&g_cont));
// delete HTTPSRedirect object
delete client;
client = nullptr;
}
void loop() {
static int error_count = 0;
static int connect_count = 0;
const unsigned int MAX_CONNECT = 20;
static bool flag = false;
//Serial.printf("Free heap: %u\n", ESP.getFreeHeap());
//Serial.printf("unmodified stack = %4d\n", cont_get_free_stack(&g_cont));
if (!flag){
//free_heap_before = ESP.getFreeHeap();
// free_stack_before = cont_get_free_stack(&g_cont);
client = new HTTPSRedirect(httpsPort);
flag = true;
client->setPrintResponseBody(true);
client->setContentTypeHeader("application/json");
}
if (client != nullptr){
if (!client->connected()){
client->connect(host, httpsPort);
payload = payload_base + "\"" + free_heap_before + "," + free_stack_before + "\"}";
client->POST(url2, host, payload, false);
}
}
else{
DPRINTLN("Error creating client object!");
error_count = 5;
}
if (connect_count > MAX_CONNECT){
//error_count = 5;
connect_count = 0;
flag = false;
delete client;
return;
}
Serial.println("GET Data from cell 'A1':");
if (client->GET(url3, host)){
++connect_count;
}
else{
++error_count;
DPRINT("Error-count while connecting: ");
DPRINTLN(error_count);
}
Serial.println("POST append memory data to spreadsheet:");
payload = payload_base;// + "\"" + ESP.getFreeHeap() + "," + cont_get_free_stack(&g_cont) + "\"}";
if(client->POST(url2, host, payload)){
;
}
else{
++error_count;
DPRINT("Error-count while connecting: ");
DPRINTLN(error_count);
}
/*
if (!(client.reConnectFinalEndpoint())){
++error_count;
DPRINT("Error-count while connecting: ");
DPRINTLN(error_count);
}
else
error_count = 0;
*/
if (error_count > 3){
Serial.println("Halting processor...");
delete client;
client = nullptr;
Serial.printf("Final free heap: %u\n", ESP.getFreeHeap());
Serial.printf("Final unmodified stack = %4d\n");//, cont_get_free_stack(&g_cont));
Serial.flush();
ESP.deepSleep(0);
}
// In my testing on a ESP-01, a delay of less than 1500 resulted
// in a crash and reboot after about 50 loop runs.
delay(4000);
}
[1]: https://github.com/electronicsguy/ESP8266/blob/master/HTTPSRedirect/GoogleScript.gs

Send Mirf values with ethercard

I have project where I'm getting data over nRF24L01 and using Mirf to that. Now I'm working for Hub which need to send data to my webservice. For ethernet my choice was ENC28j60 with ethercard library.
Question : How I can wait data from Mirf and just send data forward with Ethercard browseUrl? I can send data without Mirf but there's some loop which I'm not understand.
My code :
#include <SPI.h>
#include <Mirf.h>
#include <nRF24L01.h>
#include <MirfHardwareSpiDriver.h>
#include <EtherCard.h>
// Set network settings
static byte mymac[] = { 0x74, 0x69, 0x69, 0x2D, 0x30, 0x31 };
byte Ethernet::buffer[700];
static uint32_t timer;
// My webservice
const char website[] PROGMEM = "my.webservice.com";
// Mirf variables
int tmpVal1;
// Local components
const int Yellow = 6;
const int Blue = 5;
void setup() {
Serial.begin(57600);
// Setup leds
pinMode(Yellow, OUTPUT);
digitalWrite(Yellow, LOW);
pinMode(Blue, OUTPUT);
digitalWrite(Blue, LOW);
setupMirf();
setupEthernet();
}
void loop() {
// Waiting to get date from Mirf
while (!Mirf.dataReady()) {
//ether.packetLoop(ether.packetReceive());
}
Mirf.getData((byte *)&tmpVal1);
Serial.print(tmpVal1);
Serial.println(F(" C"));
// Receive responses
ether.packetLoop(ether.packetReceive());
if (millis() > timer) {
timer = millis() + 5000;
//Serial.println();
Serial.println("Sending data to webservice : ");
ether.browseUrl(PSTR("/sendingdata.asmx/sendingdata?"), "Device=100&DeviceValue=80", website, my_callback);
}
//ShowLedNotification();
}
// called when the client request is complete
static void my_callback (byte status, word off, word len) {
Serial.println(">>>");
Ethernet::buffer[off+300] = 0;
Serial.print((const char*) Ethernet::buffer + off);
Serial.println("...");
digitalWrite(Blue,HIGH);
delay(200);
digitalWrite(Blue,LOW);
}
void ShowLedNotification() {
if (tmpVal1 > 0 ) {
digitalWrite(Yellow, HIGH);
delay(1000);
digitalWrite(Yellow, LOW);
}
else
{
digitalWrite(Blue, HIGH);
delay(1000);
digitalWrite(Blue, LOW);
}
}
long readVcc() {
long result;
// Read 1.1V reference against AVcc
ADMUX = _BV(REFS0) | _BV(MUX3) | _BV(MUX2) | _BV(MUX1);
delay(2); // Wait for Vref to settle
ADCSRA |= _BV(ADSC); // Convert
while (bit_is_set(ADCSRA,ADSC));
result = ADCL;
result |= ADCH<<8;
result = 1126400L / result; // Back-calculate AVcc in mV
return result;
}
//Setting up network and getting DHCP IP
void setupEthernet() {
Serial.println(F("Setting up network and DHCP"));
Serial.print(F("MAC: "));
for (byte i = 0; i < 6; ++i) {
Serial.print(mymac[i], HEX);
if (i < 5)
Serial.print(':');
}
Serial.println();
if (ether.begin(sizeof Ethernet::buffer, mymac) == 0)
Serial.println(F("Failed to access Ethernet controller"));
Serial.println(F("Setting up DHCP"));
if (!ether.dhcpSetup())
Serial.println(F("DHCP failed"));
ether.printIp("My IP: ", ether.myip);
ether.printIp("Netmask: ", ether.netmask);
ether.printIp("GW IP: ", ether.gwip);
ether.printIp("DNS IP: ", ether.dnsip);
// Check network connection
if (!ether.dnsLookup(website))
Serial.println("DNS failed");
ether.printIp("SRV: ", ether.hisip);
}
void setupMirf() {
//Initialize nRF24
Serial.println(F("Initializing Mirf"));
Mirf.spi = &MirfHardwareSpi;
Mirf.init();
Mirf.setRADDR((byte *)"serv1");
Mirf.payload = sizeof(tmpVal1);
// we use channel 90 as it is outside of WLAN bands
// or channels used by wireless surveillance cameras
Mirf.channel = 90;
Mirf.config();
}
Did get that work. Now using if clause not while Mirf.dataReady()
void loop() {
if (Mirf.dataReady()) {
Mirf.getData((byte *)&tmpVal1);
Serial.print(tmpVal1);
Serial.println(F(" C"));
ShowLedNotification();
// Send data to webservice
if (millis() > timer) {
timer = millis() + 5000;
Serial.println("Sending data to webservice");
String myVarsStr = "Device=";
myVarsStr += myDeviceID;
myVarsStr += "&DeviceValue=";
myVarsStr += tmpVal1;
char myVarsCh[40];
myVarsStr.toCharArray(myVarsCh, 40);
ether.browseUrl(PSTR("/receivedata.asmx/ReceiveData?"), myVarsCh, website, my_callback);
}
}
else
{
word pos = ether.packetReceive();
word len = ether.packetLoop(pos);
delay(200);
}
}

Resources