Arduino Ethernet shield not connecting to a website - connection

I am trying to send data to a local server using the code below:
The server does not receive the data through the Ethernet shield. It says it connects successfully.
I have pinged Google with the Ethernet shield and also sent data through the browser using the link in char server[]. Both cases work well. Does anyone know the problem?
#include <Ethernet.h>
#include <SPI.h>
byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
byte ip[] = { 192, 168, 0, 116 };
char server[] = "http://192.168.0.175/test-app/listener?data=1234";
EthernetClient client;
void setup()
{
Ethernet.begin(mac, ip);
Serial.begin(9600);
delay(1000);
Serial.println("connecting...");
if (client.connect(server,8080)) {
Serial.println("connected");
//client.println("GET /search?q=arduino HTTP/1.0");
//client.println();
client.stop();
} else {
Serial.println("connection failed");
}
}
void loop()
{
if (client.connect(server,80)){
client.stop();
Serial.println("yay!!");
}
}

You are giving full path in the server name, it only needs to be the base URL.

Related

ESP8266 Subscribe to AWS IOT topic

Hi I need to create a lambda function which will access the AWS thing and publish MQTT message, I'd like to get the published message on the ESP8266 which was connected to the thing as well, and controlled turn on/off the LED on ESP8266. So far I have uploaded the private.der, cert.der and ca.der to the ESP8266 absolutely, but it couldn't subscribed AWS IOT, please point me in the right tips then please share.
Code:
#include <ESP8266WiFi.h>
#include <PubSubClient.h>
#include <NTPClient.h>
#include <WiFiUdp.h>
#include <ArduinoJson.h>
#define OUT_TOPIC "$aws/things/devices/shadow/update"
#define IN_TOPIC "$aws/things/devices/shadow/update/delta"
const char* ssid = "sid";
const char* password = "password";
WiFiUDP ntpUDP;
NTPClient timeClient(ntpUDP, "pool.ntp.org");
const char* AWS_endpoint = "endpoint.amazonaws.com";//MQTT broker ip
const char* json = "{\"state\":{\"reported\":{\"led\":\"off\"}}}";
StaticJsonDocument<1024> doc;
WiFiClientSecure espClient;
PubSubClient mqttClient(espClient);//set MQTT port number to 8883 as per standard
PubSubClient client(AWS_endpoint, 8883, espClient);
long lastMsg = 0;
char msg[50];
int value = 0;
void setup_wifi() {
delay(10);// We start by connecting to a WiFi network
espClient.setBufferSizes(512, 512);
Serial.println();
Serial.print("Connecting to ");
Serial.println(ssid);
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());
timeClient.begin();
while(!timeClient.update()){
timeClient.forceUpdate();
}
espClient.setX509Time(timeClient.getEpochTime());
int qos = 0;//Maximum size of data that can be communicated
Serial.println(MQTT_MAX_PACKET_SIZE);
if(mqttClient.subscribe(IN_TOPIC, qos)){
Serial.println("Subscribed.");
Serial.println("Success!!");
}
deserializeJson(doc, json);
JsonObject obj = doc.as<JsonObject>();
if(mqttClient.publish(OUT_TOPIC, json)){
Serial.println("Published!!");
}
}
void setup() {
Serial.begin(115200);
Serial.setDebugOutput(true);
// initialize digital pin LED_BUILTIN as an output.
pinMode(LED_BUILTIN, OUTPUT);
setup_wifi();
delay(1000);
if (!SPIFFS.begin()) {
Serial.println("Failed to mount file system");
return;
}
Serial.print("Heap: "); Serial.println(ESP.getFreeHeap());
//replace cert.crt eith your uploaded file name
File cert = SPIFFS.open("/cert.der", "r");
if (!cert) {
Serial.println("Failed to open cert file");
}
else
Serial.println("Success to open cert file");
delay(1000);
if (espClient.loadCertificate(cert))
Serial.println("cert loaded");
else
Serial.println("cert not loaded");
// Load private key file
File private_key = SPIFFS.open("/private.der", "r");//replace private eith your uploaded file name
if (!private_key) {
Serial.println("Failed to open private cert file");
}
else
Serial.println("Success to open private cert file");
delay(1000);
if (espClient.loadPrivateKey(private_key))
Serial.println("private key loaded");
else
Serial.println("private key not loaded");
// Load CA file
File ca = SPIFFS.open("/ca.der", "r");
//replace ca eith your uploaded file name
if (!ca) {
Serial.println("Failed to open ca ");
}
else
Serial.println("Success to open ca");
delay(1000);
if(espClient.loadCACert(ca))
Serial.println("ca loaded");
else
Serial.println("ca failed");
Serial.print("Heap: ");
Serial.println(ESP.getFreeHeap());
}
void callback (char* topic, byte* payload, unsigned int length) {
Serial.println("Received. topic=");
Serial.println(topic);
char subsc[length];
for(int i=0; i<length; i++){
subsc [i]=(char)payload[i];
subsc [length]='\0';
Serial.print(subsc);
}
Serial.print("\n");
digitalWrite(LED_BUILTIN, HIGH);
}
void mqttLoop() {
mqttClient.loop();
delay(100);
//digitalWrite(LED_pin, LOW);
digitalWrite(LED_BUILTIN, LOW);
Serial.print(".");
}
void loop() {
It looks like you're using the older forms of WiFiClientSecure certificate handling. I'll assume that's working OK and you're able to establish an SSL connection.
Your IN_TOPIC needs to be updated slightly to: $aws/things/<name-of-your-thing>/shadow/update/accepted (where hopefully you know what <name-of-your-thing> is). You can get this from the thing shadow on your AWS console.
Similarly AWS_endpoint needs updating: it should be of the form <random-stuff-specific-to-you>.iot.<region>.amazonaws.com. You can also find it from the same place as the MQTT topics.
You only want one instance of PubSubClient. I'll assume you delete client and keep mqttClient. You'll need to update the instantiation to include the AWS endpoint and port as you have done for client.
Before calling mqttClient.subscribe(...) you need to register the callback:
mqttClient.setCallback(::callback);
then connect to AWS:
mqttClient.connect("some-unique-name");
Finally, you need to edit PubSubClient.h (look for it in Arduino/libraries/PubSubClient/src) to update MQTT_MAX_PACKET_SIZE. The default is 128 and I've found that too small with AWS's messages. I've made mine 1024:
#define MQTT_MAX_PACKET_SIZE 1024
and that appears ample.
Once that compiles and runs you'll start seeing callback(...) called with the topics you've subscribed to and you can implement the function to do whatever you need.
The PubSubClient doesn't do much error reporting to help diagnose what's going on. I'm currently refactoring it a bit and including more diagnostic information and will eventually issue a pull request. Let me know if you'd like my hacked version before I get that far.

Arduino ESP8266 01 MQTT Raspberry pi

I want to use ESP 8266 01 and arduino uno as client in MQTT. The code For ESP8266 01 is successfully compiled and I'M getting errors in Arduino uno
The error is 'messageTemp' was not declared in this scope
Amd also I have a thought of using stm32xx in client.
If I compile for that
exit status 1
ISO C++ forbids comparison between pointer and integer [-fpermissive]
above is the error I'm getting
1)ESP code
// Loading the ESP8266WiFi library and the PubSubClient library
#include <ESP8266WiFi.h>
#include <PubSubClient.h>
// Change the credentials below, so your ESP8266 connects to your router
const char* ssid = "YOUR_SSID";
const char* password = "YOUR_PASSWORD";
const char* mqtt_server = "YOUR_RPi_IP_Address";
// Initializes the espClient
WiFiClient espClient;
PubSubClient client(espClient);
void setup_wifi() {
delay(10);
// We start by connecting to a WiFi network
Serial.println();
Serial.print("Connecting to ");
Serial.println(ssid);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.print("WiFi connected - ESP IP address: ");
Serial.println(WiFi.localIP());
}
if(topic=="home/office/esp1/gpio2"){
Serial.print("Changing GPIO 2 to ");
if(messageTemp == "1"){
// digitalWrite(ledGPIO2, HIGH);
Serial.print("On");
}
else if(messageTemp == "0"){
// digitalWrite(ledGPIO2, LOW);
Serial.print("Off");
}
}
Serial.println();
}
void reconnect() {
// Loop until we're reconnected
while (!client.connected()) {
Serial.print("Attempting MQTT connection...");
// Attempt to connect
if (client.connect("ESP8266Client")) {
Serial.println("connected");
client.subscribe("home/office/esp1/gpio2");
}
else
{
Serial.print("failed, rc=");
Serial.print(client.state());
Serial.println(" try again in 5 seconds");
// Wait 5 seconds before retrying
delay(5000);
}
}
}
void setup() {
Serial.begin(115200);
setup_wifi();
client.setServer(mqtt_server, 1883);
client.setCallback(callback);
}
void loop() {
if (!client.connected()) {
reconnect();
}
client.loop();
}
Code for Arduino UNO
void setup(){
Serial.begin(9600);
pinMode(12, OUTPUT);
digitalWrite(12, HIGH);
String messageTemp;
}
void callback(String topic, byte* message, unsigned int length) {
Serial.print("Message arrived on topic: ");
Serial.print(topic);
Serial.print(". Message: ");
String messageTemp;
for (int i = 0; i < length; i++) {
Serial.print((char)message[i]);
messageTemp += (char)message[i];
}
Serial.println();
}
void loop ()
{
if (Serial.available()){
char topic = Serial.read();
{
if (topic=="home/office/esp1/gpio2")
{
Serial.print("Changing GPIO 2 to ");
if(messageTemp == "1"){
digitalWrite(12, HIGH);
Serial.print("On");
}
else if(messageTemp == "0")
{
digitalWrite(12, LOW);
Serial.print("Off");
}
}}}}
ESP code doesn't look the whole source code you provided. In case of Arduino UNO, if you're intending to use messageTemp as a global variable, then you need to declare it only one time outside of functions. In the above code, you declared it twice in setup() and callback(), then those are considered as local variables. Even in loop(), there's no declaration, this should create the compile error.

GET request failed in Arduino-Uno

I am trying to access a simple web page running in my Rpi-server using ESP8266 and Arduino.
I have refereed this similar SO question , but it's not the solution for my problem.
Here is my current Arduino Code :
#include "WiFiEsp.h"
// Emulate Serial1 on pins 6/7 if not present
#ifndef HAVE_HWSERIAL1
#include "SoftwareSerial.h"
SoftwareSerial Serial1(2,3); // RX, TX
#endif
char ssid[] = "RPi"; // your network SSID (name)
char pass[] = "raspberry"; // your network password
int status = WL_IDLE_STATUS; // the Wifi radio's status
char server[] = "192.168.50.1";
// Initialize the Ethernet client object
WiFiEspClient client;
void setup()
{
// initialize serial for debugging
Serial.begin(9600);
// initialize serial for ESP module
Serial1.begin(9600);
// initialize ESP module
WiFi.init(&Serial1);
// check for the presence of the shield
if (WiFi.status() == WL_NO_SHIELD) {
Serial.println("WiFi shield not present");
// don't continue
while (true);
}
// attempt to connect to WiFi network
while ( status != WL_CONNECTED) {
Serial.print("Attempting to connect to WPA SSID: ");
Serial.println(ssid);
// Connect to WPA/WPA2 network
status = WiFi.begin(ssid, pass);
}
// you're connected now, so print out the data
Serial.println("You're connected to the network");
printWifiStatus();
Serial.println();
Serial.println("Starting connection to server...");
// if you get a connection, report back via serial
if (client.connect(server, 80)) {
Serial.println("Connected to server");
// Make a HTTP request
client.println("GET /simple.html HTTP/1.1");
client.println("Host: 192.168.50.1");
client.println("Connection: close");
client.println();
}
}
void loop()
{
while (client.available()) {
char c = client.read();
Serial.write(c);
}
// if the server's disconnected, stop the client
if (!client.connected()) {
Serial.println();
Serial.println("Disconnecting from server...");
client.stop();
// do nothing forevermore
while (true);
}
void printWifiStatus()
{
// print the SSID of the network you're attached to
Serial.print("SSID: ");
Serial.println(WiFi.SSID());
// print your WiFi shield's IP address
IPAddress ip = WiFi.localIP();
Serial.print("IP Address: ");
Serial.println(ip);
// print the received signal strength
long rssi = WiFi.RSSI();
Serial.print("Signal strength (RSSI):");
Serial.print(rssi);
Serial.println(" dBm");
}
Output:
Starting connection to server...
[WiFiEsp] Connecting to 192.168.50.1
Connected to server
[WiFiEsp] Data packet send error (2)
[WiFiEsp] Failed to write to socket 3
[WiFiEsp] Disconnecting 3
My simple.html looks like this.
<html>
<body>
<p>1</p>
</body>
</html>
}
I accessed to this page from web browser and it shows the content properly.
What is missing here?
Thanks in advance.
Try this line in your code
client.print("GET /simple.html HTTP/1.0\r\n\r\n");

"does not name type" error when using EtherTen and Arduino

I am currently using an EtherTen to try and connect Arduino to Twitter. However, I keep getting an error saying "'twitter'does not name a type". How can I fix this problem?
#if defined(ARDUINO) && ARDUINO > 18 // Arduino 0019 or later
#include <SPI.h>
#endif
#include <Ethernet.h>
#include <EthernetDNS.h> //Only needed in Arduino 0022 or earlier
#include <Twitter.h>
byte MACaddress[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
byte IPaddress[] = { 10, 0, 0, 177 };
Twitter twitter("MY TOKEN HERE");
char msg[] = "Hello, World! I'm Arduino!";
void setup()
{
delay(1000);
Ethernet.begin(MACaddress, IPaddress);
Serial.begin(9600);
Serial.println("connecting ...");
if (twitter.post(msg)) {
int status = twitter.wait();
if (status == 200) {
Serial.println("OK.");
}
else {
Serial.print("failed : code ");
Serial.println(status);
}
}
else {
Serial.println("connection failed.");
}
}
void loop()
{
}
This is a fair question. It looks a lot like the sample code. The first thing I would try is removing the "<<<" and the ">>>" from the constructor?
Twitter twitter("1521141456-FjH4fHVENG3xxxxxxxxxxxxxxxxxx");
If that does not help you could look at your Ethernet.begin .
Ethernet.begin(mac, ip, gateway, subnet);
rather than
Ethernet.begin(mac, ip);
NOTE
You should be careful posting your twitter token id on a forum. I think you should edit your post so as to hide your token.

Arduino Ethernet Shield Not Connecting to WebServer

I have a problem making my Arduino Ethernet shield to communicate with the server,
the result on the serial monitor is always:
my arduino code is
#include <Ethernet.h> //library for ethernet functions
#include <SPI.h>
#include <Dns.h>
#include <Client.h> //library for client functions
#include <DallasTemperature.h> //library for temperature sensors
// Ethernet settings
byte mac[] = {0x09,0xA2,0xDA,0x00,0x01,0x26}; //Replace with your Ethernet shield MAC
byte ip[] = { 192,168,0,54}; //The Arduino device IP address
byte subnet[] = { 255,255,255,0};
byte gateway[] = { 192,168,0,1};
IPAddress server(192,168,0,53); // IP-adress of server arduino sends data to
EthernetClient client;
bool connected = false;
void setup(void) {
Serial.begin(9600);
Serial.println("Initializing Ethernet.");
delay(1000);
Ethernet.begin(mac, ip , gateway , subnet);
}
void loop(void) {
if(!connected) {
Serial.println("Not connected");
if (client.connect(server, 80)) {
connected = true;
int temp =analogRead(A1);
Serial.print("Temp is ");
Serial.println(temp);
Serial.println();
Serial.println("Sending to Server: ");
client.print("GET /formSubmit.php?t0=");
Serial.print("GET /formSubmit.php?t0=");
client.print(temp);
Serial.print(temp);
client.println(" HTTP/1.1");
Serial.println(" HTTP/1.1");
client.println("Host: http://localhost/PhpProject1/");
Serial.println("Host: http://localhost/PhpProject1/");
client.println("User-Agent: Arduino");
Serial.println("User-Agent: Arduino");
client.println("Accept: text/html");
Serial.println("Accept: text/html");
//client.println("Connection: close");
//Serial.println("Connection: close");
client.println();
Serial.println();
delay(10000);
}
else{
Serial.println("Cannot connect to Server");
}
}
else {
delay(1000);
while (client.connected() && client.available()) {
char c = client.read();
Serial.print(c);
}
Serial.println();
client.stop();
connected = false;
}
}
the server is an Apache server running on a pc, the server ip address in the code is the pc ip address. For testing purposes I work at my homes network, there's no proxy or firewall, and I also turned of the antivirus and firewall on my pc.
the result in the serial monitor is always:
Not connected
Cannot connect to Server
Any thoughts??
It worked, the problem was in Ethernet.begin(mac, ip , gateway , subnet), I removed this line and configure the Ethernet Shield using the DHCP, Ethernet.begin(mac)
Have you verified the MAC address is correct?
If it still doesn't work, try using
Client client(server, 80);
in stead of
EthernetClient client
And change
if (client.connect(server, 80)) {
to
if (client.connect()) {
Hope this helps

Resources