Raspberry Pi Pico W HTTP Sample Code

Raspberry Pi Pico sample codes which are located here are pretty good, however, a few boilerplate codes are missing from these repositories. One being a simple HTTP request code. I can’t believe those people behind official pico examples repositories, haven’t included this.

Anyway, this is my Raspberry Pi Pico W HTTP Sample Code, feel free to share, modify or use it in any way. It includes sample code to connect to a WIFI in station mode as well.

#include <stdio.h>
#include "pico/stdlib.h"
#include "pico/cyw43_arch.h"
#include "lwip/apps/http_client.h"
#include "lwip/tcp.h"
#include "lwip/sys.h"
#include "lwip/timeouts.h"
#include "lwipopts.h"
#include "lwip/udp.h"

char myBuff[1000];

void result(void *arg, httpc_result_t httpc_result,
            u32_t rx_content_len, u32_t srv_res, err_t err)

{
    printf("transfer complete\n");
    printf("local result=%d\n", httpc_result);
    printf("http result=%d\n", srv_res);
}

err_t headers(httpc_state_t *connection, void *arg,
              struct pbuf *hdr, u16_t hdr_len, u32_t content_len)
{
    printf("headers recieved\n");
    printf("content length=%d\n", content_len);
    printf("header length %d\n", hdr_len);

    const char *custom_headers = "User-Agent: PicoClient\r\n"
                                 "Connection: Keep-Alive\r\n";

    pbuf_copy_partial(hdr, myBuff, hdr->tot_len, 0);
    printf("headers \n");
    printf("%s", myBuff);
    return ERR_OK;
}

err_t body(void *arg, struct altcp_pcb *conn,
           struct pbuf *p, err_t err)
{
    printf("body\n");
    pbuf_copy_partial(p, myBuff, p->tot_len, 0);
    printf("%s", myBuff);
    return ERR_OK;
}

err_t cb_recv(void *arg, struct tcp_pcb *tpcb, struct pbuf *p, err_t err)
{
    if (p == NULL)
    {
        // Connection closed by remote host
        return err;
    }

    char buffer[512];
    int copy_len = p->len;
    if (copy_len >= sizeof(buffer))
    {
        copy_len = sizeof(buffer) - 1; // avoid overflow
    }

    memcpy(buffer, p->payload, copy_len);
    printf("Received data: %s\n", buffer);
    return ERR_OK;
}

int main()
{
    stdio_init_all();

    sleep_ms(10000); // Wait for the serial console to be ready
    printf("Start!\n");

    // Initialise the Wi-Fi chip
    if (cyw43_arch_init())
    {
        printf("Wi-Fi init failed\n");
        return -1;
    }

    // Enable wifi station
    cyw43_arch_enable_sta_mode();

    // const char *ssid = "POCO M5s";
    // const char *password = "s5yk8xcynpantgb";

    const char *ssid = "Evolution";
    const char *password = "eminem1980";

    printf("Connecting to Wi-Fi...\n");
    int connectionStatus = cyw43_arch_wifi_connect_timeout_ms(ssid, password, CYW43_AUTH_WPA2_MIXED_PSK, 10000);
    if (connectionStatus)
    {
        printf("failed to connect.\n");
        return 1;
    }
    else
    {
        printf("Connected.\n");
        // Read the ip address in a human readable way
        uint8_t *ip_address = (uint8_t *)&(cyw43_state.netif[0].ip_addr.addr);
        printf("IP address %d.%d.%d.%d\n", ip_address[0], ip_address[1], ip_address[2], ip_address[3]);
        uint8_t *gateway = (uint8_t *)&(cyw43_state.netif[0].gw.addr);
        printf("Gateway %d.%d.%d.%d\n", gateway[0], gateway[1], gateway[2], gateway[3]);

        // uint8_t *dns = (uint8_t *)&(cyw43_state.netif[1].addr);

        httpc_connection_t settings;
        settings.result_fn = result;
        settings.headers_done_fn = headers;

        ip_addr_t ip;
        ip.addr = ipaddr_addr("51.77.100.163");

        err_t err;

        uint32_t start_time = sys_now();
        printf("Wi-Fi status: %d\n", connectionStatus);
        err = httpc_get_file(&ip,
                             80,
                             "/counter.php",
                             &settings,
                             body,
                             NULL,
                             NULL);
        uint32_t end_time = sys_now();

        printf("Request duration: %d ms\n", end_time - start_time);

        if (err == ERR_OK)
        {
            printf("HTTP request sent successfully.\n");
            sleep_ms(1000); // Wait for the response to be processed
        }
        else
        {
            printf("Failed to send HTTP request, error: %d\n", err);
        }
    }
}

For the CMakeLists.txt or a complete RPI Pico W code which is written by using visual studio code’s pico extension, head over to the github page.

درباره ی حمیدرضا

حمیدرضا هستم فارغ التحصیل رشته الکترونیک. رشته ام و کامپیوترها و موبایل و اینترنت و گیمینگ گوشه ای از علائق من هستن. زنده باد مایکروسافت!

این پست هم توصیه می شود:

حل مشکل JsonException: A possible object cycle was detected در ASP.Net Core

هاست رایگان ویندوز ASP.NET Core

بسیاری از تازه کاران در زمینه ی برنامه نویسی نیاز به امکان به اجرا در …

دیدگاهتان را بنویسید

نشانی ایمیل شما منتشر نخواهد شد.