WiFi Client Connectivity with a Google search Added

I am trying to write a simple sketch that connects to web and prints what it find, but without any luck. My code is based on an Arduino script I found and the references I find here.

It connects to the network, but is unable to get any sense from Google. I tried this with a local server too. It is unable to connect to that either.

#include <SPI.h>
#include <WiFi.h>

// Set these to your desired credentials.
const char *ssid = “SSID”;
const char *password = “PASSWD”;

int status = WL_IDLE_STATUS;
IPAddress server(8,8,8,8); // Google

// Initialize the client library
WiFiClient client;

void setup() {
Serial.begin(115200);
Serial.setDebugOutput(true);
Serial.println();

Serial.println(“Attempting to connect to WPA network…”);
Serial.print("SSID: ");
Serial.println(ssid);

WiFi.begin(ssid, password);
WiFi.setSleep(false);
while ( WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
// don’t do anything else:
}
Serial.println(“Connected to wifi”);
Serial.println("\nStarting connection…");
// if you get a connection, report back via serial:
if (client.connect(server, 80)) {
Serial.println(“connected”);
client.println(“GET /search?q=arduino HTTP/1.0”);
client.println();
} else {
Serial.println(“connection failed”);
}

}

void loop() {
if (client.available()) {
char c = client.read();
Serial.print(c);
}

if (client.connected()) {
Serial.println();
Serial.println(“disconnecting.”);
client.stop();
}
delay(10000);
}

Hi there,
So You forgot to paste it into the code tags " </> " from above so , Here is a basic ping the host start there
you do know you’ll need a Google API key to do a custom search , So there’s that it does work with my own Key no problem.

  // Perform Google search
  googleSearch(searchQuery);
}

void googleSearch(String query) {
  if (WiFi.status() == WL_CONNECTED) {
    HTTPClient http;
    String url = "https://www.googleapis.com/customsearch/v1?key=" + apiKey + "&cx=" + searchEngineId + "&q=" + query;
    
    // Make GET request
    http.begin(url);
    int httpCode = http.GET();

    // If the GET request was successful
    if (httpCode > 0) {
      String payload = http.getString();
      Serial.println("Search Result:");
      Serial.println(payload);
    } else {
      Serial.println("Error on HTTP request");
    }

    http.end(); // Free resources
  } else {
    Serial.println("WiFi not connected");
  }
}

Here is the code I’m using currently for testing.

#include <SPI.h>
#include <WiFi.h>

#include <ESP32Ping.h> 

const IPAddress remote_ip(8,8,8,8);
const char* remote_host = "www.google.com";

// Set these to your desired credentials.
const char *ssid = "GlassSurf-2.4";
const char *password = "SEEEDSTUDIO";  //not really

int status = WL_IDLE_STATUS;
IPAddress server(8,8,8,8); // Google
// Specify IP address or hostname
String hostName = "www.google.com";
int pingResult;
// Initialize the client library
WiFiClient client;

void setup() {
Serial.begin(9600);
//Serial.setDebugOutput(true);
Serial.println();
Serial.println();
  Serial.println("Program " __FILE__ " compiled on " __DATE__ " at " __TIME__);
  Serial.println();
  Serial.println("Processor came out of reset.");
  Serial.println();
Serial.println("Attempting to connect to WPA network…");
Serial.print("SSID: ");
Serial.println(ssid);

WiFi.begin(ssid, password);
WiFi.setSleep(false);
while ( WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
// don’t do anything else:
}
Serial.println("");
Serial.print("Connected to wifi");
 Serial.print(WiFi.localIP());

 // Ping Google
Serial.println("");
   Serial.print("Pinging ip ");
  Serial.println(remote_ip);

  if(Ping.ping(remote_ip)) {
    Serial.println("Success!!");
  } else {
    Serial.println("Error :(");
  }
Serial.print("Pinging host ");
  Serial.println(remote_host);

  if(Ping.ping(remote_host)) {
    Serial.println("Success!!");
  } else {
    Serial.println("Error :(");
  }
}

void loop() { }

Serial output.

Success!!


Program D:\Arduino_projects\Sketch_Google_ping\Sketch_Google_ping.ino compiled on Sep 10 2024 at 14:08:15

Processor came out of reset.

Attempting to connect to WPA network…
SSID: GlassSurf-2.4
.
Connected to wifi192.168.1.187
Pinging ip 8.8.8.8
Success!!
Pinging host www.google.com
Success!!

HTH
GL :slight_smile: PJ :v:

Hi there,
So I went back and created a custom search in the Google API console. It worked very well, returns a Json list of Data, Now I can can build on this by:

  • Parsing the JSON response: If you want to extract specific data like URLs or descriptions from the search results,
  • Handling different queries: I can dynamically change the search query based on input, sensors, or other conditions in the project.

HTH
GL :slight_smile: PJ :v:

#include <WiFi.h>
#include <HTTPClient.h>

const char *ssid = "GlassSurf-2.4";
const char *password = "SeeedStudio :-p ";


// Google API Key and CSE ID
const String apiKey = "REPLACE with YOUR KEY ";  // Your API key
const String searchEngineId = "REPLACEwithYOURs";  // Your CSE ID

// Search query
const String searchQuery = "Arduino project"; // you can set this to whatever your searching for

void setup() {
  Serial.begin(115200);

  // Connect to Wi-Fi
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) {
    delay(1000);
    Serial.println("Connecting to WiFi...");
  }
  Serial.println("Connected to WiFi!");
  Serial.print("IP Address: ");
  Serial.println(WiFi.localIP());

  // Perform Google search
  googleSearch(searchQuery);
}

void googleSearch(String query) {
  if (WiFi.status() == WL_CONNECTED) {
    HTTPClient http;

    // Make sure to replace spaces with '%20' for URL encoding
    String encodedQuery = query;
    encodedQuery.replace(" ", "%20");

    // Correct URL formatting for Google's Custom Search API
    String url = "https://www.googleapis.com/customsearch/v1?key=" + apiKey + "&cx=" + searchEngineId + "&q=" + encodedQuery;
    
    Serial.print("Requesting URL: ");
    Serial.println(url);
    
    // Make GET request to Google Custom Search API
    http.begin(url);
    int httpCode = http.GET();

    // If the GET request was successful
    if (httpCode > 0) {
      String payload = http.getString();
      Serial.println("Search Result:");
      Serial.println(payload);  // Print the raw JSON result from the API
    } else {
      Serial.print("Error on HTTP request: ");
      Serial.println(httpCode);
    }

    http.end();  // Free resources
  } else {
    Serial.println("WiFi not connected");
  }
}

void loop() {
  // Nothing to
}

The output is Long so I’ll only add some of it.

Connecting to WiFi...
Connected to WiFi!
IP Address: 192.168.1.187
Requesting URL: https://www.googleapis.com/customsearch/v1?key=YOMOMA...&cx=NO_MOMA&q=Arduino%20project
Search Result:
{
  "kind": "customsearch#search",
  "url": {
    "type": "application/json",
    "template": "https://www.googleapis.com/customsearch/v1?q={searchTerms}&num={count?}&start={startIndex?}&lr={language?}&safe={safe?}&cx={cx?}&sort={sort?}&filter={filter?}&gl={gl?}&cr={cr?}&googlehost={googleHost?}&c2coff={disableCnTwTranslation?}&hq={hq?}&hl={hl?}&siteSearch={siteSearch?}&siteSearchFilter={siteSearchFilter?}&exactTerms={exactTerms?}&excludeTerms={excludeTerms?}&linkSite={linkSite?}&orTerms={orTerms?}&dateRestrict={dateRestrict?}&lowRange={lowRange?}&highRange={highRange?}&searchType={searchType}&fileType={fileType?}&rights={rights?}&imgSize={imgSize?}&imgType={imgType?}&imgColorType={imgColorType?}&imgDominantColor={imgDominantColor?}&alt=json"
  },
  "queries": {
    "request": [
      {
        "title": "Google Custom Search - Arduino project",
        "totalResults": "42000000",
        "searchTerms": "Arduino project",
        "count": 10,
        "startIndex": 1,
        "inputEncoding": "utf8",
        "outputEncoding": "utf8",
        "safe": "off",
        "cx": "b7801a19959ec4def"
      }
    ],
    "nextPage": [
      {
        "title": "Google Custom Search - Arduino project",
        "totalResults": "42000000",
        "searchTerms": "Arduino project",
        "count": 10,
        "startIndex": 11,
        "inputEncoding": "utf8",
        "outputEncoding": "utf8",
        "safe": "off",
        "cx": "b7801a19959ec4def"
      }
    ]
  },
  "context": {
    "title": "SeeedTest"
},
  "searchInformation": {
    "searchTime": 0.350992,
    "formattedSearchTime": "0.35",
    "totalResults": "42000000",
    "formattedTotalResults": "42,000,000"
  },
  "items": [
    {
      "kind": "customsearch#result",
      "title": "Arduino Project Hub",
      "htmlTitle": "\u003cb\u003eArduino Project\u003c/b\u003e Hub",
      "link": "https://projecthub.arduino.cc/",
      "displayLink": "projecthub.arduino.cc",
      "snippet": "Arduino Project Hub is a website for sharing tutorials and descriptions of projects made with Arduino boards.",
      "htmlSnippet": "\u003cb\u003eArduino Project\u003c/b\u003e Hub is a website for sharing tutorials and descriptions of projects made with Arduino boards.",
      "formattedUrl": "https://projecthub.arduino.cc/",
      "htmlFormattedUrl": "https://\u003cb\u003eproject\u003c/b\u003ehub.\u003cb\u003earduino\u003c/b\u003e.cc/",
      "pagemap": {
        "cse_thumbnail": [
          {
            "src": "https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQVpvlC8drwI09Tpqidcqz-ZuCn9_wLIkhBcwCM8pZenZLcrjEqLOkW0dQ&s",
            "width": "259",
            "height": "194"
          }
        ],
        "metatags": [
          {
            "next-head-count": "10",
            "twitter:card": "summary_large_image",
            "og:site_name": "Arduino Project Hub",
            "viewport": "width=device-width",
            "og:title": "Arduino Project Hub",
            "title": "Arduino Project Hub"
          }
        ],
        "cse_image": [
          {
            "src": "https://projects.arduinocontent.cc/thumbnails/resized-mobile-e457819e-a3e1-4e2a-b906-0b6434bbb2d7.png"
          }

Works GREAT!

Thanks PJ,

This is a great start and maybe I can work with a POST to get around what I want to do, but ideally I still want to use sockets here, not HTTP ideally, and I want to understand if the socket library with this chip is broken. The ultimate goal is not to connect with HTTP, but to use my own protocol, raw sockets.

I have some iOS code that I wrote that works perfectly. I want to connect to it. I can do on the command line, but I am unable to touch the seeded studio chip?

Seeed Studio claims this works in their documentation, so what have I missed here or is simply broken? Can I report this as a bug. I did log call with tech support, but I am yet to get any response.

I want to be able to run this command on a terminal, connecting to a socket running on the seeded Studio in an ideal world.

echo -n “poke” | nc -w1 192.168.1.119 2024

So echo with the work “poke” is piped to the command “nc” which tried to pass it through to a socket running on 192.168.1.119, port 2024. Here is a link to an article on the iOS swift that does work with the nc command.

Eureka! I found the answer PJ. It is the port number; it has to be above 49152 for the server or the client to work as dedicated sockets.

They will work as 80 or 8080, but not 1984 it seems.

1984, a difficult year, although better than 2005-2009 when you worked for that Idiot :slight_smile:

Hi there,
Great!, Yea TCP/IP port numbers. 8888, 8080, 80, Private socket from device to device.
Sweet. Iphone is a little trickier with sockets so that’s cool stuff.
GL :slight_smile: PJ
:v: