arduino and esp8266 wifi module compiling issue - arduino

I want to monitor the condition of the 2HP IM to using arduino uno and sensors and want to push the data to cloud using esp8266 in thingspeak. But I keep getting the error ""Softwere serial esp8266" redeclared as different kind of symbol " when compiled. please fix this problem
this is my coding:
#include "SoftwareSerial.h"
#define RX 10
#define TX 11
String AP = "wifi name"; // CHANGE ME
String PASS = "wifi password"; // CHANGE ME
String API = "api key"; // CHANGE ME
String HOST = "api.thingspeak.com";
String PORT = "80";
String field = "field1";
int countTrueCommand;
int countTimeCommand;
boolean found = false;
int valSensor = 1;
SoftwareSerial esp8266(RX,TX,false,256);
void setup() {
Serial.begin(9600);
esp8266.begin(115200);
sendCommand("AT",5,"OK");
sendCommand("AT+CWMODE=1",5,"OK");
sendCommand("AT+CWJAP=\""+ AP +"\",\""+ PASS +"\"",20,"OK");
}
void loop() {
valSensor = getSensorData();
String getData = "GET /update?api_key="+ API +"&"+ field +"="+String(valSensor);
sendCommand("AT+CIPMUX=1",5,"OK");
sendCommand("AT+CIPSTART=0,\"TCP\",\""+ HOST +"\","+ PORT,15,"OK");
sendCommand("AT+CIPSEND=0," +String(getData.length()+4),4,">");
esp8266.println(getData);delay(1500);countTrueCommand++;
sendCommand("AT+CIPCLOSE=0",5,"OK");
}
int getSensorData(){
return random(1000); // Replace with
}
void sendCommand(String command, int maxTime, char readReplay[]) {
Serial.print(countTrueCommand);
Serial.print(". at command => ");
Serial.print(command);
Serial.print(" ");
while(countTimeCommand < (maxTime*1))
{
esp8266.println(command);//at+cipsend
if(esp8266.find(readReplay))//ok
{
found = true;
break;
}
countTimeCommand++;
}
if(found == true)
{
Serial.println("OYI");
countTrueCommand++;
countTimeCommand = 0;
}
if(found == false)
{
Serial.println("Fail");
countTrueCommand = 0;
countTimeCommand = 0;
}
found = false;
}
this is the error I am getting:
Arduino: 1.8.9 (Windows 8), Board: "Generic ESP8266 Module, 80 MHz, Flash, Disabled, ck, 26 MHz, 40MHz, DOUT (compatible), 512K (no SPIFFS), 2, v2 Lower Memory, Disabled, None, Only Sketch, 115200"
C:\Users\Admin\Desktop\n12\n12.ino: In function 'void setup()':
n12:19:10: error: expected primary-expression before '.' token
esp8266.begin(115200);
^
C:\Users\Admin\Desktop\n12\n12.ino: In function 'void loop()':
n12:30:9: error: expected primary-expression before '.' token
esp8266.println(getData);delay(1500);countTrueCommand++;
^
C:\Users\Admin\Desktop\n12\n12.ino: In function 'void sendCommand(String, int, char*)':
n12:43:12: error: expected primary-expression before '.' token
esp8266.println(command);//at+cipsend
^
n12:44:15: error: expected primary-expression before '.' token
if(esp8266.find(readReplay))//ok
^
exit status 1
expected primary-expression before '.' token
This report would have more information with
"Show verbose output during compilation"
option enabled in File -> Preferences.

Related

the code compiles on arduino nano but not on esp32 :(

void loop() {
// put your main code here, to run repeatedly:
// send packet
p = (bme.readPressure() / 100.0F );
h = (bme.readHumidity());
t = (bme.readTemperature());
alt = bme.readAltitude(SEALEVELPRESSURE_HPA);
String data = String(h) + "-" + String(t)+ "-" + String(p)+ "-" + String(alt);
int dataLength = data.length(); dataLength++;
uint8_t total[dataLength]; //variable for data to send
data.toCharArray(total, dataLength); //change type data from string ke uint8_t
Serial.println(data);
rf95.send(total, dataLength); //send data
rf95.waitPacketSent();
delay(2000);
}
im using the radiohead library and it works really well on arduino to send the data and then receives on a esp32, but if i make the esp32 the sender with this code
it throws me this error
error: invalid conversion from 'uint8_t*' {aka 'unsigned char*'} to 'char*' [-fpermissive]
refer to toCharArray() function in arduino reference as they stated that :
myString.toCharArray(buf, len)
buf: the buffer to copy the characters into. Allowed data types: array of char.
so the function expects a parameter of type char* not uint8_t*
so either change :
uint8_t total[dataLength]; -> char total[dataLength];
or
data.toCharArray(total, dataLength); -> data.toCharArray((char*)total, dataLength);
either of them should solve your problem.

Error while trying to upload code to NodeMcu that will let me control a LED Matrix

I have a code that I downloaded from a webpage that is supposed to let me control a MAX7219 LED Matrix from a Web Interface using an ESP8266 (I'm using a NodeMcu v3.0 with an ESP8266-12E), but every time I try to compile the code, the following error comes out:
MAX7219_ESP8266:45: error: invalid conversion from 'uint8_t {aka unsigned char}' to 'MD_MAX72XX::moduleType_t' [-fpermissive]
MD_MAX72XX mx = MD_MAX72XX(CS_PIN, MAX_DEVICES);
^
In file included from
E:\Searches\Desktop\MAX7219_ESP8266\MAX7219_ESP8266.ino:14:0:
E:\Documents\Arduino\libraries\MD_MAX72XX\src/MD_MAX72xx.h:362:3:
error: initializing argument 1 of
'MD_MAX72XX::MD_MAX72XX(MD_MAX72XX::moduleType_t, uint8_t, uint8_t)'
[-fpermissive]
MD_MAX72XX(moduleType_t mod, uint8_t csPin, uint8_t numDevices=1);
^
exit status 1 invalid conversion from 'uint8_t {aka unsigned char}' to
'MD_MAX72XX::moduleType_t' [-fpermissive]
What could I do in order to fix it? I tried using a different library and even modifying the library, but the same error came out.
The code is the following:
// IP address for the ESP8266 is displayed on the scrolling display
// after startup initialisation and connected to the WiFi network.
//
// Connections for ESP8266 hardware SPI are:
// Vcc 3v3 LED matrices seem to work at 3.3V
// GND GND GND
// DIN D7 HSPID or HMOSI
// CS or LD D8 HSPICS or HCS
// CLK D5 CLK or HCLK
//
#include <ESP8266WiFi.h>
#include <MD_MAX72xx.h>
#include <SPI.h>
#define PRINT_CALLBACK 0
#define DEBUG 0
#define LED_HEARTBEAT 0
#if DEBUG
#define PRINT(s, v) { Serial.print(F(s)); Serial.print(v); }
#define PRINTS(s) { Serial.print(F(s)); }
#else
#define PRINT(s, v)
#define PRINTS(s)
#endif
#if LED_HEARTBEAT
#define HB_LED D2
#define HB_LED_TIME 500 // in milliseconds
#endif
// Define the number of devices we have in the chain and the hardware interface
// NOTE: These pin numbers will probably not work with your hardware and may
// need to be adapted
#define MAX_DEVICES 4
#define CLK_PIN D5 // or SCK
#define DATA_PIN D7 // or MOSI
#define CS_PIN D8 // or SS
// SPI hardware interface
MD_MAX72XX mx = MD_MAX72XX(CS_PIN, MAX_DEVICES);
// Arbitrary pins
//MD_MAX72XX mx = MD_MAX72XX(DATA_PIN, CLK_PIN, CS_PIN, MAX_DEVICES);
// WiFi login parameters - network name and password
const char* ssid = "your SSID"; // edit your wifi SSID here
const char* password = "your Password"; // edit your wifi password here
// WiFi Server object and parameters
WiFiServer server(80);
// Global message buffers shared by Wifi and Scrolling functions
const uint8_t MESG_SIZE = 255;
const uint8_t CHAR_SPACING = 1;
const uint8_t SCROLL_DELAY = 75;
char curMessage[MESG_SIZE];
char newMessage[MESG_SIZE];
bool newMessageAvailable = false;
char WebResponse[] = "HTTP/1.1 200 OK\nContent-Type: text/html\n\n";
char WebPage[] =
"<!DOCTYPE html>" \
"<html>" \
"<head>" \
"<title>eTechPath MAX7219 ESP8266</title>" \
"<style>" \
"html, body" \
"{" \
"width: 600px;" \
"height: 400px;" \
"margin: 0px;" \
"border: 0px;" \
"padding: 10px;" \
"background-color: white;" \
"}" \
"#container " \
"{" \
"width: 100%;" \
"height: 100%;" \
"margin-left: 200px;" \
"border: solid 2px;" \
"padding: 10px;" \
"background-color: #b3cbf2;" \
"}" \
"</style>"\
"<script>" \
"strLine = \"\";" \
"function SendText()" \
"{" \
" nocache = \"/&nocache=\" + Math.random() * 1000000;" \
" var request = new XMLHttpRequest();" \
" strLine = \"&MSG=\" + document.getElementById(\"txt_form\").Message.value;" \
" request.open(\"GET\", strLine + nocache, false);" \
" request.send(null);" \
"}" \
"</script>" \
"</head>" \
"<body>" \
"<div id=\"container\">"\
"<H1><b>WiFi MAX7219 LED Matrix Display</b></H1>" \
"<form id=\"txt_form\" name=\"frmText\">" \
"<label>Msg:<input type=\"text\" name=\"Message\" maxlength=\"255\"></label><br><br>" \
"</form>" \
"<br>" \
"<input type=\"submit\" value=\"Send Text\" onclick=\"SendText()\">" \
"<p><b>Visit Us at</b></p>" \
"www.eTechPath.com" \
"</div>" \
"</body>" \
"</html>";
char *err2Str(wl_status_t code)
{
switch (code)
{
case WL_IDLE_STATUS: return("IDLE"); break; // WiFi is in process of changing between statuses
case WL_NO_SSID_AVAIL: return("NO_SSID_AVAIL"); break; // case configured SSID cannot be reached
case WL_CONNECTED: return("CONNECTED"); break; // successful connection is established
case WL_CONNECT_FAILED: return("CONNECT_FAILED"); break; // password is incorrect
case WL_DISCONNECTED: return("CONNECT_FAILED"); break; // module is not configured in station mode
default: return("??");
}
}
uint8_t htoi(char c)
{
c = toupper(c);
if ((c >= '0') && (c <= '9')) return(c - '0');
if ((c >= 'A') && (c <= 'F')) return(c - 'A' + 0xa);
return(0);
}
boolean getText(char *szMesg, char *psz, uint8_t len)
{
boolean isValid = false; // text received flag
char *pStart, *pEnd; // pointer to start and end of text
// get pointer to the beginning of the text
pStart = strstr(szMesg, "/&MSG=");
if (pStart != NULL)
{
pStart += 6; // skip to start of data
pEnd = strstr(pStart, "/&");
if (pEnd != NULL)
{
while (pStart != pEnd)
{
if ((*pStart == '%') && isdigit(*(pStart+1)))
{
// replace %xx hex code with the ASCII character
char c = 0;
pStart++;
c += (htoi(*pStart++) << 4);
c += htoi(*pStart++);
*psz++ = c;
}
else
*psz++ = *pStart++;
}
*psz = '\0'; // terminate the string
isValid = true;
}
}
return(isValid);
}
void handleWiFi(void)
{
static enum { S_IDLE, S_WAIT_CONN, S_READ, S_EXTRACT, S_RESPONSE, S_DISCONN } state = S_IDLE;
static char szBuf[1024];
static uint16_t idxBuf = 0;
static WiFiClient client;
static uint32_t timeStart;
switch (state)
{
case S_IDLE: // initialise
PRINTS("\nS_IDLE");
idxBuf = 0;
state = S_WAIT_CONN;
break;
case S_WAIT_CONN: // waiting for connection
{
client = server.available();
if (!client) break;
if (!client.connected()) break;
#if DEBUG
char szTxt[20];
sprintf(szTxt, "%03d:%03d:%03d:%03d", client.remoteIP()[0], client.remoteIP()[1], client.remoteIP()[2], client.remoteIP()[3]);
PRINT("\nNew client # ", szTxt);
#endif
timeStart = millis();
state = S_READ;
}
break;
case S_READ: // get the first line of data
PRINTS("\nS_READ");
while (client.available())
{
char c = client.read();
if ((c == '\r') || (c == '\n'))
{
szBuf[idxBuf] = '\0';
client.flush();
PRINT("\nRecv: ", szBuf);
state = S_EXTRACT;
}
else
szBuf[idxBuf++] = (char)c;
}
if (millis() - timeStart > 1000)
{
PRINTS("\nWait timeout");
state = S_DISCONN;
}
break;
case S_EXTRACT: // extract data
PRINTS("\nS_EXTRACT");
// Extract the string from the message if there is one
newMessageAvailable = getText(szBuf, newMessage, MESG_SIZE);
PRINT("\nNew Msg: ", newMessage);
state = S_RESPONSE;
break;
case S_RESPONSE: // send the response to the client
PRINTS("\nS_RESPONSE");
// Return the response to the client (web page)
client.print(WebResponse);
client.print(WebPage);
state = S_DISCONN;
break;
case S_DISCONN: // disconnect client
PRINTS("\nS_DISCONN");
client.flush();
client.stop();
state = S_IDLE;
break;
default: state = S_IDLE;
}
}
void scrollDataSink(uint8_t dev, MD_MAX72XX::transformType_t t, uint8_t col)
// Callback function for data that is being scrolled off the display
{
#if PRINT_CALLBACK
Serial.print("\n cb ");
Serial.print(dev);
Serial.print(' ');
Serial.print(t);
Serial.print(' ');
Serial.println(col);
#endif
}
uint8_t scrollDataSource(uint8_t dev, MD_MAX72XX::transformType_t t)
// Callback function for data that is required for scrolling into the display
{
static enum { S_IDLE, S_NEXT_CHAR, S_SHOW_CHAR, S_SHOW_SPACE } state = S_IDLE;
static char *p;
static uint16_t curLen, showLen;
static uint8_t cBuf[8];
uint8_t colData = 0;
// finite state machine to control what we do on the callback
switch (state)
{
case S_IDLE: // reset the message pointer and check for new message to load
PRINTS("\nS_IDLE");
p = curMessage; // reset the pointer to start of message
if (newMessageAvailable) // there is a new message waiting
{
strcpy(curMessage, newMessage); // copy it in
newMessageAvailable = false;
}
state = S_NEXT_CHAR;
break;
case S_NEXT_CHAR: // Load the next character from the font table
PRINTS("\nS_NEXT_CHAR");
if (*p == '\0')
state = S_IDLE;
else
{
showLen = mx.getChar(*p++, sizeof(cBuf) / sizeof(cBuf[0]), cBuf);
curLen = 0;
state = S_SHOW_CHAR;
}
break;
case S_SHOW_CHAR: // display the next part of the character
PRINTS("\nS_SHOW_CHAR");
colData = cBuf[curLen++];
if (curLen < showLen)
break;
// set up the inter character spacing
showLen = (*p != '\0' ? CHAR_SPACING : (MAX_DEVICES*COL_SIZE)/2);
curLen = 0;
state = S_SHOW_SPACE;
// fall through
case S_SHOW_SPACE: // display inter-character spacing (blank column)
PRINT("\nS_ICSPACE: ", curLen);
PRINT("/", showLen);
curLen++;
if (curLen == showLen)
state = S_NEXT_CHAR;
break;
default:
state = S_IDLE;
}
return(colData);
}
void scrollText(void)
{
static uint32_t prevTime = 0;
// Is it time to scroll the text?
if (millis() - prevTime >= SCROLL_DELAY)
{
mx.transform(MD_MAX72XX::TSL); // scroll along - the callback will load all the data
prevTime = millis(); // starting point for next time
}
}
void setup()
{
#if DEBUG
Serial.begin(115200);
PRINTS("\n[MD_MAX72XX WiFi Message Display]\nType a message for the scrolling display from your internet browser");
#endif
#if LED_HEARTBEAT
pinMode(HB_LED, OUTPUT);
digitalWrite(HB_LED, LOW);
#endif
// Display initialisation
mx.begin();
mx.setShiftDataInCallback(scrollDataSource);
mx.setShiftDataOutCallback(scrollDataSink);
curMessage[0] = newMessage[0] = '\0';
// Connect to and initialise WiFi network
PRINT("\nConnecting to ", ssid);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED)
{
PRINT("\n", err2Str(WiFi.status()));
delay(500);
}
PRINTS("\nWiFi connected");
// Start the server
server.begin();
PRINTS("\nServer started");
// Set up first message as the IP address
sprintf(curMessage, "%03d:%03d:%03d:%03d", WiFi.localIP()[0], WiFi.localIP()[1], WiFi.localIP()[2], WiFi.localIP()[3]);
PRINT("\nAssigned IP ", curMessage);
}
void loop()
{
#if LED_HEARTBEAT
static uint32_t timeLast = 0;
if (millis() - timeLast >= HB_LED_TIME)
{
digitalWrite(HB_LED, digitalRead(HB_LED) == LOW ? HIGH : LOW);
timeLast = millis();
}
#endif
handleWiFi();
scrollText();
}
The error indicates that you're calling the MD_MAX72XX constructor with the wrong arguments.
This is your current call to it:
MD_MAX72XX mx = MD_MAX72XX(CS_PIN, MAX_DEVICES);
The error indicates that the correct arguments are:
MD_MAX72XX(moduleType_t mod, uint8_t csPin, uint8_t numDevices=1);
The last argument has a default value. Looking at your call to the constructor, you're not passing it the moduleType_t mod argument. The compiler is taking CS_PIN to be that argument, using MAX_DEVICES for the csPin argument, and the default value of 1 for the numDevices argument. It throws the error you're seeing because CS_PIN is an integer and it's expecting a moduleType_t.
You can fix this by providing the correct first argument.
The header file for the library has a list of the possible values for the mod argument:
enum moduleType_t
{
PAROLA_HW, ///< Use the Parola style hardware modules.
GENERIC_HW, ///< Use 'generic' style hardware modules commonly available.
ICSTATION_HW, ///< Use ICStation style hardware module.
FC16_HW ///< Use FC-16 style hardware module.
};
Add the correct moduleType_t for your MAX7219 hardware as the first argument and you should see this error go away.
Believe this is because of the new updates in the library, Like #John Romkey suggested the function should be called with correct number of arguments, add this line of code in your Arduino Sketch and Select the correct hardware from the list PAROLA_H, GENERIC_HW, ICSTATION_HW, FC16_HW.
#######define HARDWARE_TYPE MD_MAX72XX::GENERIC_HW
MD_Parola P = MD_Parola(HARDWARE_TYPE,CS_PIN, MAX_DEVICES);
The library got a update and your code needs some changes to compile succesfully. Here are your options
Option-1. Modify your code to adopt updated library as suggested by John
Option-2. Use old library version. You can select library version in Arduino IDE (Sketch --> Include Library --> Manage Libraries)

How to upload data to thingsSpaek using arduino and esp8266?

I am using an arduino and an esp8266 wifi module to upload data to the things spaek site.I found this code on instructables site inorder to upload random data to the things speak site but it is giving erro on case 3.
here is the code
#include <SoftwareSerial.h>
#define DEBUG true
#define RX 2
#define TX 3
String HOST = "api.thingspeak.com";
String PORT = "80";
String AP = "AP NAME";
String PASS = "AP PASSWORD";
String API = "---------";
String field = "field1";
int countTrueCommand;
int countTimeCommand;
boolean found = false;
int valSensor = 1;
SoftwareSerial esp8266(RX,TX);
void setup() {
Serial.begin(9600);
esp8266.begin(115200);
sendCommand("AT",5,"OK");
sendCommand("AT+CWMODE=1",5,"OK");
sendCommand("AT+CWJAP=""+ AP +"",""+ PASS +""",15,"OK");
countTrueCommand = 0;
}
void loop() {
String getData = "GET /update?api_key="+ API +"&"+ field
+"="+String(valSensor);
switch(countTrueCommand) {
case 0: sendCommand("AT",5,"OK");break;
case 1: sendCommand("AT+RST",10,"invalid");break;
case 2: sendCommand("AT+CIPMUX=1",5,"OK"); break;
case 3: sendCommand("AT+CIPSTART=0,"TCP","+ HOST +","+ PORT,15,"OK");
break;
case 4: sendCommand("AT+CIPSEND=0," +String(getData.length()+4),4,">");
break;
case 5: esp8266.println(getData);delay(1500);countTrueCommand++; break;
case 6: sendCommand("AT+CIPCLOSE=0",5,"OK"); break;
case 7:
Serial.println(valSensor);
Serial.print(getData);
Serial.print(",");
Serial.println(getData.length());
valSensor = random(100000); // random value, change with sensor value if
using sensor
countTrueCommand = 0;
delay(10000);
break;
}
}
void sendCommand(String command, int maxTime, char readReplay[]) {
Serial.print(countTrueCommand);
Serial.print(". at command => ");
Serial.print(command);
Serial.print(" ");
while(countTimeCommand < (maxTime*1))
{
esp8266.println(command);//at+cipsend
if(esp8266.find(readReplay))//ok
{
found = true;
break;
}
countTimeCommand++;
}
if(found == true)
{
Serial.println("OYI");
countTrueCommand++;
countTimeCommand = 0;
}
if(found == false)
{
Serial.println("Fail");
countTrueCommand = 0;
countTimeCommand = 0;
}
found = false;
}
i am getttina an error on case 3 as
exit status 1
unable to find string literal operator 'operator""TCP'
How do i resolve it?
That line is not correct, please replace it with this:
sendCommand("AT+CIPSTART=0,\"TCP\",\""+ HOST +"\","+ PORT,15,"OK"); //Start connection as client

Arduino turn char into a string

I am trying to turn a char into a string so I can extract the values I am interested in, however it just appears empty.
The variable I am interested in is content.
I am performing a get and it returns a JSON object. And want to extract the sunrise and sunset values.
#include <SPI.h>
#include <Ethernet2.h>
#include <String.h>
#include <stdlib.h>
EthernetClient client;
const char* server = "api.sunrise-sunset.org"; // server's address
const char* resource = "/json?lat=53.440&lng=0.200&date=today"; // http resource
const unsigned long BAUD_RATE = 9600; // serial connection speed
const unsigned long HTTP_TIMEOUT = 10000; // max respone time from server
const size_t MAX_CONTENT_SIZE = 512; // max size of the HTTP response
// ARDUINO entry point #1: runs once when you press reset or power the board
void setup() {
initSerial();
initEthernet();
}
// ARDUINO entry point #2: runs over and over again forever
void loop() {
if (connect(server)) {
if (sendRequest(server, resource) && skipResponseHeaders()) {
char response[MAX_CONTENT_SIZE];
String str(response);
Serial.println(str);
char* field;
char* sunset;
char* sunrise;
field = strtok(response,"{,");
while (field != NULL)
{
field = strtok (NULL, ",}");
if(field != NULL)
{
if(strstr(field, "sunrise") != NULL)
{
int length = strlen(field);
sunrise = new char[length + 1];
strncpy(sunrise, field, length + 1); // +1 to copy a terminating null as well
}
if(strstr(field, "sunset") != NULL)
{
int length = strlen(field);
sunset = new char[length + 1];
strncpy(sunset, field, length + 1); // +1 to copy a terminating null as well
}
}
}
//Serial.println("SUNRISE DATA: %s\n\n", sunrise);
//Serial.println("SUNSET DATA: %s\n\n", sunset);
free(sunrise); // do not forget to free the memory if not needed anymore
free(sunset); // do not forget to free the memory if not needed anymore
}
disconnect();
}
wait();
}
// Initialize Serial port
void initSerial() {
Serial.begin(BAUD_RATE);
while (!Serial) {
; // wait for serial port to initialize
}
Serial.println("Serial ready");
}
// Initialize Ethernet library
void initEthernet() {
byte mac[] = {0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED};
byte ip[] = { 192,168,0,202 };
if (!Ethernet.begin(mac)) {
Serial.println("Failed to configure Ethernet");
return;
}
Serial.println("Ethernet ready");
delay(1000);
}
// Open connection to the HTTP server
bool connect(const char* hostName) {
Serial.print("Connect to ");
Serial.println(hostName);
bool ok = client.connect(hostName, 80);
Serial.println(ok ? "Connected" : "Connection Failed!");
return ok;
}
// Send the HTTP GET request to the server
bool sendRequest(const char* host, const char* resource) {
Serial.print("GET ");
Serial.println(resource);
client.print("GET ");
client.print(resource);
client.println(" HTTP/1.1");
client.print("Host: ");
client.println(server);
client.println("Connection: close");
client.println();
return true;
}
// Skip HTTP headers so that we are at the beginning of the response's body
bool skipResponseHeaders() {
// HTTP headers end with an empty line
char endOfHeaders[] = "\r\n\r\n";
client.setTimeout(HTTP_TIMEOUT);
bool ok = client.find(endOfHeaders);
if (!ok) {
Serial.println("No response or invalid response!");
}
return ok;
}
void disconnect() {
Serial.println("Disconnect");
client.stop();
}
// Pause for a 1 minute
void wait() {
Serial.println("Wait 60 seconds");
delay(60000);
}
I think there is a misunderstanding from your side. Certainly you want to process the response of the server and according to your code, this is char response[MAX_CONTENT_SIZE] where the response is stored.
Now this already is a string, more or less. An array of characters, chars. Definiton from here.
Strings are actually one-dimensional array of characters terminated by a null character '\0'. Thus a null-terminated string contains the characters that comprise the string followed by a null.
You can extract the relevant parts from it straight away.
Your response should look like something like this, according to sunrise-sunset.org/api. Note that I just copied the data into an array for testing purposes.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define MAX_CONTENT_SIZE 512
char response[MAX_CONTENT_SIZE] = \
"{\
\"results\":\
{\
\"sunrise\":\"7:27:02 AM\",\
\"sunset\":\"5:05:55 PM\",\
\"solar_noon\":\"12:16:28 PM\",\
\"day_length\":\"9:38:53\",\
\"civil_twilight_begin\":\"6:58:14 AM\",\
\"civil_twilight_end\":\"5:34:43 PM\",\
\"nautical_twilight_begin\":\"6:25:47 AM\",\
\"nautical_twilight_end\":\"6:07:10 PM\",\
\"astronomical_twilight_begin\":\"5:54:14 AM\",\
\"astronomical_twilight_end\":\"6:38:43 PM\"\
},\
\"status\":\"OK\"\
}";
You can easily process it using strtok function from string.h. Using a {, delimiter first will separate "result":{ from "sunrise .... Then you can use a }, delimiter.
With strstr you can check for "sunrise" and "sunset" field, and if you find them you can copy their value into a new string with strncpy.
int main()
{
char* field;
char* sunset;
char* sunrise;
field = strtok(response,"{,");
while (field != NULL)
{
field = strtok (NULL, ",}");
if(field != NULL)
{
if(strstr(field, "sunrise") != NULL)
{
int length = strlen(field);
sunrise = malloc(length * sizeof(char) + 1); // +1 for terminating null character '\0'
strncpy(sunrise, field, length + 1); // +1 to copy a terminating null as well
}
if(strstr(field, "sunset") != NULL)
{
int length = strlen(field);
sunset = malloc(length * sizeof(char) + 1); // +1 for terminating null character '\0'
strncpy(sunset, field, length + 1); // +1 to copy a terminating null as well
}
}
}
printf("SUNRISE DATA: %s\n\n", sunrise);
printf("SUNSET DATA: %s\n\n", sunset);
free(sunrise); // do not forget to free the memory if not needed anymore
free(sunset); // do not forget to free the memory if not needed anymore
return 0;
}
The output of this program is:
SUNRISE DATA: "sunrise":"7:27:02 AM"
SUNSET DATA: "sunset":"5:05:55 PM"
You can further process these strings with strtok again if you like. This is just an example code, you can use it to implement your solution.

the IF command cant continue to else for turn off motor dc

I’ve a project for control a robot in arduino via android.
the trouble is when I press a button for pin 6 (Maju), its turn ON.
But when I press it again its always ON, cant turn OFF.
Here's my code:
int kananMaju;
int kiriMundur;
int kananMundur;
int kiriMaju;
#define Kanan A4
#define Kiri 13
#define Maju 6
#define Mundur A5
#define STBY 12
#define PWMA 11 //left
#define PWMB 10 //right
#define AIN2 8
#define AIN1 7
#define BIN1 3
#define BIN2 2
#include <SoftwareSerial.h>
#define DEBUG true
SoftwareSerial esp8266(4,5); // make RX Arduino line is pin 2, make TX Arduino line is pin 3.
// This means that you need to connect the TX line from the esp to the Arduino's pin 2
// and the RX line from the esp to the Arduino's pin 3
void setup()
{
Serial.begin(9600);
esp8266.begin(9600); // your esp's baud rate might be different
pinMode(STBY,OUTPUT);
pinMode(BIN2,OUTPUT);
pinMode(BIN1,OUTPUT);
pinMode(AIN2,OUTPUT);
pinMode(AIN1,OUTPUT);
pinMode(PWMB,OUTPUT);
pinMode(PWMA,OUTPUT);
digitalWrite(STBY, HIGH); //standby
digitalWrite(BIN1, HIGH);
digitalWrite(BIN2, HIGH);
digitalWrite(AIN1, HIGH);
digitalWrite(AIN2, HIGH);
analogWrite(PWMB, 100); //490 Hz
analogWrite(PWMA, 100); //490 Hz
pinMode(Maju,OUTPUT);
digitalWrite(Maju,LOW);
sendCommand("AT+RST\r\n",2000,DEBUG); // reset module
sendCommand("AT+CWMODE=1\r\n",1000,DEBUG); // configure as access point
sendCommand("AT+CWJAP=\"PanduGanteng\",\"akhirpekan666\"\r\n",3000,DEBUG);
delay(10000);
sendCommand("AT+CIFSR\r\n",1000,DEBUG); // get ip address
sendCommand("AT+CIPMUX=1\r\n",1000,DEBUG); // configure for multiple connections
sendCommand("AT+CIPSERVER=1,8080\r\n",1000,DEBUG); // turn on server on port 80
Serial.println("Server Ready");
}
void loop()
{
if(esp8266.available()) // check if the esp is sending a message
{
if(esp8266.find("+IPD,"))
{
delay(1000); // wait for the serial buffer to fill up (read all the serial data)
// get the connection id so that we can then disconnect
int connectionId = esp8266.read()-48; // subtract 48 because the read() function returns
// the ASCII decimal value and 0 (the first decimal number) starts at 48
esp8266.find("pin="); // advance cursor to "pin="
int pinNumber = (esp8266.read()-48); // get first number i.e. if the pin 13 then the 1st number is 1
int secondNumber = (esp8266.read()-48);
if(secondNumber>=0 && secondNumber<=9)
{
pinNumber*=10;
pinNumber +=secondNumber; // get second number, i.e. if the pin number is 13 then the 2nd number is 3, then add to the first number
}
digitalWrite(pinNumber, !digitalRead(pinNumber)); // toggle pin
// build string that is send back to device that is requesting pin toggle
String content;
content = "Pin ";
content += pinNumber;
content += " is ";
if(digitalRead(Maju))
{
content += "ON";
kiriMaju;{
digitalWrite(STBY,HIGH);
analogWrite(PWMA, 100);
digitalWrite(AIN1,HIGH);
digitalWrite(AIN2,LOW);
}
kananMaju;{
digitalWrite(STBY,HIGH);
analogWrite(PWMB, 100);
digitalWrite(BIN1, LOW);
digitalWrite(BIN2, HIGH);
}
}
else
{
content += "OFF";
}
sendHTTPResponse(connectionId,content);
// make close command
String closeCommand = "AT+CIPCLOSE=";
closeCommand+=connectionId; // append connection id
closeCommand+="\r\n";
sendCommand(closeCommand,1000,DEBUG); // close connection
}
}
}
/*
* Name: sendData
* Description: Function used to send data to ESP8266.
* Params: command - the data/command to send; timeout - the time to wait for a response; debug - print to Serial window?(true = yes, false = no)
* Returns: The response from the esp8266 (if there is a reponse)
*/
String sendData(String command, const int timeout, boolean debug)
{
String response = "";
int dataSize = command.length();
char data[dataSize];
command.toCharArray(data,dataSize);
esp8266.write(data,dataSize); // send the read character to the esp8266
if(debug)
{
Serial.println("\r\n====== HTTP Response From Arduino ======");
Serial.write(data,dataSize);
Serial.println("\r\n========================================");
}
long int time = millis();
while( (time+timeout) > millis())
{
while(esp8266.available())
{
// The esp has data so display its output to the serial window
char c = esp8266.read(); // read the next character.
response+=c;
}
}
if(debug)
{
Serial.print(response);
}
return response;
}
/*
* Name: sendHTTPResponse
* Description: Function that sends HTTP 200, HTML UTF-8 response
*/
void sendHTTPResponse(int connectionId, String content)
{
// build HTTP response
String httpResponse;
String httpHeader;
// HTTP Header
httpHeader = "HTTP/1.1 200 OK\r\nContent-Type: text/html; charset=UTF-8\r\n";
httpHeader += "Content-Length: ";
httpHeader += content.length();
httpHeader += "\r\n";
httpHeader +="Connection: close\r\n\r\n";
httpResponse = httpHeader + content + " "; // There is a bug in this code: the last character of "content" is not sent, I cheated by adding this extra space
sendCIPData(connectionId,httpResponse);
}
/*
* Name: sendCIPDATA
* Description: sends a CIPSEND=<connectionId>,<data> command
*
*/
void sendCIPData(int connectionId, String data)
{
String cipSend = "AT+CIPSEND=";
cipSend += connectionId;
cipSend += ",";
cipSend +=data.length();
cipSend +="\r\n";
sendCommand(cipSend,1000,DEBUG);
sendData(data,1000,DEBUG);
}
/*
* Name: sendCommand
* Description: Function used to send data to ESP8266.
* Params: command - the data/command to send; timeout - the time to wait for a response; debug - print to Serial window?(true = yes, false = no)
* Returns: The response from the esp8266 (if there is a reponse)
*/
String sendCommand(String command, const int timeout, boolean debug)
{
String response = "";
esp8266.print(command); // send the read character to the esp8266
long int time = millis();
while( (time+timeout) > millis())
{
while(esp8266.available())
{
// The esp has data so display its output to the serial window
char c = esp8266.read(); // read the next character.
response+=c;
}
}
if(debug)
{
Serial.print(response);
}
return response;
}
I want to when I press button for pin 6 is ON, and when I press it again its OFF. But it's always turned ON, where's my fault?
Maju should be an input not an output
And you need to toggle a state
pinMode(Maju,INPUT);
static boolean function get_state()
{
static boolean previous = LOW;
static boolean state = LOW;
boolean current = digitalRead(Maju);
if (current == HIGH && current != previous) {
state = (state == LOW) ? HIGH : LOW;
}
previous = current;
return state;
}

Resources